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.

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