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.

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