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.

1454 lines
43 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 == RELAY_NONE) return false;
  368. if (id >= _relays.size()) return false;
  369. if (!_relayStatusLock(id, status)) {
  370. DEBUG_MSG_P(PSTR("[RELAY] #%d is locked to %s\n"), id, _relays[id].current_status ? "ON" : "OFF");
  371. _relays[id].report = true;
  372. _relays[id].group_report = true;
  373. return false;
  374. }
  375. bool changed = false;
  376. if (_relays[id].current_status == status) {
  377. if (_relays[id].target_status != status) {
  378. DEBUG_MSG_P(PSTR("[RELAY] #%d scheduled change cancelled\n"), id);
  379. _relays[id].target_status = status;
  380. _relays[id].report = false;
  381. _relays[id].group_report = false;
  382. _relays[id].change_delay = 0;
  383. changed = true;
  384. }
  385. // For RFBridge, keep sending the message even if the status is already the required
  386. #if RELAY_PROVIDER == RELAY_PROVIDER_RFBRIDGE
  387. rfbStatus(id, status);
  388. #endif
  389. // Update the pulse counter if the relay is already in the non-normal state (#454)
  390. relayPulse(id);
  391. } else {
  392. unsigned long current_time = millis();
  393. unsigned long change_delay = status ? _relays[id].delay_on : _relays[id].delay_off;
  394. _relays[id].fw_count++;
  395. _relays[id].change_start = current_time;
  396. _relays[id].change_delay = std::max(_relays[id].change_delay, change_delay);
  397. // If current_time is off-limits the floodWindow...
  398. const auto fw_diff = current_time - _relays[id].fw_start;
  399. if (fw_diff > _relay_flood_window) {
  400. // We reset the floodWindow
  401. _relays[id].fw_start = current_time;
  402. _relays[id].fw_count = 1;
  403. // If current_time is in the floodWindow and there have been too many requests...
  404. } else if (_relays[id].fw_count >= _relay_flood_changes) {
  405. // We schedule the changes to the end of the floodWindow
  406. // unless it's already delayed beyond that point
  407. _relays[id].change_delay = std::max(change_delay, _relay_flood_window - fw_diff);
  408. // Another option is to always move it forward, starting from current time
  409. //_relays[id].fw_start = current_time;
  410. }
  411. _relays[id].target_status = status;
  412. if (report) _relays[id].report = true;
  413. if (group_report) _relays[id].group_report = true;
  414. relaySync(id);
  415. DEBUG_MSG_P(PSTR("[RELAY] #%d scheduled %s in %u ms\n"),
  416. id, status ? "ON" : "OFF", _relays[id].change_delay
  417. );
  418. changed = true;
  419. }
  420. return changed;
  421. }
  422. bool relayStatus(unsigned char id, bool status) {
  423. return relayStatus(id, status, mqttForward(), true);
  424. }
  425. bool relayStatus(unsigned char id) {
  426. // Check that relay ID is valid
  427. if (id >= _relays.size()) return false;
  428. // Get status directly from storage
  429. return _relays[id].current_status;
  430. }
  431. void relaySync(unsigned char id) {
  432. // No sync if none or only one relay
  433. if (_relays.size() < 2) return;
  434. // Do not go on if we are comming from a previous sync
  435. if (_relayRecursive) return;
  436. // Flag sync mode
  437. _relayRecursive = true;
  438. bool status = _relays[id].target_status;
  439. // If RELAY_SYNC_SAME all relays should have the same state
  440. if (_relay_sync_mode == RELAY_SYNC_SAME) {
  441. for (unsigned short i=0; i<_relays.size(); i++) {
  442. if (i != id) relayStatus(i, status);
  443. }
  444. // If RELAY_SYNC_FIRST all relays should have the same state as first if first changes
  445. } else if (_relay_sync_mode == RELAY_SYNC_FIRST) {
  446. if (id == 0) {
  447. for (unsigned short i=1; i<_relays.size(); i++) {
  448. relayStatus(i, status);
  449. }
  450. }
  451. } else if ((_relay_sync_mode == RELAY_SYNC_NONE_OR_ONE) || (_relay_sync_mode == RELAY_SYNC_ONE)) {
  452. // If NONE_OR_ONE or ONE and setting ON we should set OFF all the others
  453. if (status) {
  454. if (_relay_sync_mode != RELAY_SYNC_ANY) {
  455. for (unsigned short other_id=0; other_id<_relays.size(); other_id++) {
  456. if (other_id != id) {
  457. relayStatus(other_id, false);
  458. if (relayStatus(other_id)) {
  459. _relaySyncRelaysDelay(other_id, id);
  460. }
  461. }
  462. }
  463. }
  464. // If ONLY_ONE and setting OFF we should set ON the other one
  465. } else {
  466. if (_relay_sync_mode == RELAY_SYNC_ONE) {
  467. unsigned char other_id = (id + 1) % _relays.size();
  468. _relaySyncRelaysDelay(id, other_id);
  469. relayStatus(other_id, true);
  470. }
  471. }
  472. _relayLockAll();
  473. }
  474. // Unflag sync mode
  475. _relayRecursive = false;
  476. }
  477. void relaySave(bool eeprom) {
  478. const unsigned char count = constrain(relayCount(), 0, RELAYS_MAX);
  479. auto statuses = std::bitset<RELAYS_MAX>(0);
  480. for (unsigned int id = 0; id < count; ++id) {
  481. statuses.set(id, relayStatus(id));
  482. }
  483. const RelayMask mask(statuses);
  484. DEBUG_MSG_P(PSTR("[RELAY] Setting relay mask: %s\n"), mask.as_string.c_str());
  485. // Persist only to rtcmem, unless requested to save to the eeprom
  486. _relayMaskRtcmem(mask);
  487. // The 'eeprom' flag controls whether we are commiting this change or not.
  488. // It is useful to set it to 'false' if the relay change triggering the
  489. // save involves a relay whose boot mode is independent from current mode,
  490. // thus storing the last relay value is not absolutely necessary.
  491. // Nevertheless, we store the value in the EEPROM buffer so it will be written
  492. // on the next commit.
  493. if (eeprom) {
  494. _relayMaskSettings(mask);
  495. // We are actually enqueuing the commit so it will be
  496. // executed on the main loop, in case this is called from a system context callback
  497. eepromCommit();
  498. }
  499. }
  500. void relaySave() {
  501. relaySave(false);
  502. }
  503. void relayToggle(unsigned char id, bool report, bool group_report) {
  504. if (id >= _relays.size()) return;
  505. relayStatus(id, !relayStatus(id), report, group_report);
  506. }
  507. void relayToggle(unsigned char id) {
  508. relayToggle(id, mqttForward(), true);
  509. }
  510. unsigned char relayCount() {
  511. return _relays.size();
  512. }
  513. RelayStatus relayParsePayload(const char * payload) {
  514. // Don't parse empty strings
  515. const auto len = strlen(payload);
  516. if (!len) return RelayStatus::UNKNOWN;
  517. // Check most commonly used payloads
  518. if (len == 1) {
  519. if (payload[0] == '0') return RelayStatus::OFF;
  520. if (payload[0] == '1') return RelayStatus::ON;
  521. if (payload[0] == '2') return RelayStatus::TOGGLE;
  522. return RelayStatus::UNKNOWN;
  523. }
  524. // If possible, compare to locally configured payload strings
  525. #if MQTT_SUPPORT
  526. if (_relay_mqtt_payload_off.equals(payload)) return RelayStatus::OFF;
  527. if (_relay_mqtt_payload_on.equals(payload)) return RelayStatus::ON;
  528. if (_relay_mqtt_payload_toggle.equals(payload)) return RelayStatus::TOGGLE;
  529. #endif // MQTT_SUPPORT
  530. // Finally, check for "OFF", "ON", "TOGGLE" (both lower and upper cases)
  531. String temp(payload);
  532. temp.trim();
  533. if (temp.equalsIgnoreCase("off")) {
  534. return RelayStatus::OFF;
  535. } else if (temp.equalsIgnoreCase("on")) {
  536. return RelayStatus::ON;
  537. } else if (temp.equalsIgnoreCase("toggle")) {
  538. return RelayStatus::TOGGLE;
  539. }
  540. return RelayStatus::UNKNOWN;
  541. }
  542. // BACKWARDS COMPATIBILITY
  543. void _relayBackwards() {
  544. #if defined(EEPROM_RELAY_STATUS)
  545. {
  546. uint8_t mask = EEPROMr.read(EEPROM_RELAY_STATUS);
  547. if (mask != 0xff) {
  548. _relayMaskSettings(static_cast<uint32_t>(mask));
  549. EEPROMr.write(EEPROM_RELAY_STATUS, 0xff);
  550. eepromCommit();
  551. }
  552. }
  553. #endif
  554. for (unsigned char id = 0; id < _relays.size(); ++id) {
  555. const settings_key_t key {"mqttGroupInv", id};
  556. if (!hasSetting(key)) continue;
  557. setSetting({"mqttGroupSync", id}, getSetting(key));
  558. delSetting(key);
  559. }
  560. }
  561. void _relayBoot() {
  562. _relayRecursive = true;
  563. const auto stored_mask = rtcmemStatus()
  564. ? _relayMaskRtcmem()
  565. : _relayMaskSettings();
  566. DEBUG_MSG_P(PSTR("[RELAY] Retrieving mask: %s\n"), stored_mask.as_string.c_str());
  567. auto mask = std::bitset<RELAYS_MAX>(stored_mask.as_u32);
  568. // Walk the relays
  569. unsigned char lock;
  570. bool status;
  571. for (unsigned char i=0; i<relayCount(); ++i) {
  572. const auto boot_mode = getSetting({"relayBoot", i}, RELAY_BOOT_MODE);
  573. DEBUG_MSG_P(PSTR("[RELAY] Relay #%u boot mode %d\n"), i, boot_mode);
  574. status = false;
  575. lock = RELAY_LOCK_DISABLED;
  576. switch (boot_mode) {
  577. case RELAY_BOOT_SAME:
  578. status = mask.test(i);
  579. break;
  580. case RELAY_BOOT_TOGGLE:
  581. mask.flip(i);
  582. status = mask[i];
  583. break;
  584. case RELAY_BOOT_LOCKED_ON:
  585. status = true;
  586. lock = RELAY_LOCK_ON;
  587. break;
  588. case RELAY_BOOT_LOCKED_OFF:
  589. lock = RELAY_LOCK_OFF;
  590. break;
  591. case RELAY_BOOT_ON:
  592. status = true;
  593. break;
  594. case RELAY_BOOT_OFF:
  595. default:
  596. break;
  597. }
  598. _relays[i].current_status = !status;
  599. _relays[i].target_status = status;
  600. _relays[i].change_start = millis();
  601. _relays[i].change_delay = status
  602. ? _relays[i].delay_on
  603. : _relays[i].delay_off;
  604. #if RELAY_PROVIDER == RELAY_PROVIDER_STM
  605. // XXX hack for correctly restoring relay state on boot
  606. // because of broken stm relay firmware
  607. _relays[i].change_delay = 3000 + 1000 * i;
  608. #endif
  609. _relays[i].lock = lock;
  610. }
  611. _relayRecursive = false;
  612. #if TUYA_SUPPORT
  613. tuyaSyncSwitchStatus();
  614. #endif
  615. }
  616. void _relayConfigure() {
  617. for (unsigned char i = 0, relays = _relays.size() ; (i < relays); ++i) {
  618. _relays[i].pulse = getSetting({"relayPulse", i}, RELAY_PULSE_MODE);
  619. _relays[i].pulse_ms = 1000 * getSetting({"relayTime", i}, 0.);
  620. _relays[i].delay_on = getSetting({"relayDelayOn", i}, _relayDelayOn(i));
  621. _relays[i].delay_off = getSetting({"relayDelayOff", i}, _relayDelayOff(i));
  622. if (GPIO_NONE == _relays[i].pin) continue;
  623. pinMode(_relays[i].pin, OUTPUT);
  624. if (GPIO_NONE != _relays[i].reset_pin) {
  625. pinMode(_relays[i].reset_pin, OUTPUT);
  626. }
  627. if (_relays[i].type == RELAY_TYPE_INVERSE) {
  628. //set to high to block short opening of relay
  629. digitalWrite(_relays[i].pin, HIGH);
  630. }
  631. }
  632. _relay_flood_window = (1000 * getSetting("relayFloodTime", RELAY_FLOOD_WINDOW));
  633. _relay_flood_changes = getSetting("relayFloodChanges", RELAY_FLOOD_CHANGES);
  634. _relay_delay_interlock = getSetting("relayDelayInterlock", RELAY_DELAY_INTERLOCK);
  635. _relay_sync_mode = getSetting("relaySync", RELAY_SYNC);
  636. #if MQTT_SUPPORT
  637. settingsProcessConfig({
  638. {_relay_mqtt_payload_on, "relayPayloadOn", RELAY_MQTT_ON},
  639. {_relay_mqtt_payload_off, "relayPayloadOff", RELAY_MQTT_OFF},
  640. {_relay_mqtt_payload_toggle, "relayPayloadToggle", RELAY_MQTT_TOGGLE},
  641. });
  642. #endif // MQTT_SUPPORT
  643. }
  644. //------------------------------------------------------------------------------
  645. // WEBSOCKETS
  646. //------------------------------------------------------------------------------
  647. #if WEB_SUPPORT
  648. bool _relayWebSocketOnKeyCheck(const char * key, JsonVariant& value) {
  649. return (strncmp(key, "relay", 5) == 0);
  650. }
  651. void _relayWebSocketUpdate(JsonObject& root) {
  652. JsonObject& state = root.createNestedObject("relayState");
  653. state["size"] = relayCount();
  654. JsonArray& status = state.createNestedArray("status");
  655. JsonArray& lock = state.createNestedArray("lock");
  656. for (unsigned char i=0; i<relayCount(); i++) {
  657. status.add<uint8_t>(_relays[i].target_status);
  658. lock.add(_relays[i].lock);
  659. }
  660. }
  661. String _relayFriendlyName(unsigned char i) {
  662. String res = String("GPIO") + String(_relays[i].pin);
  663. if (GPIO_NONE == _relays[i].pin) {
  664. #if (RELAY_PROVIDER == RELAY_PROVIDER_LIGHT)
  665. uint8_t physical = _relays.size() - _relayDummy;
  666. if (i >= physical) {
  667. if (_relayDummy == lightChannels()) {
  668. res = String("CH") + String(i-physical);
  669. } else if (_relayDummy == (lightChannels() + 1u)) {
  670. if (physical == i) {
  671. res = String("Light");
  672. } else {
  673. res = String("CH") + String(i-1-physical);
  674. }
  675. } else {
  676. res = String("Light");
  677. }
  678. } else {
  679. res = String("?");
  680. }
  681. #else
  682. res = String("SW") + String(i);
  683. #endif
  684. }
  685. return res;
  686. }
  687. void _relayWebSocketSendRelays(JsonObject& root) {
  688. JsonObject& relays = root.createNestedObject("relayConfig");
  689. relays["size"] = relayCount();
  690. relays["start"] = 0;
  691. JsonArray& gpio = relays.createNestedArray("gpio");
  692. JsonArray& type = relays.createNestedArray("type");
  693. JsonArray& reset = relays.createNestedArray("reset");
  694. JsonArray& boot = relays.createNestedArray("boot");
  695. JsonArray& pulse = relays.createNestedArray("pulse");
  696. JsonArray& pulse_time = relays.createNestedArray("pulse_time");
  697. #if SCHEDULER_SUPPORT
  698. JsonArray& sch_last = relays.createNestedArray("sch_last");
  699. #endif
  700. #if MQTT_SUPPORT
  701. JsonArray& group = relays.createNestedArray("group");
  702. JsonArray& group_sync = relays.createNestedArray("group_sync");
  703. JsonArray& on_disconnect = relays.createNestedArray("on_disc");
  704. #endif
  705. for (unsigned char i=0; i<relayCount(); i++) {
  706. gpio.add(_relayFriendlyName(i));
  707. type.add(_relays[i].type);
  708. reset.add(_relays[i].reset_pin);
  709. boot.add(getSetting({"relayBoot", i}, RELAY_BOOT_MODE));
  710. pulse.add(_relays[i].pulse);
  711. pulse_time.add(_relays[i].pulse_ms / 1000.0);
  712. #if SCHEDULER_SUPPORT
  713. sch_last.add(getSetting({"relayLastSch", i}, SCHEDULER_RESTORE_LAST_SCHEDULE));
  714. #endif
  715. #if MQTT_SUPPORT
  716. group.add(getSetting({"mqttGroup", i}));
  717. group_sync.add(getSetting({"mqttGroupSync", i}, 0));
  718. on_disconnect.add(getSetting({"relayOnDisc", i}, 0));
  719. #endif
  720. }
  721. }
  722. void _relayWebSocketOnVisible(JsonObject& root) {
  723. if (relayCount() == 0) return;
  724. if (relayCount() > 1) {
  725. root["multirelayVisible"] = 1;
  726. root["relaySync"] = getSetting("relaySync", RELAY_SYNC);
  727. }
  728. root["relayVisible"] = 1;
  729. }
  730. void _relayWebSocketOnConnected(JsonObject& root) {
  731. if (relayCount() == 0) return;
  732. // Per-relay configuration
  733. _relayWebSocketSendRelays(root);
  734. }
  735. void _relayWebSocketOnAction(uint32_t client_id, const char * action, JsonObject& data) {
  736. if (strcmp(action, "relay") != 0) return;
  737. if (data.containsKey("status")) {
  738. unsigned int relayID = 0;
  739. if (data.containsKey("id") && data.is<int>("id")) {
  740. relayID = data["id"];
  741. }
  742. _relayHandlePayload(relayID, data["status"]);
  743. }
  744. }
  745. void relaySetupWS() {
  746. wsRegister()
  747. .onVisible(_relayWebSocketOnVisible)
  748. .onConnected(_relayWebSocketOnConnected)
  749. .onData(_relayWebSocketUpdate)
  750. .onAction(_relayWebSocketOnAction)
  751. .onKeyCheck(_relayWebSocketOnKeyCheck);
  752. }
  753. #endif // WEB_SUPPORT
  754. //------------------------------------------------------------------------------
  755. // REST API
  756. //------------------------------------------------------------------------------
  757. #if API_SUPPORT
  758. void relaySetupAPI() {
  759. char key[20];
  760. // API entry points (protected with apikey)
  761. for (unsigned int relayID=0; relayID<relayCount(); relayID++) {
  762. snprintf_P(key, sizeof(key), PSTR("%s/%d"), MQTT_TOPIC_RELAY, relayID);
  763. apiRegister(key,
  764. [relayID](char * buffer, size_t len) {
  765. snprintf_P(buffer, len, PSTR("%d"), _relays[relayID].target_status ? 1 : 0);
  766. },
  767. [relayID](const char * payload) {
  768. if (!_relayHandlePayload(relayID, payload)) {
  769. DEBUG_MSG_P(PSTR("[RELAY] Wrong payload (%s)\n"), payload);
  770. return;
  771. }
  772. }
  773. );
  774. snprintf_P(key, sizeof(key), PSTR("%s/%d"), MQTT_TOPIC_PULSE, relayID);
  775. apiRegister(key,
  776. [relayID](char * buffer, size_t len) {
  777. dtostrf((double) _relays[relayID].pulse_ms / 1000, 1, 3, buffer);
  778. },
  779. [relayID](const char * payload) {
  780. unsigned long pulse = 1000 * atof(payload);
  781. if (0 == pulse) return;
  782. if (RELAY_PULSE_NONE != _relays[relayID].pulse) {
  783. DEBUG_MSG_P(PSTR("[RELAY] Overriding relay #%d pulse settings\n"), relayID);
  784. }
  785. _relays[relayID].pulse_ms = pulse;
  786. _relays[relayID].pulse = relayStatus(relayID) ? RELAY_PULSE_ON : RELAY_PULSE_OFF;
  787. relayToggle(relayID, true, false);
  788. }
  789. );
  790. #if defined(ITEAD_SONOFF_IFAN02)
  791. apiRegister(MQTT_TOPIC_SPEED,
  792. [relayID](char * buffer, size_t len) {
  793. snprintf(buffer, len, "%u", getSpeed());
  794. },
  795. [relayID](const char * payload) {
  796. setSpeed(atoi(payload));
  797. }
  798. );
  799. #endif
  800. }
  801. }
  802. #endif // API_SUPPORT
  803. //------------------------------------------------------------------------------
  804. // MQTT
  805. //------------------------------------------------------------------------------
  806. #if MQTT_SUPPORT
  807. const String& relayPayloadOn() {
  808. return _relay_mqtt_payload_on;
  809. }
  810. const String& relayPayloadOff() {
  811. return _relay_mqtt_payload_off;
  812. }
  813. const String& relayPayloadToggle() {
  814. return _relay_mqtt_payload_toggle;
  815. }
  816. const char* relayPayload(RelayStatus status) {
  817. if (status == RelayStatus::OFF) {
  818. return _relay_mqtt_payload_off.c_str();
  819. } else if (status == RelayStatus::ON) {
  820. return _relay_mqtt_payload_on.c_str();
  821. } else if (status == RelayStatus::TOGGLE) {
  822. return _relay_mqtt_payload_toggle.c_str();
  823. }
  824. return "";
  825. }
  826. void _relayMQTTGroup(unsigned char id) {
  827. const String topic = getSetting({"mqttGroup", id});
  828. if (!topic.length()) return;
  829. const auto mode = getSetting({"mqttGroupSync", id}, RELAY_GROUP_SYNC_NORMAL);
  830. if (mode == RELAY_GROUP_SYNC_RECEIVEONLY) return;
  831. auto status = _relayStatusTyped(id);
  832. if (mode == RELAY_GROUP_SYNC_INVERSE) status = _relayStatusInvert(status);
  833. mqttSendRaw(topic.c_str(), relayPayload(status));
  834. }
  835. void relayMQTT(unsigned char id) {
  836. if (id >= _relays.size()) return;
  837. // Send state topic
  838. if (_relays[id].report) {
  839. _relays[id].report = false;
  840. mqttSend(MQTT_TOPIC_RELAY, id, relayPayload(_relayStatusTyped(id)));
  841. }
  842. // Check group topic
  843. if (_relays[id].group_report) {
  844. _relays[id].group_report = false;
  845. _relayMQTTGroup(id);
  846. }
  847. // Send speed for IFAN02
  848. #if defined (ITEAD_SONOFF_IFAN02)
  849. char buffer[5];
  850. snprintf(buffer, sizeof(buffer), "%u", getSpeed());
  851. mqttSend(MQTT_TOPIC_SPEED, buffer);
  852. #endif
  853. }
  854. void relayMQTT() {
  855. for (unsigned int id=0; id < _relays.size(); id++) {
  856. mqttSend(MQTT_TOPIC_RELAY, id, relayPayload(_relayStatusTyped(id)));
  857. }
  858. }
  859. void relayStatusWrap(unsigned char id, RelayStatus value, bool is_group_topic) {
  860. switch (value) {
  861. case RelayStatus::OFF:
  862. relayStatus(id, false, mqttForward(), !is_group_topic);
  863. break;
  864. case RelayStatus::ON:
  865. relayStatus(id, true, mqttForward(), !is_group_topic);
  866. break;
  867. case RelayStatus::TOGGLE:
  868. relayToggle(id, true, true);
  869. break;
  870. default:
  871. _relays[id].report = true;
  872. relayMQTT(id);
  873. break;
  874. }
  875. }
  876. void relayMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  877. if (type == MQTT_CONNECT_EVENT) {
  878. // Send status on connect
  879. #if (HEARTBEAT_MODE == HEARTBEAT_NONE) or (not HEARTBEAT_REPORT_RELAY)
  880. relayMQTT();
  881. #endif
  882. // Subscribe to own /set topic
  883. char relay_topic[strlen(MQTT_TOPIC_RELAY) + 3];
  884. snprintf_P(relay_topic, sizeof(relay_topic), PSTR("%s/+"), MQTT_TOPIC_RELAY);
  885. mqttSubscribe(relay_topic);
  886. // Subscribe to pulse topic
  887. char pulse_topic[strlen(MQTT_TOPIC_PULSE) + 3];
  888. snprintf_P(pulse_topic, sizeof(pulse_topic), PSTR("%s/+"), MQTT_TOPIC_PULSE);
  889. mqttSubscribe(pulse_topic);
  890. #if defined(ITEAD_SONOFF_IFAN02)
  891. mqttSubscribe(MQTT_TOPIC_SPEED);
  892. #endif
  893. // Subscribe to group topics
  894. for (unsigned char i=0; i < _relays.size(); i++) {
  895. const auto t = getSetting({"mqttGroup", i});
  896. if (t.length() > 0) mqttSubscribeRaw(t.c_str());
  897. }
  898. }
  899. if (type == MQTT_MESSAGE_EVENT) {
  900. String t = mqttMagnitude((char *) topic);
  901. // magnitude is relay/#/pulse
  902. if (t.startsWith(MQTT_TOPIC_PULSE)) {
  903. unsigned int id = t.substring(strlen(MQTT_TOPIC_PULSE)+1).toInt();
  904. if (id >= relayCount()) {
  905. DEBUG_MSG_P(PSTR("[RELAY] Wrong relayID (%d)\n"), id);
  906. return;
  907. }
  908. unsigned long pulse = 1000 * atof(payload);
  909. if (0 == pulse) return;
  910. if (RELAY_PULSE_NONE != _relays[id].pulse) {
  911. DEBUG_MSG_P(PSTR("[RELAY] Overriding relay #%d pulse settings\n"), id);
  912. }
  913. _relays[id].pulse_ms = pulse;
  914. _relays[id].pulse = relayStatus(id) ? RELAY_PULSE_ON : RELAY_PULSE_OFF;
  915. relayToggle(id, true, false);
  916. return;
  917. }
  918. // magnitude is relay/#
  919. if (t.startsWith(MQTT_TOPIC_RELAY)) {
  920. // Get relay ID
  921. unsigned int id = t.substring(strlen(MQTT_TOPIC_RELAY)+1).toInt();
  922. if (id >= relayCount()) {
  923. DEBUG_MSG_P(PSTR("[RELAY] Wrong relayID (%d)\n"), id);
  924. return;
  925. }
  926. // Get value
  927. auto value = relayParsePayload(payload);
  928. if (value == RelayStatus::UNKNOWN) return;
  929. relayStatusWrap(id, value, false);
  930. return;
  931. }
  932. // Check group topics
  933. for (unsigned char i=0; i < _relays.size(); i++) {
  934. const String t = getSetting({"mqttGroup", i});
  935. if ((t.length() > 0) && t.equals(topic)) {
  936. auto value = relayParsePayload(payload);
  937. if (value == RelayStatus::UNKNOWN) return;
  938. if ((value == RelayStatus::ON) || (value == RelayStatus::OFF)) {
  939. if (getSetting({"mqttGroupSync", i}, RELAY_GROUP_SYNC_NORMAL) == RELAY_GROUP_SYNC_INVERSE) {
  940. value = _relayStatusInvert(value);
  941. }
  942. }
  943. DEBUG_MSG_P(PSTR("[RELAY] Matched group topic for relayID %d\n"), i);
  944. relayStatusWrap(i, value, true);
  945. }
  946. }
  947. // Itead Sonoff IFAN02
  948. #if defined (ITEAD_SONOFF_IFAN02)
  949. if (t.startsWith(MQTT_TOPIC_SPEED)) {
  950. setSpeed(atoi(payload));
  951. }
  952. #endif
  953. }
  954. if (type == MQTT_DISCONNECT_EVENT) {
  955. for (unsigned char i=0; i < _relays.size(); i++){
  956. const auto reaction = getSetting({"relayOnDisc", i}, 0);
  957. if (1 == reaction) { // switch relay OFF
  958. DEBUG_MSG_P(PSTR("[RELAY] Reset relay (%d) due to MQTT disconnection\n"), i);
  959. relayStatusWrap(i, RelayStatus::OFF, false);
  960. } else if(2 == reaction) { // switch relay ON
  961. DEBUG_MSG_P(PSTR("[RELAY] Set relay (%d) due to MQTT disconnection\n"), i);
  962. relayStatusWrap(i, RelayStatus::ON, false);
  963. }
  964. }
  965. }
  966. }
  967. void relaySetupMQTT() {
  968. mqttRegister(relayMQTTCallback);
  969. }
  970. #endif
  971. void _relaySetupProvider() {
  972. // TODO: implement something like `RelayProvider tuya_provider({.setup_cb = ..., .send_cb = ...})`?
  973. // note of the function call order! relay code is initialized before tuya's, and the easiest
  974. // way to accomplish that is to use ctor as a way to "register" callbacks even before setup() is called
  975. #if TUYA_SUPPORT
  976. tuyaSetupSwitch();
  977. #endif
  978. }
  979. //------------------------------------------------------------------------------
  980. // Settings
  981. //------------------------------------------------------------------------------
  982. #if TERMINAL_SUPPORT
  983. void _relayInitCommands() {
  984. terminalRegisterCommand(F("RELAY"), [](Embedis* e) {
  985. if (e->argc < 2) {
  986. terminalError(F("Wrong arguments"));
  987. return;
  988. }
  989. int id = String(e->argv[1]).toInt();
  990. if (id >= relayCount()) {
  991. DEBUG_MSG_P(PSTR("-ERROR: Wrong relayID (%d)\n"), id);
  992. return;
  993. }
  994. if (e->argc > 2) {
  995. int value = String(e->argv[2]).toInt();
  996. if (value == 2) {
  997. relayToggle(id);
  998. } else {
  999. relayStatus(id, value == 1);
  1000. }
  1001. }
  1002. DEBUG_MSG_P(PSTR("Status: %s\n"), _relays[id].target_status ? "true" : "false");
  1003. if (_relays[id].pulse != RELAY_PULSE_NONE) {
  1004. DEBUG_MSG_P(PSTR("Pulse: %s\n"), (_relays[id].pulse == RELAY_PULSE_ON) ? "ON" : "OFF");
  1005. DEBUG_MSG_P(PSTR("Pulse time: %d\n"), _relays[id].pulse_ms);
  1006. }
  1007. terminalOK();
  1008. });
  1009. #if 0
  1010. terminalRegisterCommand(F("RELAY.INFO"), [](Embedis* e) {
  1011. DEBUG_MSG_P(PSTR(" cur tgt pin type reset lock delay_on delay_off pulse pulse_ms\n"));
  1012. DEBUG_MSG_P(PSTR(" --- --- --- ---- ----- ---- ---------- ----------- ----- ----------\n"));
  1013. for (unsigned char index = 0; index < _relays.size(); ++index) {
  1014. const auto& relay = _relays.at(index);
  1015. DEBUG_MSG_P(PSTR("%3u %3s %3s %3u %4u %5u %4u %10u %11u %5u %10u\n"),
  1016. index,
  1017. relay.current_status ? "ON" : "OFF",
  1018. relay.target_status ? "ON" : "OFF",
  1019. relay.pin, relay.type, relay.reset_pin,
  1020. relay.lock,
  1021. relay.delay_on, relay.delay_off,
  1022. relay.pulse, relay.pulse_ms
  1023. );
  1024. }
  1025. });
  1026. #endif
  1027. }
  1028. #endif // TERMINAL_SUPPORT
  1029. //------------------------------------------------------------------------------
  1030. // Setup
  1031. //------------------------------------------------------------------------------
  1032. void _relayLoop() {
  1033. _relayProcess(false);
  1034. _relayProcess(true);
  1035. #if WEB_SUPPORT
  1036. if (_relay_report_ws) {
  1037. wsPost(_relayWebSocketUpdate);
  1038. _relay_report_ws = false;
  1039. }
  1040. #endif
  1041. }
  1042. // Dummy relays for virtual light switches, Sonoff Dual, Sonoff RF Bridge and Tuya
  1043. void relaySetupDummy(size_t size, bool reconfigure) {
  1044. if (size == _relayDummy) return;
  1045. const size_t new_size = ((_relays.size() - _relayDummy) + size);
  1046. if (new_size > RELAYS_MAX) return;
  1047. _relayDummy = size;
  1048. _relays.resize(new_size);
  1049. if (reconfigure) {
  1050. _relayConfigure();
  1051. }
  1052. #if BROKER_SUPPORT
  1053. ConfigBroker::Publish("relayDummy", String(int(size)));
  1054. #endif
  1055. }
  1056. void _relaySetupAdhoc() {
  1057. size_t relays = 0;
  1058. #if RELAY1_PIN != GPIO_NONE
  1059. ++relays;
  1060. #endif
  1061. #if RELAY2_PIN != GPIO_NONE
  1062. ++relays;
  1063. #endif
  1064. #if RELAY3_PIN != GPIO_NONE
  1065. ++relays;
  1066. #endif
  1067. #if RELAY4_PIN != GPIO_NONE
  1068. ++relays;
  1069. #endif
  1070. #if RELAY5_PIN != GPIO_NONE
  1071. ++relays;
  1072. #endif
  1073. #if RELAY6_PIN != GPIO_NONE
  1074. ++relays;
  1075. #endif
  1076. #if RELAY7_PIN != GPIO_NONE
  1077. ++relays;
  1078. #endif
  1079. #if RELAY8_PIN != GPIO_NONE
  1080. ++relays;
  1081. #endif
  1082. _relays.reserve(relays);
  1083. for (unsigned char id = 0; id < relays; ++id) {
  1084. _relays.emplace_back(id);
  1085. }
  1086. }
  1087. void relaySetup() {
  1088. // Ad-hoc relays
  1089. _relaySetupAdhoc();
  1090. // Dummy (virtual) relays
  1091. relaySetupDummy(getSetting("relayDummy", DUMMY_RELAY_COUNT));
  1092. _relaySetupProvider();
  1093. _relayBackwards();
  1094. _relayConfigure();
  1095. _relayBoot();
  1096. _relayLoop();
  1097. #if WEB_SUPPORT
  1098. relaySetupWS();
  1099. #endif
  1100. #if API_SUPPORT
  1101. relaySetupAPI();
  1102. #endif
  1103. #if MQTT_SUPPORT
  1104. relaySetupMQTT();
  1105. #endif
  1106. #if TERMINAL_SUPPORT
  1107. _relayInitCommands();
  1108. #endif
  1109. // Main callbacks
  1110. espurnaRegisterLoop(_relayLoop);
  1111. espurnaRegisterReload(_relayConfigure);
  1112. DEBUG_MSG_P(PSTR("[RELAY] Number of relays: %d\n"), _relays.size());
  1113. }