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.

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