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.

1530 lines
45 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. // Note that we expect a fixed number of entries.
  782. // Otherwise, underlying vector will reserve more than we need (likely, *2 of the current size)
  783. apiReserve(2u + (relayCount() * 2u));
  784. apiRegister({
  785. MQTT_TOPIC_RELAY, Api::Type::Json, ApiUnusedArg,
  786. [](const Api&, JsonObject& root) {
  787. JsonArray& relays = root.createNestedArray("relayStatus");
  788. for (unsigned char id = 0; id < relayCount(); ++id) {
  789. relays.add(_relays[id].target_status ? 1 : 0);
  790. }
  791. }
  792. });
  793. #if defined(ITEAD_SONOFF_IFAN02)
  794. apiRegister({
  795. MQTT_TOPIC_SPEED, Api::Type::Basic, ApiUnusedArg,
  796. [](const Api&, ApiBuffer& buffer) {
  797. snprintf(buffer.data, buffer.size, "%u", getSpeed());
  798. },
  799. [](const Api&, ApiBuffer& buffer) {
  800. setSpeed(atoi(buffer.data));
  801. snprintf(buffer.data, buffer.size, "%u", getSpeed());
  802. }
  803. });
  804. #endif
  805. char path[64] = {0};
  806. for (unsigned char id = 0; id < relayCount(); ++id) {
  807. sprintf_P(path, PSTR(MQTT_TOPIC_RELAY "/%u"), id);
  808. apiRegister({
  809. path, Api::Type::Basic, id,
  810. [](const Api& api, ApiBuffer& buffer) {
  811. snprintf_P(buffer.data, buffer.size, PSTR("%d"), _relays[api.arg].target_status ? 1 : 0);
  812. },
  813. [](const Api& api, ApiBuffer& buffer) {
  814. if (!_relayHandlePayload(api.arg, buffer.data)) {
  815. DEBUG_MSG_P(PSTR("[RELAY] Invalid API payload (%s)\n"), buffer.data);
  816. return;
  817. }
  818. }
  819. });
  820. sprintf_P(path, PSTR(MQTT_TOPIC_PULSE "/%u"), id);
  821. apiRegister({
  822. path, Api::Type::Basic, id,
  823. [](const Api& api, ApiBuffer& buffer) {
  824. dtostrf((double) _relays[api.arg].pulse_ms / 1000, 1, 3, buffer.data);
  825. },
  826. [](const Api& api, ApiBuffer& buffer) {
  827. unsigned long pulse = 1000 * atof(buffer.data);
  828. if (0 == pulse) {
  829. return;
  830. }
  831. if (RELAY_PULSE_NONE != _relays[api.arg].pulse) {
  832. DEBUG_MSG_P(PSTR("[RELAY] Overriding relay #%d pulse settings\n"), api.arg);
  833. }
  834. _relays[api.arg].pulse_ms = pulse;
  835. _relays[api.arg].pulse = relayStatus(api.arg)
  836. ? RELAY_PULSE_ON
  837. : RELAY_PULSE_OFF;
  838. relayToggle(api.arg, true, false);
  839. }
  840. });
  841. }
  842. }
  843. #endif // API_SUPPORT
  844. //------------------------------------------------------------------------------
  845. // MQTT
  846. //------------------------------------------------------------------------------
  847. #if MQTT_SUPPORT || API_SUPPORT
  848. const String& relayPayloadOn() {
  849. return _relay_rpc_payload_on;
  850. }
  851. const String& relayPayloadOff() {
  852. return _relay_rpc_payload_off;
  853. }
  854. const String& relayPayloadToggle() {
  855. return _relay_rpc_payload_toggle;
  856. }
  857. const char* relayPayload(PayloadStatus status) {
  858. switch (status) {
  859. case PayloadStatus::Off:
  860. return _relay_rpc_payload_off.c_str();
  861. case PayloadStatus::On:
  862. return _relay_rpc_payload_on.c_str();
  863. case PayloadStatus::Toggle:
  864. return _relay_rpc_payload_toggle.c_str();
  865. case PayloadStatus::Unknown:
  866. default:
  867. return "";
  868. }
  869. }
  870. #endif // MQTT_SUPPORT || API_SUPPORT
  871. #if MQTT_SUPPORT
  872. void _relayMQTTGroup(unsigned char id) {
  873. const String topic = getSetting({"mqttGroup", id});
  874. if (!topic.length()) return;
  875. const auto mode = getSetting({"mqttGroupSync", id}, RELAY_GROUP_SYNC_NORMAL);
  876. if (mode == RELAY_GROUP_SYNC_RECEIVEONLY) return;
  877. auto status = _relayStatusTyped(id);
  878. if (mode == RELAY_GROUP_SYNC_INVERSE) status = _relayStatusInvert(status);
  879. mqttSendRaw(topic.c_str(), relayPayload(status));
  880. }
  881. void relayMQTT(unsigned char id) {
  882. if (id >= _relays.size()) return;
  883. // Send state topic
  884. if (_relays[id].report) {
  885. _relays[id].report = false;
  886. mqttSend(MQTT_TOPIC_RELAY, id, relayPayload(_relayStatusTyped(id)));
  887. }
  888. // Check group topic
  889. if (_relays[id].group_report) {
  890. _relays[id].group_report = false;
  891. _relayMQTTGroup(id);
  892. }
  893. // Send speed for IFAN02
  894. #if defined (ITEAD_SONOFF_IFAN02)
  895. char buffer[5];
  896. snprintf(buffer, sizeof(buffer), "%u", getSpeed());
  897. mqttSend(MQTT_TOPIC_SPEED, buffer);
  898. #endif
  899. }
  900. void relayMQTT() {
  901. for (unsigned int id=0; id < _relays.size(); id++) {
  902. mqttSend(MQTT_TOPIC_RELAY, id, relayPayload(_relayStatusTyped(id)));
  903. }
  904. }
  905. void relayStatusWrap(unsigned char id, PayloadStatus value, bool is_group_topic) {
  906. #if MQTT_SUPPORT
  907. const auto forward = mqttForward();
  908. #else
  909. const auto forward = false;
  910. #endif
  911. switch (value) {
  912. case PayloadStatus::Off:
  913. relayStatus(id, false, forward, !is_group_topic);
  914. break;
  915. case PayloadStatus::On:
  916. relayStatus(id, true, forward, !is_group_topic);
  917. break;
  918. case PayloadStatus::Toggle:
  919. relayToggle(id, true, true);
  920. break;
  921. case PayloadStatus::Unknown:
  922. default:
  923. _relays[id].report = true;
  924. relayMQTT(id);
  925. break;
  926. }
  927. }
  928. void relayMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  929. if (type == MQTT_CONNECT_EVENT) {
  930. // Send status on connect
  931. #if (HEARTBEAT_MODE == HEARTBEAT_NONE) or (not HEARTBEAT_REPORT_RELAY)
  932. relayMQTT();
  933. #endif
  934. // Subscribe to own /set topic
  935. char relay_topic[strlen(MQTT_TOPIC_RELAY) + 3];
  936. snprintf_P(relay_topic, sizeof(relay_topic), PSTR("%s/+"), MQTT_TOPIC_RELAY);
  937. mqttSubscribe(relay_topic);
  938. // Subscribe to pulse topic
  939. char pulse_topic[strlen(MQTT_TOPIC_PULSE) + 3];
  940. snprintf_P(pulse_topic, sizeof(pulse_topic), PSTR("%s/+"), MQTT_TOPIC_PULSE);
  941. mqttSubscribe(pulse_topic);
  942. #if defined(ITEAD_SONOFF_IFAN02)
  943. mqttSubscribe(MQTT_TOPIC_SPEED);
  944. #endif
  945. // Subscribe to group topics
  946. for (unsigned char i=0; i < _relays.size(); i++) {
  947. const auto t = getSetting({"mqttGroup", i});
  948. if (t.length() > 0) mqttSubscribeRaw(t.c_str());
  949. }
  950. }
  951. if (type == MQTT_MESSAGE_EVENT) {
  952. String t = mqttMagnitude((char *) topic);
  953. // magnitude is relay/#/pulse
  954. if (t.startsWith(MQTT_TOPIC_PULSE)) {
  955. unsigned int id = t.substring(strlen(MQTT_TOPIC_PULSE)+1).toInt();
  956. if (id >= relayCount()) {
  957. DEBUG_MSG_P(PSTR("[RELAY] Wrong relayID (%d)\n"), id);
  958. return;
  959. }
  960. unsigned long pulse = 1000 * atof(payload);
  961. if (0 == pulse) return;
  962. if (RELAY_PULSE_NONE != _relays[id].pulse) {
  963. DEBUG_MSG_P(PSTR("[RELAY] Overriding relay #%d pulse settings\n"), id);
  964. }
  965. _relays[id].pulse_ms = pulse;
  966. _relays[id].pulse = relayStatus(id) ? RELAY_PULSE_ON : RELAY_PULSE_OFF;
  967. relayToggle(id, true, false);
  968. return;
  969. }
  970. // magnitude is relay/#
  971. if (t.startsWith(MQTT_TOPIC_RELAY)) {
  972. // Get relay ID
  973. unsigned int id = t.substring(strlen(MQTT_TOPIC_RELAY)+1).toInt();
  974. if (id >= relayCount()) {
  975. DEBUG_MSG_P(PSTR("[RELAY] Wrong relayID (%d)\n"), id);
  976. return;
  977. }
  978. // Get value
  979. auto value = relayParsePayload(payload);
  980. if (value == PayloadStatus::Unknown) return;
  981. relayStatusWrap(id, value, false);
  982. return;
  983. }
  984. // Check group topics
  985. for (unsigned char i=0; i < _relays.size(); i++) {
  986. const String t = getSetting({"mqttGroup", i});
  987. if ((t.length() > 0) && t.equals(topic)) {
  988. auto value = relayParsePayload(payload);
  989. if (value == PayloadStatus::Unknown) return;
  990. if ((value == PayloadStatus::On) || (value == PayloadStatus::Off)) {
  991. if (getSetting({"mqttGroupSync", i}, RELAY_GROUP_SYNC_NORMAL) == RELAY_GROUP_SYNC_INVERSE) {
  992. value = _relayStatusInvert(value);
  993. }
  994. }
  995. DEBUG_MSG_P(PSTR("[RELAY] Matched group topic for relayID %d\n"), i);
  996. relayStatusWrap(i, value, true);
  997. }
  998. }
  999. // Itead Sonoff IFAN02
  1000. #if defined (ITEAD_SONOFF_IFAN02)
  1001. if (t.startsWith(MQTT_TOPIC_SPEED)) {
  1002. setSpeed(atoi(payload));
  1003. }
  1004. #endif
  1005. }
  1006. if (type == MQTT_DISCONNECT_EVENT) {
  1007. for (unsigned char i=0; i < _relays.size(); i++){
  1008. const auto reaction = getSetting({"relayOnDisc", i}, 0);
  1009. if (1 == reaction) { // switch relay OFF
  1010. DEBUG_MSG_P(PSTR("[RELAY] Reset relay (%d) due to MQTT disconnection\n"), i);
  1011. relayStatusWrap(i, PayloadStatus::Off, false);
  1012. } else if(2 == reaction) { // switch relay ON
  1013. DEBUG_MSG_P(PSTR("[RELAY] Set relay (%d) due to MQTT disconnection\n"), i);
  1014. relayStatusWrap(i, PayloadStatus::On, false);
  1015. }
  1016. }
  1017. }
  1018. }
  1019. void relaySetupMQTT() {
  1020. mqttRegister(relayMQTTCallback);
  1021. }
  1022. #endif
  1023. void _relaySetupProvider() {
  1024. // TODO: implement something like `RelayProvider tuya_provider({.setup_cb = ..., .send_cb = ...})`?
  1025. // note of the function call order! relay code is initialized before tuya's, and the easiest
  1026. // way to accomplish that is to use ctor as a way to "register" callbacks even before setup() is called
  1027. #if TUYA_SUPPORT
  1028. Tuya::tuyaSetupSwitch();
  1029. #endif
  1030. }
  1031. //------------------------------------------------------------------------------
  1032. // Settings
  1033. //------------------------------------------------------------------------------
  1034. #if TERMINAL_SUPPORT
  1035. void _relayInitCommands() {
  1036. terminalRegisterCommand(F("RELAY"), [](const terminal::CommandContext& ctx) {
  1037. if (ctx.argc < 2) {
  1038. terminalError(F("Wrong arguments"));
  1039. return;
  1040. }
  1041. int id = ctx.argv[1].toInt();
  1042. if (id >= relayCount()) {
  1043. DEBUG_MSG_P(PSTR("-ERROR: Wrong relayID (%d)\n"), id);
  1044. return;
  1045. }
  1046. if (ctx.argc > 2) {
  1047. int value = ctx.argv[2].toInt();
  1048. if (value == 2) {
  1049. relayToggle(id);
  1050. } else {
  1051. relayStatus(id, value == 1);
  1052. }
  1053. }
  1054. DEBUG_MSG_P(PSTR("Status: %s\n"), _relays[id].target_status ? "true" : "false");
  1055. if (_relays[id].pulse != RELAY_PULSE_NONE) {
  1056. DEBUG_MSG_P(PSTR("Pulse: %s\n"), (_relays[id].pulse == RELAY_PULSE_ON) ? "ON" : "OFF");
  1057. DEBUG_MSG_P(PSTR("Pulse time: %d\n"), _relays[id].pulse_ms);
  1058. }
  1059. terminalOK();
  1060. });
  1061. #if 0
  1062. terminalRegisterCommand(F("RELAY.INFO"), [](const terminal::CommandContext&) {
  1063. DEBUG_MSG_P(PSTR(" cur tgt pin type reset lock delay_on delay_off pulse pulse_ms\n"));
  1064. DEBUG_MSG_P(PSTR(" --- --- --- ---- ----- ---- ---------- ----------- ----- ----------\n"));
  1065. for (unsigned char index = 0; index < _relays.size(); ++index) {
  1066. const auto& relay = _relays.at(index);
  1067. DEBUG_MSG_P(PSTR("%3u %3s %3s %3u %4u %5u %4u %10u %11u %5u %10u\n"),
  1068. index,
  1069. relay.current_status ? "ON" : "OFF",
  1070. relay.target_status ? "ON" : "OFF",
  1071. relay.pin, relay.type, relay.reset_pin,
  1072. relay.lock,
  1073. relay.delay_on, relay.delay_off,
  1074. relay.pulse, relay.pulse_ms
  1075. );
  1076. }
  1077. });
  1078. #endif
  1079. }
  1080. #endif // TERMINAL_SUPPORT
  1081. //------------------------------------------------------------------------------
  1082. // Setup
  1083. //------------------------------------------------------------------------------
  1084. void _relayLoop() {
  1085. _relayProcess(false);
  1086. _relayProcess(true);
  1087. #if WEB_SUPPORT
  1088. if (_relay_report_ws) {
  1089. wsPost(_relayWebSocketUpdate);
  1090. _relay_report_ws = false;
  1091. }
  1092. #endif
  1093. }
  1094. // Dummy relays for virtual light switches, Sonoff Dual, Sonoff RF Bridge and Tuya
  1095. void relaySetupDummy(size_t size, bool reconfigure) {
  1096. if (size == _relayDummy) return;
  1097. const size_t new_size = ((_relays.size() - _relayDummy) + size);
  1098. if (new_size > RelaysMax) return;
  1099. _relayDummy = size;
  1100. _relays.resize(new_size);
  1101. if (reconfigure) {
  1102. _relayConfigure();
  1103. }
  1104. #if BROKER_SUPPORT
  1105. ConfigBroker::Publish("relayDummy", String(int(size)));
  1106. #endif
  1107. }
  1108. void _relaySetupAdhoc() {
  1109. size_t relays [[gnu::unused]] = 0;
  1110. #if RELAY1_PIN != GPIO_NONE
  1111. ++relays;
  1112. #endif
  1113. #if RELAY2_PIN != GPIO_NONE
  1114. ++relays;
  1115. #endif
  1116. #if RELAY3_PIN != GPIO_NONE
  1117. ++relays;
  1118. #endif
  1119. #if RELAY4_PIN != GPIO_NONE
  1120. ++relays;
  1121. #endif
  1122. #if RELAY5_PIN != GPIO_NONE
  1123. ++relays;
  1124. #endif
  1125. #if RELAY6_PIN != GPIO_NONE
  1126. ++relays;
  1127. #endif
  1128. #if RELAY7_PIN != GPIO_NONE
  1129. ++relays;
  1130. #endif
  1131. #if RELAY8_PIN != GPIO_NONE
  1132. ++relays;
  1133. #endif
  1134. _relays.reserve(relays);
  1135. #if (RELAY_PROVIDER == RELAY_PROVIDER_RELAY) || (RELAY_PROVIDER == RELAY_PROVIDER_LIGHT)
  1136. using gpio_type = GpioPin;
  1137. #elif (RELAY_PROVIDER == RELAY_PROVIDER_MCP23S08)
  1138. using gpio_type = McpGpioPin;
  1139. #else
  1140. using gpio_type = DummyPin;
  1141. #endif
  1142. for (unsigned char id = 0; id < RelaysMax; ++id) {
  1143. const auto pin = _relayPin(id);
  1144. #if (RELAY_PROVIDER == RELAY_PROVIDER_MCP23S08)
  1145. if (!mcpGpioValid(pin)) {
  1146. #else
  1147. if (!gpioValid(pin)) {
  1148. #endif
  1149. break;
  1150. }
  1151. _relays.emplace_back(
  1152. new gpio_type(pin),
  1153. _relayType(id),
  1154. new gpio_type(_relayResetPin(id))
  1155. );
  1156. }
  1157. }
  1158. void relaySetup() {
  1159. // Ad-hoc relays
  1160. _relaySetupAdhoc();
  1161. // Dummy (virtual) relays
  1162. relaySetupDummy(getSetting("relayDummy", DUMMY_RELAY_COUNT));
  1163. _relaySetupProvider();
  1164. _relayBackwards();
  1165. _relayConfigure();
  1166. _relayBoot();
  1167. _relayLoop();
  1168. #if WEB_SUPPORT
  1169. relaySetupWS();
  1170. #endif
  1171. #if API_SUPPORT
  1172. relaySetupAPI();
  1173. #endif
  1174. #if MQTT_SUPPORT
  1175. relaySetupMQTT();
  1176. #endif
  1177. #if TERMINAL_SUPPORT
  1178. _relayInitCommands();
  1179. #endif
  1180. // Main callbacks
  1181. espurnaRegisterLoop(_relayLoop);
  1182. espurnaRegisterReload(_relayConfigure);
  1183. DEBUG_MSG_P(PSTR("[RELAY] Number of relays: %d\n"), _relays.size());
  1184. }
  1185. #endif // RELAY_SUPPORT == 1