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.

323 lines
8.6 KiB

6 years ago
6 years ago
  1. /*
  2. HOME ASSISTANT MODULE
  3. Copyright (C) 2017-2018 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #if HOMEASSISTANT_SUPPORT
  6. #include <ArduinoJson.h>
  7. bool _haEnabled = false;
  8. bool _haSendFlag = false;
  9. // -----------------------------------------------------------------------------
  10. // UTILS
  11. // -----------------------------------------------------------------------------
  12. String _haFixName(String name) {
  13. for (unsigned char i=0; i<name.length(); i++) {
  14. if (!isalnum(name.charAt(i))) name.setCharAt(i, '_');
  15. }
  16. return name;
  17. }
  18. // -----------------------------------------------------------------------------
  19. // SENSORS
  20. // -----------------------------------------------------------------------------
  21. #if SENSOR_SUPPORT
  22. void _haSendMagnitude(unsigned char i, JsonObject& config) {
  23. unsigned char type = magnitudeType(i);
  24. config["name"] = _haFixName(getSetting("hostname") + String(" ") + magnitudeTopic(type));
  25. config.set("platform", "mqtt");
  26. config["state_topic"] = mqttTopic(magnitudeTopicIndex(i).c_str(), false);
  27. config["unit_of_measurement"] = magnitudeUnits(type);
  28. }
  29. void _haSendMagnitudes() {
  30. for (unsigned char i=0; i<magnitudeCount(); i++) {
  31. String topic = getSetting("haPrefix", HOMEASSISTANT_PREFIX) +
  32. "/sensor/" +
  33. getSetting("hostname") + "_" + String(i) +
  34. "/config";
  35. String output;
  36. if (_haEnabled) {
  37. DynamicJsonBuffer jsonBuffer;
  38. JsonObject& config = jsonBuffer.createObject();
  39. _haSendMagnitude(i, config);
  40. config.printTo(output);
  41. jsonBuffer.clear();
  42. }
  43. mqttSendRaw(topic.c_str(), output.c_str());
  44. mqttSend(MQTT_TOPIC_STATUS, MQTT_STATUS_ONLINE, true);
  45. }
  46. }
  47. #endif // SENSOR_SUPPORT
  48. // -----------------------------------------------------------------------------
  49. // SWITCHES & LIGHTS
  50. // -----------------------------------------------------------------------------
  51. void _haSendSwitch(unsigned char i, JsonObject& config) {
  52. String name = getSetting("hostname");
  53. if (relayCount() > 1) {
  54. name += String("_") + String(i);
  55. }
  56. config.set("name", _haFixName(name));
  57. config.set("platform", "mqtt");
  58. if (relayCount()) {
  59. config["state_topic"] = mqttTopic(MQTT_TOPIC_RELAY, i, false);
  60. config["command_topic"] = mqttTopic(MQTT_TOPIC_RELAY, i, true);
  61. config["payload_on"] = String(HOMEASSISTANT_PAYLOAD_ON);
  62. config["payload_off"] = String(HOMEASSISTANT_PAYLOAD_OFF);
  63. config["availability_topic"] = mqttTopic(MQTT_TOPIC_STATUS, false);
  64. config["payload_available"] = String(HOMEASSISTANT_PAYLOAD_AVAILABLE);
  65. config["payload_not_available"] = String(HOMEASSISTANT_PAYLOAD_NOT_AVAILABLE);
  66. }
  67. #if LIGHT_PROVIDER != LIGHT_PROVIDER_NONE
  68. if (i == 0) {
  69. if (lightHasColor()) {
  70. config["brightness_state_topic"] = mqttTopic(MQTT_TOPIC_BRIGHTNESS, false);
  71. config["brightness_command_topic"] = mqttTopic(MQTT_TOPIC_BRIGHTNESS, true);
  72. config["rgb_state_topic"] = mqttTopic(MQTT_TOPIC_COLOR_RGB, false);
  73. config["rgb_command_topic"] = mqttTopic(MQTT_TOPIC_COLOR_RGB, true);
  74. config["color_temp_command_topic"] = mqttTopic(MQTT_TOPIC_MIRED, true);
  75. }
  76. if (lightChannels() > 3) {
  77. config["white_value_state_topic"] = mqttTopic(MQTT_TOPIC_CHANNEL, 3, false);
  78. config["white_value_command_topic"] = mqttTopic(MQTT_TOPIC_CHANNEL, 3, true);
  79. }
  80. }
  81. #endif // LIGHT_PROVIDER != LIGHT_PROVIDER_NONE
  82. }
  83. void _haSendSwitches() {
  84. #if (LIGHT_PROVIDER != LIGHT_PROVIDER_NONE) || (defined(ITEAD_SLAMPHER))
  85. String type = String("light");
  86. #else
  87. String type = String("switch");
  88. #endif
  89. for (unsigned char i=0; i<relayCount(); i++) {
  90. String topic = getSetting("haPrefix", HOMEASSISTANT_PREFIX) +
  91. "/" + type +
  92. "/" + getSetting("hostname") + "_" + String(i) +
  93. "/config";
  94. String output;
  95. if (_haEnabled) {
  96. DynamicJsonBuffer jsonBuffer;
  97. JsonObject& config = jsonBuffer.createObject();
  98. _haSendSwitch(i, config);
  99. config.printTo(output);
  100. jsonBuffer.clear();
  101. }
  102. mqttSendRaw(topic.c_str(), output.c_str());
  103. mqttSend(MQTT_TOPIC_STATUS, MQTT_STATUS_ONLINE, true);
  104. }
  105. }
  106. // -----------------------------------------------------------------------------
  107. String _haGetConfig() {
  108. String output;
  109. #if (LIGHT_PROVIDER != LIGHT_PROVIDER_NONE) || (defined(ITEAD_SLAMPHER))
  110. String type = String("light");
  111. #else
  112. String type = String("switch");
  113. #endif
  114. for (unsigned char i=0; i<relayCount(); i++) {
  115. DynamicJsonBuffer jsonBuffer;
  116. JsonObject& config = jsonBuffer.createObject();
  117. _haSendSwitch(i, config);
  118. output += "\n" + type + ":\n";
  119. bool first = true;
  120. for (auto kv : config) {
  121. if (first) {
  122. output += " - ";
  123. first = false;
  124. } else {
  125. output += " ";
  126. }
  127. output += kv.key + String(": ") + kv.value.as<String>() + String("\n");
  128. }
  129. jsonBuffer.clear();
  130. }
  131. #if SENSOR_SUPPORT
  132. for (unsigned char i=0; i<magnitudeCount(); i++) {
  133. DynamicJsonBuffer jsonBuffer;
  134. JsonObject& config = jsonBuffer.createObject();
  135. _haSendMagnitude(i, config);
  136. output += "\nsensor:\n";
  137. bool first = true;
  138. for (auto kv : config) {
  139. if (first) {
  140. output += " - ";
  141. first = false;
  142. } else {
  143. output += " ";
  144. }
  145. String value = kv.value.as<String>();
  146. value.replace("%", "'%'");
  147. output += kv.key + String(": ") + value + String("\n");
  148. }
  149. output += "\n";
  150. jsonBuffer.clear();
  151. }
  152. #endif
  153. return output;
  154. }
  155. void _haSend() {
  156. // Pending message to send?
  157. if (!_haSendFlag) return;
  158. // Are we connected?
  159. if (!mqttConnected()) return;
  160. DEBUG_MSG_P(PSTR("[HA] Sending autodiscovery MQTT message\n"));
  161. // Send messages
  162. _haSendSwitches();
  163. #if SENSOR_SUPPORT
  164. _haSendMagnitudes();
  165. #endif
  166. _haSendFlag = false;
  167. }
  168. void _haConfigure() {
  169. bool enabled = getSetting("haEnabled", HOMEASSISTANT_ENABLED).toInt() == 1;
  170. _haSendFlag = (enabled != _haEnabled);
  171. _haEnabled = enabled;
  172. _haSend();
  173. }
  174. #if WEB_SUPPORT
  175. bool _haWebSocketOnReceive(const char * key, JsonVariant& value) {
  176. return (strncmp(key, "ha", 2) == 0);
  177. }
  178. void _haWebSocketOnSend(JsonObject& root) {
  179. root["haVisible"] = 1;
  180. root["haPrefix"] = getSetting("haPrefix", HOMEASSISTANT_PREFIX);
  181. root["haEnabled"] = getSetting("haEnabled", HOMEASSISTANT_ENABLED).toInt() == 1;
  182. }
  183. void _haWebSocketOnAction(uint32_t client_id, const char * action, JsonObject& data) {
  184. if (strcmp(action, "haconfig") == 0) {
  185. String output = _haGetConfig();
  186. output.replace(" ", "&nbsp;");
  187. output.replace("\n", "<br />");
  188. output = String("{\"haConfig\": \"") + output + String("\"}");
  189. wsSend(client_id, output.c_str());
  190. }
  191. }
  192. #endif
  193. #if TERMINAL_SUPPORT
  194. void _haInitCommands() {
  195. settingsRegisterCommand(F("HA.CONFIG"), [](Embedis* e) {
  196. DEBUG_MSG(_haGetConfig().c_str());
  197. DEBUG_MSG_P(PSTR("+OK\n"));
  198. });
  199. settingsRegisterCommand(F("HA.SEND"), [](Embedis* e) {
  200. setSetting("haEnabled", "1");
  201. _haConfigure();
  202. #if WEB_SUPPORT
  203. wsSend(_haWebSocketOnSend);
  204. #endif
  205. DEBUG_MSG_P(PSTR("+OK\n"));
  206. });
  207. settingsRegisterCommand(F("HA.CLEAR"), [](Embedis* e) {
  208. setSetting("haEnabled", "0");
  209. _haConfigure();
  210. #if WEB_SUPPORT
  211. wsSend(_haWebSocketOnSend);
  212. #endif
  213. DEBUG_MSG_P(PSTR("+OK\n"));
  214. });
  215. }
  216. #endif
  217. // -----------------------------------------------------------------------------
  218. void haSetup() {
  219. _haConfigure();
  220. #if WEB_SUPPORT
  221. wsOnSendRegister(_haWebSocketOnSend);
  222. wsOnActionRegister(_haWebSocketOnAction);
  223. wsOnReceiveRegister(_haWebSocketOnReceive);
  224. #endif
  225. #if TERMINAL_SUPPORT
  226. _haInitCommands();
  227. #endif
  228. // On MQTT connect check if we have something to send
  229. mqttRegister([](unsigned int type, const char * topic, const char * payload) {
  230. if (type == MQTT_CONNECT_EVENT) _haSend();
  231. });
  232. // Main callbacks
  233. espurnaRegisterReload(_haConfigure);
  234. }
  235. #endif // HOMEASSISTANT_SUPPORT