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.

329 lines
9.6 KiB

providers: relays, lights and buttons refactoring (#2414) - gpio module now tracks the known providers (right now, hardware and mcp expander) - refactored relay struct to use 'Provider' implementing setup,notify,change,boot instead of just BasePin actions - refactored button module to use gpio provider instead of referencing types itself - removed dual & stm code from buttons, migrate both to relay module - added status notify and change callbacks for relayStatus (i.e. 'notify' when relay status was called, but not changed. and 'changed' when it did) - relays runtime configuration keys - relay command now shows configured relays and current & target statuses - refactor the code using relayStatus(0, blah) under LIGHT_PROVIDER check to use lightState instead - remove rfbridge code form relay module. implement through a basic state listener in the rfbridge module, depend on RELAY_SUPPORT - allow to bind rf codes to real relays - drop tuya-specific lights provider, remove tuya code from relays and lights modules - integrate tuya via relay listeners and providers, use lights custom provider - implement channel transitions for tuya. disabled by default, and transition time and step are overridden to 2000 + 100. needs to be set to some value below the total time (i.e. `total transition time / step time == number of steps`, we need to figure out a correct time that serial comms could handle) - lights custom provider (global, not per-pin) and state listeners - remove lights code from relay module. implement through providers & listeners in the lights module, depend on RELAY_SUPPORT - lights per-channel relay provider (unused atm), depend on RELAY_SUPPORT - refactored channel transition - calculate step only once, make sure time + step values are sane, generate quick transitions with very small delay (10ms hardcoded) for transitions during OFF state i.e. we no longer waste 500ms (or whatever transition time is set to) on boot doing nothing - transition time + step parameter for the lightUpdate - report mask parameter for the lightUpdate - minor fixes across the board resolve #2222
3 years ago
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 "light.h"
  8. #include "mqtt.h"
  9. #include "relay.h"
  10. #include "rpc.h"
  11. #include "sensor.h"
  12. #include "ws.h"
  13. bool _dcz_enabled = false;
  14. std::bitset<RelaysMax> _dcz_relay_state;
  15. //------------------------------------------------------------------------------
  16. // Private methods
  17. //------------------------------------------------------------------------------
  18. unsigned int _domoticzIdx(unsigned char relayID, unsigned int 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. JsonObject& color = root["Color"];
  48. if (color.success()) {
  49. // for ColorMode... see:
  50. // https://github.com/domoticz/domoticz/blob/development/hardware/ColorSwitch.h
  51. // https://www.domoticz.com/wiki/Domoticz_API/JSON_URL's#Set_a_light_to_a_certain_color_or_color_temperature
  52. DEBUG_MSG_P(PSTR("[DOMOTICZ] Received rgb:%u,%u,%u ww:%u,cw:%u t:%u brightness:%u for IDX %u\n"),
  53. color["r"].as<unsigned char>(),
  54. color["g"].as<unsigned char>(),
  55. color["b"].as<unsigned char>(),
  56. color["ww"].as<unsigned char>(),
  57. color["cw"].as<unsigned char>(),
  58. color["t"].as<unsigned char>(),
  59. color["Level"].as<unsigned char>(),
  60. idx
  61. );
  62. // m field contains information about color mode (enum ColorMode from domoticz ColorSwitch.h):
  63. unsigned int cmode = color["m"];
  64. if (cmode == 2) { // ColorModeWhite - WW,CW,temperature (t unused for now)
  65. if (lightChannels() < 2) return;
  66. lightChannel(0, color["ww"]);
  67. lightChannel(1, color["cw"]);
  68. } else if (cmode == 3 || cmode == 4) { // ColorModeRGB or ColorModeCustom
  69. if (lightChannels() < 3) return;
  70. lightChannel(0, color["r"]);
  71. lightChannel(1, color["g"]);
  72. lightChannel(2, color["b"]);
  73. // WARM WHITE (or MONOCHROME WHITE) and COLD WHITE are always sent.
  74. // Apply only when supported.
  75. if (lightChannels() > 3) {
  76. lightChannel(3, color["ww"]);
  77. }
  78. if (lightChannels() > 4) {
  79. lightChannel(4, color["cw"]);
  80. }
  81. }
  82. }
  83. // domoticz uses 100 as maximum value while we're using a custom scale
  84. lightBrightness((root["Level"].as<long>() / 100l) * Light::BrightnessMax);
  85. lightUpdate();
  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. #if LIGHT_PROVIDER != LIGHT_PROVIDER_NONE
  112. String stype = root["stype"];
  113. String switchType = root["switchType"];
  114. if ((_domoticzIdx(0) == idx) && (stype.startsWith("RGB") || (switchType.equals("Dimmer")))) {
  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 _domoticzConfigure() {
  128. const bool enabled = getSetting("dczEnabled", 1 == DOMOTICZ_ENABLED);
  129. if (enabled != _dcz_enabled) _domoticzMqttSubscribe(enabled);
  130. #if RELAY_SUPPORT
  131. for (size_t id = 0; id < relayCount(); ++id) {
  132. _dcz_relay_state[id] = relayStatus(id);
  133. }
  134. #endif
  135. _dcz_enabled = enabled;
  136. }
  137. void _domoticzRelayCallback(size_t id, bool status) {
  138. if (_domoticzStatus(id) != status) {
  139. _dcz_relay_state[id] = status;
  140. domoticzSendRelay(id, status);
  141. }
  142. }
  143. #if SENSOR_SUPPORT
  144. void domoticzSendMagnitude(unsigned char type, unsigned char index, double value, const char* buffer) {
  145. if (!_dcz_enabled) return;
  146. char key[15];
  147. snprintf_P(key, sizeof(key), PSTR("dczMagnitude%d"), index);
  148. // Domoticz expects some additional data, dashboard might break otherwise.
  149. // https://www.domoticz.com/wiki/Domoticz_API/JSON_URL's#Barometer
  150. // TODO: Must send 'forecast' data. Default is last 3 hours:
  151. // https://github.com/domoticz/domoticz/blob/6027b1d9e3b6588a901de42d82f3a6baf1374cd1/hardware/I2C.cpp#L1092-L1193
  152. // 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.)
  153. if (MAGNITUDE_PRESSURE == type) {
  154. String svalue = buffer;
  155. svalue += ";-1";
  156. domoticzSend(key, 0, svalue.c_str());
  157. // Special case to allow us to use it with switches directly
  158. } else if (MAGNITUDE_DIGITAL == type) {
  159. int nvalue = (buffer[0] >= 48) ? (buffer[0] - 48) : 0;
  160. domoticzSend(key, nvalue, buffer);
  161. // https://www.domoticz.com/wiki/Domoticz_API/JSON_URL's#Humidity
  162. // nvalue contains HUM (relative humidity)
  163. // svalue contains HUM_STAT, one of consts below
  164. } else if (MAGNITUDE_HUMIDITY == type) {
  165. const char status = 48 + (
  166. (value > 70) ? HUMIDITY_WET :
  167. (value > 45) ? HUMIDITY_COMFORTABLE :
  168. (value > 30) ? HUMIDITY_NORMAL :
  169. HUMIDITY_DRY
  170. );
  171. char svalue[2] = {status, '\0'};
  172. domoticzSend(key, static_cast<int>(value), svalue);
  173. // https://www.domoticz.com/wiki/Domoticz_API/JSON_URL's#Air_quality
  174. // nvalue contains the ppm
  175. // svalue is not used (?)
  176. } else if (MAGNITUDE_CO2 == type) {
  177. domoticzSend(key, static_cast<int>(value), "");
  178. // Otherwise, send char string (nvalue is only for integers)
  179. } else {
  180. domoticzSend(key, 0, buffer);
  181. }
  182. }
  183. #endif // SENSOR_SUPPORT
  184. #if WEB_SUPPORT
  185. bool _domoticzWebSocketOnKeyCheck(const char * key, JsonVariant& value) {
  186. return (strncmp(key, "dcz", 3) == 0);
  187. }
  188. void _domoticzWebSocketOnVisible(JsonObject& root) {
  189. root["dczVisible"] = static_cast<unsigned char>(haveRelaysOrSensors());
  190. }
  191. void _domoticzWebSocketOnConnected(JsonObject& root) {
  192. root["dczEnabled"] = getSetting("dczEnabled", 1 == DOMOTICZ_ENABLED);
  193. root["dczTopicIn"] = getSetting("dczTopicIn", DOMOTICZ_IN_TOPIC);
  194. root["dczTopicOut"] = getSetting("dczTopicOut", DOMOTICZ_OUT_TOPIC);
  195. JsonArray& relays = root.createNestedArray("dczRelays");
  196. for (unsigned char i=0; i<relayCount(); i++) {
  197. relays.add(_domoticzIdx(i));
  198. }
  199. #if SENSOR_SUPPORT
  200. sensorWebSocketMagnitudes(root, "dcz");
  201. #endif
  202. }
  203. #endif // WEB_SUPPORT
  204. //------------------------------------------------------------------------------
  205. // Public API
  206. //------------------------------------------------------------------------------
  207. template<typename T> void domoticzSend(const char * key, T nvalue, const char * svalue) {
  208. if (!_dcz_enabled) return;
  209. const auto idx = getSetting(key, 0);
  210. if (idx > 0) {
  211. char payload[128];
  212. snprintf(payload, sizeof(payload), "{\"idx\": %d, \"nvalue\": %s, \"svalue\": \"%s\"}", idx, String(nvalue).c_str(), svalue);
  213. mqttSendRaw(getSetting("dczTopicIn", DOMOTICZ_IN_TOPIC).c_str(), payload);
  214. }
  215. }
  216. template<typename T> void domoticzSend(const char * key, T nvalue) {
  217. domoticzSend(key, nvalue, "");
  218. }
  219. void domoticzSendRelay(unsigned char relayID, bool status) {
  220. if (!_dcz_enabled) return;
  221. char buffer[15];
  222. snprintf_P(buffer, sizeof(buffer), PSTR("dczRelayIdx%u"), relayID);
  223. domoticzSend(buffer, status ? "1" : "0");
  224. }
  225. void domoticzSendRelays() {
  226. for (uint8_t relayID=0; relayID < relayCount(); relayID++) {
  227. domoticzSendRelay(relayID, relayStatus(relayID));
  228. }
  229. }
  230. void domoticzSetup() {
  231. _domoticzConfigure();
  232. #if WEB_SUPPORT
  233. wsRegister()
  234. .onVisible(_domoticzWebSocketOnVisible)
  235. .onConnected(_domoticzWebSocketOnConnected)
  236. .onKeyCheck(_domoticzWebSocketOnKeyCheck);
  237. #endif
  238. #if RELAY_SUPPORT
  239. relaySetStatusChange(_domoticzRelayCallback);
  240. #endif
  241. // Callbacks
  242. mqttRegister(_domoticzMqtt);
  243. espurnaRegisterReload(_domoticzConfigure);
  244. }
  245. bool domoticzEnabled() {
  246. return _dcz_enabled;
  247. }
  248. #endif