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.

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