UNPKG

node-red-contrib-simple-gate

Version:
102 lines (99 loc) 4.34 kB
/** * Copyright 2017 M. I. Bell * * 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) { function GateNode(config) { RED.nodes.createNode(this,config); const openStatus = {fill:"green",shape:"dot",text:"open"}; const closedStatus = {fill:'red',shape:'ring',text:'closed'}; var status; // Copy configuration items this.controlTopic = config.controlTopic.toLowerCase(); this.openCmd = config.openCmd.toLowerCase(); this.closeCmd = config.closeCmd.toLowerCase(); this.toggleCmd = config.toggleCmd.toLowerCase(); this.defaultCmd = config.defaultCmd.toLowerCase(); this.defaultState = config.defaultState.toLowerCase(); this.statusCmd = (config.statusCmd || "status").toLowerCase(); this.persist = config.persist; this.storeName = config.storeName; // Save "this" object var node = this; var context = node.context(); var persist = node.persist; var storeName = node.storeName; context.get('state',storeName,function(err,state){ if (err) { node.error('startup error reading from context store: ' + storeName) } else { if (!persist || typeof state === 'undefined') { state = node.defaultState; } // Initialize status display status = (state === 'open') ? openStatus:closedStatus node.status(status) context.set('state',state,storeName,function(err){ if (err) { node.error('startup error writing to context store: ' + storeName) } }) } }) node.on('input', function(msg) { context.get('state',storeName,function(err,state) { if (err) { node.error('message error reading from context store: ' + storeName) } else if (typeof msg.topic === 'string' && msg.topic.toLowerCase() === node.controlTopic) { // change state if (typeof msg.payload === 'undefined' || msg.payload === null) { msg.payload = ''; } switch (msg.payload.toString().toLowerCase()) { case node.openCmd: state = 'open'; break; case node.closeCmd: state = 'closed'; break; case node.toggleCmd: if (state === 'open') { state = 'closed'; } else { state = 'open'; } break; case node.defaultCmd: state = node.defaultState; break; case node.statusCmd: break; default: node.warn('Invalid command ignored'); } status = (state === 'open') ? openStatus:closedStatus; node.status(status); context.set('state',state,storeName,function(err){ if (err){ node.error('message error writing to context store: ' + storeName) } }); } else if (state === 'open') { // transmit message node.send(msg); } }) }) } RED.nodes.registerType("gate",GateNode); }