Skip to content

Commit

Permalink
Adds --wrap-cmd.
Browse files Browse the repository at this point in the history
Use --wrap-cmd to tie the server's lifetime to a child process. This
is useful as a wrapper to launch apps that depend on the server being
accessible. Use --wrap-cwd to set the working directory for the
subprocess.
  • Loading branch information
mildmojo committed Sep 23, 2017
1 parent b072ffc commit d99fb8f
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 19 deletions.
48 changes: 43 additions & 5 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
'use strict';
const fs = require('fs');
const {spawn} = require('child_process');
const nconf = require('nconf');
const cjson = require('cjson');
const chalk = require('chalk');
Expand All @@ -19,15 +20,21 @@ if (nconf.get('version')) {

if (nconf.get('help')) {
console.log('Options:');
console.log(' --help - Prints this usage info');
console.log(' --port n - Listen port number for HTTP server (default: 3000)');
console.log(" --testmode - Simulate serial port activity, don't open real ports");
console.log(' --version - Prints server version number');
console.log(' --help - Prints this usage info');
console.log(' --port n - Listen port number for HTTP server (default: 3000)');
console.log(" --testmode - Simulate serial port activity, don't open real ports");
console.log(' --wrap-cmd cmd - Spawn `cmd` as a subprocess; kill server when subprocess dies and vice versa');
console.log(' --wrap-dir dir - Working directory for wrapped command');
console.log(' --version - Prints server version number');
process.exit();
}

const server = require('./lib/server.js');
server.start(nconf).catch(console.error);
server
.start(nconf)
.then(() => console.log(chalk.blue.bold('Press CTRL+C to quit.')))
.then(() => nconf.get('wrap-cmd') && spawnChild())
.catch(console.error);

function readConfig(file) {
if (!fs.existsSync('./config.json')) {
Expand All @@ -46,3 +53,34 @@ function verifyConfig(config) {
throw new Error('Serial ports not configured.');
}
}

// Spawn a child process with a suicide pact; parent & child die together.
function spawnChild() {
const cmd = nconf.get('wrap-cmd');
const cwd = nconf.get('wrap-dir');

console.log(chalk.green(`Spawning subprocess '${cmd}'...`))
const spawnOpts = {
stdio: 'inherit',
shell: true,
cwd: cwd
};
const child = spawn(cmd, [], spawnOpts);

function onChildExit(code) {
console.log(chalk.green('Wrapped process exited, server exiting...'));
process.removeListener('exit', onExit);
process.exit(code);
}
function onExit(code) {
console.log(chalk.green('Exiting, killing subprocess...'))
child.removeAllListeners();
process.removeListener('exit', onExit);
child.kill.bind(child);
process.exit(code);
}

process.on('SIGINT', onExit);
process.on('exit', onExit);
child.on('exit', onChildExit)
}
44 changes: 30 additions & 14 deletions lib/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,34 +9,31 @@ const SerialPort = require('serialport');
const chalk = require('chalk');
const xml2js = require('xml2js');
const ButtonStatus = require('./buttonStatus');
let httpServer = null;

module.exports = {start, stop};

// Expects a config object with a .get() function for looking up values by key.
async function start(config) {
const serverPort = config.get('port');
const serialPortNames = config.get('serialPorts');

// Read configs and create things.
const mappings = await readMappings(config.get('mappingFiles'));
const buttonStatuses = createButtonStatuses(config.get('serialPorts').length, mappings);
const serialPorts = openSerialPorts(config.get('serialPorts'));
const buttonStatuses = createButtonStatuses(serialPortNames.length, mappings);
const serialPorts = openSerialPorts(serialPortNames);

// Bind serial port data events to button status trackers.
for (let i = 0; i < serialPorts.length; i++) {
serialPorts[i].on('data', chunk => buttonStatuses[i].update(chunk));
}
// Connect serial port data inflow to button status decoders.
bindPortsToStatuses(serialPorts, buttonStatuses);

// Start servers.
const app = startApp(config, buttonStatuses);
const httpServer = http.createServer(app);
httpServer = await startHTTPServer(app, serverPort);
const wsServer = startWebSocketServer(config, httpServer, buttonStatuses);

console.log(chalk.yellow(`Starting server on port ${serverPort}...`));
httpServer.listen(serverPort, function listening() {
console.log(chalk.yellow.bold(`Server started on port ${httpServer.address().port}.`));
console.log(chalk.blue.bold(`Visit http://localhost:${serverPort}/ to see a demo status page.`));
});
}

function stop(done) {
if (done) setImmediate(done);
httpServer.close(done || (()=>{}));
}

async function readMappings(mappingFiles) {
Expand Down Expand Up @@ -86,6 +83,12 @@ function openSerialPorts(portNames, testmode) {
});
}

function bindPortsToStatuses(serialPorts, buttonStatuses) {
for (let i = 0; i < serialPorts.length; i++) {
serialPorts[i].on('data', chunk => buttonStatuses[i].update(chunk));
}
}

function startApp(config, buttonStatuses) {
const testmode = config.get('testmode');
const serialPorts = config.get('serialPorts');
Expand Down Expand Up @@ -113,6 +116,19 @@ function startApp(config, buttonStatuses) {
return app;
}

function startHTTPServer(app, serverPort) {
return new Promise(resolve => {
console.log(chalk.yellow(`Starting server on port ${serverPort}...`));

let httpServer = http.createServer(app);
httpServer.listen(serverPort, function listening() {
console.log(chalk.yellow.bold(`Server started on port ${httpServer.address().port}.`));
console.log(chalk.blue.bold(`Visit http://localhost:${serverPort}/ to see a demo status page.`));
resolve(httpServer);
});
});
}

function startWebSocketServer(config, httpServer, buttonStatuses) {
const testmode = config.get('testmode');
const serialPorts = config.get('serialPorts');
Expand Down

0 comments on commit d99fb8f

Please sign in to comment.