UNPKG

@gemini86/node-red-ds18b20

Version:

Node-RED node for ds18b20 sensors connected on GPIO (fork of iiot2k, which was removed from NPM)

116 lines (90 loc) 3.64 kB
/** * * 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("../util/gpiox.js"); if (gpiox === undefined) throw new Error("driver error ../util/gpiox"); RED.nodes.registerType("read-ds18b20", function(n) { const node = this; RED.nodes.createNode(node, n); node.gpio = parseInt(n.gpio); node.tupdate = parseInt(n.tupdate); node.onchange = n.onchange; node.fahrenheit = n.fahrenheit; node.doupdate = false; node.name = "ds18b20-gpio" + node.gpio; switch(n.resolution) { case "9": node.resolution = gpiox.RES_SENSOR_9; break; case "10": node.resolution = gpiox.RES_SENSOR_10; break; case "11": node.resolution = gpiox.RES_SENSOR_11; break; case "12": node.resolution = gpiox.RES_SENSOR_12; } const error_text = () => gpiox.error_text(); const status_text = () => n.resolution + "bit #" + gpiox.get_sensor_count(node.gpio); const update_sensors = (update) => { node.iserror = false; if ((update === false) && !gpiox.init_sensor(node.gpio, node.resolution)) { node.iserror = syslib.outError(node, error_text()); return; } if (!gpiox.scan_sensor_sync(node.gpio)) { node.iserror = syslib.outError(node, error_text()); return; } node.sensor_list = gpiox.list_sensor(node.gpio); if (node.sensor_list === undefined) node.iserror = syslib.outError(node, error_text()); else syslib.setStatus(node, status_text()); } const read_sensors = () => { if (node.onwork) return; if (node.doupdate) { update_sensors(true); node.doupdate = false; } if (node.iserror) return; node.onwork = true; gpiox.read_sensor(node.gpio, node.fahrenheit, (data) => { if (data === undefined) syslib.outError(node, error_text()); else if (!node.onchange || (JSON.stringify(data) !== node.preval)) { node.preval = JSON.stringify(data); node.send({ payload: data, topic: node.sensor_list }); syslib.setStatus(node, status_text()); } else syslib.setStatus(node, status_text()); node.onwork = false; }); } update_sensors(false); node.onwork = false; node.id_interval = setInterval(read_sensors, node.tupdate * 1000); node.on("input", (msg) => { node.doupdate = true; }); node.on('close', () => { clearInterval(node.id_interval); gpiox.deinit_gpio(node.gpio); }); }); }