Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

BooleanLogicUltimate.js 9.3KB

5 lat temu
5 lat temu
5 lat temu
5 lat temu
5 lat temu
5 lat temu
5 lat temu
5 lat temu
5 lat temu
5 lat temu
5 lat temu
5 lat temu
5 lat temu
5 lat temu
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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,msg);
  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,msg);
  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,_msg) {
  205. setNodeStatus({fill: "green",shape: "dot",text: "(AND)" + _valueAND + " (OR)" +_valueOR + " (XOR)" +_valueXOR});
  206. // 24/01/2020 Output the entire input msg by duplicating the input and replacing only relevant fields.
  207. if (_valueAND != null) {
  208. var msgAND = RED.util.cloneMessage(_msg);
  209. msgAND.topic = optionalTopic === undefined ? "result" : optionalTopic;
  210. msgAND.operation = "AND";
  211. msgAND.payload = _valueAND;
  212. }
  213. if (_valueOR!=null){
  214. var msgOR = RED.util.cloneMessage(_msg);
  215. msgOR.topic = optionalTopic === undefined ? "result" : optionalTopic;
  216. msgOR.operation = "OR";
  217. msgOR.payload= _valueOR;
  218. }
  219. if (_valueXOR != null) {
  220. var msgXOR = RED.util.cloneMessage(_msg);
  221. msgXOR.topic = optionalTopic === undefined ? "result" : optionalTopic;
  222. msgXOR.operation = "XOR";
  223. msgXOR.payload= _valueXOR;
  224. }
  225. node.send([msgAND, msgOR, msgXOR]);
  226. // if (_valueAND!=null){
  227. // var msgAND = {
  228. // topic: optionalTopic === undefined ? "result" : optionalTopic,
  229. // operation:"AND",
  230. // payload: _valueAND
  231. // };
  232. // }
  233. // if (_valueOR!=null){
  234. // var msgOR = {
  235. // topic: optionalTopic === undefined ? "result" : optionalTopic,
  236. // operation:"OR",
  237. // payload: _valueOR
  238. // };
  239. // }
  240. // if (_valueXOR!=null){
  241. // var msgXOR = {
  242. // topic: optionalTopic === undefined ? "result" : optionalTopic,
  243. // operation:"XOR",
  244. // payload: _valueXOR
  245. // };
  246. // }
  247. // node.send([msgAND,msgOR,msgXOR]);
  248. };
  249. }
  250. RED.nodes.registerType("BooleanLogicUltimate",BooleanLogicUltimate);
  251. }