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.

966 lines
29 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. 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. // BACKWARDS COMPATIBILITY
  313. void _relayBackwards() {
  314. // 1.11.0 - 2017-12-26
  315. byte relayMode = getSetting("relayMode", RELAY_BOOT_MODE).toInt();
  316. byte relayPulseMode = getSetting("relayPulseMode", RELAY_PULSE_MODE).toInt();
  317. float relayPulseTime = getSetting("relayPulseTime", RELAY_PULSE_TIME).toFloat();
  318. if (relayPulseMode == RELAY_PULSE_NONE) relayPulseTime = 0;
  319. for (unsigned int i=0; i<_relays.size(); i++) {
  320. if (!hasSetting("relayBoot", i)) setSetting("rlyBoot", i, relayMode);
  321. if (!hasSetting("relayPulse", i)) setSetting("rlyPulse", i, relayPulseMode);
  322. if (!hasSetting("relayTime", i)) setSetting("rlyTime", i, relayPulseTime);
  323. }
  324. delSetting("relayMode");
  325. delSetting("relayPulseMode");
  326. delSetting("relayPulseTime");
  327. // 1.13.1 - 2018-06-26
  328. moveSettings("relayBoot", "rlyBoot");
  329. moveSettings("relayPulse", "rlyPulse");
  330. moveSettings("relayTime", "rlyTime");
  331. moveSetting("relayOnDisc", "rlyOnDisc");
  332. moveSetting("relaySync", "rlySync");
  333. }
  334. void _relayBoot() {
  335. _relayRecursive = true;
  336. unsigned char bit = 1;
  337. bool trigger_save = false;
  338. // Get last statuses from EEPROM
  339. unsigned char mask = EEPROMr.read(EEPROM_RELAY_STATUS);
  340. DEBUG_MSG_P(PSTR("[RELAY] Retrieving mask: %d\n"), mask);
  341. // Walk the relays
  342. bool status = false;
  343. for (unsigned int i=0; i<_relays.size(); i++) {
  344. unsigned char boot_mode = getSetting("relayBoot", i, RELAY_BOOT_MODE).toInt();
  345. DEBUG_MSG_P(PSTR("[RELAY] Relay #%d boot mode %d\n"), i, boot_mode);
  346. switch (boot_mode) {
  347. case RELAY_BOOT_SAME:
  348. status = ((mask & bit) == bit);
  349. break;
  350. case RELAY_BOOT_TOGGLE:
  351. status = ((mask & bit) != bit);
  352. mask ^= bit;
  353. trigger_save = true;
  354. break;
  355. case RELAY_BOOT_ON:
  356. status = true;
  357. break;
  358. case RELAY_BOOT_OFF:
  359. default:
  360. status = false;
  361. break;
  362. }
  363. _relays[i].current_status = !status;
  364. _relays[i].target_status = status;
  365. #if RELAY_PROVIDER == RELAY_PROVIDER_STM
  366. _relays[i].change_time = millis() + 3000 + 1000 * i;
  367. #else
  368. _relays[i].change_time = millis();
  369. #endif
  370. bit <<= 1;
  371. }
  372. // Save if there is any relay in the RELAY_BOOT_TOGGLE mode
  373. if (trigger_save) {
  374. EEPROMr.write(EEPROM_RELAY_STATUS, mask);
  375. EEPROMr.commit();
  376. }
  377. _relayRecursive = false;
  378. }
  379. void _relayConfigure() {
  380. for (unsigned int i=0; i<_relays.size(); i++) {
  381. pinMode(_relays[i].pin, OUTPUT);
  382. if (_relays[i].type == RELAY_TYPE_LATCHED || _relays[i].type == RELAY_TYPE_LATCHED_INVERSE) {
  383. pinMode(_relays[i].reset_pin, OUTPUT);
  384. }
  385. _relays[i].pulse = getSetting("rlyPulse", i, RELAY_PULSE_MODE).toInt();
  386. _relays[i].pulse_ms = 1000 * getSetting("rlyTime", i, RELAY_PULSE_MODE).toFloat();
  387. }
  388. }
  389. //------------------------------------------------------------------------------
  390. // WEBSOCKETS
  391. //------------------------------------------------------------------------------
  392. #if WEB_SUPPORT
  393. bool _relayWebSocketOnReceive(const char * key, JsonVariant& value) {
  394. return (strncmp(key, "relay", 5) == 0);
  395. }
  396. void _relayWebSocketUpdate(JsonObject& root) {
  397. JsonArray& relay = root.createNestedArray("relayStatus");
  398. for (unsigned char i=0; i<relayCount(); i++) {
  399. relay.add(_relays[i].target_status);
  400. }
  401. }
  402. void _relayWebSocketOnStart(JsonObject& root) {
  403. if (relayCount() == 0) return;
  404. // Statuses
  405. _relayWebSocketUpdate(root);
  406. // Configuration
  407. JsonArray& config = root.createNestedArray("relayConfig");
  408. for (unsigned char i=0; i<relayCount(); i++) {
  409. JsonObject& line = config.createNestedObject();
  410. line["gpio"] = _relays[i].pin;
  411. line["type"] = _relays[i].type;
  412. line["reset"] = _relays[i].reset_pin;
  413. line["boot"] = getSetting("relayBoot", i, RELAY_BOOT_MODE).toInt();
  414. line["pulse"] = _relays[i].pulse;
  415. line["pulse_ms"] = _relays[i].pulse_ms / 1000.0;
  416. #if MQTT_SUPPORT
  417. line["group"] = getSetting("mqttGroup", i, "");
  418. line["group_inv"] = getSetting("mqttGroupInv", i, 0).toInt();
  419. line["on_disc"] = getSetting("rlyOnDisc", i, 0).toInt();
  420. #endif
  421. }
  422. if (relayCount() > 1) {
  423. root["mrlyVisible"] = 1;
  424. root["rlySync"] = getSetting("rlySync", RELAY_SYNC);
  425. }
  426. root["rlyVisible"] = 1;
  427. }
  428. void _relayWebSocketOnAction(uint32_t client_id, const char * action, JsonObject& data) {
  429. if (strcmp(action, "relay") != 0) return;
  430. if (data.containsKey("status")) {
  431. unsigned char value = relayParsePayload(data["status"]);
  432. if (value == 3) {
  433. wsSend(_relayWebSocketUpdate);
  434. } else if (value < 3) {
  435. unsigned int relayID = 0;
  436. if (data.containsKey("id")) {
  437. String value = data["id"];
  438. relayID = value.toInt();
  439. }
  440. // Action to perform
  441. if (value == 0) {
  442. relayStatus(relayID, false);
  443. } else if (value == 1) {
  444. relayStatus(relayID, true);
  445. } else if (value == 2) {
  446. relayToggle(relayID);
  447. }
  448. }
  449. }
  450. }
  451. void relaySetupWS() {
  452. wsOnSendRegister(_relayWebSocketOnStart);
  453. wsOnActionRegister(_relayWebSocketOnAction);
  454. wsOnAfterParseRegister(_relayConfigure);
  455. wsOnReceiveRegister(_relayWebSocketOnReceive);
  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. espurnaRegisterLoop(_relayLoop);
  724. #if WEB_SUPPORT
  725. relaySetupAPI();
  726. relaySetupWS();
  727. #endif
  728. #if MQTT_SUPPORT
  729. relaySetupMQTT();
  730. #endif
  731. #if TERMINAL_SUPPORT
  732. _relayInitCommands();
  733. #endif
  734. DEBUG_MSG_P(PSTR("[RELAY] Number of relays: %d\n"), _relays.size());
  735. }