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.

1518 lines
44 KiB

5 years ago
5 years ago
Terminal: change command-line parser (#2247) Change the underlying command line handling: - switch to a custom parser, inspired by redis / sds - update terminalRegisterCommand signature, pass only bare minimum - clean-up `help` & `commands`. update settings `set`, `get` and `del` - allow our custom test suite to run command-line tests - clean-up Stream IO to allow us to print large things into debug stream (for example, `eeprom.dump`) - send parsing errors to the debug log As a proof of concept, introduce `TERMINAL_MQTT_SUPPORT` and `TERMINAL_WEB_API_SUPPORT` - MQTT subscribes to the `<root>/cmd/set` and sends response to the `<root>/cmd`. We can't output too much, as we don't have any large-send API. - Web API listens to the `/api/cmd?apikey=...&line=...` (or PUT, params inside the body). This one is intended as a possible replacement of the `API_SUPPORT`. Internals introduce a 'task' around the AsyncWebServerRequest object that will simulate what WiFiClient does and push data into it continuously, switching between CONT and SYS. Both are experimental. We only accept a single command and not every command is updated to use Print `ctx.output` object. We are also somewhat limited by the Print / Stream overall, perhaps I am overestimating the usefulness of Arduino compatibility to such an extent :) Web API handler can also sometimes show only part of the result, whenever the command tries to yield() by itself waiting for something. Perhaps we would need to create a custom request handler for that specific use-case.
4 years ago
Terminal: change command-line parser (#2247) Change the underlying command line handling: - switch to a custom parser, inspired by redis / sds - update terminalRegisterCommand signature, pass only bare minimum - clean-up `help` & `commands`. update settings `set`, `get` and `del` - allow our custom test suite to run command-line tests - clean-up Stream IO to allow us to print large things into debug stream (for example, `eeprom.dump`) - send parsing errors to the debug log As a proof of concept, introduce `TERMINAL_MQTT_SUPPORT` and `TERMINAL_WEB_API_SUPPORT` - MQTT subscribes to the `<root>/cmd/set` and sends response to the `<root>/cmd`. We can't output too much, as we don't have any large-send API. - Web API listens to the `/api/cmd?apikey=...&line=...` (or PUT, params inside the body). This one is intended as a possible replacement of the `API_SUPPORT`. Internals introduce a 'task' around the AsyncWebServerRequest object that will simulate what WiFiClient does and push data into it continuously, switching between CONT and SYS. Both are experimental. We only accept a single command and not every command is updated to use Print `ctx.output` object. We are also somewhat limited by the Print / Stream overall, perhaps I am overestimating the usefulness of Arduino compatibility to such an extent :) Web API handler can also sometimes show only part of the result, whenever the command tries to yield() by itself waiting for something. Perhaps we would need to create a custom request handler for that specific use-case.
4 years ago
Terminal: change command-line parser (#2247) Change the underlying command line handling: - switch to a custom parser, inspired by redis / sds - update terminalRegisterCommand signature, pass only bare minimum - clean-up `help` & `commands`. update settings `set`, `get` and `del` - allow our custom test suite to run command-line tests - clean-up Stream IO to allow us to print large things into debug stream (for example, `eeprom.dump`) - send parsing errors to the debug log As a proof of concept, introduce `TERMINAL_MQTT_SUPPORT` and `TERMINAL_WEB_API_SUPPORT` - MQTT subscribes to the `<root>/cmd/set` and sends response to the `<root>/cmd`. We can't output too much, as we don't have any large-send API. - Web API listens to the `/api/cmd?apikey=...&line=...` (or PUT, params inside the body). This one is intended as a possible replacement of the `API_SUPPORT`. Internals introduce a 'task' around the AsyncWebServerRequest object that will simulate what WiFiClient does and push data into it continuously, switching between CONT and SYS. Both are experimental. We only accept a single command and not every command is updated to use Print `ctx.output` object. We are also somewhat limited by the Print / Stream overall, perhaps I am overestimating the usefulness of Arduino compatibility to such an extent :) Web API handler can also sometimes show only part of the result, whenever the command tries to yield() by itself waiting for something. Perhaps we would need to create a custom request handler for that specific use-case.
4 years ago
Terminal: change command-line parser (#2247) Change the underlying command line handling: - switch to a custom parser, inspired by redis / sds - update terminalRegisterCommand signature, pass only bare minimum - clean-up `help` & `commands`. update settings `set`, `get` and `del` - allow our custom test suite to run command-line tests - clean-up Stream IO to allow us to print large things into debug stream (for example, `eeprom.dump`) - send parsing errors to the debug log As a proof of concept, introduce `TERMINAL_MQTT_SUPPORT` and `TERMINAL_WEB_API_SUPPORT` - MQTT subscribes to the `<root>/cmd/set` and sends response to the `<root>/cmd`. We can't output too much, as we don't have any large-send API. - Web API listens to the `/api/cmd?apikey=...&line=...` (or PUT, params inside the body). This one is intended as a possible replacement of the `API_SUPPORT`. Internals introduce a 'task' around the AsyncWebServerRequest object that will simulate what WiFiClient does and push data into it continuously, switching between CONT and SYS. Both are experimental. We only accept a single command and not every command is updated to use Print `ctx.output` object. We are also somewhat limited by the Print / Stream overall, perhaps I am overestimating the usefulness of Arduino compatibility to such an extent :) Web API handler can also sometimes show only part of the result, whenever the command tries to yield() by itself waiting for something. Perhaps we would need to create a custom request handler for that specific use-case.
4 years ago
  1. /*
  2. RELAY MODULE
  3. Copyright (C) 2016-2019 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #include "relay.h"
  6. #if RELAY_SUPPORT
  7. #include <Ticker.h>
  8. #include <ArduinoJson.h>
  9. #include <vector>
  10. #include <functional>
  11. #include <bitset>
  12. #include "api.h"
  13. #include "broker.h"
  14. #include "light.h"
  15. #include "mqtt.h"
  16. #include "rfbridge.h"
  17. #include "rpc.h"
  18. #include "rtcmem.h"
  19. #include "settings.h"
  20. #include "storage_eeprom.h"
  21. #include "tuya.h"
  22. #include "utils.h"
  23. #include "ws.h"
  24. #include "mcp23s08.h"
  25. #include "libs/BasePin.h"
  26. #include "relay_config.h"
  27. struct DummyPin final : public BasePin {
  28. DummyPin(unsigned char pin) :
  29. BasePin(pin)
  30. {}
  31. void pinMode(int8_t) override {}
  32. void digitalWrite(int8_t) override {}
  33. int digitalRead() override { return 0; }
  34. };
  35. struct relay_t {
  36. using pin_type = BasePin;
  37. // Share the same dummy pin between different relays, no need to duplicate
  38. static pin_type* DummyPinInstance;
  39. // Default to empty relay configuration, as we allow switches to exist without real GPIOs
  40. relay_t() = default;
  41. relay_t(pin_type* pin_, unsigned char type_, pin_type* reset_pin_) :
  42. pin(pin_),
  43. reset_pin(reset_pin_),
  44. type(type_)
  45. {}
  46. pin_type* pin { DummyPinInstance }; // GPIO pin for the relay
  47. pin_type* reset_pin { DummyPinInstance }; // GPIO to reset the relay if RELAY_TYPE_LATCHED
  48. unsigned char type { RELAY_TYPE_NORMAL }; // RELAY_TYPE_NORMAL, RELAY_TYPE_INVERSE, RELAY_TYPE_LATCHED or RELAY_TYPE_LATCHED_INVERSE
  49. unsigned long delay_on { 0ul }; // Delay to turn relay ON
  50. unsigned long delay_off { 0ul }; // Delay to turn relay OFF
  51. unsigned char pulse { RELAY_PULSE_NONE }; // RELAY_PULSE_NONE, RELAY_PULSE_OFF or RELAY_PULSE_ON
  52. unsigned long pulse_ms { 0ul }; // Pulse length in millis
  53. // Status variables
  54. bool current_status { false }; // Holds the current (physical) status of the relay
  55. bool target_status { false }; // Holds the target status
  56. unsigned char lock { RELAY_LOCK_DISABLED }; // Holds the value of target status, that cannot be changed afterwards. (0 for false, 1 for true, 2 to disable)
  57. unsigned long fw_start { 0ul }; // Flood window start time
  58. unsigned char fw_count { 0u }; // Number of changes within the current flood window
  59. unsigned long change_start { 0ul }; // Time when relay was scheduled to change
  60. unsigned long change_delay { 0ul }; // Delay until the next change
  61. bool report { false }; // Whether to report to own topic
  62. bool group_report { false }; // Whether to report to group topic
  63. // Helper objects
  64. Ticker pulseTicker; // Holds the pulse back timer
  65. };
  66. BasePin* relay_t::DummyPinInstance = new DummyPin(GPIO_NONE);
  67. std::vector<relay_t> _relays;
  68. bool _relayRecursive = false;
  69. size_t _relayDummy = 0;
  70. unsigned long _relay_flood_window = (1000 * RELAY_FLOOD_WINDOW);
  71. unsigned long _relay_flood_changes = RELAY_FLOOD_CHANGES;
  72. unsigned long _relay_delay_interlock;
  73. unsigned char _relay_sync_mode = RELAY_SYNC_ANY;
  74. bool _relay_sync_locked = false;
  75. Ticker _relay_save_timer;
  76. Ticker _relay_sync_timer;
  77. #if WEB_SUPPORT
  78. bool _relay_report_ws = false;
  79. #endif // WEB_SUPPORT
  80. #if MQTT_SUPPORT || API_SUPPORT
  81. String _relay_rpc_payload_on;
  82. String _relay_rpc_payload_off;
  83. String _relay_rpc_payload_toggle;
  84. #endif // MQTT_SUPPORT || API_SUPPORT
  85. // -----------------------------------------------------------------------------
  86. // UTILITY
  87. // -----------------------------------------------------------------------------
  88. bool _relayHandlePayload(unsigned char relayID, const char* payload) {
  89. auto value = relayParsePayload(payload);
  90. if (value == PayloadStatus::Unknown) return false;
  91. if (value == PayloadStatus::Off) {
  92. relayStatus(relayID, false);
  93. } else if (value == PayloadStatus::On) {
  94. relayStatus(relayID, true);
  95. } else if (value == PayloadStatus::Toggle) {
  96. relayToggle(relayID);
  97. }
  98. return true;
  99. }
  100. PayloadStatus _relayStatusInvert(PayloadStatus status) {
  101. return (status == PayloadStatus::On) ? PayloadStatus::Off : status;
  102. }
  103. PayloadStatus _relayStatusTyped(unsigned char id) {
  104. if (id >= _relays.size()) return PayloadStatus::Off;
  105. const bool status = _relays[id].current_status;
  106. return (status) ? PayloadStatus::On : PayloadStatus::Off;
  107. }
  108. void _relayLockAll() {
  109. for (auto& relay : _relays) {
  110. relay.lock = relay.target_status ? RELAY_LOCK_ON : RELAY_LOCK_OFF;
  111. }
  112. _relay_sync_locked = true;
  113. }
  114. void _relayUnlockAll() {
  115. for (auto& relay : _relays) {
  116. relay.lock = RELAY_LOCK_DISABLED;
  117. }
  118. _relay_sync_locked = false;
  119. }
  120. bool _relayStatusLock(unsigned char id, bool status) {
  121. if (_relays[id].lock != RELAY_LOCK_DISABLED) {
  122. bool lock = _relays[id].lock == RELAY_LOCK_ON;
  123. if ((lock != status) || (lock != _relays[id].target_status)) {
  124. _relays[id].target_status = lock;
  125. _relays[id].change_delay = 0;
  126. return false;
  127. }
  128. }
  129. return true;
  130. }
  131. // https://github.com/xoseperez/espurna/issues/1510#issuecomment-461894516
  132. // completely reset timing on the other relay to sync with this one
  133. // to ensure that they change state sequentially
  134. void _relaySyncRelaysDelay(unsigned char first, unsigned char second) {
  135. _relays[second].fw_start = _relays[first].change_start;
  136. _relays[second].fw_count = 1;
  137. _relays[second].change_delay = std::max({
  138. _relay_delay_interlock,
  139. _relays[first].change_delay,
  140. _relays[second].change_delay
  141. });
  142. }
  143. void _relaySyncUnlock() {
  144. bool unlock = true;
  145. bool all_off = true;
  146. for (const auto& relay : _relays) {
  147. unlock = unlock && (relay.current_status == relay.target_status);
  148. if (!unlock) break;
  149. all_off = all_off && !relay.current_status;
  150. }
  151. if (!unlock) return;
  152. auto action = []() {
  153. _relayUnlockAll();
  154. #if WEB_SUPPORT
  155. _relay_report_ws = true;
  156. #endif
  157. };
  158. if (all_off) {
  159. _relay_sync_timer.once_ms(_relay_delay_interlock, action);
  160. } else {
  161. action();
  162. }
  163. }
  164. // -----------------------------------------------------------------------------
  165. // RELAY PROVIDERS
  166. // -----------------------------------------------------------------------------
  167. void _relayProviderStatus(unsigned char id, bool status) {
  168. // Check relay ID
  169. if (id >= _relays.size()) return;
  170. // Store new current status
  171. _relays[id].current_status = status;
  172. #if RELAY_PROVIDER == RELAY_PROVIDER_RFBRIDGE
  173. rfbStatus(id, status);
  174. #endif
  175. #if RELAY_PROVIDER == RELAY_PROVIDER_DUAL
  176. // Calculate mask
  177. unsigned char mask=0;
  178. for (unsigned char i=0; i<_relays.size(); i++) {
  179. if (_relays[i].current_status) mask = mask + (1 << i);
  180. }
  181. DEBUG_MSG_P(PSTR("[RELAY] [DUAL] Sending relay mask: %d\n"), mask);
  182. // Send it to F330
  183. Serial.flush();
  184. Serial.write(0xA0);
  185. Serial.write(0x04);
  186. Serial.write(mask);
  187. Serial.write(0xA1);
  188. Serial.flush();
  189. #endif
  190. #if RELAY_PROVIDER == RELAY_PROVIDER_STM
  191. Serial.flush();
  192. Serial.write(0xA0);
  193. Serial.write(id + 1);
  194. Serial.write(status);
  195. Serial.write(0xA1 + status + id);
  196. // The serial init are not full recognized by relais board.
  197. // References: https://github.com/xoseperez/espurna/issues/1519 , https://github.com/xoseperez/espurna/issues/1130
  198. delay(100);
  199. Serial.flush();
  200. #endif
  201. #if RELAY_PROVIDER == RELAY_PROVIDER_LIGHT
  202. // Real relays
  203. size_t physical = _relays.size() - _relayDummy;
  204. // Support for a mixed of dummy and real relays
  205. // Reference: https://github.com/xoseperez/espurna/issues/1305
  206. if (id >= physical) {
  207. // If the number of dummy relays matches the number of light channels
  208. // assume each relay controls one channel.
  209. // If the number of dummy relays is the number of channels plus 1
  210. // assume the first one controls all the channels and
  211. // the rest one channel each.
  212. // Otherwise every dummy relay controls all channels.
  213. if (_relayDummy == lightChannels()) {
  214. lightState(id-physical, status);
  215. lightState(true);
  216. } else if (_relayDummy == (lightChannels() + 1u)) {
  217. if (id == physical) {
  218. lightState(status);
  219. } else {
  220. lightState(id-1-physical, status);
  221. }
  222. } else {
  223. lightState(status);
  224. }
  225. lightUpdate(true, true);
  226. return;
  227. }
  228. #endif
  229. #if (RELAY_PROVIDER == RELAY_PROVIDER_RELAY) || \
  230. (RELAY_PROVIDER == RELAY_PROVIDER_LIGHT) || \
  231. (RELAY_PROVIDER == RELAY_PROVIDER_MCP23S08)
  232. // If this is a light, all dummy relays have already been processed above
  233. // we reach here if the user has toggled a physical relay
  234. if (_relays[id].type == RELAY_TYPE_NORMAL) {
  235. _relays[id].pin->digitalWrite(status);
  236. } else if (_relays[id].type == RELAY_TYPE_INVERSE) {
  237. _relays[id].pin->digitalWrite(!status);
  238. } else if (_relays[id].type == RELAY_TYPE_LATCHED || _relays[id].type == RELAY_TYPE_LATCHED_INVERSE) {
  239. bool pulse = (_relays[id].type == RELAY_TYPE_LATCHED) ? HIGH : LOW;
  240. _relays[id].pin->digitalWrite(!pulse);
  241. if (GPIO_NONE != _relays[id].reset_pin->pin) {
  242. _relays[id].reset_pin->digitalWrite(!pulse);
  243. }
  244. if (status || (GPIO_NONE == _relays[id].reset_pin->pin)) {
  245. _relays[id].pin->digitalWrite(pulse);
  246. } else {
  247. _relays[id].reset_pin->digitalWrite(pulse);
  248. }
  249. nice_delay(RELAY_LATCHING_PULSE);
  250. _relays[id].pin->digitalWrite(!pulse);
  251. if (GPIO_NONE != _relays[id].reset_pin->pin) {
  252. _relays[id].reset_pin->digitalWrite(!pulse);
  253. }
  254. }
  255. #endif
  256. }
  257. /**
  258. * Walks the relay vector processing only those relays
  259. * that have to change to the requested mode
  260. * @bool mode Requested mode
  261. */
  262. void _relayProcess(bool mode) {
  263. bool changed = false;
  264. for (unsigned char id = 0; id < _relays.size(); id++) {
  265. bool target = _relays[id].target_status;
  266. // Only process the relays we have to change
  267. if (target == _relays[id].current_status) continue;
  268. // Only process the relays we have to change to the requested mode
  269. if (target != mode) continue;
  270. // Only process if the change delay has expired
  271. if (_relays[id].change_delay && (millis() - _relays[id].change_start < _relays[id].change_delay)) continue;
  272. // Purge existing delay in case of cancelation
  273. _relays[id].change_delay = 0;
  274. changed = true;
  275. DEBUG_MSG_P(PSTR("[RELAY] #%d set to %s\n"), id, target ? "ON" : "OFF");
  276. // Call the provider to perform the action
  277. _relayProviderStatus(id, target);
  278. // Send to Broker
  279. #if BROKER_SUPPORT
  280. StatusBroker::Publish(MQTT_TOPIC_RELAY, id, target);
  281. #endif
  282. // Send MQTT
  283. #if MQTT_SUPPORT
  284. relayMQTT(id);
  285. #endif
  286. #if WEB_SUPPORT
  287. _relay_report_ws = true;
  288. #endif
  289. if (!_relayRecursive) {
  290. relayPulse(id);
  291. // We will trigger a eeprom save only if
  292. // we care about current relay status on boot
  293. const auto boot_mode = getSetting({"relayBoot", id}, RELAY_BOOT_MODE);
  294. const bool save_eeprom = ((RELAY_BOOT_SAME == boot_mode) || (RELAY_BOOT_TOGGLE == boot_mode));
  295. _relay_save_timer.once_ms(RELAY_SAVE_DELAY, relaySave, save_eeprom);
  296. }
  297. _relays[id].report = false;
  298. _relays[id].group_report = false;
  299. }
  300. // Whenever we are using sync modes and any relay had changed the state, check if we can unlock
  301. const bool needs_unlock = ((_relay_sync_mode == RELAY_SYNC_NONE_OR_ONE) || (_relay_sync_mode == RELAY_SYNC_ONE));
  302. if (_relay_sync_locked && needs_unlock && changed) {
  303. _relaySyncUnlock();
  304. }
  305. }
  306. #if defined(ITEAD_SONOFF_IFAN02)
  307. unsigned char _relay_ifan02_speeds[] = {0, 1, 3, 5};
  308. unsigned char getSpeed() {
  309. unsigned char speed =
  310. (_relays[1].target_status ? 1 : 0) +
  311. (_relays[2].target_status ? 2 : 0) +
  312. (_relays[3].target_status ? 4 : 0);
  313. for (unsigned char i=0; i<4; i++) {
  314. if (_relay_ifan02_speeds[i] == speed) return i;
  315. }
  316. return 0;
  317. }
  318. void setSpeed(unsigned char speed) {
  319. if ((0 <= speed) & (speed <= 3)) {
  320. if (getSpeed() == speed) return;
  321. unsigned char states = _relay_ifan02_speeds[speed];
  322. for (unsigned char i=0; i<3; i++) {
  323. relayStatus(i+1, states & 1 == 1);
  324. states >>= 1;
  325. }
  326. }
  327. }
  328. #endif
  329. // -----------------------------------------------------------------------------
  330. // RELAY
  331. // -----------------------------------------------------------------------------
  332. // State persistance persistance
  333. namespace {
  334. String u32toString(uint32_t value, int base) {
  335. String result;
  336. result.reserve(32 + 2);
  337. if (base == 2) {
  338. result += "0b";
  339. } else if (base == 8) {
  340. result += "0o";
  341. } else if (base == 16) {
  342. result += "0x";
  343. }
  344. char buffer[33] = {0};
  345. ultoa(value, buffer, base);
  346. result += buffer;
  347. return result;
  348. }
  349. struct RelayMask {
  350. const String as_string;
  351. uint32_t as_u32;
  352. };
  353. RelayMask INLINE _relayMask(uint32_t mask) {
  354. return {std::move(u32toString(mask, 2)), mask};
  355. }
  356. RelayMask INLINE _relayMaskRtcmem() {
  357. return _relayMask(Rtcmem->relay);
  358. }
  359. void INLINE _relayMaskRtcmem(uint32_t mask) {
  360. Rtcmem->relay = mask;
  361. }
  362. void INLINE _relayMaskRtcmem(const RelayMask& mask) {
  363. _relayMaskRtcmem(mask.as_u32);
  364. }
  365. void INLINE _relayMaskRtcmem(const std::bitset<RelaysMax>& bitset) {
  366. _relayMaskRtcmem(bitset.to_ulong());
  367. }
  368. RelayMask INLINE _relayMaskSettings() {
  369. constexpr unsigned long defaultMask { 0ul };
  370. auto value = getSetting("relayBootMask", defaultMask);
  371. return _relayMask(value);
  372. }
  373. void INLINE _relayMaskSettings(uint32_t mask) {
  374. setSetting("relayBootMask", u32toString(mask, 2));
  375. }
  376. void INLINE _relayMaskSettings(const RelayMask& mask) {
  377. setSetting("relayBootMask", mask.as_string);
  378. }
  379. void INLINE _relayMaskSettings(const std::bitset<RelaysMax>& bitset) {
  380. _relayMaskSettings(bitset.to_ulong());
  381. }
  382. } // ns anonymous
  383. // Pulse timers (timer after ON or OFF event)
  384. void relayPulse(unsigned char id) {
  385. _relays[id].pulseTicker.detach();
  386. byte mode = _relays[id].pulse;
  387. if (mode == RELAY_PULSE_NONE) return;
  388. unsigned long ms = _relays[id].pulse_ms;
  389. if (ms == 0) return;
  390. bool status = relayStatus(id);
  391. bool pulseStatus = (mode == RELAY_PULSE_ON);
  392. if (pulseStatus != status) {
  393. DEBUG_MSG_P(PSTR("[RELAY] Scheduling relay #%d back in %lums (pulse)\n"), id, ms);
  394. _relays[id].pulseTicker.once_ms(ms, relayToggle, id);
  395. // Reconfigure after dynamic pulse
  396. _relays[id].pulse = getSetting({"relayPulse", id}, RELAY_PULSE_MODE);
  397. _relays[id].pulse_ms = 1000 * getSetting({"relayTime", id}, 0.);
  398. }
  399. }
  400. // General relay status control
  401. bool relayStatus(unsigned char id, bool status, bool report, bool group_report) {
  402. if (id == RELAY_NONE) return false;
  403. if (id >= _relays.size()) return false;
  404. if (!_relayStatusLock(id, status)) {
  405. DEBUG_MSG_P(PSTR("[RELAY] #%d is locked to %s\n"), id, _relays[id].current_status ? "ON" : "OFF");
  406. _relays[id].report = true;
  407. _relays[id].group_report = true;
  408. return false;
  409. }
  410. bool changed = false;
  411. if (_relays[id].current_status == status) {
  412. if (_relays[id].target_status != status) {
  413. DEBUG_MSG_P(PSTR("[RELAY] #%d scheduled change cancelled\n"), id);
  414. _relays[id].target_status = status;
  415. _relays[id].report = false;
  416. _relays[id].group_report = false;
  417. _relays[id].change_delay = 0;
  418. changed = true;
  419. }
  420. // For RFBridge, keep sending the message even if the status is already the required
  421. #if RELAY_PROVIDER == RELAY_PROVIDER_RFBRIDGE
  422. rfbStatus(id, status);
  423. #endif
  424. // Update the pulse counter if the relay is already in the non-normal state (#454)
  425. relayPulse(id);
  426. } else {
  427. unsigned long current_time = millis();
  428. unsigned long change_delay = status ? _relays[id].delay_on : _relays[id].delay_off;
  429. _relays[id].fw_count++;
  430. _relays[id].change_start = current_time;
  431. _relays[id].change_delay = std::max(_relays[id].change_delay, change_delay);
  432. // If current_time is off-limits the floodWindow...
  433. const auto fw_diff = current_time - _relays[id].fw_start;
  434. if (fw_diff > _relay_flood_window) {
  435. // We reset the floodWindow
  436. _relays[id].fw_start = current_time;
  437. _relays[id].fw_count = 1;
  438. // If current_time is in the floodWindow and there have been too many requests...
  439. } else if (_relays[id].fw_count >= _relay_flood_changes) {
  440. // We schedule the changes to the end of the floodWindow
  441. // unless it's already delayed beyond that point
  442. _relays[id].change_delay = std::max(change_delay, _relay_flood_window - fw_diff);
  443. // Another option is to always move it forward, starting from current time
  444. //_relays[id].fw_start = current_time;
  445. }
  446. _relays[id].target_status = status;
  447. if (report) _relays[id].report = true;
  448. if (group_report) _relays[id].group_report = true;
  449. relaySync(id);
  450. DEBUG_MSG_P(PSTR("[RELAY] #%d scheduled %s in %u ms\n"),
  451. id, status ? "ON" : "OFF", _relays[id].change_delay
  452. );
  453. changed = true;
  454. }
  455. return changed;
  456. }
  457. bool relayStatus(unsigned char id, bool status) {
  458. #if MQTT_SUPPORT
  459. return relayStatus(id, status, mqttForward(), true);
  460. #else
  461. return relayStatus(id, status, false, true);
  462. #endif
  463. }
  464. bool relayStatus(unsigned char id) {
  465. // Check that relay ID is valid
  466. if (id >= _relays.size()) return false;
  467. // Get status directly from storage
  468. return _relays[id].current_status;
  469. }
  470. bool relayStatusTarget(unsigned char id) {
  471. if (id >= _relays.size()) return false;
  472. return _relays[id].target_status;
  473. }
  474. void relaySync(unsigned char id) {
  475. // No sync if none or only one relay
  476. if (_relays.size() < 2) return;
  477. // Do not go on if we are comming from a previous sync
  478. if (_relayRecursive) return;
  479. // Flag sync mode
  480. _relayRecursive = true;
  481. bool status = _relays[id].target_status;
  482. // If RELAY_SYNC_SAME all relays should have the same state
  483. if (_relay_sync_mode == RELAY_SYNC_SAME) {
  484. for (unsigned short i=0; i<_relays.size(); i++) {
  485. if (i != id) relayStatus(i, status);
  486. }
  487. // If RELAY_SYNC_FIRST all relays should have the same state as first if first changes
  488. } else if (_relay_sync_mode == RELAY_SYNC_FIRST) {
  489. if (id == 0) {
  490. for (unsigned short i=1; i<_relays.size(); i++) {
  491. relayStatus(i, status);
  492. }
  493. }
  494. } else if ((_relay_sync_mode == RELAY_SYNC_NONE_OR_ONE) || (_relay_sync_mode == RELAY_SYNC_ONE)) {
  495. // If NONE_OR_ONE or ONE and setting ON we should set OFF all the others
  496. if (status) {
  497. if (_relay_sync_mode != RELAY_SYNC_ANY) {
  498. for (unsigned short other_id=0; other_id<_relays.size(); other_id++) {
  499. if (other_id != id) {
  500. relayStatus(other_id, false);
  501. if (relayStatus(other_id)) {
  502. _relaySyncRelaysDelay(other_id, id);
  503. }
  504. }
  505. }
  506. }
  507. // If ONLY_ONE and setting OFF we should set ON the other one
  508. } else {
  509. if (_relay_sync_mode == RELAY_SYNC_ONE) {
  510. unsigned char other_id = (id + 1) % _relays.size();
  511. _relaySyncRelaysDelay(id, other_id);
  512. relayStatus(other_id, true);
  513. }
  514. }
  515. _relayLockAll();
  516. }
  517. // Unflag sync mode
  518. _relayRecursive = false;
  519. }
  520. void relaySave(bool eeprom) {
  521. const unsigned char count = constrain(relayCount(), 0, RelaysMax);
  522. auto statuses = std::bitset<RelaysMax>(0);
  523. for (unsigned int id = 0; id < count; ++id) {
  524. statuses.set(id, relayStatus(id));
  525. }
  526. const auto mask = _relayMask(statuses.to_ulong() & 0xffffffffu);
  527. DEBUG_MSG_P(PSTR("[RELAY] Setting relay mask: %s\n"), mask.as_string.c_str());
  528. // Persist only to rtcmem, unless requested to save to the eeprom
  529. _relayMaskRtcmem(mask);
  530. // The 'eeprom' flag controls whether we are commiting this change or not.
  531. // It is useful to set it to 'false' if the relay change triggering the
  532. // save involves a relay whose boot mode is independent from current mode,
  533. // thus storing the last relay value is not absolutely necessary.
  534. // Nevertheless, we store the value in the EEPROM buffer so it will be written
  535. // on the next commit.
  536. if (eeprom) {
  537. _relayMaskSettings(mask);
  538. // We are actually enqueuing the commit so it will be
  539. // executed on the main loop, in case this is called from a system context callback
  540. eepromCommit();
  541. }
  542. }
  543. void relaySave() {
  544. relaySave(false);
  545. }
  546. void relayToggle(unsigned char id, bool report, bool group_report) {
  547. if (id >= _relays.size()) return;
  548. relayStatus(id, !relayStatus(id), report, group_report);
  549. }
  550. void relayToggle(unsigned char id) {
  551. #if MQTT_SUPPORT
  552. relayToggle(id, mqttForward(), true);
  553. #else
  554. relayToggle(id, false, true);
  555. #endif
  556. }
  557. unsigned char relayCount() {
  558. return _relays.size();
  559. }
  560. PayloadStatus relayParsePayload(const char * payload) {
  561. #if MQTT_SUPPORT || API_SUPPORT
  562. return rpcParsePayload(payload, [](const char* payload) {
  563. if (_relay_rpc_payload_off.equals(payload)) return PayloadStatus::Off;
  564. if (_relay_rpc_payload_on.equals(payload)) return PayloadStatus::On;
  565. if (_relay_rpc_payload_toggle.equals(payload)) return PayloadStatus::Toggle;
  566. return PayloadStatus::Unknown;
  567. });
  568. #else
  569. return rpcParsePayload(payload);
  570. #endif
  571. }
  572. // BACKWARDS COMPATIBILITY
  573. void _relayBackwards() {
  574. for (unsigned char id = 0; id < _relays.size(); ++id) {
  575. const settings_key_t key {"mqttGroupInv", id};
  576. if (!hasSetting(key)) continue;
  577. setSetting({"mqttGroupSync", id}, getSetting(key));
  578. delSetting(key);
  579. }
  580. }
  581. void _relayBoot() {
  582. _relayRecursive = true;
  583. const auto stored_mask = rtcmemStatus()
  584. ? _relayMaskRtcmem()
  585. : _relayMaskSettings();
  586. DEBUG_MSG_P(PSTR("[RELAY] Retrieving mask: %s\n"), stored_mask.as_string.c_str());
  587. auto mask = std::bitset<RelaysMax>(stored_mask.as_u32);
  588. // Walk the relays
  589. unsigned char lock;
  590. bool status;
  591. for (unsigned char i=0; i<relayCount(); ++i) {
  592. const auto boot_mode = getSetting({"relayBoot", i}, RELAY_BOOT_MODE);
  593. DEBUG_MSG_P(PSTR("[RELAY] Relay #%u boot mode %d\n"), i, boot_mode);
  594. status = false;
  595. lock = RELAY_LOCK_DISABLED;
  596. switch (boot_mode) {
  597. case RELAY_BOOT_SAME:
  598. status = mask.test(i);
  599. break;
  600. case RELAY_BOOT_TOGGLE:
  601. mask.flip(i);
  602. status = mask[i];
  603. break;
  604. case RELAY_BOOT_LOCKED_ON:
  605. status = true;
  606. lock = RELAY_LOCK_ON;
  607. break;
  608. case RELAY_BOOT_LOCKED_OFF:
  609. lock = RELAY_LOCK_OFF;
  610. break;
  611. case RELAY_BOOT_ON:
  612. status = true;
  613. break;
  614. case RELAY_BOOT_OFF:
  615. default:
  616. break;
  617. }
  618. _relays[i].current_status = !status;
  619. _relays[i].target_status = status;
  620. _relays[i].change_start = millis();
  621. _relays[i].change_delay = status
  622. ? _relays[i].delay_on
  623. : _relays[i].delay_off;
  624. #if RELAY_PROVIDER == RELAY_PROVIDER_STM
  625. // XXX hack for correctly restoring relay state on boot
  626. // because of broken stm relay firmware
  627. _relays[i].change_delay = 3000 + 1000 * i;
  628. #endif
  629. _relays[i].lock = lock;
  630. }
  631. _relayRecursive = false;
  632. #if TUYA_SUPPORT
  633. Tuya::tuyaSyncSwitchStatus();
  634. #endif
  635. }
  636. void _relayConfigure() {
  637. for (unsigned char i = 0, relays = _relays.size() ; (i < relays); ++i) {
  638. _relays[i].pulse = getSetting({"relayPulse", i}, RELAY_PULSE_MODE);
  639. _relays[i].pulse_ms = 1000 * getSetting({"relayTime", i}, 0.);
  640. _relays[i].delay_on = getSetting({"relayDelayOn", i}, _relayDelayOn(i));
  641. _relays[i].delay_off = getSetting({"relayDelayOff", i}, _relayDelayOff(i));
  642. // make sure pin is valid before continuing with writes
  643. if (!static_cast<bool>(*_relays[i].pin)) continue;
  644. _relays[i].pin->pinMode(OUTPUT);
  645. if (static_cast<bool>(*_relays[i].reset_pin)) {
  646. _relays[i].reset_pin->pinMode(OUTPUT);
  647. }
  648. if (_relays[i].type == RELAY_TYPE_INVERSE) {
  649. //set to high to block short opening of relay
  650. _relays[i].pin->digitalWrite(HIGH);
  651. }
  652. }
  653. _relay_flood_window = (1000 * getSetting("relayFloodTime", RELAY_FLOOD_WINDOW));
  654. _relay_flood_changes = getSetting("relayFloodChanges", RELAY_FLOOD_CHANGES);
  655. _relay_delay_interlock = getSetting("relayDelayInterlock", RELAY_DELAY_INTERLOCK);
  656. _relay_sync_mode = getSetting("relaySync", RELAY_SYNC);
  657. #if MQTT_SUPPORT || API_SUPPORT
  658. settingsProcessConfig({
  659. {_relay_rpc_payload_on, "relayPayloadOn", RELAY_MQTT_ON},
  660. {_relay_rpc_payload_off, "relayPayloadOff", RELAY_MQTT_OFF},
  661. {_relay_rpc_payload_toggle, "relayPayloadToggle", RELAY_MQTT_TOGGLE},
  662. });
  663. #endif // MQTT_SUPPORT
  664. }
  665. //------------------------------------------------------------------------------
  666. // WEBSOCKETS
  667. //------------------------------------------------------------------------------
  668. #if WEB_SUPPORT
  669. bool _relayWebSocketOnKeyCheck(const char * key, JsonVariant& value) {
  670. return (strncmp(key, "relay", 5) == 0);
  671. }
  672. void _relayWebSocketUpdate(JsonObject& root) {
  673. JsonObject& state = root.createNestedObject("relayState");
  674. state["size"] = relayCount();
  675. JsonArray& status = state.createNestedArray("status");
  676. JsonArray& lock = state.createNestedArray("lock");
  677. // Note: we use byte instead of bool to ever so slightly compress json output
  678. for (unsigned char i=0; i<relayCount(); i++) {
  679. status.add<uint8_t>(_relays[i].target_status);
  680. lock.add(_relays[i].lock);
  681. }
  682. }
  683. String _relayFriendlyName(unsigned char i) {
  684. String res = String("GPIO") + String(_relays[i].pin->pin);
  685. if (GPIO_NONE == _relays[i].pin->pin) {
  686. #if (RELAY_PROVIDER == RELAY_PROVIDER_LIGHT)
  687. uint8_t physical = _relays.size() - _relayDummy;
  688. if (i >= physical) {
  689. if (_relayDummy == lightChannels()) {
  690. res = String("CH") + String(i-physical);
  691. } else if (_relayDummy == (lightChannels() + 1u)) {
  692. if (physical == i) {
  693. res = String("Light");
  694. } else {
  695. res = String("CH") + String(i-1-physical);
  696. }
  697. } else {
  698. res = String("Light");
  699. }
  700. } else {
  701. res = String("?");
  702. }
  703. #else
  704. res = String("SW") + String(i);
  705. #endif
  706. }
  707. return res;
  708. }
  709. void _relayWebSocketSendRelays(JsonObject& root) {
  710. JsonObject& relays = root.createNestedObject("relayConfig");
  711. relays["size"] = relayCount();
  712. relays["start"] = 0;
  713. JsonArray& gpio = relays.createNestedArray("gpio");
  714. JsonArray& type = relays.createNestedArray("type");
  715. JsonArray& reset = relays.createNestedArray("reset");
  716. JsonArray& boot = relays.createNestedArray("boot");
  717. JsonArray& pulse = relays.createNestedArray("pulse");
  718. JsonArray& pulse_time = relays.createNestedArray("pulse_time");
  719. #if SCHEDULER_SUPPORT
  720. JsonArray& sch_last = relays.createNestedArray("sch_last");
  721. #endif
  722. #if MQTT_SUPPORT
  723. JsonArray& group = relays.createNestedArray("group");
  724. JsonArray& group_sync = relays.createNestedArray("group_sync");
  725. JsonArray& on_disconnect = relays.createNestedArray("on_disc");
  726. #endif
  727. for (unsigned char i=0; i<relayCount(); i++) {
  728. gpio.add(_relayFriendlyName(i));
  729. type.add(_relays[i].type);
  730. reset.add(_relays[i].reset_pin->pin);
  731. boot.add(getSetting({"relayBoot", i}, RELAY_BOOT_MODE));
  732. pulse.add(_relays[i].pulse);
  733. pulse_time.add(_relays[i].pulse_ms / 1000.0);
  734. #if SCHEDULER_SUPPORT
  735. sch_last.add(getSetting({"relayLastSch", i}, SCHEDULER_RESTORE_LAST_SCHEDULE));
  736. #endif
  737. #if MQTT_SUPPORT
  738. group.add(getSetting({"mqttGroup", i}));
  739. group_sync.add(getSetting({"mqttGroupSync", i}, 0));
  740. on_disconnect.add(getSetting({"relayOnDisc", i}, 0));
  741. #endif
  742. }
  743. }
  744. void _relayWebSocketOnVisible(JsonObject& root) {
  745. if (relayCount() == 0) return;
  746. if (relayCount() > 1) {
  747. root["multirelayVisible"] = 1;
  748. root["relaySync"] = getSetting("relaySync", RELAY_SYNC);
  749. }
  750. root["relayVisible"] = 1;
  751. }
  752. void _relayWebSocketOnConnected(JsonObject& root) {
  753. if (relayCount() == 0) return;
  754. // Per-relay configuration
  755. _relayWebSocketSendRelays(root);
  756. }
  757. void _relayWebSocketOnAction(uint32_t client_id, const char * action, JsonObject& data) {
  758. if (strcmp(action, "relay") != 0) return;
  759. if (data.containsKey("status")) {
  760. unsigned int relayID = 0;
  761. if (data.containsKey("id") && data.is<int>("id")) {
  762. relayID = data["id"];
  763. }
  764. _relayHandlePayload(relayID, data["status"]);
  765. }
  766. }
  767. void relaySetupWS() {
  768. wsRegister()
  769. .onVisible(_relayWebSocketOnVisible)
  770. .onConnected(_relayWebSocketOnConnected)
  771. .onData(_relayWebSocketUpdate)
  772. .onAction(_relayWebSocketOnAction)
  773. .onKeyCheck(_relayWebSocketOnKeyCheck);
  774. }
  775. #endif // WEB_SUPPORT
  776. //------------------------------------------------------------------------------
  777. // REST API
  778. //------------------------------------------------------------------------------
  779. #if API_SUPPORT
  780. void relaySetupAPI() {
  781. char key[20];
  782. // API entry points (protected with apikey)
  783. for (unsigned int relayID=0; relayID<relayCount(); relayID++) {
  784. snprintf_P(key, sizeof(key), PSTR("%s/%d"), MQTT_TOPIC_RELAY, relayID);
  785. apiRegister(key,
  786. [relayID](char * buffer, size_t len) {
  787. snprintf_P(buffer, len, PSTR("%d"), _relays[relayID].target_status ? 1 : 0);
  788. },
  789. [relayID](const char * payload) {
  790. if (!_relayHandlePayload(relayID, payload)) {
  791. DEBUG_MSG_P(PSTR("[RELAY] Wrong payload (%s)\n"), payload);
  792. return;
  793. }
  794. }
  795. );
  796. snprintf_P(key, sizeof(key), PSTR("%s/%d"), MQTT_TOPIC_PULSE, relayID);
  797. apiRegister(key,
  798. [relayID](char * buffer, size_t len) {
  799. dtostrf((double) _relays[relayID].pulse_ms / 1000, 1, 3, buffer);
  800. },
  801. [relayID](const char * payload) {
  802. unsigned long pulse = 1000 * atof(payload);
  803. if (0 == pulse) return;
  804. if (RELAY_PULSE_NONE != _relays[relayID].pulse) {
  805. DEBUG_MSG_P(PSTR("[RELAY] Overriding relay #%d pulse settings\n"), relayID);
  806. }
  807. _relays[relayID].pulse_ms = pulse;
  808. _relays[relayID].pulse = relayStatus(relayID) ? RELAY_PULSE_ON : RELAY_PULSE_OFF;
  809. relayToggle(relayID, true, false);
  810. }
  811. );
  812. #if defined(ITEAD_SONOFF_IFAN02)
  813. apiRegister(MQTT_TOPIC_SPEED,
  814. [relayID](char * buffer, size_t len) {
  815. snprintf(buffer, len, "%u", getSpeed());
  816. },
  817. [relayID](const char * payload) {
  818. setSpeed(atoi(payload));
  819. }
  820. );
  821. #endif
  822. }
  823. }
  824. #endif // API_SUPPORT
  825. //------------------------------------------------------------------------------
  826. // MQTT
  827. //------------------------------------------------------------------------------
  828. #if MQTT_SUPPORT || API_SUPPORT
  829. const String& relayPayloadOn() {
  830. return _relay_rpc_payload_on;
  831. }
  832. const String& relayPayloadOff() {
  833. return _relay_rpc_payload_off;
  834. }
  835. const String& relayPayloadToggle() {
  836. return _relay_rpc_payload_toggle;
  837. }
  838. const char* relayPayload(PayloadStatus status) {
  839. switch (status) {
  840. case PayloadStatus::Off:
  841. return _relay_rpc_payload_off.c_str();
  842. case PayloadStatus::On:
  843. return _relay_rpc_payload_on.c_str();
  844. case PayloadStatus::Toggle:
  845. return _relay_rpc_payload_toggle.c_str();
  846. case PayloadStatus::Unknown:
  847. default:
  848. return "";
  849. }
  850. }
  851. #endif // MQTT_SUPPORT || API_SUPPORT
  852. #if MQTT_SUPPORT
  853. void _relayMQTTGroup(unsigned char id) {
  854. const String topic = getSetting({"mqttGroup", id});
  855. if (!topic.length()) return;
  856. const auto mode = getSetting({"mqttGroupSync", id}, RELAY_GROUP_SYNC_NORMAL);
  857. if (mode == RELAY_GROUP_SYNC_RECEIVEONLY) return;
  858. auto status = _relayStatusTyped(id);
  859. if (mode == RELAY_GROUP_SYNC_INVERSE) status = _relayStatusInvert(status);
  860. mqttSendRaw(topic.c_str(), relayPayload(status));
  861. }
  862. void relayMQTT(unsigned char id) {
  863. if (id >= _relays.size()) return;
  864. // Send state topic
  865. if (_relays[id].report) {
  866. _relays[id].report = false;
  867. mqttSend(MQTT_TOPIC_RELAY, id, relayPayload(_relayStatusTyped(id)));
  868. }
  869. // Check group topic
  870. if (_relays[id].group_report) {
  871. _relays[id].group_report = false;
  872. _relayMQTTGroup(id);
  873. }
  874. // Send speed for IFAN02
  875. #if defined (ITEAD_SONOFF_IFAN02)
  876. char buffer[5];
  877. snprintf(buffer, sizeof(buffer), "%u", getSpeed());
  878. mqttSend(MQTT_TOPIC_SPEED, buffer);
  879. #endif
  880. }
  881. void relayMQTT() {
  882. for (unsigned int id=0; id < _relays.size(); id++) {
  883. mqttSend(MQTT_TOPIC_RELAY, id, relayPayload(_relayStatusTyped(id)));
  884. }
  885. }
  886. void relayStatusWrap(unsigned char id, PayloadStatus value, bool is_group_topic) {
  887. #if MQTT_SUPPORT
  888. const auto forward = mqttForward();
  889. #else
  890. const auto forward = false;
  891. #endif
  892. switch (value) {
  893. case PayloadStatus::Off:
  894. relayStatus(id, false, forward, !is_group_topic);
  895. break;
  896. case PayloadStatus::On:
  897. relayStatus(id, true, forward, !is_group_topic);
  898. break;
  899. case PayloadStatus::Toggle:
  900. relayToggle(id, true, true);
  901. break;
  902. case PayloadStatus::Unknown:
  903. default:
  904. _relays[id].report = true;
  905. relayMQTT(id);
  906. break;
  907. }
  908. }
  909. void relayMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  910. if (type == MQTT_CONNECT_EVENT) {
  911. // Send status on connect
  912. #if (HEARTBEAT_MODE == HEARTBEAT_NONE) or (not HEARTBEAT_REPORT_RELAY)
  913. relayMQTT();
  914. #endif
  915. // Subscribe to own /set topic
  916. char relay_topic[strlen(MQTT_TOPIC_RELAY) + 3];
  917. snprintf_P(relay_topic, sizeof(relay_topic), PSTR("%s/+"), MQTT_TOPIC_RELAY);
  918. mqttSubscribe(relay_topic);
  919. // Subscribe to pulse topic
  920. char pulse_topic[strlen(MQTT_TOPIC_PULSE) + 3];
  921. snprintf_P(pulse_topic, sizeof(pulse_topic), PSTR("%s/+"), MQTT_TOPIC_PULSE);
  922. mqttSubscribe(pulse_topic);
  923. #if defined(ITEAD_SONOFF_IFAN02)
  924. mqttSubscribe(MQTT_TOPIC_SPEED);
  925. #endif
  926. // Subscribe to group topics
  927. for (unsigned char i=0; i < _relays.size(); i++) {
  928. const auto t = getSetting({"mqttGroup", i});
  929. if (t.length() > 0) mqttSubscribeRaw(t.c_str());
  930. }
  931. }
  932. if (type == MQTT_MESSAGE_EVENT) {
  933. String t = mqttMagnitude((char *) topic);
  934. // magnitude is relay/#/pulse
  935. if (t.startsWith(MQTT_TOPIC_PULSE)) {
  936. unsigned int id = t.substring(strlen(MQTT_TOPIC_PULSE)+1).toInt();
  937. if (id >= relayCount()) {
  938. DEBUG_MSG_P(PSTR("[RELAY] Wrong relayID (%d)\n"), id);
  939. return;
  940. }
  941. unsigned long pulse = 1000 * atof(payload);
  942. if (0 == pulse) return;
  943. if (RELAY_PULSE_NONE != _relays[id].pulse) {
  944. DEBUG_MSG_P(PSTR("[RELAY] Overriding relay #%d pulse settings\n"), id);
  945. }
  946. _relays[id].pulse_ms = pulse;
  947. _relays[id].pulse = relayStatus(id) ? RELAY_PULSE_ON : RELAY_PULSE_OFF;
  948. relayToggle(id, true, false);
  949. return;
  950. }
  951. // magnitude is relay/#
  952. if (t.startsWith(MQTT_TOPIC_RELAY)) {
  953. // Get relay ID
  954. unsigned int id = t.substring(strlen(MQTT_TOPIC_RELAY)+1).toInt();
  955. if (id >= relayCount()) {
  956. DEBUG_MSG_P(PSTR("[RELAY] Wrong relayID (%d)\n"), id);
  957. return;
  958. }
  959. // Get value
  960. auto value = relayParsePayload(payload);
  961. if (value == PayloadStatus::Unknown) return;
  962. relayStatusWrap(id, value, false);
  963. return;
  964. }
  965. // Check group topics
  966. for (unsigned char i=0; i < _relays.size(); i++) {
  967. const String t = getSetting({"mqttGroup", i});
  968. if ((t.length() > 0) && t.equals(topic)) {
  969. auto value = relayParsePayload(payload);
  970. if (value == PayloadStatus::Unknown) return;
  971. if ((value == PayloadStatus::On) || (value == PayloadStatus::Off)) {
  972. if (getSetting({"mqttGroupSync", i}, RELAY_GROUP_SYNC_NORMAL) == RELAY_GROUP_SYNC_INVERSE) {
  973. value = _relayStatusInvert(value);
  974. }
  975. }
  976. DEBUG_MSG_P(PSTR("[RELAY] Matched group topic for relayID %d\n"), i);
  977. relayStatusWrap(i, value, true);
  978. }
  979. }
  980. // Itead Sonoff IFAN02
  981. #if defined (ITEAD_SONOFF_IFAN02)
  982. if (t.startsWith(MQTT_TOPIC_SPEED)) {
  983. setSpeed(atoi(payload));
  984. }
  985. #endif
  986. }
  987. if (type == MQTT_DISCONNECT_EVENT) {
  988. for (unsigned char i=0; i < _relays.size(); i++){
  989. const auto reaction = getSetting({"relayOnDisc", i}, 0);
  990. if (1 == reaction) { // switch relay OFF
  991. DEBUG_MSG_P(PSTR("[RELAY] Reset relay (%d) due to MQTT disconnection\n"), i);
  992. relayStatusWrap(i, PayloadStatus::Off, false);
  993. } else if(2 == reaction) { // switch relay ON
  994. DEBUG_MSG_P(PSTR("[RELAY] Set relay (%d) due to MQTT disconnection\n"), i);
  995. relayStatusWrap(i, PayloadStatus::On, false);
  996. }
  997. }
  998. }
  999. }
  1000. void relaySetupMQTT() {
  1001. mqttRegister(relayMQTTCallback);
  1002. }
  1003. #endif
  1004. void _relaySetupProvider() {
  1005. // TODO: implement something like `RelayProvider tuya_provider({.setup_cb = ..., .send_cb = ...})`?
  1006. // note of the function call order! relay code is initialized before tuya's, and the easiest
  1007. // way to accomplish that is to use ctor as a way to "register" callbacks even before setup() is called
  1008. #if TUYA_SUPPORT
  1009. Tuya::tuyaSetupSwitch();
  1010. #endif
  1011. }
  1012. //------------------------------------------------------------------------------
  1013. // Settings
  1014. //------------------------------------------------------------------------------
  1015. #if TERMINAL_SUPPORT
  1016. void _relayInitCommands() {
  1017. terminalRegisterCommand(F("RELAY"), [](const terminal::CommandContext& ctx) {
  1018. if (ctx.argc < 2) {
  1019. terminalError(F("Wrong arguments"));
  1020. return;
  1021. }
  1022. int id = ctx.argv[1].toInt();
  1023. if (id >= relayCount()) {
  1024. DEBUG_MSG_P(PSTR("-ERROR: Wrong relayID (%d)\n"), id);
  1025. return;
  1026. }
  1027. if (ctx.argc > 2) {
  1028. int value = ctx.argv[2].toInt();
  1029. if (value == 2) {
  1030. relayToggle(id);
  1031. } else {
  1032. relayStatus(id, value == 1);
  1033. }
  1034. }
  1035. DEBUG_MSG_P(PSTR("Status: %s\n"), _relays[id].target_status ? "true" : "false");
  1036. if (_relays[id].pulse != RELAY_PULSE_NONE) {
  1037. DEBUG_MSG_P(PSTR("Pulse: %s\n"), (_relays[id].pulse == RELAY_PULSE_ON) ? "ON" : "OFF");
  1038. DEBUG_MSG_P(PSTR("Pulse time: %d\n"), _relays[id].pulse_ms);
  1039. }
  1040. terminalOK();
  1041. });
  1042. #if 0
  1043. terminalRegisterCommand(F("RELAY.INFO"), [](const terminal::CommandContext&) {
  1044. DEBUG_MSG_P(PSTR(" cur tgt pin type reset lock delay_on delay_off pulse pulse_ms\n"));
  1045. DEBUG_MSG_P(PSTR(" --- --- --- ---- ----- ---- ---------- ----------- ----- ----------\n"));
  1046. for (unsigned char index = 0; index < _relays.size(); ++index) {
  1047. const auto& relay = _relays.at(index);
  1048. DEBUG_MSG_P(PSTR("%3u %3s %3s %3u %4u %5u %4u %10u %11u %5u %10u\n"),
  1049. index,
  1050. relay.current_status ? "ON" : "OFF",
  1051. relay.target_status ? "ON" : "OFF",
  1052. relay.pin, relay.type, relay.reset_pin,
  1053. relay.lock,
  1054. relay.delay_on, relay.delay_off,
  1055. relay.pulse, relay.pulse_ms
  1056. );
  1057. }
  1058. });
  1059. #endif
  1060. }
  1061. #endif // TERMINAL_SUPPORT
  1062. //------------------------------------------------------------------------------
  1063. // Setup
  1064. //------------------------------------------------------------------------------
  1065. void _relayLoop() {
  1066. _relayProcess(false);
  1067. _relayProcess(true);
  1068. #if WEB_SUPPORT
  1069. if (_relay_report_ws) {
  1070. wsPost(_relayWebSocketUpdate);
  1071. _relay_report_ws = false;
  1072. }
  1073. #endif
  1074. }
  1075. // Dummy relays for virtual light switches, Sonoff Dual, Sonoff RF Bridge and Tuya
  1076. void relaySetupDummy(size_t size, bool reconfigure) {
  1077. if (size == _relayDummy) return;
  1078. const size_t new_size = ((_relays.size() - _relayDummy) + size);
  1079. if (new_size > RelaysMax) return;
  1080. _relayDummy = size;
  1081. _relays.resize(new_size);
  1082. if (reconfigure) {
  1083. _relayConfigure();
  1084. }
  1085. #if BROKER_SUPPORT
  1086. ConfigBroker::Publish("relayDummy", String(int(size)));
  1087. #endif
  1088. }
  1089. void _relaySetupAdhoc() {
  1090. size_t relays [[gnu::unused]] = 0;
  1091. #if RELAY1_PIN != GPIO_NONE
  1092. ++relays;
  1093. #endif
  1094. #if RELAY2_PIN != GPIO_NONE
  1095. ++relays;
  1096. #endif
  1097. #if RELAY3_PIN != GPIO_NONE
  1098. ++relays;
  1099. #endif
  1100. #if RELAY4_PIN != GPIO_NONE
  1101. ++relays;
  1102. #endif
  1103. #if RELAY5_PIN != GPIO_NONE
  1104. ++relays;
  1105. #endif
  1106. #if RELAY6_PIN != GPIO_NONE
  1107. ++relays;
  1108. #endif
  1109. #if RELAY7_PIN != GPIO_NONE
  1110. ++relays;
  1111. #endif
  1112. #if RELAY8_PIN != GPIO_NONE
  1113. ++relays;
  1114. #endif
  1115. _relays.reserve(relays);
  1116. #if (RELAY_PROVIDER == RELAY_PROVIDER_RELAY) || (RELAY_PROVIDER == RELAY_PROVIDER_LIGHT)
  1117. using gpio_type = GpioPin;
  1118. #elif (RELAY_PROVIDER == RELAY_PROVIDER_MCP23S08)
  1119. using gpio_type = McpGpioPin;
  1120. #else
  1121. using gpio_type = DummyPin;
  1122. #endif
  1123. for (unsigned char id = 0; id < RelaysMax; ++id) {
  1124. const auto pin = _relayPin(id);
  1125. #if (RELAY_PROVIDER == RELAY_PROVIDER_MCP23S08)
  1126. if (!mcpGpioValid(pin)) {
  1127. #else
  1128. if (!gpioValid(pin)) {
  1129. #endif
  1130. break;
  1131. }
  1132. _relays.emplace_back(
  1133. new gpio_type(pin),
  1134. _relayType(id),
  1135. new gpio_type(_relayResetPin(id))
  1136. );
  1137. }
  1138. }
  1139. void relaySetup() {
  1140. // Ad-hoc relays
  1141. _relaySetupAdhoc();
  1142. // Dummy (virtual) relays
  1143. relaySetupDummy(getSetting("relayDummy", DUMMY_RELAY_COUNT));
  1144. _relaySetupProvider();
  1145. _relayBackwards();
  1146. _relayConfigure();
  1147. _relayBoot();
  1148. _relayLoop();
  1149. #if WEB_SUPPORT
  1150. relaySetupWS();
  1151. #endif
  1152. #if API_SUPPORT
  1153. relaySetupAPI();
  1154. #endif
  1155. #if MQTT_SUPPORT
  1156. relaySetupMQTT();
  1157. #endif
  1158. #if TERMINAL_SUPPORT
  1159. _relayInitCommands();
  1160. #endif
  1161. // Main callbacks
  1162. espurnaRegisterLoop(_relayLoop);
  1163. espurnaRegisterReload(_relayConfigure);
  1164. DEBUG_MSG_P(PSTR("[RELAY] Number of relays: %d\n"), _relays.size());
  1165. }
  1166. #endif // RELAY_SUPPORT == 1