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.

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