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.

394 lines
10 KiB

6 years ago
6 years ago
5 years ago
  1. /*
  2. HOME ASSISTANT MODULE
  3. Copyright (C) 2017-2019 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(const JsonObject& deviceConfig) {
  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["uniq_id"] = getIdentifier() + "_" + magnitudeTopic(magnitudeType(i)) + "_" + String(i);
  42. config["device"] = deviceConfig;
  43. config.printTo(output);
  44. jsonBuffer.clear();
  45. }
  46. mqttSendRaw(topic.c_str(), output.c_str());
  47. mqttSend(MQTT_TOPIC_STATUS, MQTT_STATUS_ONLINE, true);
  48. }
  49. }
  50. #endif // SENSOR_SUPPORT
  51. // -----------------------------------------------------------------------------
  52. // SWITCHES & LIGHTS
  53. // -----------------------------------------------------------------------------
  54. void _haSendSwitch(unsigned char i, JsonObject& config) {
  55. String name = getSetting("hostname");
  56. if (relayCount() > 1) {
  57. name += String("_") + String(i);
  58. }
  59. config.set("name", _haFixName(name));
  60. config.set("platform", "mqtt");
  61. if (relayCount()) {
  62. config["state_topic"] = mqttTopic(MQTT_TOPIC_RELAY, i, false);
  63. config["command_topic"] = mqttTopic(MQTT_TOPIC_RELAY, i, true);
  64. config["payload_on"] = String(HOMEASSISTANT_PAYLOAD_ON);
  65. config["payload_off"] = String(HOMEASSISTANT_PAYLOAD_OFF);
  66. config["availability_topic"] = mqttTopic(MQTT_TOPIC_STATUS, false);
  67. config["payload_available"] = String(HOMEASSISTANT_PAYLOAD_AVAILABLE);
  68. config["payload_not_available"] = String(HOMEASSISTANT_PAYLOAD_NOT_AVAILABLE);
  69. }
  70. #if LIGHT_PROVIDER != LIGHT_PROVIDER_NONE
  71. if (i == 0) {
  72. if (lightHasColor()) {
  73. config["brightness_state_topic"] = mqttTopic(MQTT_TOPIC_BRIGHTNESS, false);
  74. config["brightness_command_topic"] = mqttTopic(MQTT_TOPIC_BRIGHTNESS, true);
  75. config["rgb_state_topic"] = mqttTopic(MQTT_TOPIC_COLOR_RGB, false);
  76. config["rgb_command_topic"] = mqttTopic(MQTT_TOPIC_COLOR_RGB, true);
  77. config["color_temp_command_topic"] = mqttTopic(MQTT_TOPIC_MIRED, true);
  78. }
  79. if (lightChannels() > 3) {
  80. config["white_value_state_topic"] = mqttTopic(MQTT_TOPIC_CHANNEL, 3, false);
  81. config["white_value_command_topic"] = mqttTopic(MQTT_TOPIC_CHANNEL, 3, true);
  82. }
  83. }
  84. #endif // LIGHT_PROVIDER != LIGHT_PROVIDER_NONE
  85. }
  86. void _haSendSwitches(const JsonObject& deviceConfig) {
  87. #if (LIGHT_PROVIDER != LIGHT_PROVIDER_NONE) || (defined(ITEAD_SLAMPHER))
  88. String type = String("light");
  89. #else
  90. String type = String("switch");
  91. #endif
  92. for (unsigned char i=0; i<relayCount(); i++) {
  93. String topic = getSetting("haPrefix", HOMEASSISTANT_PREFIX) +
  94. "/" + type +
  95. "/" + getSetting("hostname") + "_" + String(i) +
  96. "/config";
  97. String output;
  98. if (_haEnabled) {
  99. DynamicJsonBuffer jsonBuffer;
  100. JsonObject& config = jsonBuffer.createObject();
  101. _haSendSwitch(i, config);
  102. config["uniq_id"] = getIdentifier() + "_" + type + "_" + String(i);
  103. config["device"] = deviceConfig;
  104. config.printTo(output);
  105. jsonBuffer.clear();
  106. }
  107. mqttSendRaw(topic.c_str(), output.c_str());
  108. mqttSend(MQTT_TOPIC_STATUS, MQTT_STATUS_ONLINE, true);
  109. }
  110. }
  111. // -----------------------------------------------------------------------------
  112. void _haDumpConfig(std::function<void(String&)> printer, bool wrapJson = false) {
  113. #if (LIGHT_PROVIDER != LIGHT_PROVIDER_NONE) || (defined(ITEAD_SLAMPHER))
  114. String type = String("light");
  115. #else
  116. String type = String("switch");
  117. #endif
  118. for (unsigned char i=0; i<relayCount(); i++) {
  119. DynamicJsonBuffer jsonBuffer;
  120. JsonObject& config = jsonBuffer.createObject();
  121. _haSendSwitch(i, config);
  122. String output;
  123. output.reserve(config.measureLength() + 32);
  124. if (wrapJson) {
  125. output += "{\"haConfig\": \"";
  126. }
  127. output += "\n\n" + type + ":\n";
  128. bool first = true;
  129. for (auto kv : config) {
  130. if (first) {
  131. output += " - ";
  132. first = false;
  133. } else {
  134. output += " ";
  135. }
  136. output += kv.key;
  137. output += ": ";
  138. output += kv.value.as<String>();
  139. output += "\n";
  140. }
  141. output += " ";
  142. if (wrapJson) {
  143. output += "\"}";
  144. }
  145. jsonBuffer.clear();
  146. printer(output);
  147. }
  148. #if SENSOR_SUPPORT
  149. for (unsigned char i=0; i<magnitudeCount(); i++) {
  150. DynamicJsonBuffer jsonBuffer;
  151. JsonObject& config = jsonBuffer.createObject();
  152. _haSendMagnitude(i, config);
  153. String output;
  154. output.reserve(config.measureLength() + 32);
  155. if (wrapJson) {
  156. output += "{\"haConfig\": \"";
  157. }
  158. output += "\n\nsensor:\n";
  159. bool first = true;
  160. for (auto kv : config) {
  161. if (first) {
  162. output += " - ";
  163. first = false;
  164. } else {
  165. output += " ";
  166. }
  167. String value = kv.value.as<String>();
  168. value.replace("%", "'%'");
  169. output += kv.key;
  170. output += ": ";
  171. output += value;
  172. output += "\n";
  173. }
  174. output += " ";
  175. if (wrapJson) {
  176. output += "\"}";
  177. }
  178. jsonBuffer.clear();
  179. printer(output);
  180. }
  181. #endif
  182. }
  183. void _haGetDeviceConfig(JsonObject& config) {
  184. String identifier = getIdentifier();
  185. config.createNestedArray("identifiers").add(identifier);
  186. config["name"] = getSetting("desc", getSetting("hostname"));
  187. config["manufacturer"] = String(MANUFACTURER);
  188. config["model"] = String(DEVICE);
  189. config["sw_version"] = String(APP_NAME) + " " + String(APP_VERSION) + " (" + getCoreVersion() + ")";
  190. }
  191. void _haSend() {
  192. // Pending message to send?
  193. if (!_haSendFlag) return;
  194. // Are we connected?
  195. if (!mqttConnected()) return;
  196. DEBUG_MSG_P(PSTR("[HA] Sending autodiscovery MQTT message\n"));
  197. // Get common device config
  198. DynamicJsonBuffer jsonBuffer;
  199. JsonObject& deviceConfig = jsonBuffer.createObject();
  200. _haGetDeviceConfig(deviceConfig);
  201. // Send messages
  202. _haSendSwitches(deviceConfig);
  203. #if SENSOR_SUPPORT
  204. _haSendMagnitudes(deviceConfig);
  205. #endif
  206. jsonBuffer.clear();
  207. _haSendFlag = false;
  208. }
  209. void _haConfigure() {
  210. bool enabled = getSetting("haEnabled", HOMEASSISTANT_ENABLED).toInt() == 1;
  211. _haSendFlag = (enabled != _haEnabled);
  212. _haEnabled = enabled;
  213. _haSend();
  214. }
  215. #if WEB_SUPPORT
  216. std::queue<uint32_t> _ha_send_config;
  217. bool _haWebSocketOnReceive(const char * key, JsonVariant& value) {
  218. return (strncmp(key, "ha", 2) == 0);
  219. }
  220. void _haWebSocketOnSend(JsonObject& root) {
  221. root["haVisible"] = 1;
  222. root["haPrefix"] = getSetting("haPrefix", HOMEASSISTANT_PREFIX);
  223. root["haEnabled"] = getSetting("haEnabled", HOMEASSISTANT_ENABLED).toInt() == 1;
  224. }
  225. void _haWebSocketOnAction(uint32_t client_id, const char * action, JsonObject& data) {
  226. if (strcmp(action, "haconfig") == 0) {
  227. _ha_send_config.push(client_id);
  228. }
  229. }
  230. #endif
  231. #if TERMINAL_SUPPORT
  232. void _haInitCommands() {
  233. terminalRegisterCommand(F("HA.CONFIG"), [](Embedis* e) {
  234. _haDumpConfig([](String& data) {
  235. DEBUG_MSG(data.c_str());
  236. });
  237. DEBUG_MSG("\n");
  238. terminalOK();
  239. });
  240. terminalRegisterCommand(F("HA.SEND"), [](Embedis* e) {
  241. setSetting("haEnabled", "1");
  242. _haConfigure();
  243. #if WEB_SUPPORT
  244. wsSend(_haWebSocketOnSend);
  245. #endif
  246. terminalOK();
  247. });
  248. terminalRegisterCommand(F("HA.CLEAR"), [](Embedis* e) {
  249. setSetting("haEnabled", "0");
  250. _haConfigure();
  251. #if WEB_SUPPORT
  252. wsSend(_haWebSocketOnSend);
  253. #endif
  254. terminalOK();
  255. });
  256. }
  257. #endif
  258. // -----------------------------------------------------------------------------
  259. #if WEB_SUPPORT
  260. void _haLoop() {
  261. if (_ha_send_config.empty()) return;
  262. uint32_t client_id = _ha_send_config.front();
  263. _ha_send_config.pop();
  264. if (!wsConnected(client_id)) return;
  265. // TODO check wsConnected after each "printer" call?
  266. _haDumpConfig([client_id](String& output) {
  267. wsSend(client_id, output.c_str());
  268. yield();
  269. }, true);
  270. }
  271. #endif
  272. void haSetup() {
  273. _haConfigure();
  274. #if WEB_SUPPORT
  275. wsOnSendRegister(_haWebSocketOnSend);
  276. wsOnActionRegister(_haWebSocketOnAction);
  277. wsOnReceiveRegister(_haWebSocketOnReceive);
  278. espurnaRegisterLoop(_haLoop);
  279. #endif
  280. #if TERMINAL_SUPPORT
  281. _haInitCommands();
  282. #endif
  283. // On MQTT connect check if we have something to send
  284. mqttRegister([](unsigned int type, const char * topic, const char * payload) {
  285. if (type == MQTT_CONNECT_EVENT) _haSend();
  286. });
  287. // Main callbacks
  288. espurnaRegisterReload(_haConfigure);
  289. }
  290. #endif // HOMEASSISTANT_SUPPORT