Skip to content

Instantly share code, notes, and snippets.

@ajmas
Last active January 21, 2017 17:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ajmas/c3122389f7b5118841e7285f1e5be8f3 to your computer and use it in GitHub Desktop.
Save ajmas/c3122389f7b5118841e7285f1e5be8f3 to your computer and use it in GitHub Desktop.
/**
* Creates an HTTP server to allow to read the sensor data via
* HTTP. Improvements could include caching the data, to avoid
* the sensor being hit too frequently.
*
* Not tested in-situ.
*/
const express = require('express');
const app = express();
const net = require('net');
app.get('/sensor', function (req, res) {
const port = 1700;
const host = '172.20.8.198';
var client = new net.Socket();
client.connect(port, host, function() {
console.log('connected to: ' + host + ':' + port);
client.write(new Buffer('1234567', 'hex')[0]);
});
client.on('data', function(data) {
var json = JSON.parse(data);
res.json(json);
client.destroy();
});
client.on('error', function(error) {
res.json( { message: 'error: ' + error} );
});
client.on('timeout', function(error) {
res.json( { message: 'timeout connecting to device' } );
});
client.on('close', function() {
console.log('Connection closed');
});
});
app.get('/', function (req, res) {
res.send('Hello World!')
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
});
// ref: https://www.hacksparrow.com/tcp-socket-programming-in-node-js.html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment