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.

361 lines
9.4 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. #include <queue>
  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(getSetting("hostname") + 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. getSetting("hostname") + "_" + 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 = getSetting("hostname");
  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. "/" + getSetting("hostname") + "_" + 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. void _haDumpConfig(std::function<void(String&)> printer) {
  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. String output;
  119. output.reserve(config.measureLength() + 32);
  120. output += "\n\n" + type + ":\n";
  121. bool first = true;
  122. for (auto kv : config) {
  123. if (first) {
  124. output += " - ";
  125. first = false;
  126. } else {
  127. output += " ";
  128. }
  129. output += kv.key;
  130. output += ": ";
  131. output += kv.value.as<String>();
  132. output += "\n";
  133. }
  134. output += " ";
  135. jsonBuffer.clear();
  136. printer(output);
  137. }
  138. #if SENSOR_SUPPORT
  139. for (unsigned char i=0; i<magnitudeCount(); i++) {
  140. DynamicJsonBuffer jsonBuffer;
  141. JsonObject& config = jsonBuffer.createObject();
  142. _haSendMagnitude(i, config);
  143. String output;
  144. output.reserve(config.measureLength() + 32);
  145. output += "\n\nsensor:\n";
  146. bool first = true;
  147. for (auto kv : config) {
  148. if (first) {
  149. output += " - ";
  150. first = false;
  151. } else {
  152. output += " ";
  153. }
  154. String value = kv.value.as<String>();
  155. value.replace("%", "'%'");
  156. output += kv.key;
  157. output += ": ";
  158. output += value;
  159. output += "\n";
  160. }
  161. output += " ";
  162. jsonBuffer.clear();
  163. printer(output);
  164. }
  165. #endif
  166. }
  167. void _haSend() {
  168. // Pending message to send?
  169. if (!_haSendFlag) return;
  170. // Are we connected?
  171. if (!mqttConnected()) return;
  172. DEBUG_MSG_P(PSTR("[HA] Sending autodiscovery MQTT message\n"));
  173. // Send messages
  174. _haSendSwitches();
  175. #if SENSOR_SUPPORT
  176. _haSendMagnitudes();
  177. #endif
  178. _haSendFlag = false;
  179. }
  180. void _haConfigure() {
  181. bool enabled = getSetting("haEnabled", HOMEASSISTANT_ENABLED).toInt() == 1;
  182. _haSendFlag = (enabled != _haEnabled);
  183. _haEnabled = enabled;
  184. _haSend();
  185. }
  186. #if WEB_SUPPORT
  187. std::queue<uint32_t> _ha_send_config;
  188. bool _haWebSocketOnReceive(const char * key, JsonVariant& value) {
  189. return (strncmp(key, "ha", 2) == 0);
  190. }
  191. void _haWebSocketOnSend(JsonObject& root) {
  192. root["haVisible"] = 1;
  193. root["haPrefix"] = getSetting("haPrefix", HOMEASSISTANT_PREFIX);
  194. root["haEnabled"] = getSetting("haEnabled", HOMEASSISTANT_ENABLED).toInt() == 1;
  195. }
  196. void _haWebSocketOnAction(uint32_t client_id, const char * action, JsonObject& data) {
  197. if (strcmp(action, "haconfig") == 0) {
  198. _ha_send_config.push(client_id);
  199. }
  200. }
  201. #endif
  202. #if TERMINAL_SUPPORT
  203. void _haInitCommands() {
  204. terminalRegisterCommand(F("HA.CONFIG"), [](Embedis* e) {
  205. _haDumpConfig([](String& data) {
  206. DEBUG_MSG(data.c_str());
  207. });
  208. DEBUG_MSG("\n");
  209. terminalOK();
  210. });
  211. terminalRegisterCommand(F("HA.SEND"), [](Embedis* e) {
  212. setSetting("haEnabled", "1");
  213. _haConfigure();
  214. #if WEB_SUPPORT
  215. wsSend(_haWebSocketOnSend);
  216. #endif
  217. terminalOK();
  218. });
  219. terminalRegisterCommand(F("HA.CLEAR"), [](Embedis* e) {
  220. setSetting("haEnabled", "0");
  221. _haConfigure();
  222. #if WEB_SUPPORT
  223. wsSend(_haWebSocketOnSend);
  224. #endif
  225. terminalOK();
  226. });
  227. }
  228. #endif
  229. // -----------------------------------------------------------------------------
  230. #if WEB_SUPPORT
  231. void _haLoop() {
  232. if (_ha_send_config.empty()) return;
  233. uint32_t client_id = _ha_send_config.front();
  234. _ha_send_config.pop();
  235. if (!wsConnected(client_id)) return;
  236. // TODO check wsConnected after each "printer" call?
  237. _haDumpConfig([client_id](String& output) {
  238. output.replace(" ", "&nbsp;");
  239. output.replace("\n", "<br />");
  240. output = String("{\"haConfig\": \"") + output + String("\"}");
  241. wsSend(client_id, output.c_str());
  242. yield();
  243. });
  244. }
  245. #endif
  246. void haSetup() {
  247. _haConfigure();
  248. #if WEB_SUPPORT
  249. wsOnSendRegister(_haWebSocketOnSend);
  250. wsOnActionRegister(_haWebSocketOnAction);
  251. wsOnReceiveRegister(_haWebSocketOnReceive);
  252. espurnaRegisterLoop(_haLoop);
  253. #endif
  254. #if TERMINAL_SUPPORT
  255. _haInitCommands();
  256. #endif
  257. // On MQTT connect check if we have something to send
  258. mqttRegister([](unsigned int type, const char * topic, const char * payload) {
  259. if (type == MQTT_CONNECT_EVENT) _haSend();
  260. });
  261. // Main callbacks
  262. espurnaRegisterReload(_haConfigure);
  263. }
  264. #endif // HOMEASSISTANT_SUPPORT