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.

1071 lines
32 KiB

  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. // Support for a mixed of dummy and real relays
  68. // Reference: https://github.com/xoseperez/espurna/issues/1305
  69. if (DUMMY_RELAY_COUNT > id) {
  70. // If the number of dummy relays matches the number of light channels
  71. // assume each relay controls one channel.
  72. // If the number of dummy relays is the number of channels plus 1
  73. // assume the first one controls all the channels and
  74. // the rest one channel each.
  75. // Otherwise every dummy relay controls all channels.
  76. if (DUMMY_RELAY_COUNT == lightChannels()) {
  77. lightState(id, status);
  78. lightState(true);
  79. } else if (DUMMY_RELAY_COUNT == (lightChannels() + 1u)) {
  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. return;
  90. }
  91. #endif
  92. #if (RELAY_PROVIDER == RELAY_PROVIDER_RELAY) || (RELAY_PROVIDER == RELAY_PROVIDER_LIGHT)
  93. // If this is a light, all dummy relays have already been processed above
  94. // we reach here if the user has toggled a physical relay
  95. if (_relays[id].type == RELAY_TYPE_NORMAL) {
  96. digitalWrite(_relays[id].pin, status);
  97. } else if (_relays[id].type == RELAY_TYPE_INVERSE) {
  98. digitalWrite(_relays[id].pin, !status);
  99. } else if (_relays[id].type == RELAY_TYPE_LATCHED || _relays[id].type == RELAY_TYPE_LATCHED_INVERSE) {
  100. bool pulse = RELAY_TYPE_LATCHED ? HIGH : LOW;
  101. digitalWrite(_relays[id].pin, !pulse);
  102. if (GPIO_NONE != _relays[id].reset_pin) digitalWrite(_relays[id].reset_pin, !pulse);
  103. if (status || (GPIO_NONE == _relays[id].reset_pin)) {
  104. digitalWrite(_relays[id].pin, pulse);
  105. } else {
  106. digitalWrite(_relays[id].reset_pin, pulse);
  107. }
  108. nice_delay(RELAY_LATCHING_PULSE);
  109. digitalWrite(_relays[id].pin, !pulse);
  110. if (GPIO_NONE != _relays[id].reset_pin) digitalWrite(_relays[id].reset_pin, !pulse);
  111. }
  112. #endif
  113. }
  114. /**
  115. * Walks the relay vector processing only those relays
  116. * that have to change to the requested mode
  117. * @bool mode Requested mode
  118. */
  119. void _relayProcess(bool mode) {
  120. unsigned long current_time = millis();
  121. for (unsigned char id = 0; id < _relays.size(); id++) {
  122. bool target = _relays[id].target_status;
  123. // Only process the relays we have to change
  124. if (target == _relays[id].current_status) continue;
  125. // Only process the relays we have change to the requested mode
  126. if (target != mode) continue;
  127. // Only process if the change_time has arrived
  128. if (current_time < _relays[id].change_time) continue;
  129. DEBUG_MSG_P(PSTR("[RELAY] #%d set to %s\n"), id, target ? "ON" : "OFF");
  130. // Call the provider to perform the action
  131. _relayProviderStatus(id, target);
  132. // Send to Broker
  133. #if BROKER_SUPPORT
  134. brokerPublish(MQTT_TOPIC_RELAY, id, target ? "1" : "0");
  135. #endif
  136. // Send MQTT
  137. #if MQTT_SUPPORT
  138. relayMQTT(id);
  139. #endif
  140. if (!_relayRecursive) {
  141. relayPulse(id);
  142. // We will trigger a commit only if
  143. // we care about current relay status on boot
  144. unsigned char boot_mode = getSetting("relayBoot", id, RELAY_BOOT_MODE).toInt();
  145. bool do_commit = ((RELAY_BOOT_SAME == boot_mode) || (RELAY_BOOT_TOGGLE == boot_mode));
  146. _relaySaveTicker.once_ms(RELAY_SAVE_DELAY, relaySave, do_commit);
  147. #if WEB_SUPPORT
  148. wsSend(_relayWebSocketUpdate);
  149. #endif
  150. }
  151. #if DOMOTICZ_SUPPORT
  152. domoticzSendRelay(id);
  153. #endif
  154. #if INFLUXDB_SUPPORT
  155. relayInfluxDB(id);
  156. #endif
  157. #if THINGSPEAK_SUPPORT
  158. tspkEnqueueRelay(id, target);
  159. tspkFlush();
  160. #endif
  161. // Flag relay-based LEDs to update status
  162. #if LED_SUPPORT
  163. ledUpdate(true);
  164. #endif
  165. _relays[id].report = false;
  166. _relays[id].group_report = false;
  167. }
  168. }
  169. #if defined(ITEAD_SONOFF_IFAN02)
  170. unsigned char _relay_ifan02_speeds[] = {0, 1, 3, 5};
  171. unsigned char getSpeed() {
  172. unsigned char speed =
  173. (_relays[1].target_status ? 1 : 0) +
  174. (_relays[2].target_status ? 2 : 0) +
  175. (_relays[3].target_status ? 4 : 0);
  176. for (unsigned char i=0; i<4; i++) {
  177. if (_relay_ifan02_speeds[i] == speed) return i;
  178. }
  179. return 0;
  180. }
  181. void setSpeed(unsigned char speed) {
  182. if ((0 <= speed) & (speed <= 3)) {
  183. if (getSpeed() == speed) return;
  184. unsigned char states = _relay_ifan02_speeds[speed];
  185. for (unsigned char i=0; i<3; i++) {
  186. relayStatus(i+1, states & 1 == 1);
  187. states >>= 1;
  188. }
  189. }
  190. }
  191. #endif
  192. // -----------------------------------------------------------------------------
  193. // RELAY
  194. // -----------------------------------------------------------------------------
  195. void relayPulse(unsigned char id) {
  196. _relays[id].pulseTicker.detach();
  197. byte mode = _relays[id].pulse;
  198. if (mode == RELAY_PULSE_NONE) return;
  199. unsigned long ms = _relays[id].pulse_ms;
  200. if (ms == 0) return;
  201. bool status = relayStatus(id);
  202. bool pulseStatus = (mode == RELAY_PULSE_ON);
  203. if (pulseStatus != status) {
  204. DEBUG_MSG_P(PSTR("[RELAY] Scheduling relay #%d back in %lums (pulse)\n"), id, ms);
  205. _relays[id].pulseTicker.once_ms(ms, relayToggle, id);
  206. // Reconfigure after dynamic pulse
  207. _relays[id].pulse = getSetting("relayPulse", id, RELAY_PULSE_MODE).toInt();
  208. _relays[id].pulse_ms = 1000 * getSetting("relayTime", id, RELAY_PULSE_MODE).toFloat();
  209. }
  210. }
  211. bool relayStatus(unsigned char id, bool status, bool report, bool group_report) {
  212. if (id >= _relays.size()) return false;
  213. bool changed = false;
  214. if (_relays[id].current_status == status) {
  215. if (_relays[id].target_status != status) {
  216. DEBUG_MSG_P(PSTR("[RELAY] #%d scheduled change cancelled\n"), id);
  217. _relays[id].target_status = status;
  218. _relays[id].report = false;
  219. _relays[id].group_report = false;
  220. changed = true;
  221. }
  222. // For RFBridge, keep sending the message even if the status is already the required
  223. #if RELAY_PROVIDER == RELAY_PROVIDER_RFBRIDGE
  224. rfbStatus(id, status);
  225. #endif
  226. // Update the pulse counter if the relay is already in the non-normal state (#454)
  227. relayPulse(id);
  228. } else {
  229. unsigned long current_time = millis();
  230. unsigned long fw_end = _relays[id].fw_start + 1000 * RELAY_FLOOD_WINDOW;
  231. unsigned long delay = status ? _relays[id].delay_on : _relays[id].delay_off;
  232. _relays[id].fw_count++;
  233. _relays[id].change_time = current_time + delay;
  234. // If current_time is off-limits the floodWindow...
  235. if (current_time < _relays[id].fw_start || fw_end <= current_time) {
  236. // We reset the floodWindow
  237. _relays[id].fw_start = current_time;
  238. _relays[id].fw_count = 1;
  239. // If current_time is in the floodWindow and there have been too many requests...
  240. } else if (_relays[id].fw_count >= RELAY_FLOOD_CHANGES) {
  241. // We schedule the changes to the end of the floodWindow
  242. // unless it's already delayed beyond that point
  243. if (fw_end - delay > current_time) {
  244. _relays[id].change_time = fw_end;
  245. }
  246. }
  247. _relays[id].target_status = status;
  248. if (report) _relays[id].report = true;
  249. if (group_report) _relays[id].group_report = true;
  250. relaySync(id);
  251. DEBUG_MSG_P(PSTR("[RELAY] #%d scheduled %s in %u ms\n"),
  252. id, status ? "ON" : "OFF",
  253. (_relays[id].change_time - current_time));
  254. changed = true;
  255. }
  256. return changed;
  257. }
  258. bool relayStatus(unsigned char id, bool status) {
  259. return relayStatus(id, status, true, true);
  260. }
  261. bool relayStatus(unsigned char id) {
  262. // Check relay ID
  263. if (id >= _relays.size()) return false;
  264. // Get status from storage
  265. return _relays[id].current_status;
  266. }
  267. void relaySync(unsigned char id) {
  268. // No sync if none or only one relay
  269. if (_relays.size() < 2) return;
  270. // Do not go on if we are comming from a previous sync
  271. if (_relayRecursive) return;
  272. // Flag sync mode
  273. _relayRecursive = true;
  274. byte relaySync = getSetting("relaySync", RELAY_SYNC).toInt();
  275. bool status = _relays[id].target_status;
  276. // If RELAY_SYNC_SAME all relays should have the same state
  277. if (relaySync == RELAY_SYNC_SAME) {
  278. for (unsigned short i=0; i<_relays.size(); i++) {
  279. if (i != id) relayStatus(i, status);
  280. }
  281. // If NONE_OR_ONE or ONE and setting ON we should set OFF all the others
  282. } else if (status) {
  283. if (relaySync != RELAY_SYNC_ANY) {
  284. for (unsigned short i=0; i<_relays.size(); i++) {
  285. if (i != id) relayStatus(i, false);
  286. }
  287. }
  288. // If ONLY_ONE and setting OFF we should set ON the other one
  289. } else {
  290. if (relaySync == RELAY_SYNC_ONE) {
  291. unsigned char i = (id + 1) % _relays.size();
  292. relayStatus(i, true);
  293. }
  294. }
  295. // Unflag sync mode
  296. _relayRecursive = false;
  297. }
  298. void relaySave(bool do_commit) {
  299. // Relay status is stored in a single byte
  300. // This means that, atm,
  301. // we are only storing the status of the first 8 relays.
  302. unsigned char bit = 1;
  303. unsigned char mask = 0;
  304. unsigned char count = _relays.size();
  305. if (count > 8) count = 8;
  306. for (unsigned int i=0; i < count; i++) {
  307. if (relayStatus(i)) mask += bit;
  308. bit += bit;
  309. }
  310. EEPROMr.write(EEPROM_RELAY_STATUS, mask);
  311. DEBUG_MSG_P(PSTR("[RELAY] Setting relay mask: %d\n"), mask);
  312. // The 'do_commit' flag controls wether we are commiting this change or not.
  313. // It is useful to set it to 'false' if the relay change triggering the
  314. // save involves a relay whose boot mode is independent from current mode,
  315. // thus storing the last relay value is not absolutely necessary.
  316. // Nevertheless, we store the value in the EEPROM buffer so it will be written
  317. // on the next commit.
  318. if (do_commit) {
  319. // We are actually enqueuing the commit so it will be
  320. // executed on the main loop, in case this is called from a callback
  321. eepromCommit();
  322. }
  323. }
  324. void relaySave() {
  325. relaySave(true);
  326. }
  327. void relayToggle(unsigned char id, bool report, bool group_report) {
  328. if (id >= _relays.size()) return;
  329. relayStatus(id, !relayStatus(id), report, group_report);
  330. }
  331. void relayToggle(unsigned char id) {
  332. relayToggle(id, true, true);
  333. }
  334. unsigned char relayCount() {
  335. return _relays.size();
  336. }
  337. unsigned char relayParsePayload(const char * payload) {
  338. // Payload could be "OFF", "ON", "TOGGLE"
  339. // or its number equivalents: 0, 1 or 2
  340. if (payload[0] == '0') return 0;
  341. if (payload[0] == '1') return 1;
  342. if (payload[0] == '2') return 2;
  343. // trim payload
  344. char * p = ltrim((char *)payload);
  345. // to lower
  346. unsigned int l = strlen(p);
  347. if (l>6) l=6;
  348. for (unsigned char i=0; i<l; i++) {
  349. p[i] = tolower(p[i]);
  350. }
  351. unsigned int value = 0xFF;
  352. if (strcmp(p, "off") == 0) {
  353. value = 0;
  354. } else if (strcmp(p, "on") == 0) {
  355. value = 1;
  356. } else if (strcmp(p, "toggle") == 0) {
  357. value = 2;
  358. } else if (strcmp(p, "query") == 0) {
  359. value = 3;
  360. }
  361. return value;
  362. }
  363. // BACKWARDS COMPATIBILITY
  364. void _relayBackwards() {
  365. byte relayMode = getSetting("relayMode", RELAY_BOOT_MODE).toInt();
  366. byte relayPulseMode = getSetting("relayPulseMode", RELAY_PULSE_MODE).toInt();
  367. float relayPulseTime = getSetting("relayPulseTime", RELAY_PULSE_TIME).toFloat();
  368. if (relayPulseMode == RELAY_PULSE_NONE) relayPulseTime = 0;
  369. for (unsigned int i=0; i<_relays.size(); i++) {
  370. if (!hasSetting("relayBoot", i)) setSetting("relayBoot", i, relayMode);
  371. if (!hasSetting("relayPulse", i)) setSetting("relayPulse", i, relayPulseMode);
  372. if (!hasSetting("relayTime", i)) setSetting("relayTime", i, relayPulseTime);
  373. }
  374. delSetting("relayMode");
  375. delSetting("relayPulseMode");
  376. delSetting("relayPulseTime");
  377. }
  378. void _relayBoot() {
  379. _relayRecursive = true;
  380. unsigned char bit = 1;
  381. bool trigger_save = false;
  382. // Get last statuses from EEPROM
  383. unsigned char mask = EEPROMr.read(EEPROM_RELAY_STATUS);
  384. DEBUG_MSG_P(PSTR("[RELAY] Retrieving mask: %d\n"), mask);
  385. // Walk the relays
  386. bool status;
  387. for (unsigned int i=0; i<_relays.size(); i++) {
  388. unsigned char boot_mode = getSetting("relayBoot", i, RELAY_BOOT_MODE).toInt();
  389. DEBUG_MSG_P(PSTR("[RELAY] Relay #%d boot mode %d\n"), i, boot_mode);
  390. status = false;
  391. switch (boot_mode) {
  392. case RELAY_BOOT_SAME:
  393. if (i < 8) {
  394. status = ((mask & bit) == bit);
  395. }
  396. break;
  397. case RELAY_BOOT_TOGGLE:
  398. if (i < 8) {
  399. status = ((mask & bit) != bit);
  400. mask ^= bit;
  401. trigger_save = true;
  402. }
  403. break;
  404. case RELAY_BOOT_ON:
  405. status = true;
  406. break;
  407. case RELAY_BOOT_OFF:
  408. default:
  409. break;
  410. }
  411. _relays[i].current_status = !status;
  412. _relays[i].target_status = status;
  413. #if RELAY_PROVIDER == RELAY_PROVIDER_STM
  414. _relays[i].change_time = millis() + 3000 + 1000 * i;
  415. #else
  416. _relays[i].change_time = millis();
  417. #endif
  418. bit <<= 1;
  419. }
  420. // Save if there is any relay in the RELAY_BOOT_TOGGLE mode
  421. if (trigger_save) {
  422. EEPROMr.write(EEPROM_RELAY_STATUS, mask);
  423. eepromCommit();
  424. }
  425. _relayRecursive = false;
  426. }
  427. void _relayConfigure() {
  428. for (unsigned int i=0; i<_relays.size(); i++) {
  429. if (GPIO_NONE == _relays[i].pin) continue;
  430. pinMode(_relays[i].pin, OUTPUT);
  431. if (GPIO_NONE != _relays[i].reset_pin) {
  432. pinMode(_relays[i].reset_pin, OUTPUT);
  433. }
  434. if (_relays[i].type == RELAY_TYPE_INVERSE) {
  435. //set to high to block short opening of relay
  436. digitalWrite(_relays[i].pin, HIGH);
  437. }
  438. _relays[i].pulse = getSetting("relayPulse", i, RELAY_PULSE_MODE).toInt();
  439. _relays[i].pulse_ms = 1000 * getSetting("relayTime", i, RELAY_PULSE_MODE).toFloat();
  440. }
  441. }
  442. //------------------------------------------------------------------------------
  443. // WEBSOCKETS
  444. //------------------------------------------------------------------------------
  445. #if WEB_SUPPORT
  446. bool _relayWebSocketOnReceive(const char * key, JsonVariant& value) {
  447. return (strncmp(key, "relay", 5) == 0);
  448. }
  449. void _relayWebSocketUpdate(JsonObject& root) {
  450. JsonArray& relay = root.createNestedArray("relayStatus");
  451. for (unsigned char i=0; i<relayCount(); i++) {
  452. relay.add(_relays[i].target_status);
  453. }
  454. }
  455. void _relayWebSocketOnStart(JsonObject& root) {
  456. if (relayCount() == 0) return;
  457. // Statuses
  458. _relayWebSocketUpdate(root);
  459. // Configuration
  460. JsonArray& config = root.createNestedArray("relayConfig");
  461. for (unsigned char i=0; i<relayCount(); i++) {
  462. JsonObject& line = config.createNestedObject();
  463. line["gpio"] = _relays[i].pin;
  464. line["type"] = _relays[i].type;
  465. line["reset"] = _relays[i].reset_pin;
  466. line["boot"] = getSetting("relayBoot", i, RELAY_BOOT_MODE).toInt();
  467. line["pulse"] = _relays[i].pulse;
  468. line["pulse_ms"] = _relays[i].pulse_ms / 1000.0;
  469. #if MQTT_SUPPORT
  470. line["group"] = getSetting("mqttGroup", i, "");
  471. line["group_inv"] = getSetting("mqttGroupInv", i, 0).toInt();
  472. line["on_disc"] = getSetting("relayOnDisc", i, 0).toInt();
  473. #endif
  474. }
  475. if (relayCount() > 1) {
  476. root["multirelayVisible"] = 1;
  477. root["relaySync"] = getSetting("relaySync", RELAY_SYNC);
  478. }
  479. root["relayVisible"] = 1;
  480. }
  481. void _relayWebSocketOnAction(uint32_t client_id, const char * action, JsonObject& data) {
  482. if (strcmp(action, "relay") != 0) return;
  483. if (data.containsKey("status")) {
  484. unsigned char value = relayParsePayload(data["status"]);
  485. if (value == 3) {
  486. wsSend(_relayWebSocketUpdate);
  487. } else if (value < 3) {
  488. unsigned int relayID = 0;
  489. if (data.containsKey("id")) {
  490. String value = data["id"];
  491. relayID = value.toInt();
  492. }
  493. // Action to perform
  494. if (value == 0) {
  495. relayStatus(relayID, false);
  496. } else if (value == 1) {
  497. relayStatus(relayID, true);
  498. } else if (value == 2) {
  499. relayToggle(relayID);
  500. }
  501. }
  502. }
  503. }
  504. void relaySetupWS() {
  505. wsOnSendRegister(_relayWebSocketOnStart);
  506. wsOnActionRegister(_relayWebSocketOnAction);
  507. wsOnReceiveRegister(_relayWebSocketOnReceive);
  508. }
  509. #endif // WEB_SUPPORT
  510. //------------------------------------------------------------------------------
  511. // REST API
  512. //------------------------------------------------------------------------------
  513. #if API_SUPPORT
  514. void relaySetupAPI() {
  515. char key[20];
  516. // API entry points (protected with apikey)
  517. for (unsigned int relayID=0; relayID<relayCount(); relayID++) {
  518. snprintf_P(key, sizeof(key), PSTR("%s/%d"), MQTT_TOPIC_RELAY, relayID);
  519. apiRegister(key,
  520. [relayID](char * buffer, size_t len) {
  521. snprintf_P(buffer, len, PSTR("%d"), _relays[relayID].target_status ? 1 : 0);
  522. },
  523. [relayID](const char * payload) {
  524. unsigned char value = relayParsePayload(payload);
  525. if (value == 0xFF) {
  526. DEBUG_MSG_P(PSTR("[RELAY] Wrong payload (%s)\n"), payload);
  527. return;
  528. }
  529. if (value == 0) {
  530. relayStatus(relayID, false);
  531. } else if (value == 1) {
  532. relayStatus(relayID, true);
  533. } else if (value == 2) {
  534. relayToggle(relayID);
  535. }
  536. }
  537. );
  538. snprintf_P(key, sizeof(key), PSTR("%s/%d"), MQTT_TOPIC_PULSE, relayID);
  539. apiRegister(key,
  540. [relayID](char * buffer, size_t len) {
  541. dtostrf((double) _relays[relayID].pulse_ms / 1000, 1-len, 3, buffer);
  542. },
  543. [relayID](const char * payload) {
  544. unsigned long pulse = 1000 * String(payload).toFloat();
  545. if (0 == pulse) return;
  546. if (RELAY_PULSE_NONE != _relays[relayID].pulse) {
  547. DEBUG_MSG_P(PSTR("[RELAY] Overriding relay #%d pulse settings\n"), relayID);
  548. }
  549. _relays[relayID].pulse_ms = pulse;
  550. _relays[relayID].pulse = relayStatus(relayID) ? RELAY_PULSE_ON : RELAY_PULSE_OFF;
  551. relayToggle(relayID, true, false);
  552. }
  553. );
  554. #if defined(ITEAD_SONOFF_IFAN02)
  555. apiRegister(MQTT_TOPIC_SPEED,
  556. [relayID](char * buffer, size_t len) {
  557. snprintf(buffer, len, "%u", getSpeed());
  558. },
  559. [relayID](const char * payload) {
  560. setSpeed(atoi(payload));
  561. }
  562. );
  563. #endif
  564. }
  565. }
  566. #endif // API_SUPPORT
  567. //------------------------------------------------------------------------------
  568. // MQTT
  569. //------------------------------------------------------------------------------
  570. #if MQTT_SUPPORT
  571. void relayMQTT(unsigned char id) {
  572. if (id >= _relays.size()) return;
  573. // Send state topic
  574. if (_relays[id].report) {
  575. _relays[id].report = false;
  576. mqttSend(MQTT_TOPIC_RELAY, id, _relays[id].current_status ? RELAY_MQTT_ON : RELAY_MQTT_OFF);
  577. }
  578. // Check group topic
  579. if (_relays[id].group_report) {
  580. _relays[id].group_report = false;
  581. String t = getSetting("mqttGroup", id, "");
  582. if (t.length() > 0) {
  583. bool status = relayStatus(id);
  584. if (getSetting("mqttGroupInv", id, 0).toInt() == 1) status = !status;
  585. mqttSendRaw(t.c_str(), status ? RELAY_MQTT_ON : RELAY_MQTT_OFF);
  586. }
  587. }
  588. // Send speed for IFAN02
  589. #if defined (ITEAD_SONOFF_IFAN02)
  590. char buffer[5];
  591. snprintf(buffer, sizeof(buffer), "%u", getSpeed());
  592. mqttSend(MQTT_TOPIC_SPEED, buffer);
  593. #endif
  594. }
  595. void relayMQTT() {
  596. for (unsigned int id=0; id < _relays.size(); id++) {
  597. mqttSend(MQTT_TOPIC_RELAY, id, _relays[id].current_status ? RELAY_MQTT_ON : RELAY_MQTT_OFF);
  598. }
  599. }
  600. void relayStatusWrap(unsigned char id, unsigned char value, bool is_group_topic) {
  601. switch (value) {
  602. case 0:
  603. relayStatus(id, false, mqttForward(), !is_group_topic);
  604. break;
  605. case 1:
  606. relayStatus(id, true, mqttForward(), !is_group_topic);
  607. break;
  608. case 2:
  609. relayToggle(id, true, true);
  610. break;
  611. default:
  612. _relays[id].report = true;
  613. relayMQTT(id);
  614. break;
  615. }
  616. }
  617. void relayMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  618. if (type == MQTT_CONNECT_EVENT) {
  619. // Send status on connect
  620. #if (HEARTBEAT_MODE == HEARTBEAT_NONE) or (not HEARTBEAT_REPORT_RELAY)
  621. relayMQTT();
  622. #endif
  623. // Subscribe to own /set topic
  624. char relay_topic[strlen(MQTT_TOPIC_RELAY) + 3];
  625. snprintf_P(relay_topic, sizeof(relay_topic), PSTR("%s/+"), MQTT_TOPIC_RELAY);
  626. mqttSubscribe(relay_topic);
  627. // Subscribe to pulse topic
  628. char pulse_topic[strlen(MQTT_TOPIC_PULSE) + 3];
  629. snprintf_P(pulse_topic, sizeof(pulse_topic), PSTR("%s/+"), MQTT_TOPIC_PULSE);
  630. mqttSubscribe(pulse_topic);
  631. #if defined(ITEAD_SONOFF_IFAN02)
  632. mqttSubscribe(MQTT_TOPIC_SPEED);
  633. #endif
  634. // Subscribe to group topics
  635. for (unsigned int i=0; i < _relays.size(); i++) {
  636. String t = getSetting("mqttGroup", i, "");
  637. if (t.length() > 0) mqttSubscribeRaw(t.c_str());
  638. }
  639. }
  640. if (type == MQTT_MESSAGE_EVENT) {
  641. String t = mqttMagnitude((char *) topic);
  642. // magnitude is relay/#/pulse
  643. if (t.startsWith(MQTT_TOPIC_PULSE)) {
  644. unsigned int id = t.substring(strlen(MQTT_TOPIC_PULSE)+1).toInt();
  645. if (id >= relayCount()) {
  646. DEBUG_MSG_P(PSTR("[RELAY] Wrong relayID (%d)\n"), id);
  647. return;
  648. }
  649. unsigned long pulse = 1000 * String(payload).toFloat();
  650. if (0 == pulse) return;
  651. if (RELAY_PULSE_NONE != _relays[id].pulse) {
  652. DEBUG_MSG_P(PSTR("[RELAY] Overriding relay #%d pulse settings\n"), id);
  653. }
  654. _relays[id].pulse_ms = pulse;
  655. _relays[id].pulse = relayStatus(id) ? RELAY_PULSE_ON : RELAY_PULSE_OFF;
  656. relayToggle(id, true, false);
  657. return;
  658. }
  659. // magnitude is relay/#
  660. if (t.startsWith(MQTT_TOPIC_RELAY)) {
  661. // Get relay ID
  662. unsigned int id = t.substring(strlen(MQTT_TOPIC_RELAY)+1).toInt();
  663. if (id >= relayCount()) {
  664. DEBUG_MSG_P(PSTR("[RELAY] Wrong relayID (%d)\n"), id);
  665. return;
  666. }
  667. // Get value
  668. unsigned char value = relayParsePayload(payload);
  669. if (value == 0xFF) return;
  670. relayStatusWrap(id, value, false);
  671. return;
  672. }
  673. // Check group topics
  674. for (unsigned int i=0; i < _relays.size(); i++) {
  675. String t = getSetting("mqttGroup", i, "");
  676. if ((t.length() > 0) && t.equals(topic)) {
  677. unsigned char value = relayParsePayload(payload);
  678. if (value == 0xFF) return;
  679. if (value < 2) {
  680. if (getSetting("mqttGroupInv", i, 0).toInt() == 1) {
  681. value = 1 - value;
  682. }
  683. }
  684. DEBUG_MSG_P(PSTR("[RELAY] Matched group topic for relayID %d\n"), i);
  685. relayStatusWrap(i, value, true);
  686. }
  687. }
  688. // Itead Sonoff IFAN02
  689. #if defined (ITEAD_SONOFF_IFAN02)
  690. if (t.startsWith(MQTT_TOPIC_SPEED)) {
  691. setSpeed(atoi(payload));
  692. }
  693. #endif
  694. }
  695. if (type == MQTT_DISCONNECT_EVENT) {
  696. for (unsigned int i=0; i < _relays.size(); i++){
  697. int reaction = getSetting("relayOnDisc", i, 0).toInt();
  698. if (1 == reaction) { // switch relay OFF
  699. DEBUG_MSG_P(PSTR("[RELAY] Reset relay (%d) due to MQTT disconnection\n"), i);
  700. relayStatusWrap(i, false, false);
  701. } else if(2 == reaction) { // switch relay ON
  702. DEBUG_MSG_P(PSTR("[RELAY] Set relay (%d) due to MQTT disconnection\n"), i);
  703. relayStatusWrap(i, true, false);
  704. }
  705. }
  706. }
  707. }
  708. void relaySetupMQTT() {
  709. mqttRegister(relayMQTTCallback);
  710. }
  711. #endif
  712. //------------------------------------------------------------------------------
  713. // InfluxDB
  714. //------------------------------------------------------------------------------
  715. #if INFLUXDB_SUPPORT
  716. void relayInfluxDB(unsigned char id) {
  717. if (id >= _relays.size()) return;
  718. idbSend(MQTT_TOPIC_RELAY, id, relayStatus(id) ? "1" : "0");
  719. }
  720. #endif
  721. //------------------------------------------------------------------------------
  722. // Settings
  723. //------------------------------------------------------------------------------
  724. #if TERMINAL_SUPPORT
  725. void _relayInitCommands() {
  726. settingsRegisterCommand(F("RELAY"), [](Embedis* e) {
  727. if (e->argc < 2) {
  728. DEBUG_MSG_P(PSTR("-ERROR: Wrong arguments\n"));
  729. return;
  730. }
  731. int id = String(e->argv[1]).toInt();
  732. if (id >= relayCount()) {
  733. DEBUG_MSG_P(PSTR("-ERROR: Wrong relayID (%d)\n"), id);
  734. return;
  735. }
  736. if (e->argc > 2) {
  737. int value = String(e->argv[2]).toInt();
  738. if (value == 2) {
  739. relayToggle(id);
  740. } else {
  741. relayStatus(id, value == 1);
  742. }
  743. }
  744. DEBUG_MSG_P(PSTR("Status: %s\n"), _relays[id].target_status ? "true" : "false");
  745. if (_relays[id].pulse != RELAY_PULSE_NONE) {
  746. DEBUG_MSG_P(PSTR("Pulse: %s\n"), (_relays[id].pulse == RELAY_PULSE_ON) ? "ON" : "OFF");
  747. DEBUG_MSG_P(PSTR("Pulse time: %d\n"), _relays[id].pulse_ms);
  748. }
  749. DEBUG_MSG_P(PSTR("+OK\n"));
  750. });
  751. }
  752. #endif // TERMINAL_SUPPORT
  753. //------------------------------------------------------------------------------
  754. // Setup
  755. //------------------------------------------------------------------------------
  756. void _relayLoop() {
  757. _relayProcess(false);
  758. _relayProcess(true);
  759. }
  760. void relaySetup() {
  761. // Dummy relays for AI Light, Magic Home LED Controller, H801, Sonoff Dual and Sonoff RF Bridge
  762. // No delay_on or off for these devices to easily allow having more than
  763. // 8 channels. This behaviour will be recovered with v2.
  764. for (unsigned char i=0; i < DUMMY_RELAY_COUNT; i++) {
  765. _relays.push_back((relay_t) {GPIO_NONE, RELAY_TYPE_NORMAL, 0, 0, 0});
  766. }
  767. // Ad-hoc relays
  768. #if RELAY1_PIN != GPIO_NONE
  769. _relays.push_back((relay_t) { RELAY1_PIN, RELAY1_TYPE, RELAY1_RESET_PIN, RELAY1_DELAY_ON, RELAY1_DELAY_OFF });
  770. #endif
  771. #if RELAY2_PIN != GPIO_NONE
  772. _relays.push_back((relay_t) { RELAY2_PIN, RELAY2_TYPE, RELAY2_RESET_PIN, RELAY2_DELAY_ON, RELAY2_DELAY_OFF });
  773. #endif
  774. #if RELAY3_PIN != GPIO_NONE
  775. _relays.push_back((relay_t) { RELAY3_PIN, RELAY3_TYPE, RELAY3_RESET_PIN, RELAY3_DELAY_ON, RELAY3_DELAY_OFF });
  776. #endif
  777. #if RELAY4_PIN != GPIO_NONE
  778. _relays.push_back((relay_t) { RELAY4_PIN, RELAY4_TYPE, RELAY4_RESET_PIN, RELAY4_DELAY_ON, RELAY4_DELAY_OFF });
  779. #endif
  780. #if RELAY5_PIN != GPIO_NONE
  781. _relays.push_back((relay_t) { RELAY5_PIN, RELAY5_TYPE, RELAY5_RESET_PIN, RELAY5_DELAY_ON, RELAY5_DELAY_OFF });
  782. #endif
  783. #if RELAY6_PIN != GPIO_NONE
  784. _relays.push_back((relay_t) { RELAY6_PIN, RELAY6_TYPE, RELAY6_RESET_PIN, RELAY6_DELAY_ON, RELAY6_DELAY_OFF });
  785. #endif
  786. #if RELAY7_PIN != GPIO_NONE
  787. _relays.push_back((relay_t) { RELAY7_PIN, RELAY7_TYPE, RELAY7_RESET_PIN, RELAY7_DELAY_ON, RELAY7_DELAY_OFF });
  788. #endif
  789. #if RELAY8_PIN != GPIO_NONE
  790. _relays.push_back((relay_t) { RELAY8_PIN, RELAY8_TYPE, RELAY8_RESET_PIN, RELAY8_DELAY_ON, RELAY8_DELAY_OFF });
  791. #endif
  792. _relayBackwards();
  793. _relayConfigure();
  794. _relayBoot();
  795. _relayLoop();
  796. #if WEB_SUPPORT
  797. relaySetupWS();
  798. #endif
  799. #if API_SUPPORT
  800. relaySetupAPI();
  801. #endif
  802. #if MQTT_SUPPORT
  803. relaySetupMQTT();
  804. #endif
  805. #if TERMINAL_SUPPORT
  806. _relayInitCommands();
  807. #endif
  808. // Main callbacks
  809. espurnaRegisterLoop(_relayLoop);
  810. espurnaRegisterReload(_relayConfigure);
  811. DEBUG_MSG_P(PSTR("[RELAY] Number of relays: %d\n"), _relays.size());
  812. }