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.

191 lines
5.0 KiB

api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
3 years ago
6 years ago
providers: relays, lights and buttons refactoring (#2414) - gpio module now tracks the known providers (right now, hardware and mcp expander) - refactored relay struct to use 'Provider' implementing setup,notify,change,boot instead of just BasePin actions - refactored button module to use gpio provider instead of referencing types itself - removed dual & stm code from buttons, migrate both to relay module - added status notify and change callbacks for relayStatus (i.e. 'notify' when relay status was called, but not changed. and 'changed' when it did) - relays runtime configuration keys - relay command now shows configured relays and current & target statuses - refactor the code using relayStatus(0, blah) under LIGHT_PROVIDER check to use lightState instead - remove rfbridge code form relay module. implement through a basic state listener in the rfbridge module, depend on RELAY_SUPPORT - allow to bind rf codes to real relays - drop tuya-specific lights provider, remove tuya code from relays and lights modules - integrate tuya via relay listeners and providers, use lights custom provider - implement channel transitions for tuya. disabled by default, and transition time and step are overridden to 2000 + 100. needs to be set to some value below the total time (i.e. `total transition time / step time == number of steps`, we need to figure out a correct time that serial comms could handle) - lights custom provider (global, not per-pin) and state listeners - remove lights code from relay module. implement through providers & listeners in the lights module, depend on RELAY_SUPPORT - lights per-channel relay provider (unused atm), depend on RELAY_SUPPORT - refactored channel transition - calculate step only once, make sure time + step values are sane, generate quick transitions with very small delay (10ms hardcoded) for transitions during OFF state i.e. we no longer waste 500ms (or whatever transition time is set to) on boot doing nothing - transition time + step parameter for the lightUpdate - report mask parameter for the lightUpdate - minor fixes across the board resolve #2222
3 years ago
providers: relays, lights and buttons refactoring (#2414) - gpio module now tracks the known providers (right now, hardware and mcp expander) - refactored relay struct to use 'Provider' implementing setup,notify,change,boot instead of just BasePin actions - refactored button module to use gpio provider instead of referencing types itself - removed dual & stm code from buttons, migrate both to relay module - added status notify and change callbacks for relayStatus (i.e. 'notify' when relay status was called, but not changed. and 'changed' when it did) - relays runtime configuration keys - relay command now shows configured relays and current & target statuses - refactor the code using relayStatus(0, blah) under LIGHT_PROVIDER check to use lightState instead - remove rfbridge code form relay module. implement through a basic state listener in the rfbridge module, depend on RELAY_SUPPORT - allow to bind rf codes to real relays - drop tuya-specific lights provider, remove tuya code from relays and lights modules - integrate tuya via relay listeners and providers, use lights custom provider - implement channel transitions for tuya. disabled by default, and transition time and step are overridden to 2000 + 100. needs to be set to some value below the total time (i.e. `total transition time / step time == number of steps`, we need to figure out a correct time that serial comms could handle) - lights custom provider (global, not per-pin) and state listeners - remove lights code from relay module. implement through providers & listeners in the lights module, depend on RELAY_SUPPORT - lights per-channel relay provider (unused atm), depend on RELAY_SUPPORT - refactored channel transition - calculate step only once, make sure time + step values are sane, generate quick transitions with very small delay (10ms hardcoded) for transitions during OFF state i.e. we no longer waste 500ms (or whatever transition time is set to) on boot doing nothing - transition time + step parameter for the lightUpdate - report mask parameter for the lightUpdate - minor fixes across the board resolve #2222
3 years ago
providers: relays, lights and buttons refactoring (#2414) - gpio module now tracks the known providers (right now, hardware and mcp expander) - refactored relay struct to use 'Provider' implementing setup,notify,change,boot instead of just BasePin actions - refactored button module to use gpio provider instead of referencing types itself - removed dual & stm code from buttons, migrate both to relay module - added status notify and change callbacks for relayStatus (i.e. 'notify' when relay status was called, but not changed. and 'changed' when it did) - relays runtime configuration keys - relay command now shows configured relays and current & target statuses - refactor the code using relayStatus(0, blah) under LIGHT_PROVIDER check to use lightState instead - remove rfbridge code form relay module. implement through a basic state listener in the rfbridge module, depend on RELAY_SUPPORT - allow to bind rf codes to real relays - drop tuya-specific lights provider, remove tuya code from relays and lights modules - integrate tuya via relay listeners and providers, use lights custom provider - implement channel transitions for tuya. disabled by default, and transition time and step are overridden to 2000 + 100. needs to be set to some value below the total time (i.e. `total transition time / step time == number of steps`, we need to figure out a correct time that serial comms could handle) - lights custom provider (global, not per-pin) and state listeners - remove lights code from relay module. implement through providers & listeners in the lights module, depend on RELAY_SUPPORT - lights per-channel relay provider (unused atm), depend on RELAY_SUPPORT - refactored channel transition - calculate step only once, make sure time + step values are sane, generate quick transitions with very small delay (10ms hardcoded) for transitions during OFF state i.e. we no longer waste 500ms (or whatever transition time is set to) on boot doing nothing - transition time + step parameter for the lightUpdate - report mask parameter for the lightUpdate - minor fixes across the board resolve #2222
3 years ago
providers: relays, lights and buttons refactoring (#2414) - gpio module now tracks the known providers (right now, hardware and mcp expander) - refactored relay struct to use 'Provider' implementing setup,notify,change,boot instead of just BasePin actions - refactored button module to use gpio provider instead of referencing types itself - removed dual & stm code from buttons, migrate both to relay module - added status notify and change callbacks for relayStatus (i.e. 'notify' when relay status was called, but not changed. and 'changed' when it did) - relays runtime configuration keys - relay command now shows configured relays and current & target statuses - refactor the code using relayStatus(0, blah) under LIGHT_PROVIDER check to use lightState instead - remove rfbridge code form relay module. implement through a basic state listener in the rfbridge module, depend on RELAY_SUPPORT - allow to bind rf codes to real relays - drop tuya-specific lights provider, remove tuya code from relays and lights modules - integrate tuya via relay listeners and providers, use lights custom provider - implement channel transitions for tuya. disabled by default, and transition time and step are overridden to 2000 + 100. needs to be set to some value below the total time (i.e. `total transition time / step time == number of steps`, we need to figure out a correct time that serial comms could handle) - lights custom provider (global, not per-pin) and state listeners - remove lights code from relay module. implement through providers & listeners in the lights module, depend on RELAY_SUPPORT - lights per-channel relay provider (unused atm), depend on RELAY_SUPPORT - refactored channel transition - calculate step only once, make sure time + step values are sane, generate quick transitions with very small delay (10ms hardcoded) for transitions during OFF state i.e. we no longer waste 500ms (or whatever transition time is set to) on boot doing nothing - transition time + step parameter for the lightUpdate - report mask parameter for the lightUpdate - minor fixes across the board resolve #2222
3 years ago
providers: relays, lights and buttons refactoring (#2414) - gpio module now tracks the known providers (right now, hardware and mcp expander) - refactored relay struct to use 'Provider' implementing setup,notify,change,boot instead of just BasePin actions - refactored button module to use gpio provider instead of referencing types itself - removed dual & stm code from buttons, migrate both to relay module - added status notify and change callbacks for relayStatus (i.e. 'notify' when relay status was called, but not changed. and 'changed' when it did) - relays runtime configuration keys - relay command now shows configured relays and current & target statuses - refactor the code using relayStatus(0, blah) under LIGHT_PROVIDER check to use lightState instead - remove rfbridge code form relay module. implement through a basic state listener in the rfbridge module, depend on RELAY_SUPPORT - allow to bind rf codes to real relays - drop tuya-specific lights provider, remove tuya code from relays and lights modules - integrate tuya via relay listeners and providers, use lights custom provider - implement channel transitions for tuya. disabled by default, and transition time and step are overridden to 2000 + 100. needs to be set to some value below the total time (i.e. `total transition time / step time == number of steps`, we need to figure out a correct time that serial comms could handle) - lights custom provider (global, not per-pin) and state listeners - remove lights code from relay module. implement through providers & listeners in the lights module, depend on RELAY_SUPPORT - lights per-channel relay provider (unused atm), depend on RELAY_SUPPORT - refactored channel transition - calculate step only once, make sure time + step values are sane, generate quick transitions with very small delay (10ms hardcoded) for transitions during OFF state i.e. we no longer waste 500ms (or whatever transition time is set to) on boot doing nothing - transition time + step parameter for the lightUpdate - report mask parameter for the lightUpdate - minor fixes across the board resolve #2222
3 years ago
6 years ago
  1. /*
  2. ALEXA MODULE
  3. Copyright (C) 2016-2019 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #include "alexa.h"
  6. #if ALEXA_SUPPORT
  7. #include <queue>
  8. #include "api.h"
  9. #include "broker.h"
  10. #include "light.h"
  11. #include "relay.h"
  12. #include "rpc.h"
  13. #include "web.h"
  14. #include "ws.h"
  15. #include <fauxmoESP.h>
  16. #include <ArduinoJson.h>
  17. struct alexa_queue_element_t {
  18. unsigned char device_id;
  19. bool state;
  20. unsigned char value;
  21. };
  22. static std::queue<alexa_queue_element_t> _alexa_queue;
  23. fauxmoESP _alexa;
  24. // -----------------------------------------------------------------------------
  25. // ALEXA
  26. // -----------------------------------------------------------------------------
  27. bool _alexaWebSocketOnKeyCheck(const char * key, JsonVariant& value) {
  28. return (strncmp(key, "alexa", 5) == 0);
  29. }
  30. void _alexaWebSocketOnConnected(JsonObject& root) {
  31. root["alexaEnabled"] = alexaEnabled();
  32. root["alexaName"] = getSetting("alexaName");
  33. }
  34. void _alexaConfigure() {
  35. _alexa.enable(wifiConnected() && alexaEnabled());
  36. }
  37. #if WEB_SUPPORT
  38. bool _alexaBodyCallback(AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total) {
  39. return _alexa.process(request->client(), request->method() == HTTP_GET, request->url(), String((char *)data));
  40. }
  41. bool _alexaRequestCallback(AsyncWebServerRequest *request) {
  42. String body = (request->hasParam("body", true)) ? request->getParam("body", true)->value() : String();
  43. return _alexa.process(request->client(), request->method() == HTTP_GET, request->url(), body);
  44. }
  45. #endif
  46. void _alexaBrokerCallback(const String& topic, unsigned char id, unsigned int value) {
  47. // Only process status messages for switches and channels
  48. if (!topic.equals(MQTT_TOPIC_CHANNEL)
  49. && !topic.equals(MQTT_TOPIC_RELAY)) {
  50. return;
  51. }
  52. if (topic.equals(MQTT_TOPIC_CHANNEL)) {
  53. _alexa.setState(id + 1, value > 0, value);
  54. }
  55. if (topic.equals(MQTT_TOPIC_RELAY)) {
  56. if (id > 0) return;
  57. _alexa.setState(id, value, value > 0 ? 255 : 0);
  58. }
  59. }
  60. // -----------------------------------------------------------------------------
  61. bool alexaEnabled() {
  62. return getSetting("alexaEnabled", 1 == ALEXA_ENABLED);
  63. }
  64. void alexaLoop() {
  65. _alexa.handle();
  66. while (!_alexa_queue.empty()) {
  67. alexa_queue_element_t element = _alexa_queue.front();
  68. DEBUG_MSG_P(PSTR("[ALEXA] Device #%u state: %s value: %d\n"), element.device_id, element.state ? "ON" : "OFF", element.value);
  69. #if LIGHT_PROVIDER != LIGHT_PROVIDER_NONE
  70. if (0 == element.device_id) {
  71. lightState(element.state);
  72. } else {
  73. lightState(element.device_id - 1, element.state);
  74. lightChannel(element.device_id - 1, element.value);
  75. lightUpdate();
  76. }
  77. #else
  78. relayStatus(element.device_id, element.state);
  79. #endif
  80. _alexa_queue.pop();
  81. }
  82. }
  83. void alexaSetup() {
  84. // Backwards compatibility
  85. moveSetting("fauxmoEnabled", "alexaEnabled");
  86. // Basic fauxmoESP configuration
  87. _alexa.createServer(!WEB_SUPPORT);
  88. _alexa.setPort(80);
  89. // Use custom alexa hostname if defined, device hostname otherwise
  90. String hostname = getSetting("alexaName", ALEXA_HOSTNAME);
  91. if (hostname.length() == 0) {
  92. hostname = getSetting("hostname");
  93. }
  94. // Lights
  95. #if LIGHT_PROVIDER != LIGHT_PROVIDER_NONE
  96. // Global switch
  97. _alexa.addDevice(hostname.c_str());
  98. // For each channel
  99. for (unsigned char i = 1; i <= lightChannels(); i++) {
  100. _alexa.addDevice((hostname + " " + i).c_str());
  101. }
  102. // Relays
  103. #else
  104. unsigned int relays = relayCount();
  105. if (relays == 1) {
  106. _alexa.addDevice(hostname.c_str());
  107. } else {
  108. for (unsigned int i=1; i<=relays; i++) {
  109. _alexa.addDevice((hostname + " " + i).c_str());
  110. }
  111. }
  112. #endif
  113. // Load & cache settings
  114. _alexaConfigure();
  115. // Websockets
  116. #if WEB_SUPPORT
  117. webBodyRegister(_alexaBodyCallback);
  118. webRequestRegister(_alexaRequestCallback);
  119. wsRegister()
  120. .onVisible([](JsonObject& root) { root["alexaVisible"] = 1; })
  121. .onConnected(_alexaWebSocketOnConnected)
  122. .onKeyCheck(_alexaWebSocketOnKeyCheck);
  123. #endif
  124. // Register wifi callback
  125. wifiRegister([](justwifi_messages_t code, char * parameter) {
  126. if ((MESSAGE_CONNECTED == code) || (MESSAGE_DISCONNECTED == code)) {
  127. _alexaConfigure();
  128. }
  129. });
  130. // Callback
  131. _alexa.onSetState([&](unsigned char device_id, const char * name, bool state, unsigned char value) {
  132. alexa_queue_element_t element;
  133. element.device_id = device_id;
  134. element.state = state;
  135. element.value = value;
  136. _alexa_queue.push(element);
  137. });
  138. // Register main callbacks
  139. StatusBroker::Register(_alexaBrokerCallback);
  140. espurnaRegisterReload(_alexaConfigure);
  141. espurnaRegisterLoop(alexaLoop);
  142. }
  143. #endif