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.

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