Last active
January 21, 2017 17:55
-
-
Save ajmas/c3122389f7b5118841e7285f1e5be8f3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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