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.

117 lines
2.4 KiB

5 years ago
  1. /*
  2. NTP MODULE
  3. Copyright (C) 2016-2019 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #if RPN_RULES_SUPPORT
  6. #include "rpnlib.h"
  7. #include <Ticker.h>
  8. // -----------------------------------------------------------------------------
  9. // Custom commands
  10. // -----------------------------------------------------------------------------
  11. rpn_context _rpn_ctxt;
  12. bool _rpn_run = false;
  13. unsigned long _rpn_last = 0;
  14. // -----------------------------------------------------------------------------
  15. bool _rpnWebSocketOnReceive(const char * key, JsonVariant& value) {
  16. return (strncmp(key, "rpn", 3) == 0);
  17. }
  18. void _rpnWebSocketOnSend(JsonObject& root) {
  19. root["rpnVisible"] = 1;
  20. JsonArray& rules = root.createNestedArray("rpnRules");
  21. unsigned char i = 0;
  22. while (String rule = getSetting("rule", i, NULL)) {
  23. rules.add(rule);
  24. }
  25. }
  26. void _rpnConfigure() {
  27. }
  28. void _rpnBrokerCallback(const unsigned char type, const char * topic, unsigned char id, const char * payload) {
  29. char name[32] = {0};
  30. if (BROKER_MSG_TYPE_STATUS == type || BROKER_MSG_TYPE_SENSOR == type) {
  31. snprintf(name, sizeof(name), "%s%d", topic, id);
  32. } else if (BROKER_MSG_TYPE_DATETIME == type) {
  33. strncpy(name, topic, sizeof(name));
  34. } else {
  35. return;
  36. }
  37. rpn_variable_set(_rpn_ctxt, name, atof(payload));
  38. _rpn_last = millis();
  39. _rpn_run = true;
  40. }
  41. void _rpnInit() {
  42. // Init context
  43. rpn_init(_rpn_ctxt);
  44. // Add relay operator
  45. rpn_operator_set(_rpn_ctxt, "relay", 2, [](rpn_context & ctxt) {
  46. float a, b;
  47. rpn_stack_pop(ctxt, b); // new status
  48. rpn_stack_pop(ctxt, a); // relay number
  49. relayStatus(int(a), int(b));
  50. return true;
  51. });
  52. }
  53. void _rpnRun() {
  54. unsigned char i = 0;
  55. while (String rule = getSetting("rule", i, NULL)) {
  56. rpn_stack_clear(_rpn_ctxt);
  57. rpn_process(_rpn_ctxt, rule.c_str());
  58. }
  59. }
  60. void _rpnLoop() {
  61. if (_rpn_run && (millis() - _rpn_last > RPN_BUFFER_DELAY)) {
  62. _rpnRun();
  63. _rpn_run = false;
  64. }
  65. }
  66. void rpnSetup() {
  67. // Init context
  68. _rpnInit();
  69. // Load & cache settings
  70. _rpnConfigure();
  71. // Websockets
  72. #if WEB_SUPPORT
  73. wsOnSendRegister(_rpnWebSocketOnSend);
  74. wsOnReceiveRegister(_rpnWebSocketOnReceive);
  75. #endif
  76. brokerRegister(_rpnBrokerCallback);
  77. espurnaRegisterReload(_rpnConfigure);
  78. espurnaRegisterLoop(_rpnLoop);
  79. }
  80. #endif