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