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.

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