@iiot2k/node-red-gpio
Version:
Node-RED nodes for Raspberry Pi gpio
104 lines (86 loc) • 3.25 kB
JavaScript
/**
* Copyright 2025 Derya Y. (iiot2k@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("./syslib.js");
const gpiomon = require("@iiot2k/gpiomon");
if (gpiomon === undefined)
throw new Error("driver error @iiot2k/gpiomon");
RED.nodes.registerType("iiot2k-gpio-in", function(n) {
const node = this;
RED.nodes.createNode(node, n);
node.gpio = parseInt(n.gpio);
node.debounce = parseInt(n.debounce);
node.outbool = n.outbool;
node.sendoninit = n.sendoninit;
node.name = "gpio" + node.gpio;
switch(n.pull) {
case "nopull":
node.pull = gpiomon.GPIO_MODE_INPUT_NOPULL;
break;
case "pulldown":
node.pull = gpiomon.GPIO_MODE_INPUT_PULLDOWN;
break;
case "pullup":
node.pull = gpiomon.GPIO_MODE_INPUT_PULLUP;
break;
}
switch(n.edge) {
case "rising":
node.edge = gpiomon.GPIO_EDGE_RISING;
break;
case "falling":
node.edge = gpiomon.GPIO_EDGE_FALLING;
break;
case "both":
node.edge = gpiomon.GPIO_EDGE_BOTH;
break;
}
const send_msg = (state) => {
if (node.outbool)
node.send({ payload: state > 0, topic: node.name });
else
node.send({ payload: state, topic: node.name });
}
const status_text = (val) =>
val ? "1": "0";
const status_color = (val) =>
val ? "green" : "grey";
const error_text = () =>
gpiomon.error_text();
const watch_callback = (pin, state, edge) => {
send_msg(state);
syslib.setStatus(node, status_text(state), status_color(state));
}
const timeout_callback = () => {
var state = gpiomon.read_gpio(node.gpio)
if (state === undefined)
syslib.outError(node, error_text(), error_text());
else {
syslib.setStatus(node, status_text(state), status_color(state));
if (node.sendoninit)
send_msg(state);
}
}
if (!gpiomon.monitor_gpio(node.gpio, node.pull, node.debounce * 1000, node.edge, watch_callback))
syslib.outError(node, error_text(), error_text());
else
setTimeout(timeout_callback, 250);
node.on('close', () => {
gpiomon.deinit_gpio(node.gpio);
});
});
}