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.

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