-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
99 lines (77 loc) · 2.91 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const io = require('socket.io-client');
const jwt = require('jsonwebtoken');
const get = require('lodash.get');
const generateAccessToken = function(payload, secret, expiration) {
const token = jwt.sign(payload, secret, {
expiresIn: expiration
});
return token;
};
// Get secret key from the config file and generate an access token
const getUserHome = function() {
return process.env[(process.platform === 'win32') ? 'USERPROFILE' : 'HOME'];
};
module.exports = function(options, callback) {
options = options || {};
options.secret = get(options, 'secret', process.env['CNCJS_SECRET']);
options.baudrate = get(options, 'baudrate', 115200);
options.socketAddress = get(options, 'socketAddress', 'localhost');
options.socketPort = get(options, 'socketPort', 8000);
options.controllerType = get(options, 'controllerType', 'Grbl');
options.accessTokenLifetime = get(options, 'accessTokenLifetime', '30d');
let config = {};
if (!options.secret) {
const cncrc = path.resolve(getUserHome(), '.cncrc');
try {
config = JSON.parse(fs.readFileSync(cncrc, 'utf8'));
options.secret = config.secret;
} catch (err) {
console.error(err);
process.exit(1);
}
}
const token = generateAccessToken({ id: '', name: 'cncjs-pendant' }, options.secret, options.accessTokenLifetime);
const url = 'ws://' + options.socketAddress + ':' + options.socketPort + '?token=' + token;
let socket = io.connect('ws://' + options.socketAddress + ':' + options.socketPort, {
'query': 'token=' + token
});
socket.on('connect', () => {
console.log('Connected to ' + url);
// Open port
socket.emit('open', options.port, {
baudrate: Number(options.baudrate),
controllerType: options.controllerType
});
});
socket.on('error', (err) => {
console.error('Connection error:', err);
if (socket) {
socket.destroy();
socket = null;
}
});
socket.on('close', () => {
console.log('Connection closed.');
});
socket.on('serialport:open', function(options) {
options = options || {};
console.log('Connected to port "' + options.port + '" (Baud rate: ' + options.baudrate + ')');
callback(null, socket, config);
});
socket.on('serialport:error', function(options) {
callback(new Error('Error opening serial port "' + options.port + '"'));
});
socket.on('serialport:close', function() {
callback(new Error('Serial connection closed'))
process.exit(1)
});
socket.on('serialport:read', function(data) {
//console.log((data || '').trim());
});
socket.on('serialport:write', function(data) {
//console.log((data || '').trim());
});
};