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.

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