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.

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