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.

1436 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. typedef struct {
  15. // Configuration variables
  16. unsigned char pin; // GPIO pin for the relay
  17. unsigned char type; // RELAY_TYPE_NORMAL, RELAY_TYPE_INVERSE, RELAY_TYPE_LATCHED or RELAY_TYPE_LATCHED_INVERSE
  18. unsigned char reset_pin; // GPIO to reset the relay if RELAY_TYPE_LATCHED
  19. unsigned long delay_on; // Delay to turn relay ON
  20. unsigned long delay_off; // Delay to turn relay OFF
  21. unsigned char pulse; // RELAY_PULSE_NONE, RELAY_PULSE_OFF or RELAY_PULSE_ON
  22. unsigned long pulse_ms; // Pulse length in millis
  23. // Status variables
  24. bool current_status; // Holds the current (physical) status of the relay
  25. bool target_status; // Holds the target status
  26. unsigned char lock; // Holds the value of target status, that cannot be changed afterwards. (0 for false, 1 for true, 2 to disable)
  27. unsigned long fw_start; // Flood window start time
  28. unsigned char fw_count; // Number of changes within the current flood window
  29. unsigned long change_start; // Time when relay was scheduled to change
  30. unsigned long change_delay; // Delay until the next change
  31. bool report; // Whether to report to own topic
  32. bool group_report; // Whether to report to group topic
  33. // Helping objects
  34. Ticker pulseTicker; // Holds the pulse back timer
  35. } relay_t;
  36. std::vector<relay_t> _relays;
  37. bool _relayRecursive = false;
  38. uint8_t _relayDummy = DUMMY_RELAY_COUNT;
  39. unsigned long _relay_flood_window = (1000 * RELAY_FLOOD_WINDOW);
  40. unsigned long _relay_flood_changes = RELAY_FLOOD_CHANGES;
  41. unsigned long _relay_delay_interlock;
  42. unsigned char _relay_sync_mode = RELAY_SYNC_ANY;
  43. bool _relay_sync_locked = false;
  44. Ticker _relay_save_timer;
  45. Ticker _relay_sync_timer;
  46. #if WEB_SUPPORT
  47. bool _relay_report_ws = false;
  48. #endif // WEB_SUPPORT
  49. #if MQTT_SUPPORT
  50. String _relay_mqtt_payload_on;
  51. String _relay_mqtt_payload_off;
  52. String _relay_mqtt_payload_toggle;
  53. #endif // MQTT_SUPPORT
  54. // -----------------------------------------------------------------------------
  55. // UTILITY
  56. // -----------------------------------------------------------------------------
  57. bool _relayHandlePayload(unsigned char relayID, const char* payload) {
  58. auto value = relayParsePayload(payload);
  59. if (value == RelayStatus::UNKNOWN) return false;
  60. if (value == RelayStatus::OFF) {
  61. relayStatus(relayID, false);
  62. } else if (value == RelayStatus::ON) {
  63. relayStatus(relayID, true);
  64. } else if (value == RelayStatus::TOGGLE) {
  65. relayToggle(relayID);
  66. }
  67. return true;
  68. }
  69. RelayStatus _relayStatusInvert(RelayStatus status) {
  70. return (status == RelayStatus::ON) ? RelayStatus::OFF : status;
  71. }
  72. RelayStatus _relayStatusTyped(unsigned char id) {
  73. if (id >= _relays.size()) return RelayStatus::OFF;
  74. const bool status = _relays[id].current_status;
  75. return (status) ? RelayStatus::ON : RelayStatus::OFF;
  76. }
  77. void _relayLockAll() {
  78. for (auto& relay : _relays) {
  79. relay.lock = relay.target_status ? RELAY_LOCK_ON : RELAY_LOCK_OFF;
  80. }
  81. _relay_sync_locked = true;
  82. }
  83. void _relayUnlockAll() {
  84. for (auto& relay : _relays) {
  85. relay.lock = RELAY_LOCK_DISABLED;
  86. }
  87. _relay_sync_locked = false;
  88. }
  89. bool _relayStatusLock(unsigned char id, bool status) {
  90. if (_relays[id].lock != RELAY_LOCK_DISABLED) {
  91. bool lock = _relays[id].lock == RELAY_LOCK_ON;
  92. if ((lock != status) || (lock != _relays[id].target_status)) {
  93. _relays[id].target_status = lock;
  94. _relays[id].change_delay = 0;
  95. return false;
  96. }
  97. }
  98. return true;
  99. }
  100. // https://github.com/xoseperez/espurna/issues/1510#issuecomment-461894516
  101. // completely reset timing on the other relay to sync with this one
  102. // to ensure that they change state sequentially
  103. void _relaySyncRelaysDelay(unsigned char first, unsigned char second) {
  104. _relays[second].fw_start = _relays[first].change_start;
  105. _relays[second].fw_count = 1;
  106. _relays[second].change_delay = std::max({
  107. _relay_delay_interlock,
  108. _relays[first].change_delay,
  109. _relays[second].change_delay
  110. });
  111. }
  112. void _relaySyncUnlock() {
  113. bool unlock = true;
  114. bool all_off = true;
  115. for (const auto& relay : _relays) {
  116. unlock = unlock && (relay.current_status == relay.target_status);
  117. if (!unlock) break;
  118. all_off = all_off && !relay.current_status;
  119. }
  120. if (!unlock) return;
  121. auto action = []() {
  122. _relayUnlockAll();
  123. #if WEB_SUPPORT
  124. _relay_report_ws = true;
  125. #endif
  126. };
  127. if (all_off) {
  128. _relay_sync_timer.once_ms(_relay_delay_interlock, action);
  129. } else {
  130. action();
  131. }
  132. }
  133. // -----------------------------------------------------------------------------
  134. // RELAY PROVIDERS
  135. // -----------------------------------------------------------------------------
  136. void _relayProviderStatus(unsigned char id, bool status) {
  137. // Check relay ID
  138. if (id >= _relays.size()) return;
  139. // Store new current status
  140. _relays[id].current_status = status;
  141. #if RELAY_PROVIDER == RELAY_PROVIDER_RFBRIDGE
  142. rfbStatus(id, status);
  143. #endif
  144. #if RELAY_PROVIDER == RELAY_PROVIDER_DUAL
  145. // Calculate mask
  146. unsigned char mask=0;
  147. for (unsigned char i=0; i<_relays.size(); i++) {
  148. if (_relays[i].current_status) mask = mask + (1 << i);
  149. }
  150. DEBUG_MSG_P(PSTR("[RELAY] [DUAL] Sending relay mask: %d\n"), mask);
  151. // Send it to F330
  152. Serial.flush();
  153. Serial.write(0xA0);
  154. Serial.write(0x04);
  155. Serial.write(mask);
  156. Serial.write(0xA1);
  157. Serial.flush();
  158. #endif
  159. #if RELAY_PROVIDER == RELAY_PROVIDER_STM
  160. Serial.flush();
  161. Serial.write(0xA0);
  162. Serial.write(id + 1);
  163. Serial.write(status);
  164. Serial.write(0xA1 + status + id);
  165. // The serial init are not full recognized by relais board.
  166. // References: https://github.com/xoseperez/espurna/issues/1519 , https://github.com/xoseperez/espurna/issues/1130
  167. delay(100);
  168. Serial.flush();
  169. #endif
  170. #if RELAY_PROVIDER == RELAY_PROVIDER_LIGHT
  171. // Real relays
  172. uint8_t physical = _relays.size() - _relayDummy;
  173. // Support for a mixed of dummy and real relays
  174. // Reference: https://github.com/xoseperez/espurna/issues/1305
  175. if (id >= physical) {
  176. // If the number of dummy relays matches the number of light channels
  177. // assume each relay controls one channel.
  178. // If the number of dummy relays is the number of channels plus 1
  179. // assume the first one controls all the channels and
  180. // the rest one channel each.
  181. // Otherwise every dummy relay controls all channels.
  182. if (_relayDummy == lightChannels()) {
  183. lightState(id-physical, status);
  184. lightState(true);
  185. } else if (_relayDummy == (lightChannels() + 1u)) {
  186. if (id == physical) {
  187. lightState(status);
  188. } else {
  189. lightState(id-1-physical, status);
  190. }
  191. } else {
  192. lightState(status);
  193. }
  194. lightUpdate(true, true);
  195. return;
  196. }
  197. #endif
  198. #if (RELAY_PROVIDER == RELAY_PROVIDER_RELAY) || (RELAY_PROVIDER == RELAY_PROVIDER_LIGHT)
  199. // If this is a light, all dummy relays have already been processed above
  200. // we reach here if the user has toggled a physical relay
  201. if (_relays[id].type == RELAY_TYPE_NORMAL) {
  202. digitalWrite(_relays[id].pin, status);
  203. } else if (_relays[id].type == RELAY_TYPE_INVERSE) {
  204. digitalWrite(_relays[id].pin, !status);
  205. } else if (_relays[id].type == RELAY_TYPE_LATCHED || _relays[id].type == RELAY_TYPE_LATCHED_INVERSE) {
  206. bool pulse = RELAY_TYPE_LATCHED ? HIGH : LOW;
  207. digitalWrite(_relays[id].pin, !pulse);
  208. if (GPIO_NONE != _relays[id].reset_pin) digitalWrite(_relays[id].reset_pin, !pulse);
  209. if (status || (GPIO_NONE == _relays[id].reset_pin)) {
  210. digitalWrite(_relays[id].pin, pulse);
  211. } else {
  212. digitalWrite(_relays[id].reset_pin, pulse);
  213. }
  214. nice_delay(RELAY_LATCHING_PULSE);
  215. digitalWrite(_relays[id].pin, !pulse);
  216. if (GPIO_NONE != _relays[id].reset_pin) digitalWrite(_relays[id].reset_pin, !pulse);
  217. }
  218. #endif
  219. }
  220. /**
  221. * Walks the relay vector processing only those relays
  222. * that have to change to the requested mode
  223. * @bool mode Requested mode
  224. */
  225. void _relayProcess(bool mode) {
  226. bool changed = false;
  227. for (unsigned char id = 0; id < _relays.size(); id++) {
  228. bool target = _relays[id].target_status;
  229. // Only process the relays we have to change
  230. if (target == _relays[id].current_status) continue;
  231. // Only process the relays we have to change to the requested mode
  232. if (target != mode) continue;
  233. // Only process if the change delay has expired
  234. if (millis() - _relays[id].change_start < _relays[id].change_delay) continue;
  235. // Purge existing delay in case of cancelation
  236. _relays[id].change_delay = 0;
  237. changed = true;
  238. DEBUG_MSG_P(PSTR("[RELAY] #%d set to %s\n"), id, target ? "ON" : "OFF");
  239. // Call the provider to perform the action
  240. _relayProviderStatus(id, target);
  241. // Send to Broker
  242. #if BROKER_SUPPORT
  243. StatusBroker::Publish(MQTT_TOPIC_RELAY, id, target);
  244. #endif
  245. // Send MQTT
  246. #if MQTT_SUPPORT
  247. relayMQTT(id);
  248. #endif
  249. #if WEB_SUPPORT
  250. _relay_report_ws = true;
  251. #endif
  252. if (!_relayRecursive) {
  253. relayPulse(id);
  254. // We will trigger a eeprom save only if
  255. // we care about current relay status on boot
  256. unsigned char boot_mode = getSetting("relayBoot", id, RELAY_BOOT_MODE).toInt();
  257. bool save_eeprom = ((RELAY_BOOT_SAME == boot_mode) || (RELAY_BOOT_TOGGLE == boot_mode));
  258. _relay_save_timer.once_ms(RELAY_SAVE_DELAY, relaySave, save_eeprom);
  259. }
  260. _relays[id].report = false;
  261. _relays[id].group_report = false;
  262. }
  263. // Whenever we are using sync modes and any relay had changed the state, check if we can unlock
  264. const bool needs_unlock = ((_relay_sync_mode == RELAY_SYNC_NONE_OR_ONE) || (_relay_sync_mode == RELAY_SYNC_ONE));
  265. if (_relay_sync_locked && needs_unlock && changed) {
  266. _relaySyncUnlock();
  267. }
  268. }
  269. #if defined(ITEAD_SONOFF_IFAN02)
  270. unsigned char _relay_ifan02_speeds[] = {0, 1, 3, 5};
  271. unsigned char getSpeed() {
  272. unsigned char speed =
  273. (_relays[1].target_status ? 1 : 0) +
  274. (_relays[2].target_status ? 2 : 0) +
  275. (_relays[3].target_status ? 4 : 0);
  276. for (unsigned char i=0; i<4; i++) {
  277. if (_relay_ifan02_speeds[i] == speed) return i;
  278. }
  279. return 0;
  280. }
  281. void setSpeed(unsigned char speed) {
  282. if ((0 <= speed) & (speed <= 3)) {
  283. if (getSpeed() == speed) return;
  284. unsigned char states = _relay_ifan02_speeds[speed];
  285. for (unsigned char i=0; i<3; i++) {
  286. relayStatus(i+1, states & 1 == 1);
  287. states >>= 1;
  288. }
  289. }
  290. }
  291. #endif
  292. // -----------------------------------------------------------------------------
  293. // RELAY
  294. // -----------------------------------------------------------------------------
  295. // State persistance persistance
  296. RelayMask INLINE _relayMaskRtcmem() {
  297. return RelayMask(Rtcmem->relay);
  298. }
  299. void INLINE _relayMaskRtcmem(uint32_t mask) {
  300. Rtcmem->relay = mask;
  301. }
  302. void INLINE _relayMaskRtcmem(const RelayMask& mask) {
  303. _relayMaskRtcmem(mask.as_u32);
  304. }
  305. void INLINE _relayMaskRtcmem(const std::bitset<RELAYS_MAX>& bitset) {
  306. _relayMaskRtcmem(bitset.to_ulong());
  307. }
  308. RelayMask INLINE _relayMaskSettings() {
  309. return RelayMask(getSetting("relayBootMask"));
  310. }
  311. void INLINE _relayMaskSettings(uint32_t mask) {
  312. setSetting("relayBootMask", u32toString(mask, 2));
  313. }
  314. void INLINE _relayMaskSettings(const RelayMask& mask) {
  315. setSetting("relayBootMask", mask.as_string);
  316. }
  317. void INLINE _relayMaskSettings(const std::bitset<RELAYS_MAX>& bitset) {
  318. _relayMaskSettings(bitset.to_ulong());
  319. }
  320. // Pulse timers (timer after ON or OFF event)
  321. void relayPulse(unsigned char id) {
  322. _relays[id].pulseTicker.detach();
  323. byte mode = _relays[id].pulse;
  324. if (mode == RELAY_PULSE_NONE) return;
  325. unsigned long ms = _relays[id].pulse_ms;
  326. if (ms == 0) return;
  327. bool status = relayStatus(id);
  328. bool pulseStatus = (mode == RELAY_PULSE_ON);
  329. if (pulseStatus != status) {
  330. DEBUG_MSG_P(PSTR("[RELAY] Scheduling relay #%d back in %lums (pulse)\n"), id, ms);
  331. _relays[id].pulseTicker.once_ms(ms, relayToggle, id);
  332. // Reconfigure after dynamic pulse
  333. _relays[id].pulse = getSetting("relayPulse", id, RELAY_PULSE_MODE).toInt();
  334. _relays[id].pulse_ms = 1000 * getSetting("relayTime", id, RELAY_PULSE_MODE).toFloat();
  335. }
  336. }
  337. // General relay status control
  338. bool relayStatus(unsigned char id, bool status, bool report, bool group_report) {
  339. if (id >= _relays.size()) return false;
  340. if (!_relayStatusLock(id, status)) {
  341. DEBUG_MSG_P(PSTR("[RELAY] #%d is locked to %s\n"), id, _relays[id].current_status ? "ON" : "OFF");
  342. _relays[id].report = true;
  343. _relays[id].group_report = true;
  344. return false;
  345. }
  346. bool changed = false;
  347. if (_relays[id].current_status == status) {
  348. if (_relays[id].target_status != status) {
  349. DEBUG_MSG_P(PSTR("[RELAY] #%d scheduled change cancelled\n"), id);
  350. _relays[id].target_status = status;
  351. _relays[id].report = false;
  352. _relays[id].group_report = false;
  353. _relays[id].change_delay = 0;
  354. changed = true;
  355. }
  356. // For RFBridge, keep sending the message even if the status is already the required
  357. #if RELAY_PROVIDER == RELAY_PROVIDER_RFBRIDGE
  358. rfbStatus(id, status);
  359. #endif
  360. // Update the pulse counter if the relay is already in the non-normal state (#454)
  361. relayPulse(id);
  362. } else {
  363. unsigned long current_time = millis();
  364. unsigned long change_delay = status ? _relays[id].delay_on : _relays[id].delay_off;
  365. _relays[id].fw_count++;
  366. _relays[id].change_start = current_time;
  367. _relays[id].change_delay = std::max(_relays[id].change_delay, change_delay);
  368. // If current_time is off-limits the floodWindow...
  369. const auto fw_diff = current_time - _relays[id].fw_start;
  370. if (fw_diff > _relay_flood_window) {
  371. // We reset the floodWindow
  372. _relays[id].fw_start = current_time;
  373. _relays[id].fw_count = 1;
  374. // If current_time is in the floodWindow and there have been too many requests...
  375. } else if (_relays[id].fw_count >= _relay_flood_changes) {
  376. // We schedule the changes to the end of the floodWindow
  377. // unless it's already delayed beyond that point
  378. _relays[id].change_delay = std::max(change_delay, _relay_flood_window - fw_diff);
  379. // Another option is to always move it forward, starting from current time
  380. //_relays[id].fw_start = current_time;
  381. }
  382. _relays[id].target_status = status;
  383. if (report) _relays[id].report = true;
  384. if (group_report) _relays[id].group_report = true;
  385. relaySync(id);
  386. DEBUG_MSG_P(PSTR("[RELAY] #%d scheduled %s in %u ms\n"),
  387. id, status ? "ON" : "OFF", _relays[id].change_delay
  388. );
  389. changed = true;
  390. }
  391. return changed;
  392. }
  393. bool relayStatus(unsigned char id, bool status) {
  394. return relayStatus(id, status, mqttForward(), true);
  395. }
  396. bool relayStatus(unsigned char id) {
  397. // Check that relay ID is valid
  398. if (id >= _relays.size()) return false;
  399. // Get status directly from storage
  400. return _relays[id].current_status;
  401. }
  402. void relaySync(unsigned char id) {
  403. // No sync if none or only one relay
  404. if (_relays.size() < 2) return;
  405. // Do not go on if we are comming from a previous sync
  406. if (_relayRecursive) return;
  407. // Flag sync mode
  408. _relayRecursive = true;
  409. bool status = _relays[id].target_status;
  410. // If RELAY_SYNC_SAME all relays should have the same state
  411. if (_relay_sync_mode == RELAY_SYNC_SAME) {
  412. for (unsigned short i=0; i<_relays.size(); i++) {
  413. if (i != id) relayStatus(i, status);
  414. }
  415. // If RELAY_SYNC_FIRST all relays should have the same state as first if first changes
  416. } else if (_relay_sync_mode == RELAY_SYNC_FIRST) {
  417. if (id == 0) {
  418. for (unsigned short i=1; i<_relays.size(); i++) {
  419. relayStatus(i, status);
  420. }
  421. }
  422. } else if ((_relay_sync_mode == RELAY_SYNC_NONE_OR_ONE) || (_relay_sync_mode == RELAY_SYNC_ONE)) {
  423. // If NONE_OR_ONE or ONE and setting ON we should set OFF all the others
  424. if (status) {
  425. if (_relay_sync_mode != RELAY_SYNC_ANY) {
  426. for (unsigned short other_id=0; other_id<_relays.size(); other_id++) {
  427. if (other_id != id) {
  428. relayStatus(other_id, false);
  429. if (relayStatus(other_id)) {
  430. _relaySyncRelaysDelay(other_id, id);
  431. }
  432. }
  433. }
  434. }
  435. // If ONLY_ONE and setting OFF we should set ON the other one
  436. } else {
  437. if (_relay_sync_mode == RELAY_SYNC_ONE) {
  438. unsigned char other_id = (id + 1) % _relays.size();
  439. _relaySyncRelaysDelay(id, other_id);
  440. relayStatus(other_id, true);
  441. }
  442. }
  443. _relayLockAll();
  444. }
  445. // Unflag sync mode
  446. _relayRecursive = false;
  447. }
  448. void relaySave(bool eeprom) {
  449. const unsigned char count = constrain(relayCount(), 0, RELAYS_MAX);
  450. auto statuses = std::bitset<RELAYS_MAX>(0);
  451. for (unsigned int id = 0; id < count; ++id) {
  452. statuses.set(id, relayStatus(id));
  453. }
  454. const RelayMask mask(statuses);
  455. DEBUG_MSG_P(PSTR("[RELAY] Setting relay mask: %s\n"), mask.as_string.c_str());
  456. // Persist only to rtcmem, unless requested to save to the eeprom
  457. _relayMaskRtcmem(mask);
  458. // The 'eeprom' flag controls whether we are commiting this change or not.
  459. // It is useful to set it to 'false' if the relay change triggering the
  460. // save involves a relay whose boot mode is independent from current mode,
  461. // thus storing the last relay value is not absolutely necessary.
  462. // Nevertheless, we store the value in the EEPROM buffer so it will be written
  463. // on the next commit.
  464. if (eeprom) {
  465. _relayMaskSettings(mask);
  466. // We are actually enqueuing the commit so it will be
  467. // executed on the main loop, in case this is called from a system context callback
  468. eepromCommit();
  469. }
  470. }
  471. void relaySave() {
  472. relaySave(false);
  473. }
  474. void relayToggle(unsigned char id, bool report, bool group_report) {
  475. if (id >= _relays.size()) return;
  476. relayStatus(id, !relayStatus(id), report, group_report);
  477. }
  478. void relayToggle(unsigned char id) {
  479. relayToggle(id, mqttForward(), true);
  480. }
  481. unsigned char relayCount() {
  482. return _relays.size();
  483. }
  484. RelayStatus relayParsePayload(const char * payload) {
  485. // Don't parse empty strings
  486. const auto len = strlen(payload);
  487. if (!len) return RelayStatus::UNKNOWN;
  488. // Check most commonly used payloads
  489. if (len == 1) {
  490. if (payload[0] == '0') return RelayStatus::OFF;
  491. if (payload[0] == '1') return RelayStatus::ON;
  492. if (payload[0] == '2') return RelayStatus::TOGGLE;
  493. return RelayStatus::UNKNOWN;
  494. }
  495. // If possible, compare to locally configured payload strings
  496. #if MQTT_SUPPORT
  497. if (_relay_mqtt_payload_off.equals(payload)) return RelayStatus::OFF;
  498. if (_relay_mqtt_payload_on.equals(payload)) return RelayStatus::ON;
  499. if (_relay_mqtt_payload_toggle.equals(payload)) return RelayStatus::TOGGLE;
  500. #endif // MQTT_SUPPORT
  501. // Finally, check for "OFF", "ON", "TOGGLE" (both lower and upper cases)
  502. String temp(payload);
  503. temp.trim();
  504. if (temp.equalsIgnoreCase("off")) {
  505. return RelayStatus::OFF;
  506. } else if (temp.equalsIgnoreCase("on")) {
  507. return RelayStatus::ON;
  508. } else if (temp.equalsIgnoreCase("toggle")) {
  509. return RelayStatus::TOGGLE;
  510. }
  511. return RelayStatus::UNKNOWN;
  512. }
  513. // BACKWARDS COMPATIBILITY
  514. void _relayBackwards() {
  515. #if defined(EEPROM_RELAY_STATUS)
  516. {
  517. uint8_t mask = EEPROMr.read(EEPROM_RELAY_STATUS);
  518. if (mask != 0xff) {
  519. _relayMaskSettings(static_cast<uint32_t>(mask));
  520. EEPROMr.write(EEPROM_RELAY_STATUS, 0xff);
  521. eepromCommit();
  522. }
  523. }
  524. #endif
  525. for (unsigned int i=0; i<_relays.size(); i++) {
  526. if (!hasSetting("mqttGroupInv", i)) continue;
  527. setSetting("mqttGroupSync", i, getSetting("mqttGroupInv", i));
  528. delSetting("mqttGroupInv", i);
  529. }
  530. }
  531. void _relayBoot() {
  532. _relayRecursive = true;
  533. bool trigger_save = false;
  534. const auto stored_mask = rtcmemStatus()
  535. ? _relayMaskRtcmem()
  536. : _relayMaskSettings();
  537. DEBUG_MSG_P(PSTR("[RELAY] Retrieving mask: %s\n"), stored_mask.as_string.c_str());
  538. auto mask = std::bitset<RELAYS_MAX>(stored_mask.as_u32);
  539. // Walk the relays
  540. unsigned char lock;
  541. bool status;
  542. for (unsigned char i=0; i<relayCount(); ++i) {
  543. unsigned char boot_mode = getSetting("relayBoot", i, RELAY_BOOT_MODE).toInt();
  544. DEBUG_MSG_P(PSTR("[RELAY] Relay #%u boot mode %u\n"), i, boot_mode);
  545. status = false;
  546. lock = RELAY_LOCK_DISABLED;
  547. switch (boot_mode) {
  548. case RELAY_BOOT_SAME:
  549. status = mask.test(i);
  550. break;
  551. case RELAY_BOOT_TOGGLE:
  552. status = !mask[i];
  553. mask.flip(i);
  554. trigger_save = true;
  555. break;
  556. case RELAY_BOOT_LOCKED_ON:
  557. status = true;
  558. lock = RELAY_LOCK_ON;
  559. break;
  560. case RELAY_BOOT_LOCKED_OFF:
  561. lock = RELAY_LOCK_OFF;
  562. break;
  563. case RELAY_BOOT_ON:
  564. status = true;
  565. break;
  566. case RELAY_BOOT_OFF:
  567. default:
  568. break;
  569. }
  570. _relays[i].current_status = !status;
  571. _relays[i].target_status = status;
  572. _relays[i].change_start = millis();
  573. #if RELAY_PROVIDER == RELAY_PROVIDER_STM
  574. // XXX hack for correctly restoring relay state on boot
  575. // because of broken stm relay firmware
  576. _relays[i].change_delay = 3000 + 1000 * i;
  577. #endif
  578. _relays[i].lock = lock;
  579. }
  580. _relayMaskRtcmem(mask);
  581. // Save if there is any relay in the RELAY_BOOT_TOGGLE mode
  582. if (trigger_save) {
  583. _relayMaskSettings(mask);
  584. }
  585. _relayRecursive = false;
  586. #if TUYA_SUPPORT
  587. tuyaSyncSwitchStatus();
  588. #endif
  589. }
  590. constexpr const unsigned long _relayDelayOn(unsigned char index) {
  591. return (
  592. (index == 0) ? RELAY1_DELAY_ON :
  593. (index == 1) ? RELAY2_DELAY_ON :
  594. (index == 2) ? RELAY3_DELAY_ON :
  595. (index == 3) ? RELAY4_DELAY_ON :
  596. (index == 4) ? RELAY5_DELAY_ON :
  597. (index == 5) ? RELAY6_DELAY_ON :
  598. (index == 6) ? RELAY7_DELAY_ON :
  599. (index == 7) ? RELAY8_DELAY_ON : 0
  600. );
  601. }
  602. constexpr const unsigned long _relayDelayOff(unsigned char index) {
  603. return (
  604. (index == 0) ? RELAY1_DELAY_OFF :
  605. (index == 1) ? RELAY2_DELAY_OFF :
  606. (index == 2) ? RELAY3_DELAY_OFF :
  607. (index == 3) ? RELAY4_DELAY_OFF :
  608. (index == 4) ? RELAY5_DELAY_OFF :
  609. (index == 5) ? RELAY6_DELAY_OFF :
  610. (index == 6) ? RELAY7_DELAY_OFF :
  611. (index == 7) ? RELAY8_DELAY_OFF : 0
  612. );
  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(unsigned char size, bool reconfigure) {
  1042. size = constrain(size + _relays.size(), _relays.size(), RELAYS_MAX);
  1043. if (size == _relays.size()) return;
  1044. _relayDummy = size;
  1045. _relays.insert(_relays.end(), size, {
  1046. GPIO_NONE, RELAY_TYPE_NORMAL, GPIO_NONE
  1047. });
  1048. if (reconfigure) {
  1049. _relayConfigure();
  1050. }
  1051. #if BROKER_SUPPORT
  1052. ConfigBroker::Publish("relayDummy", String(int(size)));
  1053. #endif
  1054. }
  1055. void relaySetup() {
  1056. // Ad-hoc relays
  1057. #if RELAY1_PIN != GPIO_NONE
  1058. _relays.push_back((relay_t) { RELAY1_PIN, RELAY1_TYPE, RELAY1_RESET_PIN });
  1059. #endif
  1060. #if RELAY2_PIN != GPIO_NONE
  1061. _relays.push_back((relay_t) { RELAY2_PIN, RELAY2_TYPE, RELAY2_RESET_PIN });
  1062. #endif
  1063. #if RELAY3_PIN != GPIO_NONE
  1064. _relays.push_back((relay_t) { RELAY3_PIN, RELAY3_TYPE, RELAY3_RESET_PIN });
  1065. #endif
  1066. #if RELAY4_PIN != GPIO_NONE
  1067. _relays.push_back((relay_t) { RELAY4_PIN, RELAY4_TYPE, RELAY4_RESET_PIN });
  1068. #endif
  1069. #if RELAY5_PIN != GPIO_NONE
  1070. _relays.push_back((relay_t) { RELAY5_PIN, RELAY5_TYPE, RELAY5_RESET_PIN });
  1071. #endif
  1072. #if RELAY6_PIN != GPIO_NONE
  1073. _relays.push_back((relay_t) { RELAY6_PIN, RELAY6_TYPE, RELAY6_RESET_PIN });
  1074. #endif
  1075. #if RELAY7_PIN != GPIO_NONE
  1076. _relays.push_back((relay_t) { RELAY7_PIN, RELAY7_TYPE, RELAY7_RESET_PIN });
  1077. #endif
  1078. #if RELAY8_PIN != GPIO_NONE
  1079. _relays.push_back((relay_t) { RELAY8_PIN, RELAY8_TYPE, RELAY8_RESET_PIN });
  1080. #endif
  1081. relaySetupDummy(getSetting("relayDummy", DUMMY_RELAY_COUNT).toInt());
  1082. _relaySetupProvider();
  1083. _relayBackwards();
  1084. _relayConfigure();
  1085. _relayBoot();
  1086. _relayLoop();
  1087. #if WEB_SUPPORT
  1088. relaySetupWS();
  1089. #endif
  1090. #if API_SUPPORT
  1091. relaySetupAPI();
  1092. #endif
  1093. #if MQTT_SUPPORT
  1094. relaySetupMQTT();
  1095. #endif
  1096. #if TERMINAL_SUPPORT
  1097. _relayInitCommands();
  1098. #endif
  1099. // Main callbacks
  1100. espurnaRegisterLoop(_relayLoop);
  1101. espurnaRegisterReload(_relayConfigure);
  1102. DEBUG_MSG_P(PSTR("[RELAY] Number of relays: %d\n"), _relays.size());
  1103. }