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.

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