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.

87 lines
2.3 KiB

  1. /*
  2. DOMOTICZ MODULE
  3. Copyright (C) 2016-2017 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #if ENABLE_DOMOTICZ
  6. #include <ArduinoJson.h>
  7. template<typename T> void domoticzSend(const char * key, T nvalue, const char * svalue) {
  8. unsigned int idx = getSetting(key).toInt();
  9. if (idx > 0) {
  10. char payload[128];
  11. snprintf(payload, 128, "{\"idx\": %d, \"nvalue\": %s, \"svalue\": \"%s\"}", idx, String(nvalue).c_str(), svalue);
  12. mqttSendRaw(getSetting("dczTopicIn", DOMOTICZ_IN_TOPIC).c_str(), payload);
  13. }
  14. }
  15. template<typename T> void domoticzSend(const char * key, T nvalue) {
  16. domoticzSend(key, nvalue, "");
  17. }
  18. void relayDomoticzSend(unsigned int relayID) {
  19. char buffer[15];
  20. sprintf(buffer, "dczRelayIdx%d", relayID);
  21. domoticzSend(buffer, relayStatus(relayID) ? "1" : "0");
  22. }
  23. int relayFromIdx(unsigned int idx) {
  24. for (int relayID=0; relayID<relayCount(); relayID++) {
  25. if (relayToIdx(relayID) == idx) {
  26. return relayID;
  27. }
  28. }
  29. return -1;
  30. }
  31. int relayToIdx(unsigned int relayID) {
  32. char buffer[15];
  33. sprintf(buffer, "dczRelayIdx%d", relayID);
  34. return getSetting(buffer).toInt();
  35. }
  36. void domoticzSetup() {
  37. mqttRegister([](unsigned int type, const char * topic, const char * payload) {
  38. String dczTopicOut = getSetting("dczTopicOut", DOMOTICZ_OUT_TOPIC);
  39. if (type == MQTT_CONNECT_EVENT) {
  40. mqttSubscribeRaw(dczTopicOut.c_str());
  41. }
  42. if (type == MQTT_MESSAGE_EVENT) {
  43. // Check topic
  44. if (dczTopicOut.equals(topic)) {
  45. // Parse response
  46. DynamicJsonBuffer jsonBuffer;
  47. JsonObject& root = jsonBuffer.parseObject((char *) payload);
  48. if (!root.success()) {
  49. DEBUG_MSG_P(PSTR("[DOMOTICZ] Error parsing data\n"));
  50. return;
  51. }
  52. // IDX
  53. unsigned long idx = root["idx"];
  54. int relayID = relayFromIdx(idx);
  55. if (relayID >= 0) {
  56. unsigned long value = root["nvalue"];
  57. DEBUG_MSG_P(PSTR("[DOMOTICZ] Received value %d for IDX %d\n"), value, idx);
  58. relayStatus(relayID, value == 1);
  59. }
  60. }
  61. }
  62. });
  63. }
  64. #endif