@redplc/node-red-rpi-ads1115
Version:
Node-RED node for ads1115 16bit adc using with redPlc nodes.
87 lines (72 loc) • 3.41 kB
JavaScript
/**
* Copyright 2024 Derya Y. (iot.redplc@gmail.com).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
;
module.exports = function(RED) {
const syslib = require("./lib/syslib.js");
const sysmodule = syslib.LoadModule("rpi_ads1115");
const N_CH = 4;
RED.nodes.registerType("redplc-ads1115", function(n) {
var node = this;
RED.nodes.createNode(node, n);
node.port = parseInt(n.port);
node.devadr = parseInt(n.devadr);
node.tupdate = n.tupdate;
node.mux = [parseInt(n.mux0), parseInt(n.mux1), parseInt(n.mux2), parseInt(n.mux3)];
node.rate = [parseInt(n.rate0), parseInt(n.rate1), parseInt(n.rate2), parseInt(n.rate3)];
node.gain = [parseInt(n.gain0), parseInt(n.gain1), parseInt(n.gain2), parseInt(n.gain3)];
node.rawdata = [n.rawdata0, n.rawdata1, n.rawdata2, n.rawdata3];
node.ch_enabled = [n.enabled0, n.enabled1, n.enabled2, n.enabled3];
node.varname = "IA" + n.address;
node.name = "ads1115 #" + node.port + "@" + (node.devadr + 0x48).toString(16).toUpperCase();
node.ctxvar = new Array(N_CH).fill(0);
node.onwork = false;
node.iserror = false;
syslib.setStatus(node, node.varname, "grey");
if (sysmodule === undefined)
node.iserror = syslib.outError(node, "driver error", "driver not load, wrong os or not Raspi");
else if (!syslib.createVariable(node, node.varname, node.ctxvar))
node.iserror = syslib.outError(node, node.varname + " duplicate", node.varname + " duplicate");
else if (!sysmodule.open(node.port, node.devadr))
node.iserror = syslib.outError(node, "open error", "i2c port not open, check i2c");
node.on("input", (msg) => {
if (node.iserror || node.onwork || (msg.payload !== true)) {
node.send(msg);
return;
}
node.onwork = true;
node.id_update = setTimeout( () => {
sysmodule.read(node.port, node.devadr, node.mux, node.gain, node.rate, node.rawdata, node.ch_enabled,
(readval) => {
if (readval === undefined)
syslib.outError(node, "i2c error");
else {
syslib.setStatus(node, node.varname);
for (var i = 0; i < N_CH; i++)
if (node.ch_enabled[i])
node.ctxvar[i] = readval[i];
}
node.onwork = false;
});
}, node.tupdate);
node.send(msg);
});
node.on('close', () => {
clearTimeout(node.id_update);
syslib.deleteVariable(node, node.varname);
sysmodule.close(node.port, node.devadr);
});
});
}