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