forked from tessel/t2-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
controller.js
667 lines (605 loc) · 20.7 KB
/
controller.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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
var Tessel = require('./tessel/tessel');
var logs = require('./logs');
var Promise = require('bluebird');
var _ = require('lodash');
var discover = require('./discover');
var sprintf = require('sprintf-js').sprintf;
var cp = require('child_process');
var async = require('async');
var controller = {};
var debug = require('debug')('controller');
var Menu = require('terminal-menu');
Tessel.list = function(opts) {
return new Promise(function(resolve, reject) {
// Grab all attached Tessels
logs.info('Searching for nearby Tessels...');
// Keep a list of all the Tessels we discovered
var foundTessels = [];
// Start looking for Tessels
var seeker = new discover.TesselSeeker().start();
// When a Tessel is found
seeker.on('tessel', function displayResults(tessel) {
var note = '';
// Add it to our array
var known = false;
if (foundTessels.length >= 1) {
for (var i in foundTessels) {
if (foundTessels[i].connections[0].ip === tessel.connections[0].ip && tessel.connections[0].connectionType === 'LAN') {
// Your network topology causes a single tessel is found twice
debug('known = true');
known = true;
}
}
}
if (known) {
debug('Due to your Network-Topology ' + tessel.name + ' is found twice! (' + tessel.connections[0].ip + ')');
} else {
// Add it to our array
foundTessels.push(tessel);
// Add a note if the user isn't authorized to use it yet
if (tessel.connection.connectionType === 'LAN' && !tessel.connection.authorized) {
note = '(USB connect and run `tessel provision` to authorize)';
}
// Print out details...
logs.basic(sprintf('\t%s\t%s\t%s', tessel.name, tessel.connection.connectionType, note));
}
});
// Called after CTRL+C or timeout
function stopSearch() {
// If the seeker exists (it should)
if (seeker !== undefined) {
// Stop looking for more Tessels
debug('seeker stopped');
seeker.stop();
}
// If there were no Tessels found
if (foundTessels.length === 0) {
// Report the sadness
reject('No Tessels Found');
} else if (foundTessels.length === 1) {
// Close all opened connections and resolve
controller.closeTesselConnections(foundTessels)
.then(resolve);
}
// If we have only one Tessel or two Tessels with the same name (just USB and LAN)
else if (foundTessels.length === 1 ||
(foundTessels.length === 2 && foundTessels[0].name === foundTessels[1].name)) {
// Close all opened connections and resolve
controller.closeTesselConnections(foundTessels)
.then(resolve);
}
// Otherwise
else {
// Figure out which Tessel will be selected
controller.runHeuristics(opts, foundTessels)
.then(function logSelected(tessel) {
// Report that selected Tessel to the user
logs.info('Multiple Tessels found.');
if (tessel) {
logs.info('Will default to', tessel.name, '.');
} else {
// menu for selection
var rtm = new Menu({
// width: process.stdout.columns - 4,
width: 55,
x: 1,
y: 2,
bg: 'red'
});
controller.menu.prepareMenu(opts, foundTessels, rtm, resolve, reject,'Please select the default Tessel 2', function(name,resolve,reject){
logs.info('Selected Tessel: '+name);
logs.err('TODO: ... we need to persist the selected Tessel!');
resolve();
});
}
// Helpful instructions on how to switch
// logs.info('Set default Tessel with environment variable (e.g. \'export TESSEL=bulbasaur\') or use the --name flag.');
// Close all opened connections and resolve
controller.closeTesselConnections(foundTessels)
.then(resolve);
});
}
}
// If a timeout was provided and it's a number
if (opts.timeout && typeof opts.timeout === 'number') {
// Stop the search after that duration
setTimeout(stopSearch, opts.timeout * 1000);
}
// Stop the search if CTRL+C is hit
process.once('SIGINT', stopSearch);
});
};
Tessel.get = function(opts) {
return new Promise(function(resolve, reject) {
logs.info('Connecting to Tessel...');
// Store the amount of time to look for Tessel
var timeout = opts.timeout || 1.5;
// Collection variable as more Tessels are found
var tessels = [];
// Create a seeker object and start detecting any Tessels
var seeker = new discover.TesselSeeker().start();
// The handle for the search complete timeout
var timeoutHandle;
// When we find Tessels
seeker.on('tessel', function(tessel) {
// Check if this name matches the provided option (if any)
// This speeds up development by immediately ending the search
if (opts.name && opts.name === tessel.name) {
// Stop searching
seeker.stop();
// Don't call the timeout
clearTimeout(timeoutHandle);
// Send this Tessel back to the caller
logAndFinish(tessel);
}
// Otherwise
else {
// Store this Tessel with the others
tessels.push(tessel);
}
});
// Set the timeout for when we give up searching
timeoutHandle = setTimeout(function() {
// Stop the search
seeker.stop();
// If we found no Tessels
if (tessels.length === 0) {
// Report it
reject('No Tessels Found.');
return;
}
// If there was only one Tessel
else if (tessels.length === 1) {
// Return it immediately
logAndFinish(tessels[0]);
}
// Otherwise
else {
// Combine the same Tessels into one object
controller.reconcileTessels(tessels)
.then(function(reconciledTessels) {
tessels = reconciledTessels;
// Run the heuristics to pick which Tessel to use
return controller.runHeuristics(opts, tessels)
.then(logAndFinish);
});
}
}, timeout * 1000);
// Accesses `tessels` in closure
function logAndFinish(tessel) {
// The Tessels that we won't be using should have their connections closed
var connectionsToClose = tessels;
if (tessel) {
logs.info(sprintf('Connected to %s over %s', tessel.name, tessel.connection.connectionType));
connectionsToClose.splice(tessels.indexOf(tessel), 1);
controller.closeTesselConnections(connectionsToClose)
.then(function() {
return resolve(tessel);
});
} else {
logs.info('Please specify a Tessel by name [--name <tessel name>]');
controller.closeTesselConnections(connectionsToClose)
.then(reject);
}
}
});
};
/*
Takes a list of Tessels with connections that
may or may not be open and closes them
*/
controller.closeTesselConnections = function(tessels) {
return new Promise(function(resolve, reject) {
async.each(tessels, function closeThem(tessel, done) {
// If not an unauthorized LAN Tessel, it's connected
if (!(tessel.connection.connectionType === 'LAN' &&
!tessel.connection.authorized)) {
// Close the connection
return tessel.close()
.then(done, done);
} else {
done();
}
},
function closed(err) {
if (err) {
reject(err);
} else {
resolve();
}
});
});
};
controller.menu = {
prepareMenu: function(opts, tessels, rtm, resolve, reject, title, callback) {
// Hack for creating usebility (exit menu)
tessels.push({
connection: {
connectionType: 'exit'
}
});
rtm.reset();
rtm.write(title+'\n');
rtm.write(' \n');
// create menu entries
for (var i in tessels) {
controller.menu.makeMenu(tessels[i], i, rtm);
}
if (!opts.menu) {
// if this is no test, starting the menu as child process
controller.menu.showMenu(rtm, resolve, reject);
} else {
// because the test needs to resolve the promise ...
resolve({
opts: opts,
tessels: tessels
});
}
rtm.once('select', function(label,index) {
rtm.close();
controller.menu.clear();
// Identify the Exit command by first letter (all other entries start with numbers/index)
if (label[0] !== 'E') {
callback(tessels[index].name,resolve,reject);
// controller.ssh.runSSH(index, opts, tessels, resolve, reject);
} else {
// going to clear screen and calling exit to resolve promise
controller.menu.clear(resolve);
}
});
},
makeMenu: function(tessel, index, rtm) {
if (tessel.connection.connectionType === 'LAN') {
if (!tessel.connection.authorized) {
rtm.add(index + ') ' + tessel.name + ': ' + tessel.connection.ip + ' (not authorized) \n');
} else {
rtm.add(index + ') ' + tessel.name + ': ' + tessel.connection.ip + ' (authorized) \n');
}
} else if (tessel.connection.connectionType === 'USB') {
if (!tessel.connection.authorized) {
rtm.add(index + ') ' + tessel.name + ': [USB] (not authorized) \n');
} else {
rtm.add(index + ') ' + tessel.name + ': [USB] (authorized) \n');
}
} else {
rtm.add('EXIT\n');
}
// FIXME: Workaround for trouble with dynamic added menu elements
rtm._draw();
},
showMenu: function(rtm, resolve, reject) {
// Menu navigation
process.stdin.pipe(rtm.createStream()).pipe(process.stdout);
// raw mode for gain ability to navigate up and down within the menu
process.stdin.setRawMode(true);
// cb
rtm.on('close', function() {
process.stdin.setRawMode(false);
process.stdin.end();
});
rtm.on('error', function(e) {
process.stdin.setRawMode(false);
reject(e);
});
},
seek: function(opts) {
// to be able to replace the seeker in testing mode
return Tessel.seekTessels(opts);
},
clear: function() {
// selected exit!
process.stdout.write('\u001b[2J\u001b[0;0H');
},
exit: function(resolve) {
resolve();
//process.exit();
}
};
controller.ssh = {
runSSH: function(id, opts, tessels, resolve, reject) {
// clear console
debug('runSSH...\n root@' + tessels[id].connections[0].host);
if (opts.menu) {
// because the test needs to resolve the promise ...
resolve({
opts: opts,
tessels: tessels
});
} else {
// if this is no test, starting the menu as child process
controller.menu.clear();
var ch = require('child_process')
.spawn('ssh', ['-i',
opts.path,
'root@' + tessels[id].connections[0].ip
], {
stdio: 'inherit'
});
logs.info('Connect to ' + tessels[id].connections[0].host + '...');
// FIXME: There is no handler for poweroff Tessel ! Needs to be fixed within the firmware...
// (Terminal freezes imediatelly after poweroff the Tessel)
ch.once('error', function(e) {
if (e === 255) {
controller.menu.clear();
controller.ssh.notAuthorized();
reject();
} else {
logs.warn('Error while connected to ' + tessels[id].connections[0].host + ':', e);
reject(e);
}
});
ch.once('exit', function(e) {
if (e === 255) {
controller.menu.clear();
controller.ssh.notAuthorized();
reject();
} else if (e === 127) { // exit by user
// clear console
controller.menu.clear();
logs.warn('Connection to ' + tessels[id].connections[0].host + ' closed!\n');
resolve();
} else if (e === 0) {
// everything works fine ... now lets clear the terminal
controller.menu.clear();
logs.info('Connection to ' + tessels[id].connections[0].host + ' closed!\n');
resolve();
} else {
logs.warn('Connection to ' + tessels[id].connections[0].host + ' closed due to reason:\n', e);
reject(e);
}
});
ch.once('close', function(e) {
// tessel powers off
if (e === 0) {
// everything works fine...
resolve();
} else if (e === 255) {
//reject();
process.exit();
} else if (e === 127) {
reject();
} else {
logs.warn('Connection to ' + tessels[id].connections[0].host + ' closed due to reason:\n', e);
reject();
}
});
}
},
notAuthorized: function(){
logs.warn('Sorry, you are not authorized!');
logs.info('Maybe this Tessel didn\'t got "t2 provision" until now?');
}
};
/*
Takes list of USB and LAN Tessels and merges
and Tessels that are the same origin with difference
connection methods.
Assumes tessel.getName has already been called for each.
*/
controller.reconcileTessels = function(tessels) {
return new Promise(function(resolve) {
// If there is only one, just return
if (tessels.length <= 1) {
return resolve(tessels);
}
var accounts = {};
var reconciled = tessels.reduce(function(accum, tessel) {
if (accounts[tessel.name]) {
// Updates tessels in accum by reference
accounts[tessel.name].connections.push(tessel.connection);
} else {
accounts[tessel.name] = tessel;
accum.push(tessel);
}
return accum;
}, []);
resolve(reconciled);
});
};
/*
0. using the --name flag
1. an environment variable in the terminal, set as export TESSEL=Bulbasaur
2. if there is a single tessel connected over USB, prefer that one
3. if there is only one tessel visible, use that one
4. if none of the above are found run tessel list automatically and prompt selection
*/
// Called when multiple tessels are found are we need to figure out
// Which one the user should act upon
controller.runHeuristics = function(opts, tessels) {
var NAME_OPTION_PRIORITY = 0;
var ENV_OPTION_PRIORITY = 1;
var USB_CONN_PRIORITY = 2;
var LAN_CONN_PRIORITY = 3;
// For each of the Tessels found
return Promise.reduce(tessels, function(collector, tessel) {
// Create an object to keep track of what priority this Tessel has
// The lower the priority, the more likely the user wanted this Tessel
var entry = {
tessel: tessel,
priority: undefined
};
// If a name option was provided and it matches this Tessel
if (opts.name && opts.name === tessel.name) {
// Set it to the highest priority
entry.priority = NAME_OPTION_PRIORITY;
// Store the entry
collector.push(entry);
return collector;
}
// If an environment variable was set and it equals this Tessel
if (process.env.TESSEL && process.env.TESSEL === tessel.name) {
// Mark the priority level
entry.priority = ENV_OPTION_PRIORITY;
// Store the entry
collector.push(entry);
return collector;
}
// If this is a USB connection
if (tessel.connection.connectionType === 'USB') {
// Mark the priority
entry.priority = USB_CONN_PRIORITY;
// Store the entry
collector.push(entry);
return collector;
}
// This is a LAN connection so give it the lowest priority
entry.priority = LAN_CONN_PRIORITY;
// Store the entry
collector.push(entry);
return collector;
}, [])
.then(function selectTessel(collector) {
var usbFound = false;
var lanFound = false;
// Sort all of the entries by priority
collector = _.sortBy(collector, function(entry) {
return entry.priority;
});
// For each entry
for (var i = 0; i < collector.length; i++) {
var collectorEntry = collector[i];
// If this is a name option or environment variable option
if (collectorEntry.priority === NAME_OPTION_PRIORITY ||
collectorEntry.priority === ENV_OPTION_PRIORITY) {
// Return the Tessel and stop searching
return collectorEntry.tessel;
}
// If this is a USB Tessel
else if (collectorEntry.priority === USB_CONN_PRIORITY) {
// And no other USB Tessels have been found yet
if (usbFound === false) {
// Mark it as found and continue
usbFound = true;
}
// We have multiple USB Tessels which is an issue
else {
// Return nothing because the user needs to be more specific
return;
}
}
// If this is a LAN Tessel
else if (collectorEntry.priority === LAN_CONN_PRIORITY) {
// And we haven't found any other Tessels
if (lanFound === false) {
// Mark it as found and continue
lanFound = true;
}
// We have multiple LAN Tessels which is an issue
else {
// Return nothing because the user needs to be more specific
return;
}
}
}
// At this point, we know that no name option or env variable was set
// and we know that there is only one USB and/or on LAN Tessel
// We'll return the highest priority available
return collector[0].tessel;
});
};
controller.provisionTessel = function(opts) {
opts = opts || {};
return new Promise(function(resolve, reject) {
if (Tessel.isProvisioned()) {
if (opts.force) {
cp.exec('rm -r ' + Tessel.TESSEL_AUTH_PATH, function(error) {
if (error) {
reject(error);
} else {
resolve();
}
});
} else {
// ~/.tessel exists with keys
resolve();
}
} else {
// There is no ~/.tessel
resolve();
}
})
.then(Tessel.get.bind(null, opts))
.then(function(tessel) {
return tessel.provisionTessel(opts)
.then(function() {
return controller.closeTesselConnections(tessel);
});
});
};
controller.deployScript = function(opts, push) {
// Grab the preferred Tessel
return Tessel.get(opts)
.then(function(tessel) {
// Run the script on Tessel
return tessel.deployScript(opts, push)
.then(function() {
return controller.closeTesselConnections(tessel);
});
});
};
controller.eraseScript = function(opts) {
// Grab the preferred Tessel
return Tessel.get(opts)
.then(function(tessel) {
// Run the script on Tessel
return tessel.eraseScript(opts, false)
.then(function() {
return controller.closeTesselConnections(tessel);
});
});
};
controller.renameTessel = function(opts) {
opts = opts || {};
// Grab the preferred tessel
return new Promise(function(resolve, reject) {
if (!opts.reset && !opts.newName) {
reject('A new name must be provided.');
} else {
if (!Tessel.isValidName(opts.newName)) {
reject('Invalid name: ' + opts.newName + '. The name must be a valid hostname string. See http://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_host_names.');
} else {
resolve();
}
}
})
.then(Tessel.get.bind(null, opts))
.then(function(tessel) {
return tessel.rename(opts)
.then(function() {
return controller.closeTesselConnections(tessel);
});
});
};
controller.printAvailableNetworks = function(opts) {
// Grab the preferred Tessel
return Tessel.get(opts)
.then(function(selectedTessel) {
// Run the script on Tessel
return selectedTessel.findAvailableNetworks()
.then(function(networks) {
logs.info('Currently visible networks (' + networks.length + '):');
// Print out networks
networks.forEach(function(network) {
logs.info('\t', network.ssid, '(' + network.quality + '/' + network.quality_max + ')');
});
})
.then(function() {
return controller.closeTesselConnections(selectedTessel);
});
});
};
controller.connectToNetwork = function(opts) {
// Grab the preferred Tessel
return Tessel.get(opts)
.then(function(selectedTessel) {
// Connect to the network with provided options
return selectedTessel.connectToNetwork(opts)
.then(function() {
return controller.closeTesselConnections(selectedTessel);
});
});
};
module.exports = controller;
// Shared exports
module.exports.listTessels = Tessel.list;
module.exports.getTessel = Tessel.get;