You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

268 lines
8.4KB

  1. module.exports = function(RED) {
  2. function BooleanLogicUltimate(config) {
  3. RED.nodes.createNode(this, config);
  4. var node = this;
  5. node.config = config;
  6. node.jSonStates = {}; // JSON object with elements. It's not an array! Format: {"Rain":true,"Dusk":true,"MotionSensor":true}
  7. node.sInitializeWith = typeof node.config.sInitializeWith === "undefined" ? "WaitForPayload" : node.config.sInitializeWith;
  8. var fs = require('fs');
  9. var decimal = /^\s*[+-]{0,1}\s*([\d]+(\.[\d]*)*)\s*$/
  10. // Helper for the config html, to be able to delete the peristent states file
  11. RED.httpAdmin.get("/stateoperation_delete", RED.auth.needsPermission('BooleanLogicUltimate.read'), function (req, res) {
  12. //node.send({ req: req });
  13. // Detele the persist file
  14. //var _node = RED.nodes.getNode(req.query.nodeid); // Gets node object from nodeit, because when called from the config html, the node object is not defined
  15. var _nodeid = req.query.nodeid;
  16. try {
  17. if (fs.existsSync("states/" + _nodeid.toString())) fs.unlinkSync("states/" + _nodeid.toString());
  18. } catch (error) {
  19. }
  20. res.json({ status: 220 });
  21. });
  22. // Populate the state array with the persisten file
  23. if (node.config.persist == true) {
  24. try {
  25. var contents = fs.readFileSync("states/" + node.id.toString()).toString();
  26. if (typeof contents !== 'undefined') {
  27. node.jSonStates = JSON.parse(contents);
  28. setNodeStatus({fill: "blue",shape: "ring",text: "Loaded persistent states (" + Object.keys(node.jSonStates).length + " total)."});
  29. }
  30. } catch (error) {
  31. setNodeStatus({fill: "grey",shape: "ring",text: "No persistent states"});
  32. }
  33. } else {
  34. setNodeStatus({fill: "yellow",shape: "dot",text: "Waiting for input states"});
  35. }
  36. // 14/08/2019 If some inputs are to be initialized, create a dummy items in the array
  37. initUndefinedInputs();
  38. this.on('input', function (msg) {
  39. var topic = msg.topic;
  40. var payload = msg.payload;
  41. if (topic !== undefined && payload !== undefined) {
  42. var value = ToBoolean( payload );
  43. // 14/08/2019 if inputs are initialized, remove a "dummy" item from the state's array, as soon as new topic arrives
  44. if(node.sInitializeWith !== "WaitForPayload")
  45. {
  46. // Search if the current topic is in the state array
  47. if (typeof node.jSonStates[topic] === "undefined")
  48. {
  49. // Delete one dummy
  50. for (let index = 0; index < node.config.inputCount; index++) {
  51. if (node.jSonStates.hasOwnProperty("dummy" + index)) {
  52. //RED.log.info(JSON.stringify(node.jSonStates))
  53. delete node.jSonStates["dummy" + index];
  54. //RED.log.info(JSON.stringify(node.jSonStates))
  55. break;
  56. }
  57. }
  58. }
  59. }
  60. // Add current attribute
  61. node.jSonStates[topic] = value;
  62. // Save the state array to a perisistent file
  63. if (node.config.persist == true) {
  64. try {
  65. if (!fs.existsSync("states")) fs.mkdirSync("states");
  66. fs.writeFileSync("states/" + node.id.toString(),JSON.stringify(node.jSonStates));
  67. } catch (error) {
  68. setNodeStatus({fill: "red",shape: "dot",text: "Node cannot write to filesystem: " + error});
  69. }
  70. }
  71. // Do we have as many inputs as we expect?
  72. var keyCount = Object.keys(node.jSonStates).length;
  73. if( keyCount == node.config.inputCount ) {
  74. var resAND = CalculateResult("AND");
  75. var resOR = CalculateResult("OR");
  76. var resXOR = CalculateResult("XOR");
  77. if (node.config.filtertrue == "onlytrue") {
  78. if (!resAND) { resAND = null };
  79. if (!resOR) { resOR = null };
  80. if (!resXOR) { resXOR = null };
  81. }
  82. // Operation mode evaluation
  83. if (node.config.outputtriggeredby == "onlyonetopic") {
  84. if (typeof node.config.triggertopic !== "undefined"
  85. && node.config.triggertopic !== ""
  86. && msg.hasOwnProperty("topic") && msg.topic !==""
  87. && node.config.triggertopic === msg.topic)
  88. {
  89. SetResult(resAND, resOR, resXOR, node.config.topic);
  90. } else
  91. {
  92. setNodeStatus({ fill: "grey", shape: "ring", text: "Saved (" + (msg.hasOwnProperty("topic") ? msg.topic : "empty input topic") + ") " + value});
  93. }
  94. } else
  95. {
  96. SetResult(resAND, resOR, resXOR, node.config.topic);
  97. }
  98. }
  99. else if(keyCount > node.config.inputCount ) {
  100. setNodeStatus({ fill: "gray", shape: "ring", text: "Reset due to unexpected new topic"});
  101. DeletePersistFile();
  102. } else {
  103. setNodeStatus({ fill: "green", shape: "ring", text: "Arrived topic " + keyCount + " of " + node.config.inputCount});
  104. }
  105. }
  106. });
  107. this.on('close', function(removed, done) {
  108. if (removed) {
  109. // This node has been deleted
  110. // Delete persistent states on change/deploy
  111. DeletePersistFile();
  112. } else {
  113. // This node is being restarted
  114. }
  115. done();
  116. });
  117. function DeletePersistFile (){
  118. // Detele the persist file
  119. try {
  120. if (fs.existsSync("states/" + node.id.toString())) fs.unlinkSync("states/" + node.id.toString());
  121. setNodeStatus({fill: "red",shape: "ring",text: "Persistent states deleted ("+node.id.toString()+")."});
  122. } catch (error) {
  123. setNodeStatus({fill: "red",shape: "ring",text: "Error deleting persistent file: " + error.toString()});
  124. }
  125. node.jSonStates = {}; // Resets inputs
  126. // 14/08/2019 If the inputs are to be initialized, create a dummy items in the array
  127. initUndefinedInputs();
  128. }
  129. function initUndefinedInputs() {
  130. if (node.sInitializeWith !== "WaitForPayload")
  131. {
  132. var nTotalDummyToCreate = Number(node.config.inputCount) - Object.keys(node.jSonStates).length;
  133. if (nTotalDummyToCreate > 0) {
  134. RED.log.info("BooleanLogicUltimate: Will create " + nTotalDummyToCreate + " dummy (" + node.sInitializeWith + ") values")
  135. for (let index = 0; index < nTotalDummyToCreate; index++) {
  136. node.jSonStates["dummy" + index] = node.sInitializeWith === "false" ? false : true;
  137. }
  138. setTimeout(() => { setNodeStatus({fill: "green",shape: "ring",text: "Initialized " + nTotalDummyToCreate + " undefined inputs with " + node.sInitializeWith});}, 4000)
  139. }
  140. }
  141. }
  142. function setNodeStatus({fill, shape, text})
  143. {
  144. node.status({fill: fill,shape: shape,text: text + " (Last " + new Date().toLocaleString() + ")"})
  145. }
  146. function CalculateResult(_operation) {
  147. var res;
  148. if( _operation == "XOR") {
  149. res = PerformXOR();
  150. }
  151. else {
  152. // We need a starting value to perform AND and OR operations.
  153. var keys = Object.keys(node.jSonStates);
  154. res = node.jSonStates[keys[0]];
  155. for( var i = 1; i < keys.length; ++i ) {
  156. var key = keys[i];
  157. res = PerformSimpleOperation( _operation, res, node.jSonStates[key] );
  158. }
  159. }
  160. return res;
  161. }
  162. function PerformXOR()
  163. {
  164. // XOR = exclusively one input is true. As such, we just count the number of true values and compare to 1.
  165. var trueCount = 0;
  166. for( var key in node.jSonStates ) {
  167. if( node.jSonStates[key] ) {
  168. trueCount++;
  169. }
  170. }
  171. return trueCount == 1;
  172. }
  173. function PerformSimpleOperation( operation, val1, val2 ) {
  174. var res;
  175. if( operation === "AND" ) {
  176. res = val1 && val2;
  177. }
  178. else if( operation === "OR" ) {
  179. res = val1 || val2;
  180. }
  181. else {
  182. node.error( "Unknown operation: " + operation );
  183. }
  184. return res;
  185. }
  186. function ToBoolean( value ) {
  187. var res = false;
  188. if (typeof value === 'boolean') {
  189. res = value;
  190. }
  191. else if( typeof value === 'number' || typeof value === 'string' ) {
  192. // Is it formated as a decimal number?
  193. if( decimal.test( value ) ) {
  194. var v = parseFloat( value );
  195. res = v != 0;
  196. }
  197. else {
  198. res = value.toLowerCase() === "true";
  199. }
  200. }
  201. return res;
  202. };
  203. function SetResult(_valueAND, _valueOR, _valueXOR, optionalTopic) {
  204. setNodeStatus({fill: "green",shape: "dot",text: "(AND)" + _valueAND + " (OR)" +_valueOR + " (XOR)" +_valueXOR});
  205. if (_valueAND!=null){
  206. var msgAND = {
  207. topic: optionalTopic === undefined ? "result" : optionalTopic,
  208. operation:"AND",
  209. payload: _valueAND
  210. };
  211. }
  212. if (_valueOR!=null){
  213. var msgOR = {
  214. topic: optionalTopic === undefined ? "result" : optionalTopic,
  215. operation:"OR",
  216. payload: _valueOR
  217. };
  218. }
  219. if (_valueXOR!=null){
  220. var msgXOR = {
  221. topic: optionalTopic === undefined ? "result" : optionalTopic,
  222. operation:"XOR",
  223. payload: _valueXOR
  224. };
  225. }
  226. node.send([msgAND,msgOR,msgXOR]);
  227. };
  228. }
  229. RED.nodes.registerType("BooleanLogicUltimate",BooleanLogicUltimate);
  230. }