UNPKG

snips-sam

Version:

The Snips Assistant Manager

69 lines (60 loc) 2.29 kB
import * as process from 'process'; import cli from '../cli'; import * as yargs from 'yargs'; import { SSHService } from '../session/ssh'; import { getLocalExternalIp, scanNetwork } from '../utils/device'; import chalk from 'chalk'; import shelljs = require('shelljs'); exports.command = 'devices'; exports.desc = 'Discover devices on your local network'; exports.handler = async (argv: yargs.Argv) => { let devicesIP: string[] | void; cli.stream.loading('Scanning network:'); const ip: string[] = getLocalExternalIp().split('.'); ip[ip.length - 1] = '255'; ip[ip.length - 2] = '255'; const broadcastAddress = ip.join('.'); try { await shelljs.exec(`ping ${broadcastAddress} -c 2`, { async: true, silent: true }); } catch (e) { cli.stream.error(`Broadcasting ping failed on ${broadcastAddress}, all devices might not appear.`); } devicesIP = await scanNetwork() .catch((e) => { cli.stream.stopAndClear(); cli.stream.error('Error scanning network: ' + e.message); return; }); if (devicesIP === undefined) { cli.stream.stopAndClear(); cli.stream.error('No devices found'); return process.exit(); } const devicesIPAndHostname = await SSHService.fetchBootHostname(devicesIP) .catch((e) => { cli.stream.stopAndClear(); cli.stream.error(e); }); if (devicesIPAndHostname === undefined) { cli.stream.stopAndClear(); cli.stream.error('Error fetching devices hostnames'); return process.exit(); } const devicesPromptList = devicesIPAndHostname.map(({ ip, hostname, snipsHostname }) => { if (snipsHostname.length > 0) { return `- ${hostname} (${ip}, ${snipsHostname})`; } return `- ${hostname} (${ip})`; }); cli.stream.done(); if (devicesPromptList.length === 1) { cli.stream.print(`Found ${devicesPromptList.length} device:`); } else { cli.stream.print(`Found ${devicesPromptList.length} devices:`); } devicesPromptList.forEach((device) => { cli.stream.print(device); }); cli.stream.hint('You can now connect with ' + chalk.blue('sam connect <hostname>')); process.exit(); };