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.2 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 _domoticzMqtt(unsigned int type, const char * topic, const char * payload) {
  37. String dczTopicOut = getSetting("dczTopicOut", DOMOTICZ_OUT_TOPIC);
  38. if (type == MQTT_CONNECT_EVENT) {
  39. mqttSubscribeRaw(dczTopicOut.c_str());
  40. }
  41. if (type == MQTT_MESSAGE_EVENT) {
  42. // Check topic
  43. if (dczTopicOut.equals(topic)) {
  44. // Parse response
  45. DynamicJsonBuffer jsonBuffer;
  46. JsonObject& root = jsonBuffer.parseObject((char *) payload);
  47. if (!root.success()) {
  48. DEBUG_MSG_P(PSTR("[DOMOTICZ] Error parsing data\n"));
  49. return;
  50. }
  51. // IDX
  52. unsigned long idx = root["idx"];
  53. int relayID = relayFromIdx(idx);
  54. if (relayID >= 0) {
  55. unsigned long value = root["nvalue"];
  56. DEBUG_MSG_P(PSTR("[DOMOTICZ] Received value %d for IDX %d\n"), value, idx);
  57. relayStatus(relayID, value == 1);
  58. }
  59. }
  60. }
  61. };
  62. void domoticzSetup() {
  63. mqttRegister(_domoticzMqtt);
  64. }
  65. #endif