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.

807 lines
23 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. 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. Serial.println("_relayWebSocketUpdate");
  299. JsonArray& relay = root.createNestedArray("relayStatus");
  300. for (unsigned char i=0; i<relayCount(); i++) {
  301. relay.add(_relays[i].target_status);
  302. }
  303. }
  304. void _relayWebSocketOnStart(JsonObject& root) {
  305. if (relayCount() == 0) return;
  306. // Statuses
  307. _relayWebSocketUpdate(root);
  308. // Configuration
  309. JsonArray& config = root.createNestedArray("relayConfig");
  310. for (unsigned char i=0; i<relayCount(); i++) {
  311. JsonObject& line = config.createNestedObject();
  312. line["gpio"] = _relays[i].pin;
  313. line["type"] = _relays[i].type;
  314. line["reset"] = _relays[i].reset_pin;
  315. line["boot"] = getSetting("relayBoot", i, RELAY_BOOT_MODE).toInt();
  316. line["pulse"] = _relays[i].pulse;
  317. line["pulse_ms"] = _relays[i].pulse_ms / 1000.0;
  318. #if MQTT_SUPPORT
  319. line["group"] = getSetting("mqttGroup", i, "");
  320. line["group_inv"] = getSetting("mqttGroupInv", i, 0).toInt();
  321. #endif
  322. }
  323. if (relayCount() > 1) {
  324. root["multirelayVisible"] = 1;
  325. root["relaySync"] = getSetting("relaySync", RELAY_SYNC);
  326. }
  327. root["relayVisible"] = 1;
  328. }
  329. void _relayWebSocketOnAction(uint32_t client_id, const char * action, JsonObject& data) {
  330. if (strcmp(action, "relay") != 0) return;
  331. if (data.containsKey("status")) {
  332. unsigned char value = relayParsePayload(data["status"]);
  333. if (value == 3) {
  334. wsSend(_relayWebSocketUpdate);
  335. } else if (value < 3) {
  336. unsigned int relayID = 0;
  337. if (data.containsKey("id")) {
  338. String value = data["id"];
  339. relayID = value.toInt();
  340. }
  341. // Action to perform
  342. if (value == 0) {
  343. relayStatus(relayID, false);
  344. } else if (value == 1) {
  345. relayStatus(relayID, true);
  346. } else if (value == 2) {
  347. relayToggle(relayID);
  348. }
  349. }
  350. }
  351. }
  352. void relaySetupWS() {
  353. wsOnSendRegister(_relayWebSocketOnStart);
  354. wsOnActionRegister(_relayWebSocketOnAction);
  355. wsOnAfterParseRegister(_relayConfigure);
  356. }
  357. #endif // WEB_SUPPORT
  358. //------------------------------------------------------------------------------
  359. // REST API
  360. //------------------------------------------------------------------------------
  361. #if WEB_SUPPORT
  362. void relaySetupAPI() {
  363. // API entry points (protected with apikey)
  364. for (unsigned int relayID=0; relayID<relayCount(); relayID++) {
  365. char key[15];
  366. snprintf_P(key, sizeof(key), PSTR("%s/%d"), MQTT_TOPIC_RELAY, relayID);
  367. apiRegister(key,
  368. [relayID](char * buffer, size_t len) {
  369. snprintf_P(buffer, len, PSTR("%d"), relayStatus(relayID) ? 1 : 0);
  370. },
  371. [relayID](const char * payload) {
  372. unsigned char value = relayParsePayload(payload);
  373. if (value == 0xFF) {
  374. DEBUG_MSG_P(PSTR("[RELAY] Wrong payload (%s)\n"), payload);
  375. return;
  376. }
  377. if (value == 0) {
  378. relayStatus(relayID, false);
  379. } else if (value == 1) {
  380. relayStatus(relayID, true);
  381. } else if (value == 2) {
  382. relayToggle(relayID);
  383. }
  384. }
  385. );
  386. }
  387. }
  388. #endif // WEB_SUPPORT
  389. //------------------------------------------------------------------------------
  390. // MQTT
  391. //------------------------------------------------------------------------------
  392. #if MQTT_SUPPORT
  393. void relayMQTT(unsigned char id) {
  394. if (id >= _relays.size()) return;
  395. // Send state topic
  396. if (_relays[id].report) {
  397. _relays[id].report = false;
  398. mqttSend(MQTT_TOPIC_RELAY, id, _relays[id].current_status ? "1" : "0");
  399. }
  400. // Check group topic
  401. if (_relays[id].group_report) {
  402. _relays[id].group_report = false;
  403. String t = getSetting("mqttGroup", id, "");
  404. if (t.length() > 0) {
  405. bool status = relayStatus(id);
  406. if (getSetting("mqttGroupInv", id, 0).toInt() == 1) status = !status;
  407. mqttSendRaw(t.c_str(), status ? "1" : "0");
  408. }
  409. }
  410. }
  411. void relayMQTT() {
  412. for (unsigned int id=0; id < _relays.size(); id++) {
  413. mqttSend(MQTT_TOPIC_RELAY, id, _relays[id].current_status ? "1" : "0");
  414. }
  415. }
  416. void relayStatusWrap(unsigned char id, unsigned char value, bool is_group_topic) {
  417. // Action to perform
  418. if (value == 0) {
  419. relayStatus(id, false, mqttForward(), !is_group_topic);
  420. } else if (value == 1) {
  421. relayStatus(id, true, mqttForward(), !is_group_topic);
  422. } else if (value == 2) {
  423. relayToggle(id, true, true);
  424. }
  425. }
  426. void relayMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  427. if (type == MQTT_CONNECT_EVENT) {
  428. // Send status on connect
  429. #if not HEARTBEAT_REPORT_RELAY
  430. relayMQTT();
  431. #endif
  432. // Subscribe to own /set topic
  433. char buffer[strlen(MQTT_TOPIC_RELAY) + 3];
  434. snprintf_P(buffer, sizeof(buffer), PSTR("%s/+"), MQTT_TOPIC_RELAY);
  435. mqttSubscribe(buffer);
  436. // Subscribe to group topics
  437. for (unsigned int i=0; i < _relays.size(); i++) {
  438. String t = getSetting("mqttGroup", i, "");
  439. if (t.length() > 0) mqttSubscribeRaw(t.c_str());
  440. }
  441. }
  442. if (type == MQTT_MESSAGE_EVENT) {
  443. // Check relay topic
  444. String t = mqttTopicKey((char *) topic);
  445. if (t.startsWith(MQTT_TOPIC_RELAY)) {
  446. // Get value
  447. unsigned char value = relayParsePayload(payload);
  448. if (value == 0xFF) return;
  449. // Get relay ID
  450. unsigned int id = t.substring(strlen(MQTT_TOPIC_RELAY)+1).toInt();
  451. if (id >= relayCount()) {
  452. DEBUG_MSG_P(PSTR("[RELAY] Wrong relayID (%d)\n"), id);
  453. } else {
  454. relayStatusWrap(id, value, false);
  455. }
  456. return;
  457. }
  458. // Check group topics
  459. for (unsigned int i=0; i < _relays.size(); i++) {
  460. String t = getSetting("mqttGroup", i, "");
  461. if ((t.length() > 0) && t.equals(topic)) {
  462. unsigned char value = relayParsePayload(payload);
  463. if (value == 0xFF) return;
  464. if (value < 2) {
  465. if (getSetting("mqttGroupInv", i, 0).toInt() == 1) {
  466. value = 1 - value;
  467. }
  468. }
  469. DEBUG_MSG_P(PSTR("[RELAY] Matched group topic for relayID %d\n"), i);
  470. relayStatusWrap(i, value, true);
  471. }
  472. }
  473. }
  474. }
  475. void relaySetupMQTT() {
  476. mqttRegister(relayMQTTCallback);
  477. }
  478. #endif
  479. //------------------------------------------------------------------------------
  480. // InfluxDB
  481. //------------------------------------------------------------------------------
  482. #if INFLUXDB_SUPPORT
  483. void relayInfluxDB(unsigned char id) {
  484. if (id >= _relays.size()) return;
  485. idbSend(MQTT_TOPIC_RELAY, id, relayStatus(id) ? "1" : "0");
  486. }
  487. #endif
  488. //------------------------------------------------------------------------------
  489. // Settings
  490. //------------------------------------------------------------------------------
  491. #if TERMINAL_SUPPORT
  492. void _relayInitCommands() {
  493. settingsRegisterCommand(F("RELAY"), [](Embedis* e) {
  494. if (e->argc < 2) {
  495. DEBUG_MSG_P(PSTR("-ERROR: Wrong arguments\n"));
  496. }
  497. int id = String(e->argv[1]).toInt();
  498. if (e->argc > 2) {
  499. int value = String(e->argv[2]).toInt();
  500. if (value == 2) {
  501. relayToggle(id);
  502. } else {
  503. relayStatus(id, value == 1);
  504. }
  505. }
  506. DEBUG_MSG_P(PSTR("Status: %s\n"), relayStatus(id) ? "true" : "false");
  507. DEBUG_MSG_P(PSTR("+OK\n"));
  508. });
  509. }
  510. #endif // TERMINAL_SUPPORT
  511. //------------------------------------------------------------------------------
  512. // Setup
  513. //------------------------------------------------------------------------------
  514. void relaySetup() {
  515. // Dummy relays for AI Light, Magic Home LED Controller, H801,
  516. // Sonoff Dual and Sonoff RF Bridge
  517. #ifdef DUMMY_RELAY_COUNT
  518. for (unsigned char i=0; i < DUMMY_RELAY_COUNT; i++) {
  519. _relays.push_back((relay_t) {0, RELAY_TYPE_NORMAL});
  520. }
  521. #else
  522. #ifdef RELAY1_PIN
  523. _relays.push_back((relay_t) { RELAY1_PIN, RELAY1_TYPE, RELAY1_RESET_PIN, RELAY1_DELAY_ON, RELAY1_DELAY_OFF });
  524. #endif
  525. #ifdef RELAY2_PIN
  526. _relays.push_back((relay_t) { RELAY2_PIN, RELAY2_TYPE, RELAY2_RESET_PIN, RELAY2_DELAY_ON, RELAY2_DELAY_OFF });
  527. #endif
  528. #ifdef RELAY3_PIN
  529. _relays.push_back((relay_t) { RELAY3_PIN, RELAY3_TYPE, RELAY3_RESET_PIN, RELAY3_DELAY_ON, RELAY3_DELAY_OFF });
  530. #endif
  531. #ifdef RELAY4_PIN
  532. _relays.push_back((relay_t) { RELAY4_PIN, RELAY4_TYPE, RELAY4_RESET_PIN, RELAY4_DELAY_ON, RELAY4_DELAY_OFF });
  533. #endif
  534. #ifdef RELAY5_PIN
  535. _relays.push_back((relay_t) { RELAY5_PIN, RELAY5_TYPE, RELAY5_RESET_PIN, RELAY5_DELAY_ON, RELAY5_DELAY_OFF });
  536. #endif
  537. #ifdef RELAY6_PIN
  538. _relays.push_back((relay_t) { RELAY6_PIN, RELAY6_TYPE, RELAY6_RESET_PIN, RELAY6_DELAY_ON, RELAY6_DELAY_OFF });
  539. #endif
  540. #ifdef RELAY7_PIN
  541. _relays.push_back((relay_t) { RELAY7_PIN, RELAY7_TYPE, RELAY7_RESET_PIN, RELAY7_DELAY_ON, RELAY7_DELAY_OFF });
  542. #endif
  543. #ifdef RELAY8_PIN
  544. _relays.push_back((relay_t) { RELAY8_PIN, RELAY8_TYPE, RELAY8_RESET_PIN, RELAY8_DELAY_ON, RELAY8_DELAY_OFF });
  545. #endif
  546. #endif
  547. _relayBackwards();
  548. _relayConfigure();
  549. _relayBoot();
  550. relayLoop();
  551. espurnaRegisterLoop(relayLoop);
  552. #if WEB_SUPPORT
  553. relaySetupAPI();
  554. relaySetupWS();
  555. #endif
  556. #if MQTT_SUPPORT
  557. relaySetupMQTT();
  558. #endif
  559. #if TERMINAL_SUPPORT
  560. _relayInitCommands();
  561. #endif
  562. DEBUG_MSG_P(PSTR("[RELAY] Number of relays: %d\n"), _relays.size());
  563. }
  564. void relayLoop(void) {
  565. unsigned char id;
  566. for (id = 0; id < _relays.size(); id++) {
  567. unsigned int current_time = millis();
  568. bool status = _relays[id].target_status;
  569. if ((_relays[id].current_status != status)
  570. && (current_time >= _relays[id].change_time)) {
  571. DEBUG_MSG_P(PSTR("[RELAY] #%d set to %s\n"), id, status ? "ON" : "OFF");
  572. // Call the provider to perform the action
  573. _relayProviderStatus(id, status);
  574. // Send to Broker
  575. #if BROKER_SUPPORT
  576. brokerPublish(MQTT_TOPIC_RELAY, id, status ? "1" : "0");
  577. #endif
  578. // Send MQTT
  579. #if MQTT_SUPPORT
  580. relayMQTT(id);
  581. #endif
  582. if (!_relayRecursive) {
  583. relayPulse(id);
  584. _relaySaveTicker.once_ms(RELAY_SAVE_DELAY, relaySave);
  585. #if WEB_SUPPORT
  586. wsSend(_relayWebSocketUpdate);
  587. #endif
  588. }
  589. #if DOMOTICZ_SUPPORT
  590. domoticzSendRelay(id);
  591. #endif
  592. #if INFLUXDB_SUPPORT
  593. relayInfluxDB(id);
  594. #endif
  595. #if THINGSPEAK_SUPPORT
  596. tspkEnqueueRelay(id, status);
  597. tspkFlush();
  598. #endif
  599. // Flag relay-based LEDs to update status
  600. ledUpdate(true);
  601. _relays[id].report = false;
  602. _relays[id].group_report = false;
  603. }
  604. }
  605. }