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.

192 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...)
4 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 "mqtt.h"
  12. #include "relay.h"
  13. #include "rpc.h"
  14. #include "web.h"
  15. #include "ws.h"
  16. #include <fauxmoESP.h>
  17. #include <ArduinoJson.h>
  18. struct alexa_queue_element_t {
  19. unsigned char device_id;
  20. bool state;
  21. unsigned char value;
  22. };
  23. static std::queue<alexa_queue_element_t> _alexa_queue;
  24. fauxmoESP _alexa;
  25. // -----------------------------------------------------------------------------
  26. // ALEXA
  27. // -----------------------------------------------------------------------------
  28. bool _alexaWebSocketOnKeyCheck(const char * key, JsonVariant& value) {
  29. return (strncmp(key, "alexa", 5) == 0);
  30. }
  31. void _alexaWebSocketOnConnected(JsonObject& root) {
  32. root["alexaEnabled"] = alexaEnabled();
  33. root["alexaName"] = getSetting("alexaName");
  34. }
  35. void _alexaConfigure() {
  36. _alexa.enable(wifiConnected() && alexaEnabled());
  37. }
  38. #if WEB_SUPPORT
  39. bool _alexaBodyCallback(AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total) {
  40. return _alexa.process(request->client(), request->method() == HTTP_GET, request->url(), String((char *)data));
  41. }
  42. bool _alexaRequestCallback(AsyncWebServerRequest *request) {
  43. String body = (request->hasParam("body", true)) ? request->getParam("body", true)->value() : String();
  44. return _alexa.process(request->client(), request->method() == HTTP_GET, request->url(), body);
  45. }
  46. #endif
  47. void _alexaBrokerCallback(const String& topic, unsigned char id, unsigned int value) {
  48. // Only process status messages for switches and channels
  49. if (!topic.equals(MQTT_TOPIC_CHANNEL)
  50. && !topic.equals(MQTT_TOPIC_RELAY)) {
  51. return;
  52. }
  53. if (topic.equals(MQTT_TOPIC_CHANNEL)) {
  54. _alexa.setState(id + 1, value > 0, value);
  55. }
  56. if (topic.equals(MQTT_TOPIC_RELAY)) {
  57. if (id > 0) return;
  58. _alexa.setState(id, value, value > 0 ? 255 : 0);
  59. }
  60. }
  61. // -----------------------------------------------------------------------------
  62. bool alexaEnabled() {
  63. return getSetting("alexaEnabled", 1 == ALEXA_ENABLED);
  64. }
  65. void alexaLoop() {
  66. _alexa.handle();
  67. while (!_alexa_queue.empty()) {
  68. alexa_queue_element_t element = _alexa_queue.front();
  69. DEBUG_MSG_P(PSTR("[ALEXA] Device #%u state: %s value: %d\n"), element.device_id, element.state ? "ON" : "OFF", element.value);
  70. #if LIGHT_PROVIDER != LIGHT_PROVIDER_NONE
  71. if (0 == element.device_id) {
  72. lightState(element.state);
  73. } else {
  74. lightState(element.device_id - 1, element.state);
  75. lightChannel(element.device_id - 1, element.value);
  76. lightUpdate();
  77. }
  78. #else
  79. relayStatus(element.device_id, element.state);
  80. #endif
  81. _alexa_queue.pop();
  82. }
  83. }
  84. void alexaSetup() {
  85. // Backwards compatibility
  86. moveSetting("fauxmoEnabled", "alexaEnabled");
  87. // Basic fauxmoESP configuration
  88. _alexa.createServer(!WEB_SUPPORT);
  89. _alexa.setPort(80);
  90. // Use custom alexa hostname if defined, device hostname otherwise
  91. String hostname = getSetting("alexaName", ALEXA_HOSTNAME);
  92. if (hostname.length() == 0) {
  93. hostname = getSetting("hostname");
  94. }
  95. // Lights
  96. #if LIGHT_PROVIDER != LIGHT_PROVIDER_NONE
  97. // Global switch
  98. _alexa.addDevice(hostname.c_str());
  99. // For each channel
  100. for (unsigned char i = 1; i <= lightChannels(); i++) {
  101. _alexa.addDevice((hostname + " " + i).c_str());
  102. }
  103. // Relays
  104. #else
  105. unsigned int relays = relayCount();
  106. if (relays == 1) {
  107. _alexa.addDevice(hostname.c_str());
  108. } else {
  109. for (unsigned int i=1; i<=relays; i++) {
  110. _alexa.addDevice((hostname + " " + i).c_str());
  111. }
  112. }
  113. #endif
  114. // Load & cache settings
  115. _alexaConfigure();
  116. // Websockets
  117. #if WEB_SUPPORT
  118. webBodyRegister(_alexaBodyCallback);
  119. webRequestRegister(_alexaRequestCallback);
  120. wsRegister()
  121. .onVisible([](JsonObject& root) { root["alexaVisible"] = 1; })
  122. .onConnected(_alexaWebSocketOnConnected)
  123. .onKeyCheck(_alexaWebSocketOnKeyCheck);
  124. #endif
  125. // Register wifi callback
  126. wifiRegister([](justwifi_messages_t code, char * parameter) {
  127. if ((MESSAGE_CONNECTED == code) || (MESSAGE_DISCONNECTED == code)) {
  128. _alexaConfigure();
  129. }
  130. });
  131. // Callback
  132. _alexa.onSetState([&](unsigned char device_id, const char * name, bool state, unsigned char value) {
  133. alexa_queue_element_t element;
  134. element.device_id = device_id;
  135. element.state = state;
  136. element.value = value;
  137. _alexa_queue.push(element);
  138. });
  139. // Register main callbacks
  140. StatusBroker::Register(_alexaBrokerCallback);
  141. espurnaRegisterReload(_alexaConfigure);
  142. espurnaRegisterLoop(alexaLoop);
  143. }
  144. #endif