Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

269 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. var dDate = new Date();
  145. node.status({fill: fill,shape: shape,text: text + " (" + dDate.getDate() + ", " + dDate.toLocaleTimeString() + ")"})
  146. }
  147. function CalculateResult(_operation) {
  148. var res;
  149. if( _operation == "XOR") {
  150. res = PerformXOR();
  151. }
  152. else {
  153. // We need a starting value to perform AND and OR operations.
  154. var keys = Object.keys(node.jSonStates);
  155. res = node.jSonStates[keys[0]];
  156. for( var i = 1; i < keys.length; ++i ) {
  157. var key = keys[i];
  158. res = PerformSimpleOperation( _operation, res, node.jSonStates[key] );
  159. }
  160. }
  161. return res;
  162. }
  163. function PerformXOR()
  164. {
  165. // XOR = exclusively one input is true. As such, we just count the number of true values and compare to 1.
  166. var trueCount = 0;
  167. for( var key in node.jSonStates ) {
  168. if( node.jSonStates[key] ) {
  169. trueCount++;
  170. }
  171. }
  172. return trueCount == 1;
  173. }
  174. function PerformSimpleOperation( operation, val1, val2 ) {
  175. var res;
  176. if( operation === "AND" ) {
  177. res = val1 && val2;
  178. }
  179. else if( operation === "OR" ) {
  180. res = val1 || val2;
  181. }
  182. else {
  183. node.error( "Unknown operation: " + operation );
  184. }
  185. return res;
  186. }
  187. function ToBoolean( value ) {
  188. var res = false;
  189. if (typeof value === 'boolean') {
  190. res = value;
  191. }
  192. else if( typeof value === 'number' || typeof value === 'string' ) {
  193. // Is it formated as a decimal number?
  194. if( decimal.test( value ) ) {
  195. var v = parseFloat( value );
  196. res = v != 0;
  197. }
  198. else {
  199. res = value.toLowerCase() === "true";
  200. }
  201. }
  202. return res;
  203. };
  204. function SetResult(_valueAND, _valueOR, _valueXOR, optionalTopic) {
  205. setNodeStatus({fill: "green",shape: "dot",text: "(AND)" + _valueAND + " (OR)" +_valueOR + " (XOR)" +_valueXOR});
  206. if (_valueAND!=null){
  207. var msgAND = {
  208. topic: optionalTopic === undefined ? "result" : optionalTopic,
  209. operation:"AND",
  210. payload: _valueAND
  211. };
  212. }
  213. if (_valueOR!=null){
  214. var msgOR = {
  215. topic: optionalTopic === undefined ? "result" : optionalTopic,
  216. operation:"OR",
  217. payload: _valueOR
  218. };
  219. }
  220. if (_valueXOR!=null){
  221. var msgXOR = {
  222. topic: optionalTopic === undefined ? "result" : optionalTopic,
  223. operation:"XOR",
  224. payload: _valueXOR
  225. };
  226. }
  227. node.send([msgAND,msgOR,msgXOR]);
  228. };
  229. }
  230. RED.nodes.registerType("BooleanLogicUltimate",BooleanLogicUltimate);
  231. }