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.

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