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.

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