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.

888 lines
26 KiB

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