-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
92 lines (72 loc) · 2.74 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
#!/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');
if (!options.secret) {
const cncrc = path.resolve(getUserHome(), '.cncrc');
try {
const 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;
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.');
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);
});
socket.on('serialport:error', function(options) {
callback(new Error('Error opening serial port "' + options.port + '"'));
});
socket.on('serialport:read', function(data) {
console.log((data || '').trim());
});
socket.on('serialport:write', function(data) {
console.log((data || '').trim());
});
};