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.

505 lines
14 KiB

providers: relays, lights and buttons refactoring (#2414) - gpio module now tracks the known providers (right now, hardware and mcp expander) - refactored relay struct to use 'Provider' implementing setup,notify,change,boot instead of just BasePin actions - refactored button module to use gpio provider instead of referencing types itself - removed dual & stm code from buttons, migrate both to relay module - added status notify and change callbacks for relayStatus (i.e. 'notify' when relay status was called, but not changed. and 'changed' when it did) - relays runtime configuration keys - relay command now shows configured relays and current & target statuses - refactor the code using relayStatus(0, blah) under LIGHT_PROVIDER check to use lightState instead - remove rfbridge code form relay module. implement through a basic state listener in the rfbridge module, depend on RELAY_SUPPORT - allow to bind rf codes to real relays - drop tuya-specific lights provider, remove tuya code from relays and lights modules - integrate tuya via relay listeners and providers, use lights custom provider - implement channel transitions for tuya. disabled by default, and transition time and step are overridden to 2000 + 100. needs to be set to some value below the total time (i.e. `total transition time / step time == number of steps`, we need to figure out a correct time that serial comms could handle) - lights custom provider (global, not per-pin) and state listeners - remove lights code from relay module. implement through providers & listeners in the lights module, depend on RELAY_SUPPORT - lights per-channel relay provider (unused atm), depend on RELAY_SUPPORT - refactored channel transition - calculate step only once, make sure time + step values are sane, generate quick transitions with very small delay (10ms hardcoded) for transitions during OFF state i.e. we no longer waste 500ms (or whatever transition time is set to) on boot doing nothing - transition time + step parameter for the lightUpdate - report mask parameter for the lightUpdate - minor fixes across the board resolve #2222
3 years ago
providers: relays, lights and buttons refactoring (#2414) - gpio module now tracks the known providers (right now, hardware and mcp expander) - refactored relay struct to use 'Provider' implementing setup,notify,change,boot instead of just BasePin actions - refactored button module to use gpio provider instead of referencing types itself - removed dual & stm code from buttons, migrate both to relay module - added status notify and change callbacks for relayStatus (i.e. 'notify' when relay status was called, but not changed. and 'changed' when it did) - relays runtime configuration keys - relay command now shows configured relays and current & target statuses - refactor the code using relayStatus(0, blah) under LIGHT_PROVIDER check to use lightState instead - remove rfbridge code form relay module. implement through a basic state listener in the rfbridge module, depend on RELAY_SUPPORT - allow to bind rf codes to real relays - drop tuya-specific lights provider, remove tuya code from relays and lights modules - integrate tuya via relay listeners and providers, use lights custom provider - implement channel transitions for tuya. disabled by default, and transition time and step are overridden to 2000 + 100. needs to be set to some value below the total time (i.e. `total transition time / step time == number of steps`, we need to figure out a correct time that serial comms could handle) - lights custom provider (global, not per-pin) and state listeners - remove lights code from relay module. implement through providers & listeners in the lights module, depend on RELAY_SUPPORT - lights per-channel relay provider (unused atm), depend on RELAY_SUPPORT - refactored channel transition - calculate step only once, make sure time + step values are sane, generate quick transitions with very small delay (10ms hardcoded) for transitions during OFF state i.e. we no longer waste 500ms (or whatever transition time is set to) on boot doing nothing - transition time + step parameter for the lightUpdate - report mask parameter for the lightUpdate - minor fixes across the board resolve #2222
3 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
7 years ago
providers: relays, lights and buttons refactoring (#2414) - gpio module now tracks the known providers (right now, hardware and mcp expander) - refactored relay struct to use 'Provider' implementing setup,notify,change,boot instead of just BasePin actions - refactored button module to use gpio provider instead of referencing types itself - removed dual & stm code from buttons, migrate both to relay module - added status notify and change callbacks for relayStatus (i.e. 'notify' when relay status was called, but not changed. and 'changed' when it did) - relays runtime configuration keys - relay command now shows configured relays and current & target statuses - refactor the code using relayStatus(0, blah) under LIGHT_PROVIDER check to use lightState instead - remove rfbridge code form relay module. implement through a basic state listener in the rfbridge module, depend on RELAY_SUPPORT - allow to bind rf codes to real relays - drop tuya-specific lights provider, remove tuya code from relays and lights modules - integrate tuya via relay listeners and providers, use lights custom provider - implement channel transitions for tuya. disabled by default, and transition time and step are overridden to 2000 + 100. needs to be set to some value below the total time (i.e. `total transition time / step time == number of steps`, we need to figure out a correct time that serial comms could handle) - lights custom provider (global, not per-pin) and state listeners - remove lights code from relay module. implement through providers & listeners in the lights module, depend on RELAY_SUPPORT - lights per-channel relay provider (unused atm), depend on RELAY_SUPPORT - refactored channel transition - calculate step only once, make sure time + step values are sane, generate quick transitions with very small delay (10ms hardcoded) for transitions during OFF state i.e. we no longer waste 500ms (or whatever transition time is set to) on boot doing nothing - transition time + step parameter for the lightUpdate - report mask parameter for the lightUpdate - minor fixes across the board resolve #2222
3 years ago
providers: relays, lights and buttons refactoring (#2414) - gpio module now tracks the known providers (right now, hardware and mcp expander) - refactored relay struct to use 'Provider' implementing setup,notify,change,boot instead of just BasePin actions - refactored button module to use gpio provider instead of referencing types itself - removed dual & stm code from buttons, migrate both to relay module - added status notify and change callbacks for relayStatus (i.e. 'notify' when relay status was called, but not changed. and 'changed' when it did) - relays runtime configuration keys - relay command now shows configured relays and current & target statuses - refactor the code using relayStatus(0, blah) under LIGHT_PROVIDER check to use lightState instead - remove rfbridge code form relay module. implement through a basic state listener in the rfbridge module, depend on RELAY_SUPPORT - allow to bind rf codes to real relays - drop tuya-specific lights provider, remove tuya code from relays and lights modules - integrate tuya via relay listeners and providers, use lights custom provider - implement channel transitions for tuya. disabled by default, and transition time and step are overridden to 2000 + 100. needs to be set to some value below the total time (i.e. `total transition time / step time == number of steps`, we need to figure out a correct time that serial comms could handle) - lights custom provider (global, not per-pin) and state listeners - remove lights code from relay module. implement through providers & listeners in the lights module, depend on RELAY_SUPPORT - lights per-channel relay provider (unused atm), depend on RELAY_SUPPORT - refactored channel transition - calculate step only once, make sure time + step values are sane, generate quick transitions with very small delay (10ms hardcoded) for transitions during OFF state i.e. we no longer waste 500ms (or whatever transition time is set to) on boot doing nothing - transition time + step parameter for the lightUpdate - report mask parameter for the lightUpdate - minor fixes across the board resolve #2222
3 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 "mqtt.h"
  9. #include "relay.h"
  10. #include "rpc.h"
  11. #include "ws.h"
  12. #include "led_pattern.h"
  13. #include "led_config.h"
  14. // LED helper class
  15. led_t::led_t(unsigned char pin_, bool inverse_, unsigned char mode_, unsigned char relayID_) :
  16. pin(pin_),
  17. inverse(inverse_),
  18. mode(mode_),
  19. relayID(relayID_)
  20. {
  21. pinMode(pin, OUTPUT);
  22. status(false);
  23. }
  24. bool led_t::status() {
  25. bool result = digitalRead(pin);
  26. return inverse ? !result : result;
  27. }
  28. bool led_t::status(bool new_status) {
  29. digitalWrite(pin, inverse ? !new_status : new_status);
  30. return new_status;
  31. }
  32. bool led_t::toggle() {
  33. return status(!status());
  34. }
  35. led_delay_t::led_delay_t(unsigned long on_ms, unsigned long off_ms, unsigned char repeats) :
  36. type(repeats ? led_delay_mode_t::Finite : led_delay_mode_t::Infinite),
  37. on(microsecondsToClockCycles(on_ms * 1000)),
  38. off(microsecondsToClockCycles(off_ms * 1000)),
  39. repeats(repeats ? repeats : 0)
  40. {}
  41. led_delay_t::led_delay_t(unsigned long on_ms, unsigned long off_ms) :
  42. led_delay_t(on_ms, off_ms, 0)
  43. {}
  44. led_pattern_t::led_pattern_t(const std::vector<led_delay_t>& delays) :
  45. delays(delays),
  46. queue(),
  47. clock_last(ESP.getCycleCount()),
  48. clock_delay(delays.size() ? delays.back().on : 0)
  49. {}
  50. bool led_pattern_t::started() {
  51. return queue.size() > 0;
  52. }
  53. bool led_pattern_t::ready() {
  54. return delays.size() > 0;
  55. }
  56. void led_pattern_t::start() {
  57. clock_last = ESP.getCycleCount();
  58. clock_delay = 0;
  59. queue = {
  60. delays.rbegin(), delays.rend()
  61. };
  62. }
  63. void led_pattern_t::stop() {
  64. queue.clear();
  65. }
  66. // For relay-based modes
  67. bool _led_update = false;
  68. // For network-based modes, cycle ON & OFF (time in milliseconds)
  69. // XXX: internals convert these to clock cycles, delay cannot be longer than 25000 / 50000 ms
  70. const led_delay_t _ledDelays[] {
  71. {100, 100}, // Autoconfig
  72. {100, 4900}, // Connected
  73. {4900, 100}, // Connected (inverse)
  74. {100, 900}, // Config / AP
  75. {900, 100}, // Config / AP (inverse)
  76. {500, 500} // Idle
  77. };
  78. std::vector<led_t> _leds;
  79. // -----------------------------------------------------------------------------
  80. unsigned char ledCount() {
  81. return _leds.size();
  82. }
  83. bool _ledStatus(led_t& led) {
  84. return led.pattern.started() || led.status();
  85. }
  86. bool _ledStatus(led_t& led, bool status) {
  87. bool result = false;
  88. // when led has pattern, status depends on whether it's running
  89. if (led.pattern.ready()) {
  90. if (status) {
  91. if (!led.pattern.started()) {
  92. led.pattern.start();
  93. }
  94. result = true;
  95. } else {
  96. led.pattern.stop();
  97. led.status(false);
  98. result = false;
  99. }
  100. // if not, simply proxy status directly to the led pin
  101. } else {
  102. result = led.status(status);
  103. }
  104. return result;
  105. }
  106. bool _ledToggle(led_t& led) {
  107. return _ledStatus(led, !_ledStatus(led));
  108. }
  109. bool ledStatus(unsigned char id, bool status) {
  110. if (id >= ledCount()) return false;
  111. return _ledStatus(_leds[id], status);
  112. }
  113. bool ledStatus(unsigned char id) {
  114. if (id >= ledCount()) return false;
  115. return _ledStatus(_leds[id]);
  116. }
  117. const led_delay_t& _ledModeToDelay(LedMode mode) {
  118. static_assert(
  119. (sizeof(_ledDelays) / sizeof(_ledDelays[0])) <= static_cast<int>(LedMode::None),
  120. "LedMode mapping out-of-bounds"
  121. );
  122. return _ledDelays[static_cast<int>(mode)];
  123. }
  124. void _ledPattern(led_t& led) {
  125. const auto clock_current = ESP.getCycleCount();
  126. if (clock_current - led.pattern.clock_last >= led.pattern.clock_delay) {
  127. const bool status = led.toggle();
  128. auto& current = led.pattern.queue.back();
  129. switch (current.type) {
  130. case led_delay_mode_t::Finite:
  131. if (status && !--current.repeats) {
  132. led.pattern.queue.pop_back();
  133. if (!led.pattern.queue.size()) {
  134. led.status(false);
  135. return;
  136. }
  137. }
  138. break;
  139. case led_delay_mode_t::Infinite:
  140. case led_delay_mode_t::None:
  141. default:
  142. break;
  143. }
  144. led.pattern.clock_delay = status ? current.on : current.off;
  145. led.pattern.clock_last = ESP.getCycleCount();
  146. }
  147. }
  148. void _ledBlink(led_t& led, const led_delay_t& delays) {
  149. static auto clock_last = ESP.getCycleCount();
  150. static auto delay_for = delays.on;
  151. const auto clock_current = ESP.getCycleCount();
  152. if (clock_current - clock_last >= delay_for) {
  153. delay_for = led.toggle() ? delays.on : delays.off;
  154. clock_last = clock_current;
  155. }
  156. }
  157. inline void _ledBlink(led_t& led, const LedMode mode) {
  158. _ledBlink(led, _ledModeToDelay(mode));
  159. }
  160. #if WEB_SUPPORT
  161. bool _ledWebSocketOnKeyCheck(const char * key, JsonVariant& value) {
  162. return (strncmp(key, "led", 3) == 0);
  163. }
  164. void _ledWebSocketOnVisible(JsonObject& root) {
  165. if (ledCount() > 0) {
  166. root["ledVisible"] = 1;
  167. }
  168. }
  169. void _ledWebSocketOnConnected(JsonObject& root) {
  170. if (!ledCount()) return;
  171. JsonObject& module = root.createNestedObject("led");
  172. JsonArray& schema = module.createNestedArray("schema");
  173. schema.add("GPIO");
  174. schema.add("Inv");
  175. schema.add("Mode");
  176. schema.add("Relay");
  177. JsonArray& leds = module.createNestedArray("list");
  178. for (unsigned char index = 0; index < ledCount(); ++index) {
  179. JsonArray& led = leds.createNestedArray();
  180. led.add(getSetting({"ledGPIO", index}, _ledPin(index)));
  181. led.add(static_cast<int>(getSetting({"ledInv", index}, _ledInverse(index))));
  182. led.add(getSetting({"ledMode", index}, _ledMode(index)));
  183. led.add(getSetting({"ledRelay", index}, _ledRelay(index)));
  184. }
  185. }
  186. #endif
  187. #if MQTT_SUPPORT
  188. void _ledMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  189. if (type == MQTT_CONNECT_EVENT) {
  190. char buffer[strlen(MQTT_TOPIC_LED) + 3];
  191. snprintf_P(buffer, sizeof(buffer), PSTR("%s/+"), MQTT_TOPIC_LED);
  192. mqttSubscribe(buffer);
  193. }
  194. if (type == MQTT_MESSAGE_EVENT) {
  195. // Only want `led/+/<MQTT_SETTER>`
  196. const String magnitude = mqttMagnitude((char *) topic);
  197. if (!magnitude.startsWith(MQTT_TOPIC_LED)) return;
  198. // Get led ID from after the slash when t is `led/<LED_ID>`
  199. unsigned int ledID = magnitude.substring(strlen(MQTT_TOPIC_LED) + 1).toInt();
  200. if (ledID >= ledCount()) {
  201. DEBUG_MSG_P(PSTR("[LED] Wrong ledID (%d)\n"), ledID);
  202. return;
  203. }
  204. // Check if LED is managed
  205. if (_leds[ledID].mode != LED_MODE_MANUAL) return;
  206. // Get value based on rpc payload logic (see rpc.ino)
  207. const auto value = rpcParsePayload(payload);
  208. switch (value) {
  209. case PayloadStatus::On:
  210. case PayloadStatus::Off:
  211. _ledStatus(_leds[ledID], (value == PayloadStatus::On));
  212. break;
  213. case PayloadStatus::Toggle:
  214. _ledToggle(_leds[ledID]);
  215. break;
  216. case PayloadStatus::Unknown:
  217. default:
  218. _ledLoadPattern(_leds[ledID], payload);
  219. _ledStatus(_leds[ledID], true);
  220. break;
  221. }
  222. }
  223. }
  224. #endif
  225. void _ledConfigure() {
  226. for (unsigned char id = 0; id < _leds.size(); ++id) {
  227. _leds[id].mode = getSetting({"ledMode", id}, _ledMode(id));
  228. _leds[id].relayID = getSetting({"ledRelay", id}, _ledRelay(id));
  229. _leds[id].pattern.stop();
  230. _ledLoadPattern(_leds[id], getSetting({"ledPattern", id}).c_str());
  231. }
  232. _led_update = true;
  233. }
  234. // -----------------------------------------------------------------------------
  235. void ledUpdate(bool do_update) {
  236. _led_update = do_update;
  237. }
  238. void ledLoop() {
  239. const auto wifi_state = wifiState();
  240. for (auto& led : _leds) {
  241. switch (led.mode) {
  242. case LED_MODE_WIFI:
  243. if ((wifi_state & WIFI_STATE_WPS) || (wifi_state & WIFI_STATE_SMARTCONFIG)) {
  244. _ledBlink(led, LedMode::NetworkAutoconfig);
  245. } else if (wifi_state & WIFI_STATE_STA) {
  246. _ledBlink(led, LedMode::NetworkConnected);
  247. } else if (wifi_state & WIFI_STATE_AP) {
  248. _ledBlink(led, LedMode::NetworkConfig);
  249. } else {
  250. _ledBlink(led, LedMode::NetworkIdle);
  251. }
  252. break;
  253. #if RELAY_SUPPORT
  254. case LED_MODE_FINDME_WIFI:
  255. if ((wifi_state & WIFI_STATE_WPS) || (wifi_state & WIFI_STATE_SMARTCONFIG)) {
  256. _ledBlink(led, LedMode::NetworkAutoconfig);
  257. } else if (wifi_state & WIFI_STATE_STA) {
  258. if (relayStatus(led.relayID)) {
  259. _ledBlink(led, LedMode::NetworkConnected);
  260. } else {
  261. _ledBlink(led, LedMode::NetworkConnectedInverse);
  262. }
  263. } else if (wifi_state & WIFI_STATE_AP) {
  264. if (relayStatus(led.relayID)) {
  265. _ledBlink(led, LedMode::NetworkConfig);
  266. } else {
  267. _ledBlink(led, LedMode::NetworkConfigInverse);
  268. }
  269. } else {
  270. _ledBlink(led, LedMode::NetworkIdle);
  271. }
  272. break;
  273. case LED_MODE_RELAY_WIFI:
  274. if ((wifi_state & WIFI_STATE_WPS) || (wifi_state & WIFI_STATE_SMARTCONFIG)) {
  275. _ledBlink(led, LedMode::NetworkAutoconfig);
  276. } else if (wifi_state & WIFI_STATE_STA) {
  277. if (relayStatus(led.relayID)) {
  278. _ledBlink(led, LedMode::NetworkConnected);
  279. } else {
  280. _ledBlink(led, LedMode::NetworkConnectedInverse);
  281. }
  282. } else if (wifi_state & WIFI_STATE_AP) {
  283. if (relayStatus(led.relayID)) {
  284. _ledBlink(led, LedMode::NetworkConfig);
  285. } else {
  286. _ledBlink(led, LedMode::NetworkConfigInverse);
  287. }
  288. } else {
  289. _ledBlink(led, LedMode::NetworkIdle);
  290. }
  291. break;
  292. case LED_MODE_FOLLOW:
  293. if (!_led_update) break;
  294. _ledStatus(led, relayStatus(led.relayID));
  295. break;
  296. case LED_MODE_FOLLOW_INVERSE:
  297. if (!_led_update) break;
  298. led.status(!relayStatus(led.relayID));
  299. _ledStatus(led, !relayStatus(led.relayID));
  300. break;
  301. case LED_MODE_FINDME: {
  302. if (!_led_update) break;
  303. bool status = true;
  304. for (unsigned char relayID = 0; relayID < relayCount(); ++relayID) {
  305. if (relayStatus(relayID)) {
  306. status = false;
  307. break;
  308. }
  309. }
  310. _ledStatus(led, status);
  311. break;
  312. }
  313. case LED_MODE_RELAY: {
  314. if (!_led_update) break;
  315. bool status = false;
  316. for (unsigned char relayID = 0; relayID < relayCount(); ++relayID) {
  317. if (relayStatus(relayID)) {
  318. status = true;
  319. break;
  320. }
  321. }
  322. _ledStatus(led, status);
  323. break;
  324. }
  325. #endif // RELAY_SUPPORT == 1
  326. case LED_MODE_ON:
  327. if (!_led_update) break;
  328. _ledStatus(led, true);
  329. break;
  330. case LED_MODE_OFF:
  331. if (!_led_update) break;
  332. _ledStatus(led, false);
  333. break;
  334. }
  335. if (led.pattern.started()) {
  336. _ledPattern(led);
  337. continue;
  338. }
  339. }
  340. _led_update = false;
  341. }
  342. void _ledSettingsMigrate(int version) {
  343. if (!version || (version >= 5)) {
  344. return;
  345. }
  346. delSettingPrefix({
  347. "ledGPIO",
  348. "ledLogic"
  349. });
  350. }
  351. void ledSetup() {
  352. _ledSettingsMigrate(migrateVersion());
  353. size_t leds = 0;
  354. #if LED1_PIN != GPIO_NONE
  355. ++leds;
  356. #endif
  357. #if LED2_PIN != GPIO_NONE
  358. ++leds;
  359. #endif
  360. #if LED3_PIN != GPIO_NONE
  361. ++leds;
  362. #endif
  363. #if LED4_PIN != GPIO_NONE
  364. ++leds;
  365. #endif
  366. #if LED5_PIN != GPIO_NONE
  367. ++leds;
  368. #endif
  369. #if LED6_PIN != GPIO_NONE
  370. ++leds;
  371. #endif
  372. #if LED7_PIN != GPIO_NONE
  373. ++leds;
  374. #endif
  375. #if LED8_PIN != GPIO_NONE
  376. ++leds;
  377. #endif
  378. _leds.reserve(leds);
  379. for (unsigned char index=0; index < LedsMax; ++index) {
  380. const auto pin = getSetting({"ledGPIO", index}, _ledPin(index));
  381. if (!gpioLock(pin)) {
  382. break;
  383. }
  384. _leds.emplace_back(
  385. pin,
  386. getSetting({"ledInv", index}, _ledInverse(index)),
  387. getSetting({"ledMode", index}, _ledMode(index)),
  388. getSetting({"ledRelay", index}, _ledRelay(index))
  389. );
  390. }
  391. _led_update = true;
  392. #if MQTT_SUPPORT
  393. mqttRegister(_ledMQTTCallback);
  394. #endif
  395. #if WEB_SUPPORT
  396. wsRegister()
  397. .onVisible(_ledWebSocketOnVisible)
  398. .onConnected(_ledWebSocketOnConnected)
  399. .onKeyCheck(_ledWebSocketOnKeyCheck);
  400. #endif
  401. #if RELAY_SUPPORT
  402. relaySetStatusNotify([](size_t, bool) {
  403. ledUpdate(true);
  404. });
  405. #endif
  406. DEBUG_MSG_P(PSTR("[LED] Number of leds: %d\n"), _leds.size());
  407. // Main callbacks
  408. espurnaRegisterLoop(ledLoop);
  409. espurnaRegisterReload(_ledConfigure);
  410. }
  411. #endif // LED_SUPPORT