Skip to content

Instantly share code, notes, and snippets.

@KiNgMaR
Created February 9, 2014 16:18
Show Gist options
  • Save KiNgMaR/8901392 to your computer and use it in GitHub Desktop.
Save KiNgMaR/8901392 to your computer and use it in GitHub Desktop.
Reads data from a Mighty Ohm Geiger Counter that is connected via RS232, makes it available via a callback and a TCP socket.
/**
* RADIATION WIDGET - SERVER BIT
*/
var
serialport = require('serialport'),
net = require('net');
exports.widget = function(eventTarget) {
const CONFIG = {
device: '/dev/ttyUSB3',
srv: { bind: '0.0.0.0', port: 42420 },
};
const LINE_REGEXP = /^CPS, (\d+), CPM, (\d+), .+?, ([\d.]+), (SLOW|FAST)/;
var prev_pushed = '';
// --- from local/radiation/radiation.js ---
var linebuf = {}, prev_time = Date.now();
var sp = new serialport.SerialPort(CONFIG.device, {
parser: serialport.parsers.readline("\n")
})
.on('data', function(line) {
var now = Math.floor(Date.now() / 1000);
if(!line)
return;
// max 1 sample per second:
linebuf[now] = line;
// discard accumulated data from serial buffer(s):
if(Date.now() - prev_time < 0.5 * 1000) {
linebuf = [];
}
else {
for(var time in linebuf) {
var line = linebuf[time].trim();
if(line == prev_pushed) {
continue;
}
var match = LINE_REGEXP.exec(line);
if(match) {
// "CPS, 0, CPM, 29, uSv/hr, 0.16, SLOW"
var dat = {
cps: parseInt(match[1]),
cpm: parseInt(match[2]),
usievert: parseFloat(match[3]),
mode: (match[4] === 'SLOW' ? 0 : 1),
raw: line,
};
eventTarget('geiger', dat);
send_to_echo_clients(dat);
prev_pushed = line;
}
}
linebuf = [];
}
prev_time = Date.now();
}).on('error', function(err) {
console.log('Error in radiation.js: ' + err.message);
});
// -- TCP echo server --
var srv_clients = [];
if(CONFIG.srv) {
net.createServer(function(socket) {
srv_clients.push(socket);
function discard_socket() {
srv_clients = srv_clients.filter(function(s) { return (s !== socket); });
}
socket.on('close', discard_socket);
socket.on('error', discard_socket);
})
.listen(CONFIG.srv.port, CONFIG.srv.bind);
}
function send_to_echo_clients(data) {
if(srv_clients.length < 1)
return;
var line = JSON.stringify(data) + '\n';
for(var i in srv_clients) {
srv_clients[i].write(line);
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment