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.

296 lines
7.9 KiB

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