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.

881 lines
25 KiB

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