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.

341 lines
9.7 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. #include "domoticz.h"
  6. #if DOMOTICZ_SUPPORT
  7. #include "broker.h"
  8. #include "light.h"
  9. #include "mqtt.h"
  10. #include "relay.h"
  11. #include "rpc.h"
  12. #include "sensor.h"
  13. #include "ws.h"
  14. bool _dcz_enabled = false;
  15. std::bitset<RELAYS_MAX> _dcz_relay_state;
  16. //------------------------------------------------------------------------------
  17. // Private methods
  18. //------------------------------------------------------------------------------
  19. unsigned char _domoticzIdx(unsigned char relayID, unsigned char defaultValue = 0) {
  20. return getSetting({"dczRelayIdx", relayID}, defaultValue);
  21. }
  22. int _domoticzRelay(unsigned int idx) {
  23. for (unsigned char relayID=0; relayID<relayCount(); relayID++) {
  24. if (_domoticzIdx(relayID) == idx) {
  25. return relayID;
  26. }
  27. }
  28. return -1;
  29. }
  30. void _domoticzMqttSubscribe(bool value) {
  31. const String dczTopicOut = getSetting("dczTopicOut", DOMOTICZ_OUT_TOPIC);
  32. if (value) {
  33. mqttSubscribeRaw(dczTopicOut.c_str());
  34. } else {
  35. mqttUnsubscribeRaw(dczTopicOut.c_str());
  36. }
  37. }
  38. bool _domoticzStatus(unsigned char id) {
  39. return _dcz_relay_state[id];
  40. }
  41. void _domoticzStatus(unsigned char id, bool status) {
  42. _dcz_relay_state[id] = status;
  43. relayStatus(id, status);
  44. }
  45. #if LIGHT_PROVIDER != LIGHT_PROVIDER_NONE
  46. #include "light.h"
  47. void _domoticzLight(unsigned int idx, const JsonObject& root) {
  48. if (!lightHasColor()) return;
  49. JsonObject& color = root["Color"];
  50. if (!color.success()) return;
  51. // for ColorMode... see:
  52. // https://github.com/domoticz/domoticz/blob/development/hardware/ColorSwitch.h
  53. // https://www.domoticz.com/wiki/Domoticz_API/JSON_URL's#Set_a_light_to_a_certain_color_or_color_temperature
  54. DEBUG_MSG_P(PSTR("[DOMOTICZ] Received rgb:%u,%u,%u ww:%u,cw:%u t:%u brightness:%u for IDX %u\n"),
  55. color["r"].as<unsigned char>(),
  56. color["g"].as<unsigned char>(),
  57. color["b"].as<unsigned char>(),
  58. color["ww"].as<unsigned char>(),
  59. color["cw"].as<unsigned char>(),
  60. color["t"].as<unsigned char>(),
  61. color["Level"].as<unsigned char>(),
  62. idx
  63. );
  64. // m field contains information about color mode (enum ColorMode from domoticz ColorSwitch.h):
  65. unsigned int cmode = color["m"];
  66. if (cmode == 2) { // ColorModeWhite - WW,CW,temperature (t unused for now)
  67. if (lightChannels() < 2) return;
  68. lightChannel(0, color["ww"]);
  69. lightChannel(1, color["cw"]);
  70. } else if (cmode == 3 || cmode == 4) { // ColorModeRGB or ColorModeCustom
  71. if (lightChannels() < 3) return;
  72. lightChannel(0, color["r"]);
  73. lightChannel(1, color["g"]);
  74. lightChannel(2, color["b"]);
  75. // WARM WHITE (or MONOCHROME WHITE) and COLD WHITE are always sent.
  76. // Apply only when supported.
  77. if (lightChannels() > 3) {
  78. lightChannel(3, color["ww"]);
  79. }
  80. if (lightChannels() > 4) {
  81. lightChannel(4, color["cw"]);
  82. }
  83. }
  84. // domoticz uses 100 as maximum value while we're using Light::BRIGHTNESS_MAX (unsigned char)
  85. lightBrightness((root["Level"].as<unsigned char>() / 100.0) * Light::BRIGHTNESS_MAX);
  86. lightUpdate(true, mqttForward());
  87. }
  88. #endif
  89. void _domoticzMqtt(unsigned int type, const char * topic, char * payload) {
  90. if (!_dcz_enabled) return;
  91. const String dczTopicOut = getSetting("dczTopicOut", DOMOTICZ_OUT_TOPIC);
  92. if (type == MQTT_CONNECT_EVENT) {
  93. // Subscribe to domoticz action topics
  94. mqttSubscribeRaw(dczTopicOut.c_str());
  95. // Send relays state on connection
  96. #if RELAY_SUPPORT
  97. domoticzSendRelays();
  98. #endif
  99. }
  100. if (type == MQTT_MESSAGE_EVENT) {
  101. // Check topic
  102. if (dczTopicOut.equals(topic)) {
  103. // Parse response
  104. DynamicJsonBuffer jsonBuffer(1024);
  105. JsonObject& root = jsonBuffer.parseObject(payload);
  106. if (!root.success()) {
  107. DEBUG_MSG_P(PSTR("[DOMOTICZ] Error parsing data\n"));
  108. return;
  109. }
  110. // IDX
  111. unsigned int idx = root["idx"];
  112. String stype = root["stype"];
  113. #if LIGHT_PROVIDER != LIGHT_PROVIDER_NONE
  114. if (stype.startsWith("RGB") && (_domoticzIdx(0) == idx)) {
  115. _domoticzLight(idx, root);
  116. }
  117. #endif
  118. int relayID = _domoticzRelay(idx);
  119. if (relayID >= 0) {
  120. unsigned char value = root["nvalue"];
  121. DEBUG_MSG_P(PSTR("[DOMOTICZ] Received value %u for IDX %u\n"), value, idx);
  122. _domoticzStatus(relayID, value >= 1);
  123. }
  124. }
  125. }
  126. };
  127. void _domoticzRelayConfigure(size_t size) {
  128. for (size_t n = 0; n < size; ++n) {
  129. _dcz_relay_state[n] = relayStatus(n);
  130. }
  131. }
  132. void _domoticzConfigure() {
  133. const bool enabled = getSetting("dczEnabled", 1 == DOMOTICZ_ENABLED);
  134. if (enabled != _dcz_enabled) _domoticzMqttSubscribe(enabled);
  135. #if RELAY_SUPPORT
  136. _domoticzRelayConfigure(relayCount());
  137. #endif
  138. _dcz_enabled = enabled;
  139. }
  140. void _domoticzConfigCallback(const String& key, const String& value) {
  141. if (key.equals("relayDummy")) {
  142. _domoticzRelayConfigure(value.toInt());
  143. return;
  144. }
  145. }
  146. void _domoticzBrokerCallback(const String& topic, unsigned char id, unsigned int value) {
  147. // Only process status messages for switches
  148. if (!topic.equals(MQTT_TOPIC_RELAY)) {
  149. return;
  150. }
  151. if (_domoticzStatus(id) == value) return;
  152. _dcz_relay_state[id] = value;
  153. domoticzSendRelay(id, value);
  154. }
  155. #if SENSOR_SUPPORT
  156. void domoticzSendMagnitude(unsigned char type, unsigned char index, double value, const char* buffer) {
  157. if (!_dcz_enabled) return;
  158. char key[15];
  159. snprintf_P(key, sizeof(key), PSTR("dczMagnitude%d"), index);
  160. // Domoticz expects some additional data, dashboard might break otherwise.
  161. // https://www.domoticz.com/wiki/Domoticz_API/JSON_URL's#Barometer
  162. // TODO: Must send 'forecast' data. Default is last 3 hours:
  163. // https://github.com/domoticz/domoticz/blob/6027b1d9e3b6588a901de42d82f3a6baf1374cd1/hardware/I2C.cpp#L1092-L1193
  164. // For now, just send invalid value. Consider simplifying sampling function and adding it here, with custom sampling time (3 hours, 6 hours, 12 hours etc.)
  165. if (MAGNITUDE_PRESSURE == type) {
  166. String svalue = buffer;
  167. svalue += ";-1";
  168. domoticzSend(key, 0, svalue.c_str());
  169. // Special case to allow us to use it with switches directly
  170. } else if (MAGNITUDE_DIGITAL == type) {
  171. int nvalue = (buffer[0] >= 48) ? (buffer[0] - 48) : 0;
  172. domoticzSend(key, nvalue, buffer);
  173. // https://www.domoticz.com/wiki/Domoticz_API/JSON_URL's#Humidity
  174. // nvalue contains HUM (relative humidity)
  175. // svalue contains HUM_STAT, one of consts below
  176. } else if (MAGNITUDE_HUMIDITY == type) {
  177. const char status = 48 + (
  178. (value > 70) ? HUMIDITY_WET :
  179. (value > 45) ? HUMIDITY_COMFORTABLE :
  180. (value > 30) ? HUMIDITY_NORMAL :
  181. HUMIDITY_DRY
  182. );
  183. char svalue[2] = {status, '\0'};
  184. domoticzSend(key, static_cast<int>(value), svalue);
  185. // Otherwise, send char string (nvalue is only for integers)
  186. } else {
  187. domoticzSend(key, 0, buffer);
  188. }
  189. }
  190. #endif // SENSOR_SUPPORT
  191. #if WEB_SUPPORT
  192. bool _domoticzWebSocketOnKeyCheck(const char * key, JsonVariant& value) {
  193. return (strncmp(key, "dcz", 3) == 0);
  194. }
  195. void _domoticzWebSocketOnVisible(JsonObject& root) {
  196. root["dczVisible"] = static_cast<unsigned char>(haveRelaysOrSensors());
  197. }
  198. void _domoticzWebSocketOnConnected(JsonObject& root) {
  199. root["dczEnabled"] = getSetting("dczEnabled", 1 == DOMOTICZ_ENABLED);
  200. root["dczTopicIn"] = getSetting("dczTopicIn", DOMOTICZ_IN_TOPIC);
  201. root["dczTopicOut"] = getSetting("dczTopicOut", DOMOTICZ_OUT_TOPIC);
  202. JsonArray& relays = root.createNestedArray("dczRelays");
  203. for (unsigned char i=0; i<relayCount(); i++) {
  204. relays.add(_domoticzIdx(i));
  205. }
  206. #if SENSOR_SUPPORT
  207. sensorWebSocketMagnitudes(root, "dcz");
  208. #endif
  209. }
  210. #endif // WEB_SUPPORT
  211. //------------------------------------------------------------------------------
  212. // Public API
  213. //------------------------------------------------------------------------------
  214. template<typename T> void domoticzSend(const char * key, T nvalue, const char * svalue) {
  215. if (!_dcz_enabled) return;
  216. const auto idx = getSetting(key, 0);
  217. if (idx > 0) {
  218. char payload[128];
  219. snprintf(payload, sizeof(payload), "{\"idx\": %d, \"nvalue\": %s, \"svalue\": \"%s\"}", idx, String(nvalue).c_str(), svalue);
  220. mqttSendRaw(getSetting("dczTopicIn", DOMOTICZ_IN_TOPIC).c_str(), payload);
  221. }
  222. }
  223. template<typename T> void domoticzSend(const char * key, T nvalue) {
  224. domoticzSend(key, nvalue, "");
  225. }
  226. void domoticzSendRelay(unsigned char relayID, bool status) {
  227. if (!_dcz_enabled) return;
  228. char buffer[15];
  229. snprintf_P(buffer, sizeof(buffer), PSTR("dczRelayIdx%u"), relayID);
  230. domoticzSend(buffer, status ? "1" : "0");
  231. }
  232. void domoticzSendRelays() {
  233. for (uint8_t relayID=0; relayID < relayCount(); relayID++) {
  234. domoticzSendRelay(relayID, relayStatus(relayID));
  235. }
  236. }
  237. void domoticzSetup() {
  238. _domoticzConfigure();
  239. #if WEB_SUPPORT
  240. wsRegister()
  241. .onVisible(_domoticzWebSocketOnVisible)
  242. .onConnected(_domoticzWebSocketOnConnected)
  243. .onKeyCheck(_domoticzWebSocketOnKeyCheck);
  244. #endif
  245. StatusBroker::Register(_domoticzBrokerCallback);
  246. ConfigBroker::Register(_domoticzConfigCallback);
  247. // Callbacks
  248. mqttRegister(_domoticzMqtt);
  249. espurnaRegisterReload(_domoticzConfigure);
  250. }
  251. bool domoticzEnabled() {
  252. return _dcz_enabled;
  253. }
  254. #endif