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.

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