UNPKG

@redplc/node-red-gpio

Version:

Node-RED nodes for Raspberry Pi gpio using with redPlc nodes

103 lines (85 loc) 3.61 kB
/** * 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. **/ "use strict"; module.exports = function(RED) { const syslib = require("./syslib.js"); const gpiox = require("@iiot2k/gpiox"); const NOSET = 0; if (gpiox === undefined) throw new Error("driver error @iiot2k/gpiox"); RED.nodes.registerType("redplc-gpio-in", function(n) { const node = this; RED.nodes.createNode(node, n); node.varname = "I" + n.address; node.name = "gpio-in " + node.varname; node.tupdate = n.tupdate; node.ctxvar = new Array(28); node.isdi = false; node.iserror = false; node.onwork = false; syslib.setStatus(node, node.varname, "grey"); if (!syslib.createVariable(node, node.varname, node.ctxvar)) node.iserror = syslib.outError(node, node.varname + " duplicate", node.varname + " duplicate"); else if (n.gpioinit.length == 0) node.iserror = syslib.setStatus(node, node.varname + " noselect", "grey"); else { for (var idx = 0; idx <= 25; idx++) { var gpiomode; switch(parseInt(n.gpioinit[idx])) { case 1: gpiomode = gpiox.GPIO_MODE_INPUT_NOPULL; break; case 2: gpiomode = gpiox.GPIO_MODE_INPUT_PULLDOWN; break; case 3: gpiomode = gpiox.GPIO_MODE_INPUT_PULLUP; break; default: continue; } var pin = idx + 2; // gpio pin 2..27 node.isdi = true; node.ctxvar[pin] = false; if (!gpiox.init_gpio(pin, gpiomode, parseInt(n.gpiodeb[idx]) * 1000)) { node.iserror = syslib.outError(node, " pin " + pin + " " + gpiox.error_text(), " pin " + pin + " " + gpiox.error_text()); break; } } if (!node.isdi) node.iserror = syslib.setStatus(node, node.varname + " noselect", "grey"); } function update() { for (var idx = 0; idx <= 25; idx++) { if (n.gpioinit[idx] == NOSET) continue; var pin = idx + 2; // gpio pin 2..27 node.ctxvar[pin] = gpiox.get_gpio(pin); } node.onwork = false; } node.on("input", function (msg) { if (node.iserror || node.onwork || (msg.payload !== true)) { node.send(msg); return; } node.onwork = true; node.id_update = setTimeout(update, node.tupdate); syslib.setStatus(node, node.varname); node.send(msg); }); node.on('close', function () { clearTimeout(node.id_update); syslib.deleteVariable(node, node.varname); for (var idx = 0; idx <= 25; idx++) if (n.gpioinit[idx] != NOSET) gpiox.deinit_gpio(idx + 2); }); }); }