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.

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