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.

77 lines
1.9 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 <Hash.h>
  7. #include <ArduinoJson.h>
  8. void domoticzMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  9. String dczTopicOut = getSetting("dczTopicOut", DOMOTICZ_OUT_TOPIC);
  10. if (type == MQTT_CONNECT_EVENT) {
  11. mqttSubscribeRaw(dczTopicOut.c_str());
  12. }
  13. if (type == MQTT_MESSAGE_EVENT) {
  14. // Check topic
  15. if (dczTopicOut.equals(topic)) {
  16. // Parse response
  17. DynamicJsonBuffer jsonBuffer;
  18. JsonObject& root = jsonBuffer.parseObject((char *) payload);
  19. if (!root.success()) {
  20. DEBUG_MSG("[DOMOTICZ] Error parsing data\n");
  21. return;
  22. }
  23. // IDX
  24. unsigned long idx = root["idx"];
  25. int relayID = domoticzRelay(idx);
  26. if (relayID >= 0) {
  27. unsigned long value = root["nvalue"];
  28. DEBUG_MSG("[DOMOTICZ] Received value %d for IDX %d\n", value, idx);
  29. relayStatus(relayID, value == 1);
  30. }
  31. }
  32. }
  33. }
  34. int domoticzIdx(unsigned int relayID) {
  35. return getSetting("dczIdx" + String(relayID)).toInt();
  36. }
  37. int domoticzRelay(unsigned int idx) {
  38. for (int relayID=0; relayID<relayCount(); relayID++) {
  39. if (domoticzIdx(relayID) == idx) {
  40. return relayID;
  41. }
  42. }
  43. return -1;
  44. }
  45. void domoticzSend(unsigned int relayID) {
  46. unsigned int idx = domoticzIdx(relayID);
  47. if (idx > 0) {
  48. unsigned int value = relayStatus(relayID) ? 1 : 0;
  49. char payload[45];
  50. sprintf(payload, "{\"idx\": %d, \"nvalue\": %d, \"svalue\": \"\"}", idx, value);
  51. mqttSendRaw(getSetting("dczTopicIn", DOMOTICZ_IN_TOPIC).c_str(), payload);
  52. }
  53. }
  54. void domoticzSetup() {
  55. mqttRegister(domoticzMQTTCallback);
  56. }
  57. #endif