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.

799 lines
22 KiB

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