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.

78 lines
1.9 KiB

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