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.

95 lines
2.4 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. /*
  2. ALEXA MODULE
  3. Copyright (C) 2016-2018 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #if ALEXA_SUPPORT
  6. #include <fauxmoESP.h>
  7. fauxmoESP alexa;
  8. struct AlexaDevChange {
  9. AlexaDevChange(unsigned char device_id, bool state) : device_id(device_id), state(state) {};
  10. unsigned char device_id = 0;
  11. bool state = false;
  12. };
  13. #include <queue>
  14. static std::queue<AlexaDevChange> _alexa_dev_changes;
  15. // -----------------------------------------------------------------------------
  16. // ALEXA
  17. // -----------------------------------------------------------------------------
  18. bool _alexaWebSocketOnReceive(const char * key, JsonVariant& value) {
  19. return (strncmp(key, "alexa", 5) == 0);
  20. }
  21. void _alexaWebSocketOnSend(JsonObject& root) {
  22. root["alexaVisible"] = 1;
  23. root["alexaEnabled"] = getSetting("alexaEnabled", ALEXA_ENABLED).toInt() == 1;
  24. }
  25. void _alexaConfigure() {
  26. alexa.enable(getSetting("alexaEnabled", ALEXA_ENABLED).toInt() == 1);
  27. }
  28. // -----------------------------------------------------------------------------
  29. void alexaSetup() {
  30. // Backwards compatibility
  31. moveSetting("fauxmoEnabled", "alexaEnabled");
  32. // Load & cache settings
  33. _alexaConfigure();
  34. #if WEB_SUPPORT
  35. // Websockets
  36. wsOnSendRegister(_alexaWebSocketOnSend);
  37. wsOnAfterParseRegister(_alexaConfigure);
  38. wsOnReceiveRegister(_alexaWebSocketOnReceive);
  39. #endif
  40. unsigned int relays = relayCount();
  41. String hostname = getSetting("hostname");
  42. if (relays == 1) {
  43. alexa.addDevice(hostname.c_str());
  44. } else {
  45. for (unsigned int i=0; i<relays; i++) {
  46. alexa.addDevice((hostname + "_" + i).c_str());
  47. }
  48. }
  49. alexa.onSetState([&](unsigned char device_id, const char * name, bool state) {
  50. AlexaDevChange change(device_id, state);
  51. _alexa_dev_changes.push(change);
  52. });
  53. alexa.onGetState([](unsigned char device_id, const char * name) {
  54. return relayStatus(device_id);
  55. });
  56. // Register loop
  57. espurnaRegisterLoop(alexaLoop);
  58. }
  59. void alexaLoop() {
  60. alexa.handle();
  61. while (!_alexa_dev_changes.empty()) {
  62. AlexaDevChange& change = _alexa_dev_changes.front();
  63. DEBUG_MSG_P(PSTR("[ALEXA] Device #%u state: %s\n"), change.device_id, change.state ? "ON" : "OFF");
  64. relayStatus(change.device_id, change.state);
  65. _alexa_dev_changes.pop();
  66. }
  67. }
  68. #endif