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.

500 lines
14 KiB

7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  1. /*
  2. LED MODULE
  3. Copyright (C) 2016-2019 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #include "led.h"
  6. #if LED_SUPPORT
  7. #include <algorithm>
  8. #include "broker.h"
  9. #include "mqtt.h"
  10. #include "relay.h"
  11. #include "rpc.h"
  12. #include "ws.h"
  13. #include "led_pattern.h"
  14. #include "led_config.h"
  15. // LED helper class
  16. led_t::led_t(unsigned char pin, bool inverse, unsigned char mode, unsigned char relayID) :
  17. pin(pin),
  18. inverse(inverse),
  19. mode(mode),
  20. relayID(relayID)
  21. {
  22. if (pin != GPIO_NONE) {
  23. pinMode(pin, OUTPUT);
  24. status(false);
  25. }
  26. }
  27. bool led_t::status() {
  28. bool result = digitalRead(pin);
  29. return inverse ? !result : result;
  30. }
  31. bool led_t::status(bool new_status) {
  32. digitalWrite(pin, inverse ? !new_status : new_status);
  33. return new_status;
  34. }
  35. bool led_t::toggle() {
  36. return status(!status());
  37. }
  38. led_delay_t::led_delay_t(unsigned long on_ms, unsigned long off_ms, unsigned char repeats) :
  39. type(repeats ? led_delay_mode_t::Finite : led_delay_mode_t::Infinite),
  40. on(microsecondsToClockCycles(on_ms * 1000)),
  41. off(microsecondsToClockCycles(off_ms * 1000)),
  42. repeats(repeats ? repeats : 0)
  43. {}
  44. led_delay_t::led_delay_t(unsigned long on_ms, unsigned long off_ms) :
  45. led_delay_t(on_ms, off_ms, 0)
  46. {}
  47. led_pattern_t::led_pattern_t(const std::vector<led_delay_t>& delays) :
  48. delays(delays),
  49. queue(),
  50. clock_last(ESP.getCycleCount()),
  51. clock_delay(delays.size() ? delays.back().on : 0)
  52. {}
  53. bool led_pattern_t::started() {
  54. return queue.size() > 0;
  55. }
  56. bool led_pattern_t::ready() {
  57. return delays.size() > 0;
  58. }
  59. void led_pattern_t::start() {
  60. clock_last = ESP.getCycleCount();
  61. clock_delay = 0;
  62. queue = {
  63. delays.rbegin(), delays.rend()
  64. };
  65. }
  66. void led_pattern_t::stop() {
  67. queue.clear();
  68. }
  69. // For relay-based modes
  70. bool _led_update = false;
  71. // For network-based modes, cycle ON & OFF (time in milliseconds)
  72. // XXX: internals convert these to clock cycles, delay cannot be longer than 25000 / 50000 ms
  73. const led_delay_t _ledDelays[] {
  74. {100, 100}, // Autoconfig
  75. {100, 4900}, // Connected
  76. {4900, 100}, // Connected (inverse)
  77. {100, 900}, // Config / AP
  78. {900, 100}, // Config / AP (inverse)
  79. {500, 500} // Idle
  80. };
  81. std::vector<led_t> _leds;
  82. // -----------------------------------------------------------------------------
  83. unsigned char ledCount() {
  84. return _leds.size();
  85. }
  86. bool _ledStatus(led_t& led) {
  87. return led.pattern.started() || led.status();
  88. }
  89. bool _ledStatus(led_t& led, bool status) {
  90. bool result = false;
  91. // when led has pattern, status depends on whether it's running
  92. if (led.pattern.ready()) {
  93. if (status) {
  94. if (!led.pattern.started()) {
  95. led.pattern.start();
  96. }
  97. result = true;
  98. } else {
  99. led.pattern.stop();
  100. led.status(false);
  101. result = false;
  102. }
  103. // if not, simply proxy status directly to the led pin
  104. } else {
  105. result = led.status(status);
  106. }
  107. return result;
  108. }
  109. bool _ledToggle(led_t& led) {
  110. return _ledStatus(led, !_ledStatus(led));
  111. }
  112. bool ledStatus(unsigned char id, bool status) {
  113. if (id >= ledCount()) return false;
  114. return _ledStatus(_leds[id], status);
  115. }
  116. bool ledStatus(unsigned char id) {
  117. if (id >= ledCount()) return false;
  118. return _ledStatus(_leds[id]);
  119. }
  120. const led_delay_t& _ledModeToDelay(LedMode mode) {
  121. static_assert(
  122. (sizeof(_ledDelays) / sizeof(_ledDelays[0])) <= static_cast<int>(LedMode::None),
  123. "LedMode mapping out-of-bounds"
  124. );
  125. return _ledDelays[static_cast<int>(mode)];
  126. }
  127. void _ledPattern(led_t& led) {
  128. const auto clock_current = ESP.getCycleCount();
  129. if (clock_current - led.pattern.clock_last >= led.pattern.clock_delay) {
  130. const bool status = led.toggle();
  131. auto& current = led.pattern.queue.back();
  132. switch (current.type) {
  133. case led_delay_mode_t::Finite:
  134. if (status && !--current.repeats) {
  135. led.pattern.queue.pop_back();
  136. if (!led.pattern.queue.size()) {
  137. led.status(false);
  138. return;
  139. }
  140. }
  141. break;
  142. case led_delay_mode_t::Infinite:
  143. case led_delay_mode_t::None:
  144. default:
  145. break;
  146. }
  147. led.pattern.clock_delay = status ? current.on : current.off;
  148. led.pattern.clock_last = ESP.getCycleCount();
  149. }
  150. }
  151. void _ledBlink(led_t& led, const led_delay_t& delays) {
  152. static auto clock_last = ESP.getCycleCount();
  153. static auto delay_for = delays.on;
  154. const auto clock_current = ESP.getCycleCount();
  155. if (clock_current - clock_last >= delay_for) {
  156. delay_for = led.toggle() ? delays.on : delays.off;
  157. clock_last = clock_current;
  158. }
  159. }
  160. inline void _ledBlink(led_t& led, const LedMode mode) {
  161. _ledBlink(led, _ledModeToDelay(mode));
  162. }
  163. #if WEB_SUPPORT
  164. bool _ledWebSocketOnKeyCheck(const char * key, JsonVariant& value) {
  165. return (strncmp(key, "led", 3) == 0);
  166. }
  167. void _ledWebSocketOnVisible(JsonObject& root) {
  168. if (ledCount() > 0) {
  169. root["ledVisible"] = 1;
  170. }
  171. }
  172. void _ledWebSocketOnConnected(JsonObject& root) {
  173. if (!ledCount()) return;
  174. JsonObject& module = root.createNestedObject("led");
  175. JsonArray& schema = module.createNestedArray("schema");
  176. schema.add("GPIO");
  177. schema.add("Inv");
  178. schema.add("Mode");
  179. schema.add("Relay");
  180. JsonArray& leds = module.createNestedArray("list");
  181. for (unsigned char index = 0; index < ledCount(); ++index) {
  182. JsonArray& led = leds.createNestedArray();
  183. led.add(getSetting({"ledGPIO", index}, _ledPin(index)));
  184. led.add(static_cast<int>(getSetting({"ledInv", index}, _ledInverse(index))));
  185. led.add(getSetting({"ledMode", index}, _ledMode(index)));
  186. led.add(getSetting({"ledRelay", index}, _ledRelay(index)));
  187. }
  188. }
  189. #endif
  190. void _ledBrokerCallback(const String& topic, unsigned char, unsigned int) {
  191. // Only process status messages for switches
  192. if (topic.equals(MQTT_TOPIC_RELAY)) {
  193. ledUpdate(true);
  194. }
  195. }
  196. #if MQTT_SUPPORT
  197. void _ledMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  198. if (type == MQTT_CONNECT_EVENT) {
  199. char buffer[strlen(MQTT_TOPIC_LED) + 3];
  200. snprintf_P(buffer, sizeof(buffer), PSTR("%s/+"), MQTT_TOPIC_LED);
  201. mqttSubscribe(buffer);
  202. }
  203. if (type == MQTT_MESSAGE_EVENT) {
  204. // Only want `led/+/<MQTT_SETTER>`
  205. const String magnitude = mqttMagnitude((char *) topic);
  206. if (!magnitude.startsWith(MQTT_TOPIC_LED)) return;
  207. // Get led ID from after the slash when t is `led/<LED_ID>`
  208. unsigned int ledID = magnitude.substring(strlen(MQTT_TOPIC_LED) + 1).toInt();
  209. if (ledID >= ledCount()) {
  210. DEBUG_MSG_P(PSTR("[LED] Wrong ledID (%d)\n"), ledID);
  211. return;
  212. }
  213. // Check if LED is managed
  214. if (_leds[ledID].mode != LED_MODE_MANUAL) return;
  215. // Get value based on rpc payload logic (see rpc.ino)
  216. const auto value = rpcParsePayload(payload);
  217. switch (value) {
  218. case PayloadStatus::On:
  219. case PayloadStatus::Off:
  220. _ledStatus(_leds[ledID], (value == PayloadStatus::On));
  221. break;
  222. case PayloadStatus::Toggle:
  223. _ledToggle(_leds[ledID]);
  224. break;
  225. case PayloadStatus::Unknown:
  226. default:
  227. _ledLoadPattern(_leds[ledID], payload);
  228. _ledStatus(_leds[ledID], true);
  229. break;
  230. }
  231. }
  232. }
  233. #endif
  234. void _ledConfigure() {
  235. for (unsigned char id = 0; id < _leds.size(); ++id) {
  236. _leds[id].mode = getSetting({"ledMode", id}, _ledMode(id));
  237. _leds[id].relayID = getSetting({"ledRelay", id}, _ledRelay(id));
  238. _leds[id].pattern.stop();
  239. _ledLoadPattern(_leds[id], getSetting({"ledPattern", id}).c_str());
  240. }
  241. _led_update = true;
  242. }
  243. // -----------------------------------------------------------------------------
  244. void ledUpdate(bool do_update) {
  245. _led_update = do_update;
  246. }
  247. void ledLoop() {
  248. const auto wifi_state = wifiState();
  249. for (auto& led : _leds) {
  250. switch (led.mode) {
  251. case LED_MODE_WIFI:
  252. if ((wifi_state & WIFI_STATE_WPS) || (wifi_state & WIFI_STATE_SMARTCONFIG)) {
  253. _ledBlink(led, LedMode::NetworkAutoconfig);
  254. } else if (wifi_state & WIFI_STATE_STA) {
  255. _ledBlink(led, LedMode::NetworkConnected);
  256. } else if (wifi_state & WIFI_STATE_AP) {
  257. _ledBlink(led, LedMode::NetworkConfig);
  258. } else {
  259. _ledBlink(led, LedMode::NetworkIdle);
  260. }
  261. break;
  262. #if RELAY_SUPPORT
  263. case LED_MODE_FINDME_WIFI:
  264. if ((wifi_state & WIFI_STATE_WPS) || (wifi_state & WIFI_STATE_SMARTCONFIG)) {
  265. _ledBlink(led, LedMode::NetworkAutoconfig);
  266. } else if (wifi_state & WIFI_STATE_STA) {
  267. if (relayStatus(led.relayID)) {
  268. _ledBlink(led, LedMode::NetworkConnected);
  269. } else {
  270. _ledBlink(led, LedMode::NetworkConnectedInverse);
  271. }
  272. } else if (wifi_state & WIFI_STATE_AP) {
  273. if (relayStatus(led.relayID)) {
  274. _ledBlink(led, LedMode::NetworkConfig);
  275. } else {
  276. _ledBlink(led, LedMode::NetworkConfigInverse);
  277. }
  278. } else {
  279. _ledBlink(led, LedMode::NetworkIdle);
  280. }
  281. break;
  282. case LED_MODE_RELAY_WIFI:
  283. if ((wifi_state & WIFI_STATE_WPS) || (wifi_state & WIFI_STATE_SMARTCONFIG)) {
  284. _ledBlink(led, LedMode::NetworkAutoconfig);
  285. } else if (wifi_state & WIFI_STATE_STA) {
  286. if (relayStatus(led.relayID)) {
  287. _ledBlink(led, LedMode::NetworkConnected);
  288. } else {
  289. _ledBlink(led, LedMode::NetworkConnectedInverse);
  290. }
  291. } else if (wifi_state & WIFI_STATE_AP) {
  292. if (relayStatus(led.relayID)) {
  293. _ledBlink(led, LedMode::NetworkConfig);
  294. } else {
  295. _ledBlink(led, LedMode::NetworkConfigInverse);
  296. }
  297. } else {
  298. _ledBlink(led, LedMode::NetworkIdle);
  299. }
  300. break;
  301. case LED_MODE_FOLLOW:
  302. if (!_led_update) break;
  303. _ledStatus(led, relayStatus(led.relayID));
  304. break;
  305. case LED_MODE_FOLLOW_INVERSE:
  306. if (!_led_update) break;
  307. led.status(!relayStatus(led.relayID));
  308. _ledStatus(led, !relayStatus(led.relayID));
  309. break;
  310. case LED_MODE_FINDME: {
  311. if (!_led_update) break;
  312. bool status = true;
  313. for (unsigned char relayID = 0; relayID < relayCount(); ++relayID) {
  314. if (relayStatus(relayID)) {
  315. status = false;
  316. break;
  317. }
  318. }
  319. _ledStatus(led, status);
  320. break;
  321. }
  322. case LED_MODE_RELAY: {
  323. if (!_led_update) break;
  324. bool status = false;
  325. for (unsigned char relayID = 0; relayID < relayCount(); ++relayID) {
  326. if (relayStatus(relayID)) {
  327. status = true;
  328. break;
  329. }
  330. }
  331. _ledStatus(led, status);
  332. break;
  333. }
  334. #endif // RELAY_SUPPORT == 1
  335. case LED_MODE_ON:
  336. if (!_led_update) break;
  337. _ledStatus(led, true);
  338. break;
  339. case LED_MODE_OFF:
  340. if (!_led_update) break;
  341. _ledStatus(led, false);
  342. break;
  343. }
  344. if (led.pattern.started()) {
  345. _ledPattern(led);
  346. continue;
  347. }
  348. }
  349. _led_update = false;
  350. }
  351. void ledSetup() {
  352. size_t leds = 0;
  353. #if LED1_PIN != GPIO_NONE
  354. ++leds;
  355. #endif
  356. #if LED2_PIN != GPIO_NONE
  357. ++leds;
  358. #endif
  359. #if LED3_PIN != GPIO_NONE
  360. ++leds;
  361. #endif
  362. #if LED4_PIN != GPIO_NONE
  363. ++leds;
  364. #endif
  365. #if LED5_PIN != GPIO_NONE
  366. ++leds;
  367. #endif
  368. #if LED6_PIN != GPIO_NONE
  369. ++leds;
  370. #endif
  371. #if LED7_PIN != GPIO_NONE
  372. ++leds;
  373. #endif
  374. #if LED8_PIN != GPIO_NONE
  375. ++leds;
  376. #endif
  377. _leds.reserve(leds);
  378. for (unsigned char index=0; index < LedsMax; ++index) {
  379. const auto pin = getSetting({"ledGPIO", index}, _ledPin(index));
  380. if (!gpioValid(pin)) {
  381. break;
  382. }
  383. _leds.emplace_back(
  384. pin,
  385. getSetting({"ledInv", index}, _ledInverse(index)),
  386. getSetting({"ledMode", index}, _ledMode(index)),
  387. getSetting({"ledRelay", index}, _ledRelay(index))
  388. );
  389. }
  390. _led_update = true;
  391. #if MQTT_SUPPORT
  392. mqttRegister(_ledMQTTCallback);
  393. #endif
  394. #if WEB_SUPPORT
  395. wsRegister()
  396. .onVisible(_ledWebSocketOnVisible)
  397. .onConnected(_ledWebSocketOnConnected)
  398. .onKeyCheck(_ledWebSocketOnKeyCheck);
  399. #endif
  400. StatusBroker::Register(_ledBrokerCallback);
  401. DEBUG_MSG_P(PSTR("[LED] Number of leds: %d\n"), _leds.size());
  402. // Main callbacks
  403. espurnaRegisterLoop(ledLoop);
  404. espurnaRegisterReload(_ledConfigure);
  405. }
  406. #endif // LED_SUPPORT