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.

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