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.

1406 lines
42 KiB

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