node-red-contrib-lorawan
Version:
Node-RED module for the LoRaWAN RN2483 and RN2903 radio modules
91 lines (81 loc) • 2.06 kB
JavaScript
const SerialPort = require('serialport');
const ASync = require('async');
const Delimiter = require('@serialport/parser-delimiter');
//var RN2483 = require('./commands.js');
const port = new SerialPort('/dev/ttyAMA0', {
baudRate: 57600,
dataBits: 8,
stopBits: 1,
parity: 'none',
rtscts: false,
});
port.on('error', function (err) {
console.log('Error: ', err.message)
});
// Pipe the data into another stream (like a parser or standard out)
const parser = port.pipe(new Delimiter({
delimiter: '\r\n'
}));
parser.on('data', receive);
function sendCommand(cmd, ...args) {
transmit(cmd);
}
function receive(data) {
if (callbackStack.length > 0) {
console.log(callbackStack);
var item = callbackStack.pop();
var cmd = item.data;
var callback = item.callback;
console.log('Answer to "' + cmd + '": ' + data.toString('ascii'));
callback(null, data);
};
}
function transmit(data, callback) {
console.log("Send command " + data);
port.write(data + "\r\n", function (err, res) {
if (err) {
// I'm assuming that if there is an error on the line
// you won't receive serial data for the request. Hence
// we remove the callback from the stack.
callbackStack.splice(callbackStack.indexOf({
data,
callback
}), 1);
callback(err);
};
});
callbackStack.unshift({
data,
callback
});
}
var callbackStack = [];
var init_sequence_p2p = [
'mac pause',
'radio set pwr ' + '15',
'radio set freq ' + '868100000',
'radio set sf ' + 'sf12',
'radio set cr ' + '4/5',
'radio set bw ' + '125',
'radio set crc ' + 'on'
];
function init() {
var async = require('async');
var cmds_sequence = init_sequence_p2p
console.log(cmds_sequence);
async.eachSeries(cmds_sequence, function (item, next) {
transmit(item, function (err, data) {
if (data == 'invalid_param')
return;
if ((data == "4294967245") || (data == "ok"))
next();
})
},
function (err) {
if (err == null)
console.log('Initialisation OK !');
else
console.log('Error on initialization: ' + err);
});
}
init();