Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // envisalink.js
- const nwTcp = require('net');
- const Invisalink = ({
- network,
- authentication,
- defaultCallbackHandlers = {},
- callbacks,
- runningOptions
- } = {}) => {
- const retr = {};
- const connectionOptions = {
- ...network
- };
- const auth = {
- ...authentication
- };
- const parsedCallbacks = {
- ...callbacks
- };
- const options = {
- ...runningOptions
- };
- let shouldReconnect = true;
- let activeConnection = null;
- let pollTimer = null;
- let cbs = {};
- const printDebug = (message) => {
- if (options.printDebug) {
- console.log(message);
- }
- };
- const printReceivePacket = (packetData) => {
- if (options.printReceivePacket) {
- console.log(packetData);
- }
- };
- const printSendPacket = (packetData) => {
- if (options.printSendPacket) {
- console.log(packetData);
- }
- };
- const printCommandData = (packetData) => {
- if (options.printCommandData) {
- console.log(packetData);
- }
- };
- const connOnError = (err) => {
- console.log(err);
- };
- const connOnEnd = (param) => {
- console.log('End', param);
- };
- const connOnClose = (hadErr) => {
- clearInterval(pollTimer);
- console.log('Closed', hadErr);
- setTimeout(() => {
- if (shouldReconnect && (!activeConnection || activeConnection.destroyed)) {
- retr.connect()
- }
- }, 5000);
- };
- const loginResponse = (data) => {
- printDebug(`[Debug] [loginResponse()]: Processing Login...`);
- const loginStatus = data;
- if (loginStatus === 'FAILED') {
- printDebug(`[Debug] [loginResponse()]: Login Failed: 'Bad Password'`);
- throw new Error(JSON.stringify({
- error: 'login failed',
- reason: 'bad credentials'
- }));
- } else if (loginStatus === 'OK') {
- printDebug(`[Debug] [loginResponse()]: Login Success`);
- sendCommand({ data: '001' })
- clearInterval(pollTimer);
- pollTimer = setInterval(function () {
- sendCommand({ data: '000' });
- }, 60000);
- } else if (loginStatus === 'Timed Out!') {
- printDebug(`[Debug] [loginResponse()]: Login Failed: 'Password timeout'`);
- throw new Error(JSON.stringify({
- error: 'login failed',
- reason: 'password not entered in time'
- }));
- } else if (loginStatus === 'Login:') {
- printDebug(`[Debug] [loginResponse()]: Sending authentication credentials`);
- sendCommand({ data: auth.user })
- }
- };
- const connOnData = (data) => {
- const dataBuffer = data.toString().replace(/[\n\r]/g, '|').split('|');
- // printDebug(`[Debug] [connOnData()]: Commands received: '${dataBuffer.length}'`);
- printReceivePacket(`Data received: '${dataBuffer}'`);
- for (let i = 0; i < dataBuffer.length; i++) {
- const commandData = dataBuffer[i];
- if (commandData !== '') { // TODO: Add error checking
- printCommandData(`Data received: '${commandData}'`);
- if (commandData) { // TODO: Add protocol checking
- if (commandData === '' || commandData === 0) {
- } else {
- if (commandData.trim() === 'Login:') {
- loginResponse(commandData);
- } else {
- console.log('datarec:', commandData);
- }
- }
- }
- }
- }
- };
- const sendCommand = ({ data, includeChecksum = false, includeSentinels = false }) => {
- let checksum = 0
- for (let i = 0; i < data.length; i++) {
- checksum += data.charCodeAt(i);
- }
- checksum = checksum.toString(16).slice(-2).toUpperCase();
- let sendData = data;
- if (includeSentinels) {
- sendData = '^' + sendData + '$';
- }
- if (includeChecksum) {
- sendData += checksum;
- }
- printSendPacket(`Data sent: '${sendData}'<crlf>`);
- sendData += '\r\n';
- activeConnection.write(sendData);
- };
- const connectToInvisalink = (netCon, cbs) => {
- const port = netCon.port || '4025';
- if (Number.isNaN(Number.parseInt(port))
- || port < 1
- || port > 65535) {
- throw new Error(JSON.stringify({
- error: 'Bad port',
- reason: 'Port number is not valid',
- data: port
- }));
- }
- activeConnection = nwTcp.createConnection({ port: port || '4025', host: netCon.host });
- printDebug(`[Debug] [connectToInvisalink()]: TCP link established to port '${netCon.port}'`);
- activeConnection.on('error', cbs.onErrCb);
- activeConnection.on('close', cbs.onCloseCb);
- activeConnection.on('end', cbs.onEndCb);
- activeConnection.on('data', cbs.onDataCb);
- printDebug(`[Debug] [connectToInvisalink()]: Callbacks registered`);
- };
- retr.connect = () => {
- connectToInvisalink(connectionOptions, cbs);
- };
- const init = () => {
- cbs = {
- onErrCb: connOnError,
- onCloseCb: connOnClose,
- onEndCb: connOnEnd,
- onDataCb: connOnData,
- ...defaultCallbackHandlers
- };
- shouldReconnect = connectionOptions.shouldReconnect === null || connectionOptions.shouldReconnect === undefined ? true : shouldReconnect;
- if (!connectionOptions.host) {
- throw new Error(JSON.stringify({
- error: 'Bad host',
- reason: 'Host is not valid',
- data: connectionOptions.host
- }));
- }
- if (!authentication.user) {
- throw new Error(JSON.stringify({
- error: 'Bad user',
- reason: 'user is not valid'
- }));
- }
- if (typeof(cbs.onErrCb) !== 'function') {
- throw new Error(JSON.stringify({
- error: 'Bad parameter',
- reason: 'Default callback: onErrCb is not a function',
- data: typeof(cbs.onErrCb)
- }));
- }
- if (typeof(cbs.onCloseCb) !== 'function') {
- throw new Error(JSON.stringify({
- error: 'Bad parameter',
- reason: 'Default callback: onCloseCb is not a function',
- data: typeof(cbs.onCloseCb)
- }));
- }
- if (typeof(cbs.onEndCb) !== 'function') {
- throw new Error(JSON.stringify({
- error: 'Bad parameter',
- reason: 'Default callback: onEndCb is not a function',
- data: typeof(cbs.onEndCb)
- }));
- }
- if (typeof(cbs.onDataCb) !== 'function') {
- throw new Error(JSON.stringify({
- error: 'Bad parameter',
- reason: 'Default callback: onDataCb is not a function',
- data: typeof(cbs.onDataCb)
- }));
- }
- if (typeof(parsedCallbacks.onData) !== 'function') {
- throw new Error(JSON.stringify({
- error: 'Bad callback',
- reason: 'Callback: onData is not a function',
- data: typeof(parsedCallbacks.onData)
- }));
- }
- if (typeof(parsedCallbacks.onError) !== 'function') {
- throw new Error(JSON.stringify({
- error: 'Bad callback',
- reason: 'Callback: onError is not a function',
- data: typeof(parsedCallbacks.onError)
- }));
- }
- if (process.stdin.isTTY) {
- process.stdin.setRawMode(true);
- }
- process.stdin.setEncoding('utf8');
- process.stdin.on('data', function (chunk) {
- chunk = chunk.trim();
- console.log(`data: '${chunk}'`);
- if (chunk === 'c' || chunk.name === 'c') {
- process.exit();
- }
- if ( chunk === '\u0003' ) {
- process.exit();
- }
- if (chunk === 'q') {
- const includeSentinels = true;
- sendCommand({ data: '*99', includeSentinels: false });
- sendCommand({ data: '*99', includeSentinels });
- }
- if (chunk === 'p') {
- sendCommand({ data: '01', includeSentinels: true });
- }
- if (chunk === 'r') {
- sendCommand({ data: '02', includeSentinels: true });
- }
- if (chunk === 'o') {
- sendCommand({ data: '08', includeSentinels: true });
- }
- if (chunk === 's') {
- const includeSentinels = true;
- sendCommand({ data: '0000#', includeSentinels });
- sendCommand({ data: '63', includeSentinels });
- }
- });
- process.stdin.resume();
- };
- init();
- return retr;
- };
- module.exports = Invisalink;
- // index.js
- const Invisalink = require('./envisalink');
- const onData = (data) => {
- console.log('got data', data);
- }
- const onError = (err) => {
- console.log('got err', err);
- }
- const invisalink = Invisalink({
- network: {
- host: '192.168.1.6',
- port: 4025
- },
- authentication: {
- user: 'user'
- },
- callbacks: {
- onData,
- onError
- },
- runningOptions: {
- printDebug: true,
- printCommandData: true,
- printSendPacket: true
- }
- });
- setTimeout(() => {
- invisalink.connect();
- }, 500)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement