Fork of the espurna firmware for `mhsw` switches
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.

391 lines
11 KiB

  1. /*
  2. RPN RULES MODULE
  3. Use RPNLib library (https://github.com/xoseperez/rpnlib)
  4. Copyright (C) 2019 by Xose Pérez <xose dot perez at gmail dot com>
  5. */
  6. #if RPN_RULES_SUPPORT
  7. #include "ntp.h"
  8. #include "relay.h"
  9. #include "rpnrules.h"
  10. // -----------------------------------------------------------------------------
  11. // Custom commands
  12. // -----------------------------------------------------------------------------
  13. rpn_context _rpn_ctxt;
  14. bool _rpn_run = false;
  15. unsigned long _rpn_delay = RPN_DELAY;
  16. unsigned long _rpn_last = 0;
  17. // -----------------------------------------------------------------------------
  18. bool _rpnWebSocketOnKeyCheck(const char * key, JsonVariant& value) {
  19. return (strncmp(key, "rpn", 3) == 0);
  20. }
  21. void _rpnWebSocketOnConnected(JsonObject& root) {
  22. root["rpnSticky"] = getSetting("rpnSticky", 1 == RPN_STICKY);
  23. root["rpnDelay"] = getSetting("rpnDelay", RPN_DELAY);
  24. JsonArray& rules = root.createNestedArray("rpnRules");
  25. unsigned char i = 0;
  26. String rule = getSetting({"rpnRule", i});
  27. while (rule.length()) {
  28. rules.add(rule);
  29. rule = getSetting({"rpnRule", ++i});
  30. }
  31. #if MQTT_SUPPORT
  32. i=0;
  33. JsonArray& topics = root.createNestedArray("rpnTopics");
  34. JsonArray& names = root.createNestedArray("rpnNames");
  35. String rpn_topic = getSetting({"rpnTopic", i});
  36. while (rpn_topic.length() > 0) {
  37. String rpn_name = getSetting({"rpnName", i});
  38. topics.add(rpn_topic);
  39. names.add(rpn_name);
  40. rpn_topic = getSetting({"rpnTopic", ++i});
  41. }
  42. #endif
  43. }
  44. #if MQTT_SUPPORT
  45. void _rpnMQTTSubscribe() {
  46. unsigned char i = 0;
  47. String rpn_topic = getSetting({"rpnTopic", i});
  48. while (rpn_topic.length()) {
  49. mqttSubscribeRaw(rpn_topic.c_str());
  50. rpn_topic = getSetting({"rpnTopic", ++i});
  51. }
  52. }
  53. void _rpnMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  54. if (type == MQTT_CONNECT_EVENT) {
  55. _rpnMQTTSubscribe();
  56. }
  57. if (type == MQTT_MESSAGE_EVENT) {
  58. unsigned char i = 0;
  59. String rpn_topic = getSetting({"rpnTopic", i});
  60. while (rpn_topic.length()) {
  61. if (rpn_topic.equals(topic)) {
  62. String rpn_name = getSetting({"rpnName", i});
  63. if (rpn_name.length()) {
  64. rpn_variable_set(_rpn_ctxt, rpn_name.c_str(), atof(payload));
  65. _rpn_last = millis();
  66. _rpn_run = true;
  67. break;
  68. }
  69. }
  70. rpn_topic = getSetting({"rpnTopic", ++i});
  71. }
  72. }
  73. }
  74. #endif // MQTT_SUPPORT
  75. void _rpnConfigure() {
  76. #if MQTT_SUPPORT
  77. if (mqttConnected()) _rpnMQTTSubscribe();
  78. #endif
  79. _rpn_delay = getSetting("rpnDelay", RPN_DELAY);
  80. }
  81. void _rpnBrokerCallback(const String& topic, unsigned char id, double value, const char*) {
  82. char name[32] = {0};
  83. snprintf(name, sizeof(name), "%s%u", topic.c_str(), id);
  84. rpn_variable_set(_rpn_ctxt, name, value);
  85. _rpn_last = millis();
  86. _rpn_run = true;
  87. }
  88. void _rpnBrokerStatus(const String& topic, unsigned char id, unsigned int value) {
  89. _rpnBrokerCallback(topic, id, double(value), nullptr);
  90. }
  91. #if NTP_SUPPORT
  92. bool _rpnNtpNow(rpn_context & ctxt) {
  93. if (!ntpSynced()) return false;
  94. rpn_stack_push(ctxt, now());
  95. return true;
  96. }
  97. bool _rpnNtpFunc(rpn_context & ctxt, int (*func)(time_t)) {
  98. float timestamp;
  99. rpn_stack_pop(ctxt, timestamp);
  100. rpn_stack_push(ctxt, func(time_t(timestamp)));
  101. return true;
  102. }
  103. #endif
  104. void _rpnInit() {
  105. // Init context
  106. rpn_init(_rpn_ctxt);
  107. // Time functions need NTP support
  108. // TODO: since 1.14.2, timelib+ntpclientlib are no longer used with latest Cores
  109. // `now` is always in UTC, `utc_...` functions to be used instead to convert time
  110. #if NTP_SUPPORT && !NTP_LEGACY_SUPPORT
  111. rpn_operator_set(_rpn_ctxt, "utc", 0, _rpnNtpNow);
  112. rpn_operator_set(_rpn_ctxt, "now", 0, _rpnNtpNow);
  113. rpn_operator_set(_rpn_ctxt, "utc_month", 1, [](rpn_context & ctxt) {
  114. return _rpnNtpFunc(ctxt, utc_month);
  115. });
  116. rpn_operator_set(_rpn_ctxt, "month", 1, [](rpn_context & ctxt) {
  117. return _rpnNtpFunc(ctxt, month);
  118. });
  119. rpn_operator_set(_rpn_ctxt, "utc_day", 1, [](rpn_context & ctxt) {
  120. return _rpnNtpFunc(ctxt, utc_day);
  121. });
  122. rpn_operator_set(_rpn_ctxt, "day", 1, [](rpn_context & ctxt) {
  123. return _rpnNtpFunc(ctxt, day);
  124. });
  125. rpn_operator_set(_rpn_ctxt, "utc_dow", 1, [](rpn_context & ctxt) {
  126. return _rpnNtpFunc(ctxt, utc_weekday);
  127. });
  128. rpn_operator_set(_rpn_ctxt, "dow", 1, [](rpn_context & ctxt) {
  129. return _rpnNtpFunc(ctxt, weekday);
  130. });
  131. rpn_operator_set(_rpn_ctxt, "utc_hour", 1, [](rpn_context & ctxt) {
  132. return _rpnNtpFunc(ctxt, utc_hour);
  133. });
  134. rpn_operator_set(_rpn_ctxt, "hour", 1, [](rpn_context & ctxt) {
  135. return _rpnNtpFunc(ctxt, hour);
  136. });
  137. rpn_operator_set(_rpn_ctxt, "utc_minute", 1, [](rpn_context & ctxt) {
  138. return _rpnNtpFunc(ctxt, utc_minute);
  139. });
  140. rpn_operator_set(_rpn_ctxt, "minute", 1, [](rpn_context & ctxt) {
  141. return _rpnNtpFunc(ctxt, minute);
  142. });
  143. #endif
  144. // TODO: 1.14.0 weekday(...) conversion seemed to have 0..6 range with Monday as 0
  145. // using classic Sunday as first, but instead of 0 it is 1
  146. // Implementation above also uses 1 for Sunday, staying compatible with TimeLib
  147. #if NTP_SUPPORT && NTP_LEGACY_SUPPORT
  148. rpn_operator_set(_rpn_ctxt, "utc", 0, [](rpn_context & ctxt) {
  149. if (!ntpSynced()) return false;
  150. rpn_stack_push(ctxt, ntpLocal2UTC(now()));
  151. return true;
  152. });
  153. rpn_operator_set(_rpn_ctxt, "now", 0, _rpnNtpNow);
  154. rpn_operator_set(_rpn_ctxt, "month", 1, [](rpn_context & ctxt) {
  155. return _rpnNtpFunc(ctxt, month);
  156. });
  157. rpn_operator_set(_rpn_ctxt, "day", 1, [](rpn_context & ctxt) {
  158. return _rpnNtpFunc(ctxt, day);
  159. });
  160. rpn_operator_set(_rpn_ctxt, "dow", 1, [](rpn_context & ctxt) {
  161. return _rpnNtpFunc(ctxt, weekday);
  162. });
  163. rpn_operator_set(_rpn_ctxt, "hour", 1, [](rpn_context & ctxt) {
  164. return _rpnNtpFunc(ctxt, hour);
  165. });
  166. rpn_operator_set(_rpn_ctxt, "minute", 1, [](rpn_context & ctxt) {
  167. return _rpnNtpFunc(ctxt, minute);
  168. });
  169. #endif
  170. // Dumps RPN stack contents
  171. rpn_operator_set(_rpn_ctxt, "debug", 0, [](rpn_context & ctxt) {
  172. _rpnDump();
  173. return true;
  174. });
  175. // Accept relay number and numeric API status value (0, 1 and 2)
  176. rpn_operator_set(_rpn_ctxt, "relay", 2, [](rpn_context & ctxt) {
  177. float status, id;
  178. rpn_stack_pop(ctxt, id);
  179. rpn_stack_pop(ctxt, status);
  180. if (int(status) == 2) {
  181. relayToggle(int(id));
  182. } else {
  183. relayStatus(int(id), int(status) == 1);
  184. }
  185. return true;
  186. });
  187. // Channel operators
  188. #if RELAY_PROVIDER == RELAY_PROVIDER_LIGHT
  189. rpn_operator_set(_rpn_ctxt, "update", 0, [](rpn_context & ctxt) {
  190. lightUpdate(true, true);
  191. return true;
  192. });
  193. rpn_operator_set(_rpn_ctxt, "black", 0, [](rpn_context & ctxt) {
  194. lightColor((unsigned long) 0);
  195. return true;
  196. });
  197. rpn_operator_set(_rpn_ctxt, "channel", 2, [](rpn_context & ctxt) {
  198. float value, id;
  199. rpn_stack_pop(ctxt, id);
  200. rpn_stack_pop(ctxt, value);
  201. lightChannel(int(id), int(value));
  202. return true;
  203. });
  204. #endif
  205. }
  206. #if TERMINAL_SUPPORT
  207. void _rpnInitCommands() {
  208. terminalRegisterCommand(F("RPN.VARS"), [](Embedis* e) {
  209. unsigned char num = rpn_variables_size(_rpn_ctxt);
  210. if (0 == num) {
  211. DEBUG_MSG_P(PSTR("[RPN] No variables\n"));
  212. } else {
  213. DEBUG_MSG_P(PSTR("[RPN] Variables:\n"));
  214. for (unsigned char i=0; i<num; i++) {
  215. char * name = rpn_variable_name(_rpn_ctxt, i);
  216. float value;
  217. rpn_variable_get(_rpn_ctxt, name, value);
  218. DEBUG_MSG_P(PSTR(" %s: %s\n"), name, String(value).c_str());
  219. }
  220. }
  221. terminalOK();
  222. });
  223. terminalRegisterCommand(F("RPN.OPS"), [](Embedis* e) {
  224. unsigned char num = _rpn_ctxt.operators.size();
  225. DEBUG_MSG_P(PSTR("[RPN] Operators:\n"));
  226. for (unsigned char i=0; i<num; i++) {
  227. DEBUG_MSG_P(PSTR(" %s (%d)\n"), _rpn_ctxt.operators[i].name, _rpn_ctxt.operators[i].argc);
  228. }
  229. terminalOK();
  230. });
  231. terminalRegisterCommand(F("RPN.TEST"), [](Embedis* e) {
  232. if (e->argc == 2) {
  233. DEBUG_MSG_P(PSTR("[RPN] Running \"%s\"\n"), e->argv[1]);
  234. rpn_process(_rpn_ctxt, e->argv[1], true);
  235. _rpnDump();
  236. rpn_stack_clear(_rpn_ctxt);
  237. terminalOK();
  238. } else {
  239. terminalError(F("Wrong arguments"));
  240. }
  241. });
  242. }
  243. #endif
  244. void _rpnDump() {
  245. float value;
  246. DEBUG_MSG_P(PSTR("[RPN] Stack:\n"));
  247. unsigned char num = rpn_stack_size(_rpn_ctxt);
  248. if (0 == num) {
  249. DEBUG_MSG_P(PSTR(" (empty)\n"));
  250. } else {
  251. unsigned char index = num - 1;
  252. while (rpn_stack_get(_rpn_ctxt, index, value)) {
  253. DEBUG_MSG_P(PSTR(" %02d: %s\n"), index--, String(value).c_str());
  254. }
  255. }
  256. }
  257. void _rpnRun() {
  258. unsigned char i = 0;
  259. String rule = getSetting({"rpnRule", i});
  260. while (rule.length()) {
  261. //DEBUG_MSG_P(PSTR("[RPN] Running \"%s\"\n"), rule.c_str());
  262. rpn_process(_rpn_ctxt, rule.c_str(), true);
  263. //_rpnDump();
  264. rule = getSetting({"rpnRule", ++i});
  265. rpn_stack_clear(_rpn_ctxt);
  266. }
  267. if (getSetting("rpnSticky", 1 == RPN_STICKY)) {
  268. rpn_variables_clear(_rpn_ctxt);
  269. }
  270. }
  271. void _rpnLoop() {
  272. if (_rpn_run && (millis() - _rpn_last > _rpn_delay)) {
  273. _rpnRun();
  274. _rpn_run = false;
  275. }
  276. }
  277. void rpnSetup() {
  278. // Init context
  279. _rpnInit();
  280. // Load & cache settings
  281. _rpnConfigure();
  282. // Terminal commands
  283. #if TERMINAL_SUPPORT
  284. _rpnInitCommands();
  285. #endif
  286. // Websockets
  287. #if WEB_SUPPORT
  288. wsRegister()
  289. .onVisible([](JsonObject& root) { root["rpnVisible"] = 1; })
  290. .onConnected(_rpnWebSocketOnConnected)
  291. .onKeyCheck(_rpnWebSocketOnKeyCheck);
  292. #endif
  293. // MQTT
  294. #if MQTT_SUPPORT
  295. mqttRegister(_rpnMQTTCallback);
  296. #endif
  297. #if NTP_SUPPORT
  298. NtpBroker::Register([](const NtpTick tick, time_t timestamp, const String& datetime) {
  299. static const String tick_every_hour(F("tick1h"));
  300. static const String tick_every_minute(F("tick1m"));
  301. const char* ptr =
  302. (tick == NtpTick::EveryMinute) ? tick_every_minute.c_str() :
  303. (tick == NtpTick::EveryHour) ? tick_every_hour.c_str() : nullptr;
  304. if (ptr != nullptr) {
  305. rpn_variable_set(_rpn_ctxt, ptr, timestamp);
  306. _rpn_last = millis();
  307. _rpn_run = true;
  308. }
  309. });
  310. #endif
  311. StatusBroker::Register(_rpnBrokerStatus);
  312. SensorReadBroker::Register(_rpnBrokerCallback);
  313. espurnaRegisterReload(_rpnConfigure);
  314. espurnaRegisterLoop(_rpnLoop);
  315. }
  316. #endif // RPN_RULES_SUPPORT