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.

321 lines
8.5 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 += 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. output += "\n";
  131. jsonBuffer.clear();
  132. }
  133. #if SENSOR_SUPPORT
  134. for (unsigned char i=0; i<magnitudeCount(); i++) {
  135. DynamicJsonBuffer jsonBuffer;
  136. JsonObject& config = jsonBuffer.createObject();
  137. _haSendMagnitude(i, config);
  138. output += "sensor:\n";
  139. bool first = true;
  140. for (auto kv : config) {
  141. if (first) {
  142. output += " - ";
  143. first = false;
  144. } else {
  145. output += " ";
  146. }
  147. output += kv.key + String(": ") + kv.value.as<String>() + 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. bool _haKeyCheck(const char * key) {
  175. return (strncmp(key, "ha", 2) == 0);
  176. }
  177. #if WEB_SUPPORT
  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. #endif
  224. // On MQTT connect check if we have something to send
  225. mqttRegister([](unsigned int type, const char * topic, const char * payload) {
  226. if (type == MQTT_CONNECT_EVENT) _haSend();
  227. });
  228. #if TERMINAL_SUPPORT
  229. _haInitCommands();
  230. #endif
  231. settingsRegisterKeyCheck(_haKeyCheck);
  232. // Main callbacks
  233. espurnaRegisterReload(_haConfigure);
  234. }
  235. #endif // HOMEASSISTANT_SUPPORT