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.

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