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.

960 lines
28 KiB

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