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.

298 lines
8.0 KiB

6 years ago
6 years ago
  1. /*
  2. DOMOTICZ MODULE
  3. Copyright (C) 2016-2019 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #if DOMOTICZ_SUPPORT
  6. #include "relay.h"
  7. #include "broker.h"
  8. #include <bitset>
  9. #include <ArduinoJson.h>
  10. bool _dcz_enabled = false;
  11. std::bitset<RELAYS_MAX> _dcz_relay_state;
  12. //------------------------------------------------------------------------------
  13. // Private methods
  14. //------------------------------------------------------------------------------
  15. int _domoticzRelay(unsigned int idx) {
  16. for (unsigned char relayID=0; relayID<relayCount(); relayID++) {
  17. if (domoticzIdx(relayID) == idx) {
  18. return relayID;
  19. }
  20. }
  21. return -1;
  22. }
  23. void _domoticzMqttSubscribe(bool value) {
  24. String dczTopicOut = getSetting("dczTopicOut", DOMOTICZ_OUT_TOPIC);
  25. if (value) {
  26. mqttSubscribeRaw(dczTopicOut.c_str());
  27. } else {
  28. mqttUnsubscribeRaw(dczTopicOut.c_str());
  29. }
  30. }
  31. bool _domoticzStatus(unsigned char id) {
  32. return _dcz_relay_state[id];
  33. }
  34. void _domoticzStatus(unsigned char id, bool status) {
  35. _dcz_relay_state[id] = status;
  36. relayStatus(id, status);
  37. }
  38. #if LIGHT_PROVIDER != LIGHT_PROVIDER_NONE
  39. #include "light.h"
  40. void _domoticzLight(unsigned int idx, const JsonObject& root) {
  41. if (!lightHasColor()) return;
  42. JsonObject& color = root["Color"];
  43. if (!color.success()) return;
  44. // for ColorMode... see:
  45. // https://github.com/domoticz/domoticz/blob/development/hardware/ColorSwitch.h
  46. // https://www.domoticz.com/wiki/Domoticz_API/JSON_URL's#Set_a_light_to_a_certain_color_or_color_temperature
  47. DEBUG_MSG_P(PSTR("[DOMOTICZ] Received rgb:%u,%u,%u ww:%u,cw:%u t:%u brightness:%u for IDX %u\n"),
  48. color["r"].as<unsigned char>(),
  49. color["g"].as<unsigned char>(),
  50. color["b"].as<unsigned char>(),
  51. color["ww"].as<unsigned char>(),
  52. color["cw"].as<unsigned char>(),
  53. color["t"].as<unsigned char>(),
  54. color["Level"].as<unsigned char>(),
  55. idx
  56. );
  57. // m field contains information about color mode (enum ColorMode from domoticz ColorSwitch.h):
  58. unsigned int cmode = color["m"];
  59. if (cmode == 2) { // ColorModeWhite - WW,CW,temperature (t unused for now)
  60. if (lightChannels() < 2) return;
  61. lightChannel(0, color["ww"]);
  62. lightChannel(1, color["cw"]);
  63. } else if (cmode == 3 || cmode == 4) { // ColorModeRGB or ColorModeCustom
  64. if (lightChannels() < 3) return;
  65. lightChannel(0, color["r"]);
  66. lightChannel(1, color["g"]);
  67. lightChannel(2, color["b"]);
  68. // WARM WHITE (or MONOCHROME WHITE) and COLD WHITE are always sent.
  69. // Apply only when supported.
  70. if (lightChannels() > 3) {
  71. lightChannel(3, color["ww"]);
  72. }
  73. if (lightChannels() > 4) {
  74. lightChannel(4, color["cw"]);
  75. }
  76. }
  77. // domoticz uses 100 as maximum value while we're using Light::BRIGHTNESS_MAX (unsigned char)
  78. lightBrightness((root["Level"].as<unsigned char>() / 100.0) * Light::BRIGHTNESS_MAX);
  79. lightUpdate(true, mqttForward());
  80. }
  81. #endif
  82. void _domoticzMqtt(unsigned int type, const char * topic, char * payload) {
  83. if (!_dcz_enabled) return;
  84. String dczTopicOut = getSetting("dczTopicOut", DOMOTICZ_OUT_TOPIC);
  85. if (type == MQTT_CONNECT_EVENT) {
  86. // Subscribe to domoticz action topics
  87. mqttSubscribeRaw(dczTopicOut.c_str());
  88. // Send relays state on connection
  89. domoticzSendRelays();
  90. }
  91. if (type == MQTT_MESSAGE_EVENT) {
  92. // Check topic
  93. if (dczTopicOut.equals(topic)) {
  94. // Parse response
  95. DynamicJsonBuffer jsonBuffer(1024);
  96. JsonObject& root = jsonBuffer.parseObject(payload);
  97. if (!root.success()) {
  98. DEBUG_MSG_P(PSTR("[DOMOTICZ] Error parsing data\n"));
  99. return;
  100. }
  101. // IDX
  102. unsigned int idx = root["idx"];
  103. String stype = root["stype"];
  104. #if LIGHT_PROVIDER != LIGHT_PROVIDER_NONE
  105. if (stype.startsWith("RGB") && (domoticzIdx(0) == idx)) {
  106. _domoticzLight(idx, root);
  107. }
  108. #endif
  109. int relayID = _domoticzRelay(idx);
  110. if (relayID >= 0) {
  111. unsigned char value = root["nvalue"];
  112. DEBUG_MSG_P(PSTR("[DOMOTICZ] Received value %u for IDX %u\n"), value, idx);
  113. _domoticzStatus(relayID, value >= 1);
  114. }
  115. }
  116. }
  117. };
  118. #if BROKER_SUPPORT
  119. void _domoticzConfigCallback(const String& key, const String& value) {
  120. if (key.equals("relayDummy")) {
  121. _domoticzRelayConfigure(value.toInt());
  122. return;
  123. }
  124. }
  125. void _domoticzBrokerCallback(const String& topic, unsigned char id, unsigned int value) {
  126. // Only process status messages for switches
  127. if (!topic.equals(MQTT_TOPIC_RELAY)) {
  128. return;
  129. }
  130. if (_domoticzStatus(id) == value) return;
  131. _dcz_relay_state[id] = value;
  132. domoticzSendRelay(id, value);
  133. }
  134. #endif // BROKER_SUPPORT
  135. #if WEB_SUPPORT
  136. bool _domoticzWebSocketOnKeyCheck(const char * key, JsonVariant& value) {
  137. return (strncmp(key, "dcz", 3) == 0);
  138. }
  139. void _domoticzWebSocketOnVisible(JsonObject& root) {
  140. root["dczVisible"] = static_cast<unsigned char>(haveRelaysOrSensors());
  141. }
  142. void _domoticzWebSocketOnConnected(JsonObject& root) {
  143. root["dczEnabled"] = getSetting("dczEnabled", DOMOTICZ_ENABLED).toInt() == 1;
  144. root["dczTopicIn"] = getSetting("dczTopicIn", DOMOTICZ_IN_TOPIC);
  145. root["dczTopicOut"] = getSetting("dczTopicOut", DOMOTICZ_OUT_TOPIC);
  146. JsonArray& relays = root.createNestedArray("dczRelays");
  147. for (unsigned char i=0; i<relayCount(); i++) {
  148. relays.add(domoticzIdx(i));
  149. }
  150. #if SENSOR_SUPPORT
  151. _sensorWebSocketMagnitudes(root, "dcz");
  152. #endif
  153. }
  154. #endif // WEB_SUPPORT
  155. void _domoticzRelayConfigure(size_t size) {
  156. for (size_t n = 0; n < size; ++n) {
  157. _dcz_relay_state[n] = relayStatus(n);
  158. }
  159. }
  160. void _domoticzConfigure() {
  161. bool enabled = getSetting("dczEnabled", DOMOTICZ_ENABLED).toInt() == 1;
  162. if (enabled != _dcz_enabled) _domoticzMqttSubscribe(enabled);
  163. _domoticzRelayConfigure(relayCount());
  164. _dcz_enabled = enabled;
  165. }
  166. //------------------------------------------------------------------------------
  167. // Public API
  168. //------------------------------------------------------------------------------
  169. template<typename T> void domoticzSend(const char * key, T nvalue, const char * svalue) {
  170. if (!_dcz_enabled) return;
  171. unsigned int idx = getSetting(key).toInt();
  172. if (idx > 0) {
  173. char payload[128];
  174. snprintf(payload, sizeof(payload), "{\"idx\": %u, \"nvalue\": %s, \"svalue\": \"%s\"}", idx, String(nvalue).c_str(), svalue);
  175. mqttSendRaw(getSetting("dczTopicIn", DOMOTICZ_IN_TOPIC).c_str(), payload);
  176. }
  177. }
  178. template<typename T> void domoticzSend(const char * key, T nvalue) {
  179. domoticzSend(key, nvalue, "");
  180. }
  181. void domoticzSendRelay(unsigned char relayID, bool status) {
  182. if (!_dcz_enabled) return;
  183. char buffer[15];
  184. snprintf_P(buffer, sizeof(buffer), PSTR("dczRelayIdx%u"), relayID);
  185. domoticzSend(buffer, status ? "1" : "0");
  186. }
  187. void domoticzSendRelays() {
  188. for (uint8_t relayID=0; relayID < relayCount(); relayID++) {
  189. domoticzSendRelay(relayID, relayStatus(relayID));
  190. }
  191. }
  192. unsigned int domoticzIdx(unsigned char relayID) {
  193. char buffer[15];
  194. snprintf_P(buffer, sizeof(buffer), PSTR("dczRelayIdx%u"), relayID);
  195. return getSetting(buffer).toInt();
  196. }
  197. void domoticzSetup() {
  198. _domoticzConfigure();
  199. #if WEB_SUPPORT
  200. wsRegister()
  201. .onVisible(_domoticzWebSocketOnVisible)
  202. .onConnected(_domoticzWebSocketOnConnected)
  203. .onKeyCheck(_domoticzWebSocketOnKeyCheck);
  204. #endif
  205. #if BROKER_SUPPORT
  206. StatusBroker::Register(_domoticzBrokerCallback);
  207. ConfigBroker::Register(_domoticzConfigCallback);
  208. #endif
  209. // Callbacks
  210. mqttRegister(_domoticzMqtt);
  211. espurnaRegisterReload(_domoticzConfigure);
  212. }
  213. bool domoticzEnabled() {
  214. return _dcz_enabled;
  215. }
  216. #endif