選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

225 行
6.0KB

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