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.

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