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.

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