Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

243 lines
6.8KB

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