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.

967 lines
29 KiB

6 years ago
6 years ago
6 years ago
6 years ago
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. Module key prefix: rly
  5. */
  6. #include <EEPROM_Rotate.h>
  7. #include <Ticker.h>
  8. #include <ArduinoJson.h>
  9. #include <vector>
  10. #include <functional>
  11. typedef struct {
  12. // Configuration variables
  13. unsigned char pin; // GPIO pin for the relay
  14. unsigned char type; // RELAY_TYPE_NORMAL, RELAY_TYPE_INVERSE, RELAY_TYPE_LATCHED or RELAY_TYPE_LATCHED_INVERSE
  15. unsigned char reset_pin; // GPIO to reset the relay if RELAY_TYPE_LATCHED
  16. unsigned long delay_on; // Delay to turn relay ON
  17. unsigned long delay_off; // Delay to turn relay OFF
  18. unsigned char pulse; // RELAY_PULSE_NONE, RELAY_PULSE_OFF or RELAY_PULSE_ON
  19. unsigned long pulse_ms; // Pulse length in millis
  20. // Status variables
  21. bool current_status; // Holds the current (physical) status of the relay
  22. bool target_status; // Holds the target status
  23. unsigned long fw_start; // Flood window start time
  24. unsigned char fw_count; // Number of changes within the current flood window
  25. unsigned long change_time; // Scheduled time to change
  26. bool report; // Whether to report to own topic
  27. bool group_report; // Whether to report to group topic
  28. // Helping objects
  29. Ticker pulseTicker; // Holds the pulse back timer
  30. } relay_t;
  31. std::vector<relay_t> _relays;
  32. bool _relayRecursive = false;
  33. Ticker _relaySaveTicker;
  34. // -----------------------------------------------------------------------------
  35. // RELAY PROVIDERS
  36. // -----------------------------------------------------------------------------
  37. void _relayProviderStatus(unsigned char id, bool status) {
  38. // Check relay ID
  39. if (id >= _relays.size()) return;
  40. // Store new current status
  41. _relays[id].current_status = status;
  42. #if RELAY_PROVIDER == RELAY_PROVIDER_RFBRIDGE
  43. rfbStatus(id, status);
  44. #endif
  45. #if RELAY_PROVIDER == RELAY_PROVIDER_DUAL
  46. // Calculate mask
  47. unsigned char mask=0;
  48. for (unsigned char i=0; i<_relays.size(); i++) {
  49. if (_relays[i].current_status) mask = mask + (1 << i);
  50. }
  51. // Send it to F330
  52. Serial.flush();
  53. Serial.write(0xA0);
  54. Serial.write(0x04);
  55. Serial.write(mask);
  56. Serial.write(0xA1);
  57. Serial.flush();
  58. #endif
  59. #if RELAY_PROVIDER == RELAY_PROVIDER_STM
  60. Serial.flush();
  61. Serial.write(0xA0);
  62. Serial.write(id + 1);
  63. Serial.write(status);
  64. Serial.write(0xA1 + status + id);
  65. Serial.flush();
  66. #endif
  67. #if RELAY_PROVIDER == RELAY_PROVIDER_LIGHT
  68. // If the number of relays matches the number of light channels
  69. // assume each relay controls one channel.
  70. // If the number of relays is the number of channels plus 1
  71. // assume the first one controls all the channels and
  72. // the rest one channel each.
  73. // Otherwise every relay controls all channels.
  74. // TODO: this won't work with a mixed of dummy and real relays
  75. // but this option is not allowed atm (YANGNI)
  76. if (_relays.size() == lightChannels()) {
  77. lightState(id, status);
  78. lightState(true);
  79. } else if (_relays.size() == lightChannels() + 1) {
  80. if (id == 0) {
  81. lightState(status);
  82. } else {
  83. lightState(id-1, status);
  84. }
  85. } else {
  86. lightState(status);
  87. }
  88. lightUpdate(true, true);
  89. #endif
  90. #if RELAY_PROVIDER == RELAY_PROVIDER_RELAY
  91. if (_relays[id].type == RELAY_TYPE_NORMAL) {
  92. digitalWrite(_relays[id].pin, status);
  93. } else if (_relays[id].type == RELAY_TYPE_INVERSE) {
  94. digitalWrite(_relays[id].pin, !status);
  95. } else if (_relays[id].type == RELAY_TYPE_LATCHED || _relays[id].type == RELAY_TYPE_LATCHED_INVERSE) {
  96. bool pulse = RELAY_TYPE_LATCHED ? HIGH : LOW;
  97. digitalWrite(_relays[id].pin, !pulse);
  98. digitalWrite(_relays[id].reset_pin, !pulse);
  99. if (status) {
  100. digitalWrite(_relays[id].pin, pulse);
  101. } else {
  102. digitalWrite(_relays[id].reset_pin, pulse);
  103. }
  104. nice_delay(RELAY_LATCHING_PULSE);
  105. digitalWrite(_relays[id].pin, !pulse);
  106. digitalWrite(_relays[id].reset_pin, !pulse);
  107. }
  108. #endif
  109. }
  110. /**
  111. * Walks the relay vector processing only those relays
  112. * that have to change to the requested mode
  113. * @bool mode Requested mode
  114. */
  115. void _relayProcess(bool mode) {
  116. unsigned long current_time = millis();
  117. for (unsigned char id = 0; id < _relays.size(); id++) {
  118. bool target = _relays[id].target_status;
  119. // Only process the relays we have to change
  120. if (target == _relays[id].current_status) continue;
  121. // Only process the relays we have change to the requested mode
  122. if (target != mode) continue;
  123. // Only process if the change_time has arrived
  124. if (current_time < _relays[id].change_time) continue;
  125. DEBUG_MSG_P(PSTR("[RELAY] #%d set to %s\n"), id, target ? "ON" : "OFF");
  126. // Call the provider to perform the action
  127. _relayProviderStatus(id, target);
  128. // Send to Broker
  129. #if BROKER_SUPPORT
  130. brokerPublish(MQTT_TOPIC_RELAY, id, target ? "1" : "0");
  131. #endif
  132. // Send MQTT
  133. #if MQTT_SUPPORT
  134. relayMQTT(id);
  135. #endif
  136. if (!_relayRecursive) {
  137. relayPulse(id);
  138. _relaySaveTicker.once_ms(RELAY_SAVE_DELAY, relaySave);
  139. #if WEB_SUPPORT
  140. wsSend(_relayWebSocketUpdate);
  141. #endif
  142. }
  143. #if DOMOTICZ_SUPPORT
  144. domoticzSendRelay(id);
  145. #endif
  146. #if INFLUXDB_SUPPORT
  147. relayInfluxDB(id);
  148. #endif
  149. #if THINGSPEAK_SUPPORT
  150. tspkEnqueueRelay(id, target);
  151. tspkFlush();
  152. #endif
  153. // Flag relay-based LEDs to update status
  154. #if LED_SUPPORT
  155. ledUpdate(true);
  156. #endif
  157. _relays[id].report = false;
  158. _relays[id].group_report = false;
  159. }
  160. }
  161. // -----------------------------------------------------------------------------
  162. // RELAY
  163. // -----------------------------------------------------------------------------
  164. void relayPulse(unsigned char id) {
  165. _relays[id].pulseTicker.detach();
  166. byte mode = _relays[id].pulse;
  167. if (mode == RELAY_PULSE_NONE) return;
  168. unsigned long ms = _relays[id].pulse_ms;
  169. if (ms == 0) return;
  170. bool status = relayStatus(id);
  171. bool pulseStatus = (mode == RELAY_PULSE_ON);
  172. if (pulseStatus != status) {
  173. DEBUG_MSG_P(PSTR("[RELAY] Scheduling relay #%d back in %lums (pulse)\n"), id, ms);
  174. _relays[id].pulseTicker.once_ms(ms, relayToggle, id);
  175. // Reconfigure after dynamic pulse
  176. _relays[id].pulse = getSetting("rlyPulse", id, RELAY_PULSE_MODE).toInt();
  177. _relays[id].pulse_ms = 1000 * getSetting("rlyTime", id, RELAY_PULSE_MODE).toFloat();
  178. }
  179. }
  180. bool relayStatus(unsigned char id, bool status, bool report, bool group_report) {
  181. if (id >= _relays.size()) return false;
  182. bool changed = false;
  183. if (_relays[id].current_status == status) {
  184. if (_relays[id].target_status != status) {
  185. DEBUG_MSG_P(PSTR("[RELAY] #%d scheduled change cancelled\n"), id);
  186. _relays[id].target_status = status;
  187. _relays[id].report = false;
  188. _relays[id].group_report = false;
  189. changed = true;
  190. }
  191. // For RFBridge, keep sending the message even if the status is already the required
  192. #if RELAY_PROVIDER == RELAY_PROVIDER_RFBRIDGE
  193. rfbStatus(id, status);
  194. #endif
  195. // Update the pulse counter if the relay is already in the non-normal state (#454)
  196. relayPulse(id);
  197. } else {
  198. unsigned int current_time = millis();
  199. unsigned int fw_end = _relays[id].fw_start + 1000 * RELAY_FLOOD_WINDOW;
  200. unsigned long delay = status ? _relays[id].delay_on : _relays[id].delay_off;
  201. _relays[id].fw_count++;
  202. _relays[id].change_time = current_time + delay;
  203. // If current_time is off-limits the floodWindow...
  204. if (current_time < _relays[id].fw_start || fw_end <= current_time) {
  205. // We reset the floodWindow
  206. _relays[id].fw_start = current_time;
  207. _relays[id].fw_count = 1;
  208. // If current_time is in the floodWindow and there have been too many requests...
  209. } else if (_relays[id].fw_count >= RELAY_FLOOD_CHANGES) {
  210. // We schedule the changes to the end of the floodWindow
  211. // unless it's already delayed beyond that point
  212. if (fw_end - delay > current_time) {
  213. _relays[id].change_time = fw_end;
  214. }
  215. }
  216. _relays[id].target_status = status;
  217. if (report) _relays[id].report = true;
  218. if (group_report) _relays[id].group_report = true;
  219. relaySync(id);
  220. DEBUG_MSG_P(PSTR("[RELAY] #%d scheduled %s in %u ms\n"),
  221. id, status ? "ON" : "OFF",
  222. (_relays[id].change_time - current_time));
  223. changed = true;
  224. }
  225. return changed;
  226. }
  227. bool relayStatus(unsigned char id, bool status) {
  228. return relayStatus(id, status, true, true);
  229. }
  230. bool relayStatus(unsigned char id) {
  231. // Check relay ID
  232. if (id >= _relays.size()) return false;
  233. // Get status from storage
  234. return _relays[id].current_status;
  235. }
  236. void relaySync(unsigned char id) {
  237. // No sync if none or only one relay
  238. if (_relays.size() < 2) return;
  239. // Do not go on if we are comming from a previous sync
  240. if (_relayRecursive) return;
  241. // Flag sync mode
  242. _relayRecursive = true;
  243. byte relaySync = getSetting("rlySync", RELAY_SYNC).toInt();
  244. bool status = _relays[id].target_status;
  245. // If RELAY_SYNC_SAME all relays should have the same state
  246. if (relaySync == RELAY_SYNC_SAME) {
  247. for (unsigned short i=0; i<_relays.size(); i++) {
  248. if (i != id) relayStatus(i, status);
  249. }
  250. // If NONE_OR_ONE or ONE and setting ON we should set OFF all the others
  251. } else if (status) {
  252. if (relaySync != RELAY_SYNC_ANY) {
  253. for (unsigned short i=0; i<_relays.size(); i++) {
  254. if (i != id) relayStatus(i, false);
  255. }
  256. }
  257. // If ONLY_ONE and setting OFF we should set ON the other one
  258. } else {
  259. if (relaySync == RELAY_SYNC_ONE) {
  260. unsigned char i = (id + 1) % _relays.size();
  261. relayStatus(i, true);
  262. }
  263. }
  264. // Unflag sync mode
  265. _relayRecursive = false;
  266. }
  267. void relaySave() {
  268. unsigned char bit = 1;
  269. unsigned char mask = 0;
  270. for (unsigned int i=0; i < _relays.size(); i++) {
  271. if (relayStatus(i)) mask += bit;
  272. bit += bit;
  273. }
  274. EEPROMr.write(EEPROM_RELAY_STATUS, mask);
  275. DEBUG_MSG_P(PSTR("[RELAY] Saving mask: %d\n"), mask);
  276. EEPROMr.commit();
  277. }
  278. void relayToggle(unsigned char id, bool report, bool group_report) {
  279. if (id >= _relays.size()) return;
  280. relayStatus(id, !relayStatus(id), report, group_report);
  281. }
  282. void relayToggle(unsigned char id) {
  283. relayToggle(id, true, true);
  284. }
  285. unsigned char relayCount() {
  286. return _relays.size();
  287. }
  288. unsigned char relayParsePayload(const char * payload) {
  289. // Payload could be "OFF", "ON", "TOGGLE"
  290. // or its number equivalents: 0, 1 or 2
  291. if (payload[0] == '0') return 0;
  292. if (payload[0] == '1') return 1;
  293. if (payload[0] == '2') return 2;
  294. // trim payload
  295. char * p = ltrim((char *)payload);
  296. // to lower
  297. unsigned int l = strlen(p);
  298. if (l>6) l=6;
  299. for (unsigned char i=0; i<l; i++) {
  300. p[i] = tolower(p[i]);
  301. }
  302. unsigned int value = 0xFF;
  303. if (strcmp(p, "off") == 0) {
  304. value = 0;
  305. } else if (strcmp(p, "on") == 0) {
  306. value = 1;
  307. } else if (strcmp(p, "toggle") == 0) {
  308. value = 2;
  309. } else if (strcmp(p, "query") == 0) {
  310. value = 3;
  311. }
  312. return value;
  313. }
  314. bool _relayKeyCheck(const char * key) {
  315. return (strncmp(key, "rly", 3) == 0);
  316. }
  317. void _relayBackwards() {
  318. // 1.11.0 - 2017-12-26
  319. byte relayMode = getSetting("relayMode", RELAY_BOOT_MODE).toInt();
  320. byte relayPulseMode = getSetting("relayPulseMode", RELAY_PULSE_MODE).toInt();
  321. float relayPulseTime = getSetting("relayPulseTime", RELAY_PULSE_TIME).toFloat();
  322. if (relayPulseMode == RELAY_PULSE_NONE) relayPulseTime = 0;
  323. for (unsigned int i=0; i<_relays.size(); i++) {
  324. if (!hasSetting("rlyBoot", i)) setSetting("rlyBoot", i, relayMode);
  325. if (!hasSetting("rlyPulse", i)) setSetting("rlyPulse", i, relayPulseMode);
  326. if (!hasSetting("rlyTime", i)) setSetting("rlyTime", i, relayPulseTime);
  327. }
  328. delSetting("relayMode");
  329. delSetting("relayPulseMode");
  330. delSetting("relayPulseTime");
  331. // 1.14.0 - 2018-06-26
  332. moveSettings("relayBoot", "rlyBoot");
  333. moveSettings("relayPulse", "rlyPulse");
  334. moveSettings("relayTime", "rlyTime");
  335. moveSettings("relayOnDisc", "rlyOnDisc");
  336. moveSetting("relaySync", "rlySync");
  337. }
  338. void _relayBoot() {
  339. _relayRecursive = true;
  340. unsigned char bit = 1;
  341. bool trigger_save = false;
  342. // Get last statuses from EEPROM
  343. unsigned char mask = EEPROMr.read(EEPROM_RELAY_STATUS);
  344. DEBUG_MSG_P(PSTR("[RELAY] Retrieving mask: %d\n"), mask);
  345. // Walk the relays
  346. bool status = false;
  347. for (unsigned int i=0; i<_relays.size(); i++) {
  348. unsigned char boot_mode = getSetting("rlyBoot", i, RELAY_BOOT_MODE).toInt();
  349. DEBUG_MSG_P(PSTR("[RELAY] Relay #%d boot mode %d\n"), i, boot_mode);
  350. switch (boot_mode) {
  351. case RELAY_BOOT_SAME:
  352. status = ((mask & bit) == bit);
  353. break;
  354. case RELAY_BOOT_TOGGLE:
  355. status = ((mask & bit) != bit);
  356. mask ^= bit;
  357. trigger_save = true;
  358. break;
  359. case RELAY_BOOT_ON:
  360. status = true;
  361. break;
  362. case RELAY_BOOT_OFF:
  363. default:
  364. status = false;
  365. break;
  366. }
  367. _relays[i].current_status = !status;
  368. _relays[i].target_status = status;
  369. #if RELAY_PROVIDER == RELAY_PROVIDER_STM
  370. _relays[i].change_time = millis() + 3000 + 1000 * i;
  371. #else
  372. _relays[i].change_time = millis();
  373. #endif
  374. bit <<= 1;
  375. }
  376. // Save if there is any relay in the RELAY_BOOT_TOGGLE mode
  377. if (trigger_save) {
  378. EEPROMr.write(EEPROM_RELAY_STATUS, mask);
  379. EEPROMr.commit();
  380. }
  381. _relayRecursive = false;
  382. }
  383. void _relayConfigure() {
  384. for (unsigned int i=0; i<_relays.size(); i++) {
  385. pinMode(_relays[i].pin, OUTPUT);
  386. if (_relays[i].type == RELAY_TYPE_LATCHED || _relays[i].type == RELAY_TYPE_LATCHED_INVERSE) {
  387. pinMode(_relays[i].reset_pin, OUTPUT);
  388. }
  389. _relays[i].pulse = getSetting("rlyPulse", i, RELAY_PULSE_MODE).toInt();
  390. _relays[i].pulse_ms = 1000 * getSetting("rlyTime", i, RELAY_PULSE_MODE).toFloat();
  391. }
  392. }
  393. //------------------------------------------------------------------------------
  394. // WEBSOCKETS
  395. //------------------------------------------------------------------------------
  396. #if WEB_SUPPORT
  397. void _relayWebSocketUpdate(JsonObject& root) {
  398. JsonArray& relay = root.createNestedArray("relayStatus");
  399. for (unsigned char i=0; i<relayCount(); i++) {
  400. relay.add(_relays[i].target_status);
  401. }
  402. }
  403. void _relayWebSocketOnStart(JsonObject& root) {
  404. if (relayCount() == 0) return;
  405. // Statuses
  406. _relayWebSocketUpdate(root);
  407. // Configuration
  408. JsonArray& config = root.createNestedArray("relayConfig");
  409. for (unsigned char i=0; i<relayCount(); i++) {
  410. JsonObject& line = config.createNestedObject();
  411. line["gpio"] = _relays[i].pin;
  412. line["type"] = _relays[i].type;
  413. line["reset"] = _relays[i].reset_pin;
  414. line["boot"] = getSetting("rlyBoot", i, RELAY_BOOT_MODE).toInt();
  415. line["pulse"] = _relays[i].pulse;
  416. line["pulse_ms"] = _relays[i].pulse_ms / 1000.0;
  417. #if MQTT_SUPPORT
  418. line["group"] = getSetting("mqttGroup", i, "");
  419. line["group_inv"] = getSetting("mqttGroupInv", i, 0).toInt();
  420. line["on_disc"] = getSetting("rlyOnDisc", i, 0).toInt();
  421. #endif
  422. }
  423. if (relayCount() > 1) {
  424. root["mrlyVisible"] = 1;
  425. root["rlySync"] = getSetting("rlySync", RELAY_SYNC);
  426. }
  427. root["rlyVisible"] = 1;
  428. }
  429. void _relayWebSocketOnAction(uint32_t client_id, const char * action, JsonObject& data) {
  430. if (strcmp(action, "relay") != 0) return;
  431. if (data.containsKey("status")) {
  432. unsigned char value = relayParsePayload(data["status"]);
  433. if (value == 3) {
  434. wsSend(_relayWebSocketUpdate);
  435. } else if (value < 3) {
  436. unsigned int relayID = 0;
  437. if (data.containsKey("id")) {
  438. String value = data["id"];
  439. relayID = value.toInt();
  440. }
  441. // Action to perform
  442. if (value == 0) {
  443. relayStatus(relayID, false);
  444. } else if (value == 1) {
  445. relayStatus(relayID, true);
  446. } else if (value == 2) {
  447. relayToggle(relayID);
  448. }
  449. }
  450. }
  451. }
  452. void relaySetupWS() {
  453. wsOnSendRegister(_relayWebSocketOnStart);
  454. wsOnActionRegister(_relayWebSocketOnAction);
  455. wsOnAfterParseRegister(_relayConfigure);
  456. }
  457. #endif // WEB_SUPPORT
  458. //------------------------------------------------------------------------------
  459. // REST API
  460. //------------------------------------------------------------------------------
  461. #if WEB_SUPPORT
  462. void relaySetupAPI() {
  463. // API entry points (protected with apikey)
  464. for (unsigned int relayID=0; relayID<relayCount(); relayID++) {
  465. char key[20];
  466. snprintf_P(key, sizeof(key), PSTR("%s/%d"), MQTT_TOPIC_RELAY, relayID);
  467. apiRegister(key,
  468. [relayID](char * buffer, size_t len) {
  469. snprintf_P(buffer, len, PSTR("%d"), _relays[relayID].target_status ? 1 : 0);
  470. },
  471. [relayID](const char * payload) {
  472. unsigned char value = relayParsePayload(payload);
  473. if (value == 0xFF) {
  474. DEBUG_MSG_P(PSTR("[RELAY] Wrong payload (%s)\n"), payload);
  475. return;
  476. }
  477. if (value == 0) {
  478. relayStatus(relayID, false);
  479. } else if (value == 1) {
  480. relayStatus(relayID, true);
  481. } else if (value == 2) {
  482. relayToggle(relayID);
  483. }
  484. }
  485. );
  486. snprintf_P(key, sizeof(key), PSTR("%s/%d"), MQTT_TOPIC_PULSE, relayID);
  487. apiRegister(key,
  488. [relayID](char * buffer, size_t len) {
  489. dtostrf((double) _relays[relayID].pulse_ms / 1000, 1-len, 3, buffer);
  490. },
  491. [relayID](const char * payload) {
  492. unsigned long pulse = 1000 * String(payload).toFloat();
  493. if (0 == pulse) return;
  494. if (RELAY_PULSE_NONE != _relays[relayID].pulse) {
  495. DEBUG_MSG_P(PSTR("[RELAY] Overriding relay #%d pulse settings\n"), relayID);
  496. }
  497. _relays[relayID].pulse_ms = pulse;
  498. _relays[relayID].pulse = relayStatus(relayID) ? RELAY_PULSE_ON : RELAY_PULSE_OFF;
  499. relayToggle(relayID, true, false);
  500. return;
  501. }
  502. );
  503. }
  504. }
  505. #endif // WEB_SUPPORT
  506. //------------------------------------------------------------------------------
  507. // MQTT
  508. //------------------------------------------------------------------------------
  509. #if MQTT_SUPPORT
  510. void relayMQTT(unsigned char id) {
  511. if (id >= _relays.size()) return;
  512. // Send state topic
  513. if (_relays[id].report) {
  514. _relays[id].report = false;
  515. mqttSend(MQTT_TOPIC_RELAY, id, _relays[id].current_status ? "1" : "0");
  516. }
  517. // Check group topic
  518. if (_relays[id].group_report) {
  519. _relays[id].group_report = false;
  520. String t = getSetting("mqttGroup", id, "");
  521. if (t.length() > 0) {
  522. bool status = relayStatus(id);
  523. if (getSetting("mqttGroupInv", id, 0).toInt() == 1) status = !status;
  524. mqttSendRaw(t.c_str(), status ? "1" : "0");
  525. }
  526. }
  527. }
  528. void relayMQTT() {
  529. for (unsigned int id=0; id < _relays.size(); id++) {
  530. mqttSend(MQTT_TOPIC_RELAY, id, _relays[id].current_status ? "1" : "0");
  531. }
  532. }
  533. void relayStatusWrap(unsigned char id, unsigned char value, bool is_group_topic) {
  534. switch (value) {
  535. case 0:
  536. relayStatus(id, false, mqttForward(), !is_group_topic);
  537. break;
  538. case 1:
  539. relayStatus(id, true, mqttForward(), !is_group_topic);
  540. break;
  541. case 2:
  542. relayToggle(id, true, true);
  543. break;
  544. default:
  545. _relays[id].report = true;
  546. relayMQTT(id);
  547. break;
  548. }
  549. }
  550. void relayMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  551. if (type == MQTT_CONNECT_EVENT) {
  552. // Send status on connect
  553. #if not HEARTBEAT_REPORT_RELAY
  554. relayMQTT();
  555. #endif
  556. // Subscribe to own /set topic
  557. char relay_topic[strlen(MQTT_TOPIC_RELAY) + 3];
  558. snprintf_P(relay_topic, sizeof(relay_topic), PSTR("%s/+"), MQTT_TOPIC_RELAY);
  559. mqttSubscribe(relay_topic);
  560. // Subscribe to pulse topic
  561. char pulse_topic[strlen(MQTT_TOPIC_PULSE) + 3];
  562. snprintf_P(pulse_topic, sizeof(pulse_topic), PSTR("%s/+"), MQTT_TOPIC_PULSE);
  563. mqttSubscribe(pulse_topic);
  564. // Subscribe to group topics
  565. for (unsigned int i=0; i < _relays.size(); i++) {
  566. String t = getSetting("mqttGroup", i, "");
  567. if (t.length() > 0) mqttSubscribeRaw(t.c_str());
  568. }
  569. }
  570. if (type == MQTT_MESSAGE_EVENT) {
  571. String t = mqttMagnitude((char *) topic);
  572. // magnitude is relay/#/pulse
  573. if (t.startsWith(MQTT_TOPIC_PULSE)) {
  574. unsigned int id = t.substring(strlen(MQTT_TOPIC_PULSE)+1).toInt();
  575. if (id >= relayCount()) {
  576. DEBUG_MSG_P(PSTR("[RELAY] Wrong relayID (%d)\n"), id);
  577. return;
  578. }
  579. unsigned long pulse = 1000 * String(payload).toFloat();
  580. if (0 == pulse) return;
  581. if (RELAY_PULSE_NONE != _relays[id].pulse) {
  582. DEBUG_MSG_P(PSTR("[RELAY] Overriding relay #%d pulse settings\n"), id);
  583. }
  584. _relays[id].pulse_ms = pulse;
  585. _relays[id].pulse = relayStatus(id) ? RELAY_PULSE_ON : RELAY_PULSE_OFF;
  586. relayToggle(id, true, false);
  587. return;
  588. }
  589. // magnitude is relay/#
  590. if (t.startsWith(MQTT_TOPIC_RELAY)) {
  591. // Get relay ID
  592. unsigned int id = t.substring(strlen(MQTT_TOPIC_RELAY)+1).toInt();
  593. if (id >= relayCount()) {
  594. DEBUG_MSG_P(PSTR("[RELAY] Wrong relayID (%d)\n"), id);
  595. return;
  596. }
  597. // Get value
  598. unsigned char value = relayParsePayload(payload);
  599. if (value == 0xFF) return;
  600. relayStatusWrap(id, value, false);
  601. return;
  602. }
  603. // Check group topics
  604. for (unsigned int i=0; i < _relays.size(); i++) {
  605. String t = getSetting("mqttGroup", i, "");
  606. if ((t.length() > 0) && t.equals(topic)) {
  607. unsigned char value = relayParsePayload(payload);
  608. if (value == 0xFF) return;
  609. if (value < 2) {
  610. if (getSetting("mqttGroupInv", i, 0).toInt() == 1) {
  611. value = 1 - value;
  612. }
  613. }
  614. DEBUG_MSG_P(PSTR("[RELAY] Matched group topic for relayID %d\n"), i);
  615. relayStatusWrap(i, value, true);
  616. }
  617. }
  618. }
  619. if (type == MQTT_DISCONNECT_EVENT) {
  620. for (unsigned int i=0; i < _relays.size(); i++){
  621. int reaction = getSetting("rlyOnDisc", i, 0).toInt();
  622. if (1 == reaction) { // switch relay OFF
  623. DEBUG_MSG_P(PSTR("[RELAY] Reset relay (%d) due to MQTT disconnection\n"), i);
  624. relayStatusWrap(i, false, false);
  625. } else if(2 == reaction) { // switch relay ON
  626. DEBUG_MSG_P(PSTR("[RELAY] Set relay (%d) due to MQTT disconnection\n"), i);
  627. relayStatusWrap(i, true, false);
  628. }
  629. }
  630. }
  631. }
  632. void relaySetupMQTT() {
  633. mqttRegister(relayMQTTCallback);
  634. }
  635. #endif
  636. //------------------------------------------------------------------------------
  637. // InfluxDB
  638. //------------------------------------------------------------------------------
  639. #if INFLUXDB_SUPPORT
  640. void relayInfluxDB(unsigned char id) {
  641. if (id >= _relays.size()) return;
  642. idbSend(MQTT_TOPIC_RELAY, id, relayStatus(id) ? "1" : "0");
  643. }
  644. #endif
  645. //------------------------------------------------------------------------------
  646. // Settings
  647. //------------------------------------------------------------------------------
  648. #if TERMINAL_SUPPORT
  649. void _relayInitCommands() {
  650. settingsRegisterCommand(F("RELAY"), [](Embedis* e) {
  651. if (e->argc < 2) {
  652. DEBUG_MSG_P(PSTR("-ERROR: Wrong arguments\n"));
  653. return;
  654. }
  655. int id = String(e->argv[1]).toInt();
  656. if (id >= relayCount()) {
  657. DEBUG_MSG_P(PSTR("-ERROR: Wrong relayID (%d)\n"), id);
  658. return;
  659. }
  660. if (e->argc > 2) {
  661. int value = String(e->argv[2]).toInt();
  662. if (value == 2) {
  663. relayToggle(id);
  664. } else {
  665. relayStatus(id, value == 1);
  666. }
  667. }
  668. DEBUG_MSG_P(PSTR("Status: %s\n"), _relays[id].target_status ? "true" : "false");
  669. if (_relays[id].pulse != RELAY_PULSE_NONE) {
  670. DEBUG_MSG_P(PSTR("Pulse: %s\n"), (_relays[id].pulse == RELAY_PULSE_ON) ? "ON" : "OFF");
  671. DEBUG_MSG_P(PSTR("Pulse time: %d\n"), _relays[id].pulse_ms);
  672. }
  673. DEBUG_MSG_P(PSTR("+OK\n"));
  674. });
  675. }
  676. #endif // TERMINAL_SUPPORT
  677. //------------------------------------------------------------------------------
  678. // Setup
  679. //------------------------------------------------------------------------------
  680. void _relayLoop() {
  681. _relayProcess(false);
  682. _relayProcess(true);
  683. }
  684. void relaySetup() {
  685. // Dummy relays for AI Light, Magic Home LED Controller, H801,
  686. // Sonoff Dual and Sonoff RF Bridge
  687. #if DUMMY_RELAY_COUNT > 0
  688. 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};
  689. 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};
  690. for (unsigned char i=0; i < DUMMY_RELAY_COUNT; i++) {
  691. _relays.push_back((relay_t) {0, RELAY_TYPE_NORMAL,0,_delay_on[i], _delay_off[i]});
  692. }
  693. #else
  694. #if RELAY1_PIN != GPIO_NONE
  695. _relays.push_back((relay_t) { RELAY1_PIN, RELAY1_TYPE, RELAY1_RESET_PIN, RELAY1_DELAY_ON, RELAY1_DELAY_OFF });
  696. #endif
  697. #if RELAY2_PIN != GPIO_NONE
  698. _relays.push_back((relay_t) { RELAY2_PIN, RELAY2_TYPE, RELAY2_RESET_PIN, RELAY2_DELAY_ON, RELAY2_DELAY_OFF });
  699. #endif
  700. #if RELAY3_PIN != GPIO_NONE
  701. _relays.push_back((relay_t) { RELAY3_PIN, RELAY3_TYPE, RELAY3_RESET_PIN, RELAY3_DELAY_ON, RELAY3_DELAY_OFF });
  702. #endif
  703. #if RELAY4_PIN != GPIO_NONE
  704. _relays.push_back((relay_t) { RELAY4_PIN, RELAY4_TYPE, RELAY4_RESET_PIN, RELAY4_DELAY_ON, RELAY4_DELAY_OFF });
  705. #endif
  706. #if RELAY5_PIN != GPIO_NONE
  707. _relays.push_back((relay_t) { RELAY5_PIN, RELAY5_TYPE, RELAY5_RESET_PIN, RELAY5_DELAY_ON, RELAY5_DELAY_OFF });
  708. #endif
  709. #if RELAY6_PIN != GPIO_NONE
  710. _relays.push_back((relay_t) { RELAY6_PIN, RELAY6_TYPE, RELAY6_RESET_PIN, RELAY6_DELAY_ON, RELAY6_DELAY_OFF });
  711. #endif
  712. #if RELAY7_PIN != GPIO_NONE
  713. _relays.push_back((relay_t) { RELAY7_PIN, RELAY7_TYPE, RELAY7_RESET_PIN, RELAY7_DELAY_ON, RELAY7_DELAY_OFF });
  714. #endif
  715. #if RELAY8_PIN != GPIO_NONE
  716. _relays.push_back((relay_t) { RELAY8_PIN, RELAY8_TYPE, RELAY8_RESET_PIN, RELAY8_DELAY_ON, RELAY8_DELAY_OFF });
  717. #endif
  718. #endif
  719. _relayBackwards();
  720. _relayConfigure();
  721. _relayBoot();
  722. _relayLoop();
  723. settingsRegisterKeyCheck(_relayKeyCheck);
  724. espurnaRegisterLoop(_relayLoop);
  725. #if WEB_SUPPORT
  726. relaySetupAPI();
  727. relaySetupWS();
  728. #endif
  729. #if MQTT_SUPPORT
  730. relaySetupMQTT();
  731. #endif
  732. #if TERMINAL_SUPPORT
  733. _relayInitCommands();
  734. #endif
  735. DEBUG_MSG_P(PSTR("[RELAY] Number of relays: %d\n"), _relays.size());
  736. }