/
NodeMCU-Tool.js
executable file
·488 lines (389 loc) · 14.5 KB
/
NodeMCU-Tool.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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
var _fs = require('fs');
var _nodeMcuConnector = require('./NodeMcuConnector');
var _serialTerminal = require('./SerialTerminal');
var _path = require('path');
var _loggingFacility = require('logging-facility');
// NodeMCU-Tool Context Logger
var _logger = _loggingFacility.getLogger('NodeMCU-Tool');
// NodeMCU Context Logger
var _mculogger = _loggingFacility.getLogger('NodeMCU');
// Serial Terminal Context Logger
var _terminallogger = _loggingFacility.getLogger('SerialTerminal');
// output
var outputHandler = function(message){
console.log(message);
};
var writeOutput = function(message){
if (outputHandler){
outputHandler(message);
}
};
// global options
var _options = {
// serial port baudrate
baudrate: 115200,
// serial device connected to nodemcu
device: '/dev/ttyUSB0',
// delay after opening the connection
connectionDelay: 0
};
// Programmatic Access to the core functions
var Tool = {
// access the connector directly
Connector: _nodeMcuConnector,
// set output handler
onOutput: function (handler) {
outputHandler = handler;
},
// set connector options
setOptions: function(opt){
// merge with default options
Object.keys(_options).forEach(function(key){
_options[key] = opt[key] || _options[key];
});
}
};
// helper function to create a NodeMCU Tool Connection
var getConnection = function(cb){
// create new connector
var connector = new _nodeMcuConnector(_options.device, _options.baudrate);
// open connection with connection check
connector.connect(function(error, response){
if (error) {
_logger.error('Unable to establish connection - ' + error);
// finished!
connector.disconnect();
}else{
// status message
_logger.log('Connected');
_mculogger.log(response);
cb(connector);
}
}, true, _options.connectionDelay);
};
// show file-system info
Tool.fsinfo = function(format){
// try to establish a connection to the module
getConnection(function(connector){
connector.fsinfo(function(err, meta, files){
// finished!
connector.disconnect();
if (err){
_logger.error(err);
}else{
// json output - third party applications
if (format == 'json') {
writeOutput(JSON.stringify({
files: files,
meta: meta
}));
// raw format - suitable for use in bash scripts
}else if (format == 'raw'){
// print fileinfo
files.forEach(function(file){
writeOutput(file.name);
});
}else{
_mculogger.log('Free Disk Space: ' + meta.remaining + ' KB | Total: ' + meta.total + ' KB | ' + files.length + ' Files');
// files found ?
if (files.length==0){
_mculogger.log('No Files found - have you created the file-system?');
}else{
_mculogger.log('Files stored into Flash (SPIFFS)');
// print fileinfo
files.forEach(function(file){
writeOutput('\t |- ' + file.name + ' (' + file.size + ' Bytes)');
});
}
}
}
});
});
};
// upload a local file to nodemcu
Tool.upload = function(localFiles, options, onProgess){
// the index of the current uploaded file
var fileUploadIndex = 0;
var uploadFile = function(connector, localFile, remoteFilename, onComplete){
// increment upload index
fileUploadIndex++;
// get file stats
try{
var fileInfo = _fs.statSync(localFile);
// check if file is directory
if (fileInfo.isDirectory()) {
_mculogger.error('Path "' + localFile + '" is a directory.');
onComplete();
return;
}
// local file available
} catch (err){
_logger.error('Local file not found "' + localFile + '" skipping...');
onComplete();
return;
}
// display filename
_logger.log('Uploading "' + localFile + '" >> "' + remoteFilename + '"...');
// normalize the remote filename (strip relative parts)
remoteFilename = remoteFilename.replace(/\.\.\//g, '').replace(/\.\./g, '').replace(/^\.\//, '');
// delete old file (may existent)
connector.removeFile(remoteFilename, function(err){
// handle error
if (err){
connector.disconnect();
_logger.error(err);
return;
}
// start the file transfer
connector.upload(localFile, remoteFilename, options,
// onComplete
function(err){
// handle error
if (err){
connector.disconnect();
_logger.error(err);
return;
}
// compile flag set ? and is a lua file ?
if (options.compile && _path.extname(localFile).toLowerCase() == '.lua'){
_mculogger.log(' |- compiling lua file..');
connector.compile(remoteFilename, function(error){
// success ? empty line will return (null)
if (error){
connector.disconnect();
_mculogger.error('Error: ' + error);
}else{
_mculogger.log(' |- success');
// drop original lua file
connector.removeFile(remoteFilename, function(error){
if (error){
connector.disconnect();
_mculogger.error('Error: ' + error);
return;
}
_mculogger.log(' |- original Lua file removed');
onComplete();
});
}
});
}else{
// directly call complete handler
onComplete();
}
},
// on progress handler
function(current, total){
// proxy and append file-number
onProgess(current, total, fileUploadIndex);
}
);
});
};
// try to establish a connection to the module
getConnection(function(connector){
// single file upload ?
if (localFiles.length == 1){
// extract first element
var localFile = localFiles[0];
// filename defaults to original filename minus path.
// this behaviour can be overridden by --keeppath and --remotename options
var remoteFile = options.remotename ? options.remotename : (options.keeppath ? localFile : _path.basename(localFile));
// start single file upload
uploadFile(connector, localFile, remoteFile, function(){
// close connection
connector.disconnect();
// log message
_logger.log('File Transfer complete!');
});
// bulk upload ?
}else{
var uploadNext = function(){
// file available ?
if (localFiles.length > 0){
// extract file
var localFile = localFiles.shift();
// keep-path option set ?
var remoteFile = (options.keeppath ? localFile : _path.basename(localFile));
// trigger upload
uploadFile(connector, localFile, remoteFile, uploadNext);
// no more file available
}else{
// close connection
connector.disconnect();
// log message
_logger.log('Bulk File Transfer complete!');
}
};
// trigger initial upload
uploadNext();
}
});
};
// download a remote file from nodemcu
Tool.download = function(remoteFile){
// strip path
var localFilename = _path.basename(remoteFile);
// local file with same name already available ?
if (_fs.existsSync(remoteFile)){
// change filename
localFilename += '.' + (new Date().getTime());
_logger.log('Local file "' + remoteFile + '" already exist - new file renamed to "' + localFilename + '"');
}
// try to establish a connection to the module
getConnection(function(connector){
_logger.log('Downloading "' + remoteFile + '" ...');
connector.download(remoteFile,
// onComplete
function(err, filedata){
// finished!
connector.disconnect();
if (err){
_logger.error('Data Transfer FAILED!');
}else{
_logger.log('Data Transfer complete!');
// store local file
_fs.writeFileSync(localFilename, filedata);
_logger.log('File "' + localFilename + '" created');
}
}
);
});
};
// run a file on NodeMCU (.lc or .lua)
Tool.run = function(filename){
// try to establish a connection to the module
getConnection(function(connector){
connector.run(filename, function(err, output){
// finished!
connector.disconnect();
if (err){
_mculogger.error(err);
}else{
// show command response
_mculogger.log('Running "' + filename + '"');
_mculogger.log('>----------------------------->');
writeOutput(output);
_mculogger.log('>----------------------------->');
}
});
});
};
// removes a file from NodeMCU
Tool.remove = function(filename){
// try to establish a connection to the module
getConnection(function(connector){
connector.removeFile(filename, function(err){
// finished!
connector.disconnect();
if (err){
_mculogger.error(err);
}else{
// just show complete message (no feedback from nodemcu)
_mculogger.log('File "' + filename + '" removed!');
}
});
});
};
// format the file system
Tool.mkfs = function(){
// try to establish a connection to the module
getConnection(function(connector){
_mculogger.log('Formatting the file system...this will take around ~30s');
connector.format(function(err, response){
// finished!
connector.disconnect();
if (err){
_mculogger.error('Formatting failed - ' + err);
}else{
// just show complete message
_mculogger.log('File System created | ' + response);
}
});
});
};
// serial terminal <> console session
Tool.terminal = function(initialCommand){
// create new connector
var terminal = new _serialTerminal();
_terminallogger.log('Starting Terminal Mode - press ctrl+c to exit');
// run initial command before starting terminal session ?
if (initialCommand){
terminal.onConnect(function(device){
device.write(initialCommand + '\n');
});
}
// start
terminal.passthrough(_options.device, _options.baudrate, function(err){
if (err){
_terminallogger.error(err);
}else{
_terminallogger.log('Connection closed');
}
});
};
// show serial devices connected to the system
Tool.devices = function(showAll, jsonOutput){
// create new connector
var connector = new _nodeMcuConnector(_options.device, _options.baudrate);
// retrieve the device list (not bound to an opened connection)
connector.deviceInfo(showAll, function(err, devices){
if (err){
_mculogger.error('Cannot retrieve serial device list - ' + err);
}else{
if (jsonOutput){
writeOutput(JSON.stringify(devices));
}else{
// just show complete message
if (devices.length == 0){
_mculogger.error('No Connected Devices found | Total: ' + devices.length);
}else{
_mculogger.log('Connected Devices | Total: ' + devices.length);
// print fileinfo
devices.forEach(function(device){
writeOutput('\t |- ' + device.comName + ' (' + device.manufacturer + ', ' + device.pnpId + ')');
});
}
}
}
});
};
// Reset of the NodeMCU Module
Tool.reset = function(){
// create new connector
var connector = new _nodeMcuConnector(_options.device, _options.baudrate);
// open connection without connection check
connector.connect(function(error, response){
if (error) {
_logger.error('Unable to establish connection - ' + error);
}else{
// status message
_logger.log('Connected');
// execute reset
connector.reset(function(err){
// finished!
connector.disconnect();
if (err){
_mculogger.error(err);
}else{
_mculogger.log('Hard-Reset executed (100ms)');
}
})
}
}, false);
};
// Reset of the NodeMCU Module
Tool.softreset = function(){
// try to establish a connection to the module
getConnection(function(connector){
connector.softreset(function(err){
// finished!
connector.disconnect();
if (err){
_mculogger.error(err);
}else{
_mculogger.log('Soft-Reset executed (node.restart())');
}
});
});
};
module.exports = Tool;