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.

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