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.

846 lines
24 KiB

7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
  1. /*
  2. RELAY MODULE
  3. Copyright (C) 2016-2018 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #include <EEPROM.h>
  6. #include <Ticker.h>
  7. #include <ArduinoJson.h>
  8. #include <vector>
  9. #include <functional>
  10. typedef struct {
  11. // Configuration variables
  12. unsigned char pin; // GPIO pin for the relay
  13. unsigned char type; // RELAY_TYPE_NORMAL, RELAY_TYPE_INVERSE or RELAY_TYPE_LATCHED
  14. unsigned char reset_pin; // GPIO to reset the relay if RELAY_TYPE_LATCHED
  15. unsigned long delay_on; // Delay to turn relay ON
  16. unsigned long delay_off; // Delay to turn relay OFF
  17. unsigned char pulse; // RELAY_PULSE_NONE, RELAY_PULSE_OFF or RELAY_PULSE_ON
  18. unsigned long pulse_ms; // Pulse length in millis
  19. // Status variables
  20. bool current_status; // Holds the current (physical) status of the relay
  21. bool target_status; // Holds the target status
  22. unsigned long fw_start; // Flood window start time
  23. unsigned char fw_count; // Number of changes within the current flood window
  24. unsigned long change_time; // Scheduled time to change
  25. bool report; // Whether to report to own topic
  26. bool group_report; // Whether to report to group topic
  27. // Helping objects
  28. Ticker pulseTicker; // Holds the pulse back timer
  29. } relay_t;
  30. std::vector<relay_t> _relays;
  31. bool _relayRecursive = false;
  32. Ticker _relaySaveTicker;
  33. // -----------------------------------------------------------------------------
  34. // RELAY PROVIDERS
  35. // -----------------------------------------------------------------------------
  36. void _relayProviderStatus(unsigned char id, bool status) {
  37. // Check relay ID
  38. if (id >= _relays.size()) return;
  39. // Store new current status
  40. _relays[id].current_status = status;
  41. #if RELAY_PROVIDER == RELAY_PROVIDER_RFBRIDGE
  42. rfbStatus(id, status);
  43. #endif
  44. #if RELAY_PROVIDER == RELAY_PROVIDER_DUAL
  45. // Calculate mask
  46. unsigned char mask=0;
  47. for (unsigned char i=0; i<_relays.size(); i++) {
  48. if (_relays[i].current_status) mask = mask + (1 << i);
  49. }
  50. // Send it to F330
  51. Serial.flush();
  52. Serial.write(0xA0);
  53. Serial.write(0x04);
  54. Serial.write(mask);
  55. Serial.write(0xA1);
  56. Serial.flush();
  57. #endif
  58. #if RELAY_PROVIDER == RELAY_PROVIDER_LIGHT
  59. // If the number of relays matches the number of light channels
  60. // assume each relay controls one channel.
  61. // If the number of relays is the number of channels plus 1
  62. // assume the first one controls all the channels and
  63. // the rest one channel each.
  64. // Otherwise every relay controls all channels.
  65. // TODO: this won't work with a mixed of dummy and real relays
  66. // but this option is not allowed atm (YANGNI)
  67. if (_relays.size() == lightChannels()) {
  68. lightState(id, status);
  69. lightState(true);
  70. } else if (_relays.size() == lightChannels() + 1) {
  71. if (id == 0) {
  72. lightState(status);
  73. } else {
  74. lightState(id-1, status);
  75. }
  76. } else {
  77. lightState(status);
  78. }
  79. lightUpdate(true, true);
  80. #endif
  81. #if RELAY_PROVIDER == RELAY_PROVIDER_RELAY
  82. if (_relays[id].type == RELAY_TYPE_NORMAL) {
  83. digitalWrite(_relays[id].pin, status);
  84. } else if (_relays[id].type == RELAY_TYPE_INVERSE) {
  85. digitalWrite(_relays[id].pin, !status);
  86. } else if (_relays[id].type == RELAY_TYPE_LATCHED) {
  87. digitalWrite(_relays[id].pin, LOW);
  88. digitalWrite(_relays[id].reset_pin, LOW);
  89. if (status) {
  90. digitalWrite(_relays[id].pin, HIGH);
  91. } else {
  92. digitalWrite(_relays[id].reset_pin, HIGH);
  93. }
  94. delay(RELAY_LATCHING_PULSE);
  95. digitalWrite(_relays[id].pin, LOW);
  96. digitalWrite(_relays[id].reset_pin, LOW);
  97. }
  98. #endif
  99. }
  100. // -----------------------------------------------------------------------------
  101. // RELAY
  102. // -----------------------------------------------------------------------------
  103. void relayPulse(unsigned char id) {
  104. byte mode = _relays[id].pulse;
  105. if (mode == RELAY_PULSE_NONE) return;
  106. unsigned long ms = _relays[id].pulse_ms;
  107. if (ms == 0) return;
  108. bool status = relayStatus(id);
  109. bool pulseStatus = (mode == RELAY_PULSE_ON);
  110. if (pulseStatus == status) {
  111. _relays[id].pulseTicker.detach();
  112. } else {
  113. _relays[id].pulseTicker.once_ms(ms, relayToggle, id);
  114. }
  115. }
  116. bool relayStatus(unsigned char id, bool status, bool report, bool group_report) {
  117. if (id >= _relays.size()) return false;
  118. bool changed = false;
  119. if (_relays[id].current_status == status) {
  120. if (_relays[id].target_status != status) {
  121. DEBUG_MSG_P(PSTR("[RELAY] #%d scheduled change cancelled\n"), id);
  122. _relays[id].target_status = status;
  123. _relays[id].report = false;
  124. _relays[id].group_report = false;
  125. changed = true;
  126. }
  127. // For RFBridge, keep sending the message even if the status is already the required
  128. #if RELAY_PROVIDER == RELAY_PROVIDER_RFBRIDGE
  129. rfbStatus(id, status);
  130. #endif
  131. // Update the pulse counter if the relay is already in the non-normal state (#454)
  132. relayPulse(id);
  133. } else {
  134. unsigned int current_time = millis();
  135. unsigned int fw_end = _relays[id].fw_start + 1000 * RELAY_FLOOD_WINDOW;
  136. unsigned long delay = status ? _relays[id].delay_on : _relays[id].delay_off;
  137. _relays[id].fw_count++;
  138. _relays[id].change_time = current_time + delay;
  139. // If current_time is off-limits the floodWindow...
  140. if (current_time < _relays[id].fw_start || fw_end <= current_time) {
  141. // We reset the floodWindow
  142. _relays[id].fw_start = current_time;
  143. _relays[id].fw_count = 1;
  144. // If current_time is in the floodWindow and there have been too many requests...
  145. } else if (_relays[id].fw_count >= RELAY_FLOOD_CHANGES) {
  146. // We schedule the changes to the end of the floodWindow
  147. // unless it's already delayed beyond that point
  148. if (fw_end - delay > current_time) {
  149. _relays[id].change_time = fw_end;
  150. }
  151. }
  152. _relays[id].target_status = status;
  153. if (report) _relays[id].report = true;
  154. if (group_report) _relays[id].group_report = true;
  155. relaySync(id);
  156. DEBUG_MSG_P(PSTR("[RELAY] #%d scheduled %s in %u ms\n"),
  157. id, status ? "ON" : "OFF",
  158. (_relays[id].change_time - current_time));
  159. changed = true;
  160. }
  161. return changed;
  162. }
  163. bool relayStatus(unsigned char id, bool status) {
  164. return relayStatus(id, status, true, true);
  165. }
  166. bool relayStatus(unsigned char id) {
  167. // Check relay ID
  168. if (id >= _relays.size()) return false;
  169. // Get status from storage
  170. return _relays[id].current_status;
  171. }
  172. void relaySync(unsigned char id) {
  173. // No sync if none or only one relay
  174. if (_relays.size() < 2) return;
  175. // Do not go on if we are comming from a previous sync
  176. if (_relayRecursive) return;
  177. // Flag sync mode
  178. _relayRecursive = true;
  179. byte relaySync = getSetting("relaySync", RELAY_SYNC).toInt();
  180. bool status = _relays[id].target_status;
  181. // If RELAY_SYNC_SAME all relays should have the same state
  182. if (relaySync == RELAY_SYNC_SAME) {
  183. for (unsigned short i=0; i<_relays.size(); i++) {
  184. if (i != id) relayStatus(i, status);
  185. }
  186. // If NONE_OR_ONE or ONE and setting ON we should set OFF all the others
  187. } else if (status) {
  188. if (relaySync != RELAY_SYNC_ANY) {
  189. for (unsigned short i=0; i<_relays.size(); i++) {
  190. if (i != id) relayStatus(i, false);
  191. }
  192. }
  193. // If ONLY_ONE and setting OFF we should set ON the other one
  194. } else {
  195. if (relaySync == RELAY_SYNC_ONE) {
  196. unsigned char i = (id + 1) % _relays.size();
  197. relayStatus(i, true);
  198. }
  199. }
  200. // Unflag sync mode
  201. _relayRecursive = false;
  202. }
  203. void relaySave() {
  204. unsigned char bit = 1;
  205. unsigned char mask = 0;
  206. for (unsigned int i=0; i < _relays.size(); i++) {
  207. if (relayStatus(i)) mask += bit;
  208. bit += bit;
  209. }
  210. EEPROM.write(EEPROM_RELAY_STATUS, mask);
  211. DEBUG_MSG_P(PSTR("[RELAY] Saving mask: %d\n"), mask);
  212. EEPROM.commit();
  213. }
  214. void relayToggle(unsigned char id, bool report, bool group_report) {
  215. if (id >= _relays.size()) return;
  216. relayStatus(id, !relayStatus(id), report, group_report);
  217. }
  218. void relayToggle(unsigned char id) {
  219. relayToggle(id, true, true);
  220. }
  221. unsigned char relayCount() {
  222. return _relays.size();
  223. }
  224. unsigned char relayParsePayload(const char * payload) {
  225. // Payload could be "OFF", "ON", "TOGGLE"
  226. // or its number equivalents: 0, 1 or 2
  227. if (payload[0] == '0') return 0;
  228. if (payload[0] == '1') return 1;
  229. if (payload[0] == '2') return 2;
  230. // trim payload
  231. char * p = ltrim((char *)payload);
  232. // to lower
  233. unsigned int l = strlen(p);
  234. if (l>6) l=6;
  235. for (unsigned char i=0; i<l; i++) {
  236. p[i] = tolower(p[i]);
  237. }
  238. unsigned int value = 0xFF;
  239. if (strcmp(p, "off") == 0) {
  240. value = 0;
  241. } else if (strcmp(p, "on") == 0) {
  242. value = 1;
  243. } else if (strcmp(p, "toggle") == 0) {
  244. value = 2;
  245. } else if (strcmp(p, "query") == 0) {
  246. value = 3;
  247. }
  248. return value;
  249. }
  250. // BACKWARDS COMPATIBILITY
  251. void _relayBackwards() {
  252. byte relayMode = getSetting("relayMode", RELAY_BOOT_MODE).toInt();
  253. byte relayPulseMode = getSetting("relayPulseMode", RELAY_PULSE_MODE).toInt();
  254. float relayPulseTime = getSetting("relayPulseTime", RELAY_PULSE_TIME).toFloat();
  255. if (relayPulseMode == RELAY_PULSE_NONE) relayPulseTime = 0;
  256. for (unsigned int i=0; i<_relays.size(); i++) {
  257. if (!hasSetting("relayBoot", i)) setSetting("relayBoot", i, relayMode);
  258. if (!hasSetting("relayPulse", i)) setSetting("relayPulse", i, relayPulseMode);
  259. if (!hasSetting("relayTime", i)) setSetting("relayTime", i, relayPulseTime);
  260. }
  261. delSetting("relayMode");
  262. delSetting("relayPulseMode");
  263. delSetting("relayPulseTime");
  264. }
  265. void _relayBoot() {
  266. _relayRecursive = true;
  267. unsigned char bit = 1;
  268. bool trigger_save = false;
  269. // Get last statuses from EEPROM
  270. unsigned char mask = EEPROM.read(EEPROM_RELAY_STATUS);
  271. DEBUG_MSG_P(PSTR("[RELAY] Retrieving mask: %d\n"), mask);
  272. // Walk the relays
  273. bool status = false;
  274. for (unsigned int i=0; i<_relays.size(); i++) {
  275. unsigned char boot_mode = getSetting("relayBoot", i, RELAY_BOOT_MODE).toInt();
  276. DEBUG_MSG_P(PSTR("[RELAY] Relay #%d boot mode %d\n"), i, boot_mode);
  277. switch (boot_mode) {
  278. case RELAY_BOOT_SAME:
  279. status = ((mask & bit) == bit);
  280. break;
  281. case RELAY_BOOT_TOGGLE:
  282. status = ((mask & bit) != bit);
  283. mask ^= bit;
  284. trigger_save = true;
  285. break;
  286. case RELAY_BOOT_ON:
  287. status = true;
  288. break;
  289. case RELAY_BOOT_OFF:
  290. default:
  291. status = false;
  292. break;
  293. }
  294. _relays[i].current_status = !status;
  295. _relays[i].target_status = status;
  296. _relays[i].change_time = millis();
  297. bit <<= 1;
  298. }
  299. // Save if there is any relay in the RELAY_BOOT_TOGGLE mode
  300. if (trigger_save) {
  301. EEPROM.write(EEPROM_RELAY_STATUS, mask);
  302. EEPROM.commit();
  303. }
  304. _relayRecursive = false;
  305. }
  306. void _relayConfigure() {
  307. for (unsigned int i=0; i<_relays.size(); i++) {
  308. pinMode(_relays[i].pin, OUTPUT);
  309. if (_relays[i].type == RELAY_TYPE_LATCHED) pinMode(_relays[i].reset_pin, OUTPUT);
  310. _relays[i].pulse = getSetting("relayPulse", i, RELAY_PULSE_MODE).toInt();
  311. _relays[i].pulse_ms = 1000 * getSetting("relayTime", i, RELAY_PULSE_MODE).toFloat();
  312. }
  313. }
  314. //------------------------------------------------------------------------------
  315. // WEBSOCKETS
  316. //------------------------------------------------------------------------------
  317. #if WEB_SUPPORT
  318. void _relayWebSocketUpdate(JsonObject& root) {
  319. JsonArray& relay = root.createNestedArray("relayStatus");
  320. for (unsigned char i=0; i<relayCount(); i++) {
  321. relay.add(_relays[i].target_status);
  322. }
  323. }
  324. void _relayWebSocketOnStart(JsonObject& root) {
  325. if (relayCount() == 0) return;
  326. // Statuses
  327. _relayWebSocketUpdate(root);
  328. // Configuration
  329. JsonArray& config = root.createNestedArray("relayConfig");
  330. for (unsigned char i=0; i<relayCount(); i++) {
  331. JsonObject& line = config.createNestedObject();
  332. line["gpio"] = _relays[i].pin;
  333. line["type"] = _relays[i].type;
  334. line["reset"] = _relays[i].reset_pin;
  335. line["boot"] = getSetting("relayBoot", i, RELAY_BOOT_MODE).toInt();
  336. line["pulse"] = _relays[i].pulse;
  337. line["pulse_ms"] = _relays[i].pulse_ms / 1000.0;
  338. #if MQTT_SUPPORT
  339. line["group"] = getSetting("mqttGroup", i, "");
  340. line["group_inv"] = getSetting("mqttGroupInv", i, 0).toInt();
  341. line["disc_react"] = getSetting("mqttDisconnectReaction",i,0).toInt();
  342. #endif
  343. }
  344. if (relayCount() > 1) {
  345. root["multirelayVisible"] = 1;
  346. root["relaySync"] = getSetting("relaySync", RELAY_SYNC);
  347. }
  348. root["relayVisible"] = 1;
  349. }
  350. void _relayWebSocketOnAction(uint32_t client_id, const char * action, JsonObject& data) {
  351. if (strcmp(action, "relay") != 0) return;
  352. if (data.containsKey("status")) {
  353. unsigned char value = relayParsePayload(data["status"]);
  354. if (value == 3) {
  355. wsSend(_relayWebSocketUpdate);
  356. } else if (value < 3) {
  357. unsigned int relayID = 0;
  358. if (data.containsKey("id")) {
  359. String value = data["id"];
  360. relayID = value.toInt();
  361. }
  362. // Action to perform
  363. if (value == 0) {
  364. relayStatus(relayID, false);
  365. } else if (value == 1) {
  366. relayStatus(relayID, true);
  367. } else if (value == 2) {
  368. relayToggle(relayID);
  369. }
  370. }
  371. }
  372. }
  373. void relaySetupWS() {
  374. wsOnSendRegister(_relayWebSocketOnStart);
  375. wsOnActionRegister(_relayWebSocketOnAction);
  376. wsOnAfterParseRegister(_relayConfigure);
  377. }
  378. #endif // WEB_SUPPORT
  379. //------------------------------------------------------------------------------
  380. // REST API
  381. //------------------------------------------------------------------------------
  382. #if WEB_SUPPORT
  383. void relaySetupAPI() {
  384. // API entry points (protected with apikey)
  385. for (unsigned int relayID=0; relayID<relayCount(); relayID++) {
  386. char key[15];
  387. snprintf_P(key, sizeof(key), PSTR("%s/%d"), MQTT_TOPIC_RELAY, relayID);
  388. apiRegister(key,
  389. [relayID](char * buffer, size_t len) {
  390. snprintf_P(buffer, len, PSTR("%d"), relayStatus(relayID) ? 1 : 0);
  391. },
  392. [relayID](const char * payload) {
  393. unsigned char value = relayParsePayload(payload);
  394. if (value == 0xFF) {
  395. DEBUG_MSG_P(PSTR("[RELAY] Wrong payload (%s)\n"), payload);
  396. return;
  397. }
  398. if (value == 0) {
  399. relayStatus(relayID, false);
  400. } else if (value == 1) {
  401. relayStatus(relayID, true);
  402. } else if (value == 2) {
  403. relayToggle(relayID);
  404. }
  405. }
  406. );
  407. }
  408. }
  409. #endif // WEB_SUPPORT
  410. //------------------------------------------------------------------------------
  411. // MQTT
  412. //------------------------------------------------------------------------------
  413. #if MQTT_SUPPORT
  414. void relayMQTT(unsigned char id) {
  415. if (id >= _relays.size()) return;
  416. // Send state topic
  417. if (_relays[id].report) {
  418. _relays[id].report = false;
  419. mqttSend(MQTT_TOPIC_RELAY, id, _relays[id].current_status ? "1" : "0");
  420. }
  421. // Check group topic
  422. if (_relays[id].group_report) {
  423. _relays[id].group_report = false;
  424. String t = getSetting("mqttGroup", id, "");
  425. if (t.length() > 0) {
  426. bool status = relayStatus(id);
  427. if (getSetting("mqttGroupInv", id, 0).toInt() == 1) status = !status;
  428. mqttSendRaw(t.c_str(), status ? "1" : "0");
  429. }
  430. }
  431. }
  432. void relayMQTT() {
  433. for (unsigned int id=0; id < _relays.size(); id++) {
  434. mqttSend(MQTT_TOPIC_RELAY, id, _relays[id].current_status ? "1" : "0");
  435. }
  436. }
  437. void relayStatusWrap(unsigned char id, unsigned char value, bool is_group_topic) {
  438. // Action to perform
  439. if (value == 0) {
  440. relayStatus(id, false, mqttForward(), !is_group_topic);
  441. } else if (value == 1) {
  442. relayStatus(id, true, mqttForward(), !is_group_topic);
  443. } else if (value == 2) {
  444. relayToggle(id, true, true);
  445. }
  446. }
  447. void relayMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  448. if (type == MQTT_CONNECT_EVENT) {
  449. // Send status on connect
  450. #if not HEARTBEAT_REPORT_RELAY
  451. relayMQTT();
  452. #endif
  453. // Subscribe to own /set topic
  454. char buffer[strlen(MQTT_TOPIC_RELAY) + 3];
  455. snprintf_P(buffer, sizeof(buffer), PSTR("%s/+"), MQTT_TOPIC_RELAY);
  456. mqttSubscribe(buffer);
  457. // Subscribe to group topics
  458. for (unsigned int i=0; i < _relays.size(); i++) {
  459. String t = getSetting("mqttGroup", i, "");
  460. if (t.length() > 0) mqttSubscribeRaw(t.c_str());
  461. }
  462. }
  463. if (type == MQTT_MESSAGE_EVENT) {
  464. // Check relay topic
  465. String t = mqttTopicKey((char *) topic);
  466. if (t.startsWith(MQTT_TOPIC_RELAY)) {
  467. // Get value
  468. unsigned char value = relayParsePayload(payload);
  469. if (value == 0xFF) return;
  470. // Get relay ID
  471. unsigned int id = t.substring(strlen(MQTT_TOPIC_RELAY)+1).toInt();
  472. if (id >= relayCount()) {
  473. DEBUG_MSG_P(PSTR("[RELAY] Wrong relayID (%d)\n"), id);
  474. } else {
  475. relayStatusWrap(id, value, false);
  476. }
  477. return;
  478. }
  479. // Check group topics
  480. for (unsigned int i=0; i < _relays.size(); i++) {
  481. String t = getSetting("mqttGroup", i, "");
  482. if ((t.length() > 0) && t.equals(topic)) {
  483. unsigned char value = relayParsePayload(payload);
  484. if (value == 0xFF) return;
  485. if (value < 2) {
  486. if (getSetting("mqttGroupInv", i, 0).toInt() == 1) {
  487. value = 1 - value;
  488. }
  489. }
  490. DEBUG_MSG_P(PSTR("[RELAY] Matched group topic for relayID %d\n"), i);
  491. relayStatusWrap(i, value, true);
  492. }
  493. }
  494. }
  495. if (type == MQTT_DISCONNECT_EVENT) {
  496. for (unsigned int i=0; i < _relays.size(); i++){
  497. int reaction = getSetting("mqttDisconnectReaction",i,0).toInt();
  498. if (reaction == 1) { // switch relay OFF
  499. DEBUG_MSG_P(PSTR("[RELAY] Reset relay (%d) due to MQTT disconnection\n"), i);
  500. relayStatusWrap(i, false, false);
  501. }
  502. else if(reaction == 2) { // switch relay ON
  503. DEBUG_MSG_P(PSTR("[RELAY] Set relay (%d) due to MQTT disconnection\n"), i);
  504. relayStatusWrap(i, true, false);
  505. }
  506. }
  507. }
  508. }
  509. void relaySetupMQTT() {
  510. mqttRegister(relayMQTTCallback);
  511. }
  512. #endif
  513. //------------------------------------------------------------------------------
  514. // InfluxDB
  515. //------------------------------------------------------------------------------
  516. #if INFLUXDB_SUPPORT
  517. void relayInfluxDB(unsigned char id) {
  518. if (id >= _relays.size()) return;
  519. idbSend(MQTT_TOPIC_RELAY, id, relayStatus(id) ? "1" : "0");
  520. }
  521. #endif
  522. //------------------------------------------------------------------------------
  523. // Settings
  524. //------------------------------------------------------------------------------
  525. #if TERMINAL_SUPPORT
  526. void _relayInitCommands() {
  527. settingsRegisterCommand(F("RELAY"), [](Embedis* e) {
  528. if (e->argc < 2) {
  529. DEBUG_MSG_P(PSTR("-ERROR: Wrong arguments\n"));
  530. }
  531. int id = String(e->argv[1]).toInt();
  532. if (e->argc > 2) {
  533. int value = String(e->argv[2]).toInt();
  534. if (value == 2) {
  535. relayToggle(id);
  536. } else {
  537. relayStatus(id, value == 1);
  538. }
  539. }
  540. DEBUG_MSG_P(PSTR("Status: %s\n"), relayStatus(id) ? "true" : "false");
  541. DEBUG_MSG_P(PSTR("+OK\n"));
  542. });
  543. }
  544. #endif // TERMINAL_SUPPORT
  545. //------------------------------------------------------------------------------
  546. // Setup
  547. //------------------------------------------------------------------------------
  548. void relaySetup() {
  549. // Dummy relays for AI Light, Magic Home LED Controller, H801,
  550. // Sonoff Dual and Sonoff RF Bridge
  551. #ifdef DUMMY_RELAY_COUNT
  552. for (unsigned char i=0; i < DUMMY_RELAY_COUNT; i++) {
  553. _relays.push_back((relay_t) {0, RELAY_TYPE_NORMAL});
  554. }
  555. #else
  556. #ifdef RELAY1_PIN
  557. _relays.push_back((relay_t) { RELAY1_PIN, RELAY1_TYPE, RELAY1_RESET_PIN, RELAY1_DELAY_ON, RELAY1_DELAY_OFF });
  558. #endif
  559. #ifdef RELAY2_PIN
  560. _relays.push_back((relay_t) { RELAY2_PIN, RELAY2_TYPE, RELAY2_RESET_PIN, RELAY2_DELAY_ON, RELAY2_DELAY_OFF });
  561. #endif
  562. #ifdef RELAY3_PIN
  563. _relays.push_back((relay_t) { RELAY3_PIN, RELAY3_TYPE, RELAY3_RESET_PIN, RELAY3_DELAY_ON, RELAY3_DELAY_OFF });
  564. #endif
  565. #ifdef RELAY4_PIN
  566. _relays.push_back((relay_t) { RELAY4_PIN, RELAY4_TYPE, RELAY4_RESET_PIN, RELAY4_DELAY_ON, RELAY4_DELAY_OFF });
  567. #endif
  568. #ifdef RELAY5_PIN
  569. _relays.push_back((relay_t) { RELAY5_PIN, RELAY5_TYPE, RELAY5_RESET_PIN, RELAY5_DELAY_ON, RELAY5_DELAY_OFF });
  570. #endif
  571. #ifdef RELAY6_PIN
  572. _relays.push_back((relay_t) { RELAY6_PIN, RELAY6_TYPE, RELAY6_RESET_PIN, RELAY6_DELAY_ON, RELAY6_DELAY_OFF });
  573. #endif
  574. #ifdef RELAY7_PIN
  575. _relays.push_back((relay_t) { RELAY7_PIN, RELAY7_TYPE, RELAY7_RESET_PIN, RELAY7_DELAY_ON, RELAY7_DELAY_OFF });
  576. #endif
  577. #ifdef RELAY8_PIN
  578. _relays.push_back((relay_t) { RELAY8_PIN, RELAY8_TYPE, RELAY8_RESET_PIN, RELAY8_DELAY_ON, RELAY8_DELAY_OFF });
  579. #endif
  580. #endif
  581. _relayBackwards();
  582. _relayConfigure();
  583. _relayBoot();
  584. relayLoop();
  585. espurnaRegisterLoop(relayLoop);
  586. #if WEB_SUPPORT
  587. relaySetupAPI();
  588. relaySetupWS();
  589. #endif
  590. #if MQTT_SUPPORT
  591. relaySetupMQTT();
  592. #endif
  593. #if TERMINAL_SUPPORT
  594. _relayInitCommands();
  595. #endif
  596. DEBUG_MSG_P(PSTR("[RELAY] Number of relays: %d\n"), _relays.size());
  597. }
  598. void relayLoop(void) {
  599. unsigned char id;
  600. for (id = 0; id < _relays.size(); id++) {
  601. unsigned int current_time = millis();
  602. bool status = _relays[id].target_status;
  603. if ((_relays[id].current_status != status)
  604. && (current_time >= _relays[id].change_time)) {
  605. DEBUG_MSG_P(PSTR("[RELAY] #%d set to %s\n"), id, status ? "ON" : "OFF");
  606. // Call the provider to perform the action
  607. _relayProviderStatus(id, status);
  608. // Send to Broker
  609. #if BROKER_SUPPORT
  610. brokerPublish(MQTT_TOPIC_RELAY, id, status ? "1" : "0");
  611. #endif
  612. // Send MQTT
  613. #if MQTT_SUPPORT
  614. relayMQTT(id);
  615. #endif
  616. if (!_relayRecursive) {
  617. relayPulse(id);
  618. _relaySaveTicker.once_ms(RELAY_SAVE_DELAY, relaySave);
  619. #if WEB_SUPPORT
  620. wsSend(_relayWebSocketUpdate);
  621. #endif
  622. }
  623. #if DOMOTICZ_SUPPORT
  624. domoticzSendRelay(id);
  625. #endif
  626. #if INFLUXDB_SUPPORT
  627. relayInfluxDB(id);
  628. #endif
  629. #if THINGSPEAK_SUPPORT
  630. tspkEnqueueRelay(id, status);
  631. tspkFlush();
  632. #endif
  633. // Flag relay-based LEDs to update status
  634. ledUpdate(true);
  635. _relays[id].report = false;
  636. _relays[id].group_report = false;
  637. }
  638. }
  639. }