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.

972 lines
28 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. /*
  2. RELAY MODULE
  3. Copyright (C) 2016-2018 by Xose Pérez <xose dot perez at gmail dot com>
  4. 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 _relayClear() {
  384. for (unsigned char i = 0; i < _relays.size(); i++) {
  385. relay_t element = _relays[i];
  386. element.pulseTicker.detach();
  387. }
  388. _relays.clear();
  389. }
  390. void _relayConfigure() {
  391. _relayClear();
  392. // Dummy relays for AI Light, Magic Home LED Controller, H801,
  393. // Sonoff Dual and Sonoff RF Bridge
  394. unsigned char dummy = getSetting("rlyDummy", 0).toInt();
  395. if (dummy > 0) {
  396. for (unsigned char index=0; index < dummy; index++) {
  397. unsigned long delay_on = getSetting("rlyDelayOn", index, 0).toInt();
  398. unsigned long delay_off = getSetting("rlyDelayOff", index, 0).toInt();
  399. _relays.push_back((relay_t) {0, RELAY_TYPE_NORMAL, 0, delay_on, delay_off});
  400. }
  401. } else {
  402. unsigned char index = 0;
  403. while (index < MAX_COMPONENTS) {
  404. unsigned char pin = getSetting("rlyGPIO", index, GPIO_NONE).toInt();
  405. if (GPIO_NONE == pin) break;
  406. pinMode(pin, OUTPUT);
  407. unsigned char type = getSetting("rlyType", index, RELAY_TYPE_NORMAL).toInt();
  408. unsigned char reset = getSetting("rlyResetGPIO", index, GPIO_NONE).toInt();
  409. if (((type & RELAY_TYPE_LATCHED) == RELAY_TYPE_LATCHED) && (GPIO_NONE == reset)) break;
  410. if (GPIO_NONE != reset) pinMode(reset, OUTPUT);
  411. unsigned long delay_on = getSetting("rlyDelayOn", index, 0).toInt();
  412. unsigned long delay_off = getSetting("rlyDelayOff", index, 0).toInt();
  413. unsigned char pulse = getSetting("rlyPulse", index, RELAY_PULSE_MODE).toInt();
  414. float pulse_ms = 1000 * getSetting("rlyTime", index, RELAY_PULSE_TIME).toFloat();
  415. _relays.push_back((relay_t) { pin, type, reset, delay_on, delay_off, pulse, pulse_ms });
  416. ++index;
  417. }
  418. }
  419. DEBUG_MSG_P(PSTR("[RELAY] Relays: %d\n"), _relays.size());
  420. }
  421. //------------------------------------------------------------------------------
  422. // WEBSOCKETS
  423. //------------------------------------------------------------------------------
  424. #if WEB_SUPPORT
  425. void _relayWebSocketUpdate(JsonObject& root) {
  426. JsonArray& relay = root.createNestedArray("relayStatus");
  427. for (unsigned char i=0; i<relayCount(); i++) {
  428. relay.add(_relays[i].target_status);
  429. }
  430. }
  431. void _relayWebSocketOnStart(JsonObject& root) {
  432. if (relayCount() == 0) return;
  433. // Statuses
  434. _relayWebSocketUpdate(root);
  435. // Configuration
  436. JsonArray& config = root.createNestedArray("relayConfig");
  437. for (unsigned char i=0; i<relayCount(); i++) {
  438. JsonObject& line = config.createNestedObject();
  439. line["gpio"] = _relays[i].pin;
  440. line["type"] = _relays[i].type;
  441. line["reset"] = _relays[i].reset_pin;
  442. line["boot"] = getSetting("rlyBoot", i, RELAY_BOOT_MODE).toInt();
  443. line["pulse"] = _relays[i].pulse;
  444. line["pulse_ms"] = _relays[i].pulse_ms / 1000.0;
  445. #if MQTT_SUPPORT
  446. line["group"] = getSetting("mqttGroup", i, "");
  447. line["group_inv"] = getSetting("mqttGroupInv", i, 0).toInt();
  448. line["on_disc"] = getSetting("rlyOnDisc", i, 0).toInt();
  449. #endif
  450. }
  451. if (relayCount() > 1) {
  452. root["mrlyVisible"] = 1;
  453. root["rlySync"] = getSetting("rlySync", RELAY_SYNC);
  454. }
  455. root["rlyVisible"] = 1;
  456. }
  457. void _relayWebSocketOnAction(uint32_t client_id, const char * action, JsonObject& data) {
  458. if (strcmp(action, "relay") != 0) return;
  459. if (data.containsKey("status")) {
  460. unsigned char value = relayParsePayload(data["status"]);
  461. if (value == 3) {
  462. wsSend(_relayWebSocketUpdate);
  463. } else if (value < 3) {
  464. unsigned int relayID = 0;
  465. if (data.containsKey("id")) {
  466. String value = data["id"];
  467. relayID = value.toInt();
  468. }
  469. // Action to perform
  470. if (value == 0) {
  471. relayStatus(relayID, false);
  472. } else if (value == 1) {
  473. relayStatus(relayID, true);
  474. } else if (value == 2) {
  475. relayToggle(relayID);
  476. }
  477. }
  478. }
  479. }
  480. void relaySetupWS() {
  481. wsOnSendRegister(_relayWebSocketOnStart);
  482. wsOnActionRegister(_relayWebSocketOnAction);
  483. wsOnAfterParseRegister(_relayConfigure);
  484. }
  485. #endif // WEB_SUPPORT
  486. //------------------------------------------------------------------------------
  487. // REST API
  488. //------------------------------------------------------------------------------
  489. #if WEB_SUPPORT
  490. void relaySetupAPI() {
  491. // API entry points (protected with apikey)
  492. for (unsigned int relayID=0; relayID<relayCount(); relayID++) {
  493. char key[20];
  494. snprintf_P(key, sizeof(key), PSTR("%s/%d"), MQTT_TOPIC_RELAY, relayID);
  495. apiRegister(key,
  496. [relayID](char * buffer, size_t len) {
  497. snprintf_P(buffer, len, PSTR("%d"), _relays[relayID].target_status ? 1 : 0);
  498. },
  499. [relayID](const char * payload) {
  500. unsigned char value = relayParsePayload(payload);
  501. if (value == 0xFF) {
  502. DEBUG_MSG_P(PSTR("[RELAY] Wrong payload (%s)\n"), payload);
  503. return;
  504. }
  505. if (value == 0) {
  506. relayStatus(relayID, false);
  507. } else if (value == 1) {
  508. relayStatus(relayID, true);
  509. } else if (value == 2) {
  510. relayToggle(relayID);
  511. }
  512. }
  513. );
  514. snprintf_P(key, sizeof(key), PSTR("%s/%d"), MQTT_TOPIC_PULSE, relayID);
  515. apiRegister(key,
  516. [relayID](char * buffer, size_t len) {
  517. dtostrf((double) _relays[relayID].pulse_ms / 1000, 1-len, 3, buffer);
  518. },
  519. [relayID](const char * payload) {
  520. unsigned long pulse = 1000 * String(payload).toFloat();
  521. if (0 == pulse) return;
  522. if (RELAY_PULSE_NONE != _relays[relayID].pulse) {
  523. DEBUG_MSG_P(PSTR("[RELAY] Overriding relay #%d pulse settings\n"), relayID);
  524. }
  525. _relays[relayID].pulse_ms = pulse;
  526. _relays[relayID].pulse = relayStatus(relayID) ? RELAY_PULSE_ON : RELAY_PULSE_OFF;
  527. relayToggle(relayID, true, false);
  528. return;
  529. }
  530. );
  531. }
  532. }
  533. #endif // WEB_SUPPORT
  534. //------------------------------------------------------------------------------
  535. // MQTT
  536. //------------------------------------------------------------------------------
  537. #if MQTT_SUPPORT
  538. void relayMQTT(unsigned char id) {
  539. if (id >= _relays.size()) return;
  540. // Send state topic
  541. if (_relays[id].report) {
  542. _relays[id].report = false;
  543. mqttSend(MQTT_TOPIC_RELAY, id, _relays[id].current_status ? "1" : "0");
  544. }
  545. // Check group topic
  546. if (_relays[id].group_report) {
  547. _relays[id].group_report = false;
  548. String t = getSetting("mqttGroup", id, "");
  549. if (t.length() > 0) {
  550. bool status = relayStatus(id);
  551. if (getSetting("mqttGroupInv", id, 0).toInt() == 1) status = !status;
  552. mqttSendRaw(t.c_str(), status ? "1" : "0");
  553. }
  554. }
  555. }
  556. void relayMQTT() {
  557. for (unsigned int id=0; id < _relays.size(); id++) {
  558. mqttSend(MQTT_TOPIC_RELAY, id, _relays[id].current_status ? "1" : "0");
  559. }
  560. }
  561. void relayStatusWrap(unsigned char id, unsigned char value, bool is_group_topic) {
  562. switch (value) {
  563. case 0:
  564. relayStatus(id, false, mqttForward(), !is_group_topic);
  565. break;
  566. case 1:
  567. relayStatus(id, true, mqttForward(), !is_group_topic);
  568. break;
  569. case 2:
  570. relayToggle(id, true, true);
  571. break;
  572. default:
  573. _relays[id].report = true;
  574. relayMQTT(id);
  575. break;
  576. }
  577. }
  578. void relayMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  579. if (type == MQTT_CONNECT_EVENT) {
  580. // Send status on connect
  581. #if not HEARTBEAT_REPORT_RELAY
  582. relayMQTT();
  583. #endif
  584. // Subscribe to own /set topic
  585. char relay_topic[strlen(MQTT_TOPIC_RELAY) + 3];
  586. snprintf_P(relay_topic, sizeof(relay_topic), PSTR("%s/+"), MQTT_TOPIC_RELAY);
  587. mqttSubscribe(relay_topic);
  588. // Subscribe to pulse topic
  589. char pulse_topic[strlen(MQTT_TOPIC_PULSE) + 3];
  590. snprintf_P(pulse_topic, sizeof(pulse_topic), PSTR("%s/+"), MQTT_TOPIC_PULSE);
  591. mqttSubscribe(pulse_topic);
  592. // Subscribe to group topics
  593. for (unsigned int i=0; i < _relays.size(); i++) {
  594. String t = getSetting("mqttGroup", i, "");
  595. if (t.length() > 0) mqttSubscribeRaw(t.c_str());
  596. }
  597. }
  598. if (type == MQTT_MESSAGE_EVENT) {
  599. String t = mqttMagnitude((char *) topic);
  600. // magnitude is relay/#/pulse
  601. if (t.startsWith(MQTT_TOPIC_PULSE)) {
  602. unsigned int id = t.substring(strlen(MQTT_TOPIC_PULSE)+1).toInt();
  603. if (id >= relayCount()) {
  604. DEBUG_MSG_P(PSTR("[RELAY] Wrong relayID (%d)\n"), id);
  605. return;
  606. }
  607. unsigned long pulse = 1000 * String(payload).toFloat();
  608. if (0 == pulse) return;
  609. if (RELAY_PULSE_NONE != _relays[id].pulse) {
  610. DEBUG_MSG_P(PSTR("[RELAY] Overriding relay #%d pulse settings\n"), id);
  611. }
  612. _relays[id].pulse_ms = pulse;
  613. _relays[id].pulse = relayStatus(id) ? RELAY_PULSE_ON : RELAY_PULSE_OFF;
  614. relayToggle(id, true, false);
  615. return;
  616. }
  617. // magnitude is relay/#
  618. if (t.startsWith(MQTT_TOPIC_RELAY)) {
  619. // Get relay ID
  620. unsigned int id = t.substring(strlen(MQTT_TOPIC_RELAY)+1).toInt();
  621. if (id >= relayCount()) {
  622. DEBUG_MSG_P(PSTR("[RELAY] Wrong relayID (%d)\n"), id);
  623. return;
  624. }
  625. // Get value
  626. unsigned char value = relayParsePayload(payload);
  627. if (value == 0xFF) return;
  628. relayStatusWrap(id, value, false);
  629. return;
  630. }
  631. // Check group topics
  632. for (unsigned int i=0; i < _relays.size(); i++) {
  633. String t = getSetting("mqttGroup", i, "");
  634. if ((t.length() > 0) && t.equals(topic)) {
  635. unsigned char value = relayParsePayload(payload);
  636. if (value == 0xFF) return;
  637. if (value < 2) {
  638. if (getSetting("mqttGroupInv", i, 0).toInt() == 1) {
  639. value = 1 - value;
  640. }
  641. }
  642. DEBUG_MSG_P(PSTR("[RELAY] Matched group topic for relayID %d\n"), i);
  643. relayStatusWrap(i, value, true);
  644. }
  645. }
  646. }
  647. if (type == MQTT_DISCONNECT_EVENT) {
  648. for (unsigned int i=0; i < _relays.size(); i++){
  649. int reaction = getSetting("rlyOnDisc", i, 0).toInt();
  650. if (1 == reaction) { // switch relay OFF
  651. DEBUG_MSG_P(PSTR("[RELAY] Reset relay (%d) due to MQTT disconnection\n"), i);
  652. relayStatusWrap(i, false, false);
  653. } else if(2 == reaction) { // switch relay ON
  654. DEBUG_MSG_P(PSTR("[RELAY] Set relay (%d) due to MQTT disconnection\n"), i);
  655. relayStatusWrap(i, true, false);
  656. }
  657. }
  658. }
  659. }
  660. void relaySetupMQTT() {
  661. mqttRegister(relayMQTTCallback);
  662. }
  663. #endif
  664. //------------------------------------------------------------------------------
  665. // InfluxDB
  666. //------------------------------------------------------------------------------
  667. #if INFLUXDB_SUPPORT
  668. void relayInfluxDB(unsigned char id) {
  669. if (id >= _relays.size()) return;
  670. idbSend(MQTT_TOPIC_RELAY, id, relayStatus(id) ? "1" : "0");
  671. }
  672. #endif
  673. //------------------------------------------------------------------------------
  674. // Settings
  675. //------------------------------------------------------------------------------
  676. #if TERMINAL_SUPPORT
  677. void _relayInitCommands() {
  678. settingsRegisterCommand(F("RELAY"), [](Embedis* e) {
  679. if (e->argc < 2) {
  680. DEBUG_MSG_P(PSTR("-ERROR: Wrong arguments\n"));
  681. return;
  682. }
  683. int id = String(e->argv[1]).toInt();
  684. if (id >= relayCount()) {
  685. DEBUG_MSG_P(PSTR("-ERROR: Wrong relayID (%d)\n"), id);
  686. return;
  687. }
  688. if (e->argc > 2) {
  689. int value = String(e->argv[2]).toInt();
  690. if (value == 2) {
  691. relayToggle(id);
  692. } else {
  693. relayStatus(id, value == 1);
  694. }
  695. }
  696. DEBUG_MSG_P(PSTR("Status: %s\n"), _relays[id].target_status ? "true" : "false");
  697. if (_relays[id].pulse != RELAY_PULSE_NONE) {
  698. DEBUG_MSG_P(PSTR("Pulse: %s\n"), (_relays[id].pulse == RELAY_PULSE_ON) ? "ON" : "OFF");
  699. DEBUG_MSG_P(PSTR("Pulse time: %d\n"), _relays[id].pulse_ms);
  700. }
  701. DEBUG_MSG_P(PSTR("+OK\n"));
  702. });
  703. }
  704. #endif // TERMINAL_SUPPORT
  705. //------------------------------------------------------------------------------
  706. // Setup
  707. //------------------------------------------------------------------------------
  708. void _relayLoop() {
  709. _relayProcess(false);
  710. _relayProcess(true);
  711. }
  712. void relaySetup() {
  713. _relayBackwards();
  714. _relayConfigure();
  715. _relayBoot();
  716. _relayLoop();
  717. settingsRegisterKeyCheck(_relayKeyCheck);
  718. espurnaRegisterLoop(_relayLoop);
  719. #if WEB_SUPPORT
  720. relaySetupAPI();
  721. relaySetupWS();
  722. #endif
  723. #if MQTT_SUPPORT
  724. relaySetupMQTT();
  725. #endif
  726. #if TERMINAL_SUPPORT
  727. _relayInitCommands();
  728. #endif
  729. }