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.

537 lines
15 KiB

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 <Ticker.h>
  7. #include <Schedule.h>
  8. #include <ArduinoJson.h>
  9. bool _ha_enabled = false;
  10. bool _ha_send_flag = false;
  11. // -----------------------------------------------------------------------------
  12. // UTILS
  13. // -----------------------------------------------------------------------------
  14. // per yaml 1.1 spec, following scalars are converted to bool. we want the string, so quoting the output
  15. // y|Y|yes|Yes|YES|n|N|no|No|NO |true|True|TRUE|false|False|FALSE |on|On|ON|off|Off|OFF
  16. String _haFixPayload(const String& value) {
  17. if (value.equalsIgnoreCase("y")
  18. || value.equalsIgnoreCase("n")
  19. || value.equalsIgnoreCase("yes")
  20. || value.equalsIgnoreCase("no")
  21. || value.equalsIgnoreCase("true")
  22. || value.equalsIgnoreCase("false")
  23. || value.equalsIgnoreCase("on")
  24. || value.equalsIgnoreCase("off")
  25. ) {
  26. String temp;
  27. temp.reserve(value.length() + 2);
  28. temp = "\"";
  29. temp += value;
  30. temp += "\"";
  31. return temp;
  32. }
  33. return value;
  34. }
  35. String& _haFixName(String& name) {
  36. for (unsigned char i=0; i<name.length(); i++) {
  37. if (!isalnum(name.charAt(i))) name.setCharAt(i, '_');
  38. }
  39. return name;
  40. }
  41. #if (LIGHT_PROVIDER != LIGHT_PROVIDER_NONE) || (defined(ITEAD_SLAMPHER))
  42. const String switchType("light");
  43. #else
  44. const String switchType("switch");
  45. #endif
  46. // -----------------------------------------------------------------------------
  47. // Shared context object to store entity and entity registry data
  48. // -----------------------------------------------------------------------------
  49. struct ha_config_t {
  50. static const size_t DEFAULT_BUFFER_SIZE = 2048;
  51. ha_config_t(size_t size) :
  52. jsonBuffer(size),
  53. deviceConfig(jsonBuffer.createObject()),
  54. root(jsonBuffer.createObject()),
  55. identifier(getIdentifier()),
  56. name(getSetting("desc", getSetting("hostname"))),
  57. version(String(APP_NAME " " APP_VERSION " (") + getCoreVersion() + ")")
  58. {
  59. deviceConfig.createNestedArray("identifiers").add(identifier.c_str());
  60. deviceConfig["name"] = name.c_str();
  61. deviceConfig["sw_version"] = version.c_str();
  62. deviceConfig["manufacturer"] = MANUFACTURER;
  63. deviceConfig["model"] = DEVICE;
  64. }
  65. ha_config_t() : ha_config_t(DEFAULT_BUFFER_SIZE) {}
  66. size_t size() { return jsonBuffer.size(); }
  67. DynamicJsonBuffer jsonBuffer;
  68. JsonObject& deviceConfig;
  69. JsonObject& root;
  70. const String identifier;
  71. const String name;
  72. const String version;
  73. };
  74. // -----------------------------------------------------------------------------
  75. // MQTT discovery
  76. // -----------------------------------------------------------------------------
  77. struct ha_discovery_t {
  78. constexpr static const unsigned long SEND_TIMEOUT = 1000;
  79. ha_discovery_t() {
  80. #if SENSOR_SUPPORT
  81. _messages.reserve(magnitudeCount() + relayCount());
  82. #else
  83. _messages.reserve(relayCount());
  84. #endif
  85. }
  86. // TODO: is this expected behaviour?
  87. void add(String& topic, String& message) {
  88. _messages.emplace_back(std::move(topic), std::move(message));
  89. }
  90. // We don't particulary care about the order since names have indexes?
  91. // If we ever do, use iterators to reference elems and pop the String contents instead
  92. mqtt_msg_t& next() {
  93. return _messages.back();
  94. }
  95. void pop() {
  96. _messages.pop_back();
  97. }
  98. const bool empty() const {
  99. return !_messages.size();
  100. }
  101. void prepareSwitches(ha_config_t& config);
  102. #if SENSOR_SUPPORT
  103. void prepareMagnitudes(ha_config_t& config);
  104. #endif
  105. Ticker timer;
  106. std::vector<mqtt_msg_t> _messages;
  107. };
  108. std::unique_ptr<ha_discovery_t> _ha_discovery = nullptr;
  109. void _haSendDiscovery() {
  110. if (!_ha_discovery) return;
  111. if (_ha_discovery->empty()) {
  112. return;
  113. }
  114. const unsigned long ts = millis();
  115. do {
  116. if (_ha_discovery->empty()) break;
  117. auto& message = _ha_discovery->next();
  118. if (!mqttSendRaw(message.first.c_str(), message.second.c_str())) {
  119. break;
  120. }
  121. _ha_discovery->pop();
  122. // XXX: should not reach this timeout, most common case is the break above
  123. } while (millis() - ts < ha_discovery_t::SEND_TIMEOUT);
  124. mqttSendStatus();
  125. if (_ha_discovery->empty()) {
  126. _ha_discovery = nullptr;
  127. } else {
  128. // 2.3.0: Ticker callback arguments are not preserved and once_ms_scheduled is missing
  129. // We need to use global discovery object to reschedule it
  130. // Otherwise, this would've been shared_ptr from _haSend
  131. _ha_discovery->timer.once_ms(ha_discovery_t::SEND_TIMEOUT, []() {
  132. schedule_function(_haSendDiscovery);
  133. });
  134. }
  135. }
  136. // -----------------------------------------------------------------------------
  137. // SENSORS
  138. // -----------------------------------------------------------------------------
  139. #if SENSOR_SUPPORT
  140. void _haSendMagnitude(unsigned char i, JsonObject& config) {
  141. unsigned char type = magnitudeType(i);
  142. config["name"] = _haFixName(getSetting("hostname") + String(" ") + magnitudeTopic(type));
  143. config["state_topic"] = mqttTopic(magnitudeTopicIndex(i).c_str(), false);
  144. config["unit_of_measurement"] = magnitudeUnits(type);
  145. }
  146. void ha_discovery_t::prepareMagnitudes(ha_config_t& config) {
  147. // Note: because none of the keys are erased, use a separate object to avoid accidentally sending switch data
  148. JsonObject& root = config.jsonBuffer.createObject();
  149. for (unsigned char i=0; i<magnitudeCount(); i++) {
  150. String topic = getSetting("haPrefix", HOMEASSISTANT_PREFIX) +
  151. "/sensor/" +
  152. getSetting("hostname") + "_" + String(i) +
  153. "/config";
  154. String message;
  155. if (_ha_enabled) {
  156. _haSendMagnitude(i, root);
  157. root["uniq_id"] = getIdentifier() + "_" + magnitudeTopic(magnitudeType(i)) + "_" + String(i);
  158. root["device"] = config.deviceConfig;
  159. message.reserve(root.measureLength());
  160. root.printTo(message);
  161. }
  162. add(topic, message);
  163. }
  164. }
  165. #endif // SENSOR_SUPPORT
  166. // -----------------------------------------------------------------------------
  167. // SWITCHES & LIGHTS
  168. // -----------------------------------------------------------------------------
  169. void _haSendSwitch(unsigned char i, JsonObject& config) {
  170. String name = getSetting("hostname");
  171. if (relayCount() > 1) {
  172. name += String("_") + String(i);
  173. }
  174. config.set("name", _haFixName(name));
  175. if (relayCount()) {
  176. config["state_topic"] = mqttTopic(MQTT_TOPIC_RELAY, i, false);
  177. config["command_topic"] = mqttTopic(MQTT_TOPIC_RELAY, i, true);
  178. config["payload_on"] = relayPayload(RelayStatus::ON);
  179. config["payload_off"] = relayPayload(RelayStatus::OFF);
  180. config["availability_topic"] = mqttTopic(MQTT_TOPIC_STATUS, false);
  181. config["payload_available"] = mqttPayloadStatus(true);
  182. config["payload_not_available"] = mqttPayloadStatus(false);
  183. }
  184. #if LIGHT_PROVIDER != LIGHT_PROVIDER_NONE
  185. if (i == 0) {
  186. config["brightness_state_topic"] = mqttTopic(MQTT_TOPIC_BRIGHTNESS, false);
  187. config["brightness_command_topic"] = mqttTopic(MQTT_TOPIC_BRIGHTNESS, true);
  188. if (lightHasColor()) {
  189. config["rgb_state_topic"] = mqttTopic(MQTT_TOPIC_COLOR_RGB, false);
  190. config["rgb_command_topic"] = mqttTopic(MQTT_TOPIC_COLOR_RGB, true);
  191. }
  192. if (lightUseCCT()) {
  193. config["color_temp_command_topic"] = mqttTopic(MQTT_TOPIC_MIRED, true);
  194. config["color_temp_state_topic"] = mqttTopic(MQTT_TOPIC_MIRED, false);
  195. }
  196. if (lightChannels() > 3) {
  197. config["white_value_state_topic"] = mqttTopic(MQTT_TOPIC_CHANNEL, 3, false);
  198. config["white_value_command_topic"] = mqttTopic(MQTT_TOPIC_CHANNEL, 3, true);
  199. }
  200. }
  201. #endif // LIGHT_PROVIDER != LIGHT_PROVIDER_NONE
  202. }
  203. void ha_discovery_t::prepareSwitches(ha_config_t& config) {
  204. // Note: because none of the keys are erased, use a separate object to avoid accidentally sending magnitude data
  205. JsonObject& root = config.jsonBuffer.createObject();
  206. for (unsigned char i=0; i<relayCount(); i++) {
  207. String topic = getSetting("haPrefix", HOMEASSISTANT_PREFIX) +
  208. "/" + switchType +
  209. "/" + getSetting("hostname") + "_" + String(i) +
  210. "/config";
  211. String message;
  212. if (_ha_enabled) {
  213. _haSendSwitch(i, root);
  214. root["uniq_id"] = getIdentifier() + "_" + switchType + "_" + String(i);
  215. root["device"] = config.deviceConfig;
  216. message.reserve(root.measureLength());
  217. root.printTo(message);
  218. }
  219. add(topic, message);
  220. }
  221. }
  222. // -----------------------------------------------------------------------------
  223. constexpr const size_t HA_YAML_BUFFER_SIZE = 1024;
  224. void _haSwitchYaml(unsigned char index, JsonObject& root) {
  225. String output;
  226. output.reserve(HA_YAML_BUFFER_SIZE);
  227. JsonObject& config = root.createNestedObject("config");
  228. config["platform"] = "mqtt";
  229. _haSendSwitch(index, config);
  230. if (index == 0) output += "\n\n" + switchType + ":";
  231. output += "\n";
  232. bool first = true;
  233. for (auto kv : config) {
  234. if (first) {
  235. output += " - ";
  236. first = false;
  237. } else {
  238. output += " ";
  239. }
  240. output += kv.key;
  241. output += ": ";
  242. if (strncmp(kv.key, "payload_", strlen("payload_")) == 0) {
  243. output += _haFixPayload(kv.value.as<String>());
  244. } else {
  245. output += kv.value.as<String>();
  246. }
  247. output += "\n";
  248. }
  249. output += " ";
  250. root.remove("config");
  251. root["haConfig"] = output;
  252. }
  253. #if SENSOR_SUPPORT
  254. void _haSensorYaml(unsigned char index, JsonObject& root) {
  255. String output;
  256. output.reserve(HA_YAML_BUFFER_SIZE);
  257. JsonObject& config = root.createNestedObject("config");
  258. config["platform"] = "mqtt";
  259. _haSendMagnitude(index, config);
  260. if (index == 0) output += "\n\nsensor:";
  261. output += "\n";
  262. bool first = true;
  263. for (auto kv : config) {
  264. if (first) {
  265. output += " - ";
  266. first = false;
  267. } else {
  268. output += " ";
  269. }
  270. String value = kv.value.as<String>();
  271. value.replace("%", "'%'");
  272. output += kv.key;
  273. output += ": ";
  274. output += value;
  275. output += "\n";
  276. }
  277. output += " ";
  278. root.remove("config");
  279. root["haConfig"] = output;
  280. }
  281. #endif // SENSOR_SUPPORT
  282. void _haGetDeviceConfig(JsonObject& config) {
  283. config.createNestedArray("identifiers").add(getIdentifier());
  284. config["name"] = getSetting("desc", getSetting("hostname"));
  285. config["manufacturer"] = MANUFACTURER;
  286. config["model"] = DEVICE;
  287. config["sw_version"] = String(APP_NAME) + " " + APP_VERSION + " (" + getCoreVersion() + ")";
  288. }
  289. void _haSend() {
  290. // Pending message to send?
  291. if (!_ha_send_flag) return;
  292. // Are we connected?
  293. if (!mqttConnected()) return;
  294. // Are we still trying to send discovery messages?
  295. if (_ha_discovery) return;
  296. DEBUG_MSG_P(PSTR("[HA] Sending autodiscovery MQTT message\n"));
  297. // Get common device config / context object
  298. ha_config_t config;
  299. // We expect only one instance, create now
  300. _ha_discovery = std::make_unique<ha_discovery_t>();
  301. // Prepare all of the messages and send them in the scheduled function later
  302. _ha_discovery->prepareSwitches(config);
  303. #if SENSOR_SUPPORT
  304. _ha_discovery->prepareMagnitudes(config);
  305. #endif
  306. _ha_send_flag = false;
  307. schedule_function(_haSendDiscovery);
  308. }
  309. void _haConfigure() {
  310. const bool enabled = getSetting("haEnabled", HOMEASSISTANT_ENABLED).toInt() == 1;
  311. _ha_send_flag = (enabled != _ha_enabled);
  312. _ha_enabled = enabled;
  313. _haSend();
  314. }
  315. #if WEB_SUPPORT
  316. bool _haWebSocketOnKeyCheck(const char * key, JsonVariant& value) {
  317. return (strncmp(key, "ha", 2) == 0);
  318. }
  319. void _haWebSocketOnVisible(JsonObject& root) {
  320. root["haVisible"] = 1;
  321. }
  322. void _haWebSocketOnConnected(JsonObject& root) {
  323. root["haPrefix"] = getSetting("haPrefix", HOMEASSISTANT_PREFIX);
  324. root["haEnabled"] = getSetting("haEnabled", HOMEASSISTANT_ENABLED).toInt() == 1;
  325. }
  326. void _haWebSocketOnAction(uint32_t client_id, const char * action, JsonObject& data) {
  327. if (strcmp(action, "haconfig") == 0) {
  328. ws_on_send_callback_list_t callbacks;
  329. #if SENSOR_SUPPORT
  330. callbacks.reserve(magnitudeCount() + relayCount());
  331. #else
  332. callbacks.reserve(relayCount());
  333. #endif // SENSOR_SUPPORT
  334. {
  335. for (unsigned char idx=0; idx<relayCount(); ++idx) {
  336. callbacks.push_back([idx](JsonObject& root) {
  337. _haSwitchYaml(idx, root);
  338. });
  339. }
  340. }
  341. #if SENSOR_SUPPORT
  342. {
  343. for (unsigned char idx=0; idx<magnitudeCount(); ++idx) {
  344. callbacks.push_back([idx](JsonObject& root) {
  345. _haSensorYaml(idx, root);
  346. });
  347. }
  348. }
  349. #endif // SENSOR_SUPPORT
  350. if (callbacks.size()) wsPostSequence(client_id, std::move(callbacks));
  351. }
  352. }
  353. #endif // WEB_SUPPORT
  354. #if TERMINAL_SUPPORT
  355. void _haInitCommands() {
  356. terminalRegisterCommand(F("HA.CONFIG"), [](Embedis* e) {
  357. for (unsigned char idx=0; idx<relayCount(); ++idx) {
  358. DynamicJsonBuffer jsonBuffer(1024);
  359. JsonObject& root = jsonBuffer.createObject();
  360. _haSwitchYaml(idx, root);
  361. DEBUG_MSG(root["haConfig"].as<String>().c_str());
  362. }
  363. #if SENSOR_SUPPORT
  364. for (unsigned char idx=0; idx<magnitudeCount(); ++idx) {
  365. DynamicJsonBuffer jsonBuffer(1024);
  366. JsonObject& root = jsonBuffer.createObject();
  367. _haSensorYaml(idx, root);
  368. DEBUG_MSG(root["haConfig"].as<String>().c_str());
  369. }
  370. #endif // SENSOR_SUPPORT
  371. DEBUG_MSG("\n");
  372. terminalOK();
  373. });
  374. terminalRegisterCommand(F("HA.SEND"), [](Embedis* e) {
  375. setSetting("haEnabled", "1");
  376. _haConfigure();
  377. #if WEB_SUPPORT
  378. wsPost(_haWebSocketOnConnected);
  379. #endif
  380. terminalOK();
  381. });
  382. terminalRegisterCommand(F("HA.CLEAR"), [](Embedis* e) {
  383. setSetting("haEnabled", "0");
  384. _haConfigure();
  385. #if WEB_SUPPORT
  386. wsPost(_haWebSocketOnConnected);
  387. #endif
  388. terminalOK();
  389. });
  390. }
  391. #endif
  392. // -----------------------------------------------------------------------------
  393. void haSetup() {
  394. _haConfigure();
  395. #if WEB_SUPPORT
  396. wsRegister()
  397. .onVisible(_haWebSocketOnVisible)
  398. .onConnected(_haWebSocketOnConnected)
  399. .onAction(_haWebSocketOnAction)
  400. .onKeyCheck(_haWebSocketOnKeyCheck);
  401. #endif
  402. #if TERMINAL_SUPPORT
  403. _haInitCommands();
  404. #endif
  405. // On MQTT connect check if we have something to send
  406. mqttRegister([](unsigned int type, const char * topic, const char * payload) {
  407. if (type == MQTT_CONNECT_EVENT) _haSend();
  408. if (type == MQTT_DISCONNECT_EVENT) _ha_send_flag = false;
  409. });
  410. // Main callbacks
  411. espurnaRegisterReload(_haConfigure);
  412. }
  413. #endif // HOMEASSISTANT_SUPPORT