-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathset-device-uuid.js
315 lines (280 loc) · 9.65 KB
/
set-device-uuid.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
var serial = require('serialport');
var fs = require('fs');
var stream = require('binary-stream');
var sets = require('simplesets');
var commons = require('./commons');
var parsers = require('./parsing');
var uuid = require('uuid-v4');
var CRC = require('crc');
function ChillhubDevice(ttyPath) {
var self = this;
var ESC = 0xfe;
var STX = 0xff;
self.deviceType = '';
self.UUID = '';
self.buf = [];
self.msgBody = [];
self.resources = {};
self.registered = false;
self.newUUID = '';
self.uid = ttyPath;
self.tty = new serial.SerialPort('/dev/'+ttyPath, {
baudrate: 115200,
disconnectedCallback: function(err) {
if (err) {
console.log('error in disconnectedCallback');
console.log(err);
console.log('UUID is ' + self.UUID);
}
}
});
self.tty.open(function(err) {
if (err) {
console.log('error opening serial port');
console.log(err);
return;
}
self.tty.flush(function(err) {
if (err) {
console.log("Error flushing the serial port input buffer.");
console.log(err);
return;
}
console.log("Serial port input buffer flushed.");
self.scanForStx = function() {
while (self.buf.length > 0) {
var c = self.buf.shift();
if (c == STX) {
self.commHandler = self.waitForLength;
self.waitForLength();
break;
}
}
}
self.waitForLength = function() {
if (self.buf.length > 1) {
if (self.buf[0] == ESC) {
self.buf.shift();
}
self.msgLen = self.buf.shift();
self.bufIndex = 0;
self.msgBody.length = 0;
self.commHandler = self.waitForMessage;
self.waitForMessage();
}
}
self.waitForMessage = function() {
while (self.buf.length > self.bufIndex) {
if (self.buf[self.bufIndex] == ESC) {
if ((self.buf.length - self.bufIndex) > 1) {
self.bufIndex++;
} else {
return;
}
}
self.msgBody.push(self.buf[self.bufIndex++]);
// wait for message plus sent checksum
if (self.msgBody.length >= self.msgLen+2) {
self.checkMessage();
}
}
}
self.checkMessage= function() {
var crcSent = self.msgBody.pop() + self.msgBody.pop()*256;
crc = CRC.crc16ccitt(self.msgBody);
if (crc == crcSent) {
// remove message from input buffer
self.buf.splice(0, self.bufIndex);
self.msgBody.shift();
if (self.ignoreMsgCount > 0) {
self.ignoreMsgCount--;
} else {
routeIncomingMessage(self.msgBody);
}
} else {
console.log("Check sum error.");
self.buf.shift();
}
self.commHandler = self.scanForStx;
self.scanForStx();
}
self.commHandler = self.scanForStx;
self.tty.on('data', function(data) {
// network byte order is big endian... let's go with that
self.buf = self.buf.concat((new stream.Reader(data, stream.BIG_ENDIAN)).readBytes(data.length));
self.commHandler();
return;
while(self.buf.length > self.buf[0]) {
msg = self.buf.slice(1,self.buf[0]+1);
self.buf = self.buf.slice(self.buf[0]+1,self.buf.length);
if (msg.length > 0) {
routeIncomingMessage(msg);
}
}
});
self.tty.on('error', function(err) {
console.log('serial error:');
console.log(err);
});
self.tty.on('disconnect', function(err) {
console.log('error disconnecting?');
console.log(err);
});
self.send = function(data) {
// parse data into the format that usb devices expect and transmit it
var dataBytes = parsers.parseJsonToStream(data);
var writer = new stream.Writer(dataBytes.length+1, stream.BIG_ENDIAN);
writer.writeUInt8(dataBytes.length);
writer.writeBytes(dataBytes);
var buf = writer.toArray();
var outBuf = [];
if (buf.length > 255) {
console.log("ERROR: Cannot send a message longer than 255 bytes!!!");
return;
}
var encodeByteToArray = function(b, a) {
if (b == ESC || b == STX) {
a.push(ESC);
}
a.push(b);
}
// Take message body, wrap in STX and checksum, add escapes as needed.
outBuf.push(STX);
encodeByteToArray(buf.length, outBuf);
var crc = CRC.crc16ccitt(buf);
for (var i=0; i<buf.length; i++) {
encodeByteToArray(buf[i], outBuf);
}
encodeByteToArray(commons.getNibble(crc, 2), outBuf);
encodeByteToArray(commons.getNibble(crc, 1), outBuf);
self.tty.write(outBuf, function(err) {
if (err) {
console.log('error writing to serial');
console.log(err);
}
});
return;
};
if (self.onOpenCallback) {
self.onOpenCallback();
}
});
});
function setDeviceUUID() {
self.send({
type: 0x0c,
content: self.newUUID
});
// wait a little, then request UUID again.
setTimeout(function() {
self.send({
type: 0x08,
content: {
numericType: 'U8',
numericValue: 1
}
});
}, 2000);
}
function startSetUUIDProcess() {
self.newUUID = uuid();
console.log("Attempting to set UUID to: " + self.newUUID);
setDeviceUUID();
}
function routeIncomingMessage(data) {
// parse into whatever form and then send it along
var jsonData = parsers.parseStreamToJson(data);
switch (jsonData.type) {
case 0x00:
if (self.registered == false) {
if (jsonData.content === undefined) {
console.log("Content is missing from message type 0x00 received from attachment.");
return;
}
self.deviceType = jsonData.content[0];
self.UUID = jsonData.content[1];
console.log('Found device "'+self.deviceType+'" with UUID '+ self.UUID + '!');
self.registered = true;
startSetUUIDProcess();
} else {
// we were registered, see if the set UUID process worked.
if (jsonData.content === undefined) {
console.log("Content is missing from message type 0x00 received from attachment.");
return;
}
self.deviceType = jsonData.content[0];
self.UUID = jsonData.content[1];
if (self.UUID === self.newUUID) {
console.log("New UUID successfully set.");
process.exit(0);
} else {
console.log("ERROR: Unable to set the UUID on the device.");
console.log("The device sent a UUID of " + self.UUID);
process.exit(1);
}
}
break;
}
}
self.cleanup = function() {
};
self.registerOpenCallback = function(func) {
self.onOpenCallback = func;
}
self.sendRegistrationRequest = function sendRegistrationRequest () {
self.send({
type: 0x08,
content: {
numericType: 'U8',
numericValue: 1
}
});
}
self.checkForDeviceRegistration = function checkForDeviceRegistration() {
if (!self.registered) {
console.log("Device was not properly registered, requesting registration info again.");
self.sendRegistrationRequest();
setTimeout(self.checkForDeviceRegistration, 5000);
}
}
setTimeout(self.checkForDeviceRegistration, 5000);
}
var devices = {};
if (process.platform === 'darwin') {
console.log("We are running on a Mac, look for tty.usbmodem devices.");
var filePattern = /^tty.usbmodem[0-9]+$/;
} else {
var filePattern = /^(ttyACM[0-9]{1,2}|ttyUSB[0-9]{1,2})$/;
}
fs.readdir('/dev/', function(err, files) {
files = files.filter(function(file) {
return filePattern.test(file);
});
files.forEach(function(filename) {
console.log('registering new USB device ' + filename);
devices[filename] = new ChillhubDevice(filename);
(function() {
var what = filename;
devices[filename].registerOpenCallback (function() {
devices[what].sendRegistrationRequest();
});
})();
});
});
// watch for new devices
fs.watch('/dev/', function(event, filename) {
console.log("Saw a change in dev.");
if (!filePattern.test(filename))
return;
fs.exists('/dev/'+filename, function (exists) {
if (devices[filename] && !exists) {
console.log('unregistering USB device ' + filename);
devices[filename].cleanup();
delete devices[filename];
}
else if (!devices[filename] && exists) {
console.log('registering new USB device ' + filename);
devices[filename] = new ChillhubDevice(filename);
}
});
});