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.

1096 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. if (GPIO_NONE == _relays[i].pin) {
  464. #if (RELAY_PROVIDER == RELAY_PROVIDER_LIGHT)
  465. if (DUMMY_RELAY_COUNT > i) {
  466. if (DUMMY_RELAY_COUNT == lightChannels()) {
  467. line["gpio"] = String("CH") + String(i);
  468. } else if (DUMMY_RELAY_COUNT == (lightChannels() + 1u)) {
  469. if (0 == i) {
  470. line["gpio"] = String("Light");
  471. } else {
  472. line["gpio"] = String("CH") + String(i-1);
  473. }
  474. } else {
  475. line["gpio"] = String("Light");
  476. }
  477. } else {
  478. line["gpio"] = String("?");
  479. }
  480. #else
  481. line["gpio"] = String("SW") + String(i);
  482. #endif
  483. } else {
  484. line["gpio"] = String("GPIO") + String(_relays[i].pin);
  485. }
  486. line["type"] = _relays[i].type;
  487. line["reset"] = _relays[i].reset_pin;
  488. line["boot"] = getSetting("relayBoot", i, RELAY_BOOT_MODE).toInt();
  489. line["pulse"] = _relays[i].pulse;
  490. line["pulse_ms"] = _relays[i].pulse_ms / 1000.0;
  491. #if MQTT_SUPPORT
  492. line["group"] = getSetting("mqttGroup", i, "");
  493. line["group_inv"] = getSetting("mqttGroupInv", i, 0).toInt();
  494. line["on_disc"] = getSetting("relayOnDisc", i, 0).toInt();
  495. #endif
  496. }
  497. if (relayCount() > 1) {
  498. root["multirelayVisible"] = 1;
  499. root["relaySync"] = getSetting("relaySync", RELAY_SYNC);
  500. }
  501. root["relayVisible"] = 1;
  502. }
  503. void _relayWebSocketOnAction(uint32_t client_id, const char * action, JsonObject& data) {
  504. if (strcmp(action, "relay") != 0) return;
  505. if (data.containsKey("status")) {
  506. unsigned char value = relayParsePayload(data["status"]);
  507. if (value == 3) {
  508. wsSend(_relayWebSocketUpdate);
  509. } else if (value < 3) {
  510. unsigned int relayID = 0;
  511. if (data.containsKey("id")) {
  512. String value = data["id"];
  513. relayID = value.toInt();
  514. }
  515. // Action to perform
  516. if (value == 0) {
  517. relayStatus(relayID, false);
  518. } else if (value == 1) {
  519. relayStatus(relayID, true);
  520. } else if (value == 2) {
  521. relayToggle(relayID);
  522. }
  523. }
  524. }
  525. }
  526. void relaySetupWS() {
  527. wsOnSendRegister(_relayWebSocketOnStart);
  528. wsOnActionRegister(_relayWebSocketOnAction);
  529. wsOnReceiveRegister(_relayWebSocketOnReceive);
  530. }
  531. #endif // WEB_SUPPORT
  532. //------------------------------------------------------------------------------
  533. // REST API
  534. //------------------------------------------------------------------------------
  535. #if API_SUPPORT
  536. void relaySetupAPI() {
  537. char key[20];
  538. // API entry points (protected with apikey)
  539. for (unsigned int relayID=0; relayID<relayCount(); relayID++) {
  540. snprintf_P(key, sizeof(key), PSTR("%s/%d"), MQTT_TOPIC_RELAY, relayID);
  541. apiRegister(key,
  542. [relayID](char * buffer, size_t len) {
  543. snprintf_P(buffer, len, PSTR("%d"), _relays[relayID].target_status ? 1 : 0);
  544. },
  545. [relayID](const char * payload) {
  546. unsigned char value = relayParsePayload(payload);
  547. if (value == 0xFF) {
  548. DEBUG_MSG_P(PSTR("[RELAY] Wrong payload (%s)\n"), payload);
  549. return;
  550. }
  551. if (value == 0) {
  552. relayStatus(relayID, false);
  553. } else if (value == 1) {
  554. relayStatus(relayID, true);
  555. } else if (value == 2) {
  556. relayToggle(relayID);
  557. }
  558. }
  559. );
  560. snprintf_P(key, sizeof(key), PSTR("%s/%d"), MQTT_TOPIC_PULSE, relayID);
  561. apiRegister(key,
  562. [relayID](char * buffer, size_t len) {
  563. dtostrf((double) _relays[relayID].pulse_ms / 1000, 1-len, 3, buffer);
  564. },
  565. [relayID](const char * payload) {
  566. unsigned long pulse = 1000 * String(payload).toFloat();
  567. if (0 == pulse) return;
  568. if (RELAY_PULSE_NONE != _relays[relayID].pulse) {
  569. DEBUG_MSG_P(PSTR("[RELAY] Overriding relay #%d pulse settings\n"), relayID);
  570. }
  571. _relays[relayID].pulse_ms = pulse;
  572. _relays[relayID].pulse = relayStatus(relayID) ? RELAY_PULSE_ON : RELAY_PULSE_OFF;
  573. relayToggle(relayID, true, false);
  574. }
  575. );
  576. #if defined(ITEAD_SONOFF_IFAN02)
  577. apiRegister(MQTT_TOPIC_SPEED,
  578. [relayID](char * buffer, size_t len) {
  579. snprintf(buffer, len, "%u", getSpeed());
  580. },
  581. [relayID](const char * payload) {
  582. setSpeed(atoi(payload));
  583. }
  584. );
  585. #endif
  586. }
  587. }
  588. #endif // API_SUPPORT
  589. //------------------------------------------------------------------------------
  590. // MQTT
  591. //------------------------------------------------------------------------------
  592. #if MQTT_SUPPORT
  593. void relayMQTT(unsigned char id) {
  594. if (id >= _relays.size()) return;
  595. // Send state topic
  596. if (_relays[id].report) {
  597. _relays[id].report = false;
  598. mqttSend(MQTT_TOPIC_RELAY, id, _relays[id].current_status ? RELAY_MQTT_ON : RELAY_MQTT_OFF);
  599. }
  600. // Check group topic
  601. if (_relays[id].group_report) {
  602. _relays[id].group_report = false;
  603. String t = getSetting("mqttGroup", id, "");
  604. if (t.length() > 0) {
  605. bool status = relayStatus(id);
  606. if (getSetting("mqttGroupInv", id, 0).toInt() == 1) status = !status;
  607. mqttSendRaw(t.c_str(), status ? RELAY_MQTT_ON : RELAY_MQTT_OFF);
  608. }
  609. }
  610. // Send speed for IFAN02
  611. #if defined (ITEAD_SONOFF_IFAN02)
  612. char buffer[5];
  613. snprintf(buffer, sizeof(buffer), "%u", getSpeed());
  614. mqttSend(MQTT_TOPIC_SPEED, buffer);
  615. #endif
  616. }
  617. void relayMQTT() {
  618. for (unsigned int id=0; id < _relays.size(); id++) {
  619. mqttSend(MQTT_TOPIC_RELAY, id, _relays[id].current_status ? RELAY_MQTT_ON : RELAY_MQTT_OFF);
  620. }
  621. }
  622. void relayStatusWrap(unsigned char id, unsigned char value, bool is_group_topic) {
  623. switch (value) {
  624. case 0:
  625. relayStatus(id, false, mqttForward(), !is_group_topic);
  626. break;
  627. case 1:
  628. relayStatus(id, true, mqttForward(), !is_group_topic);
  629. break;
  630. case 2:
  631. relayToggle(id, true, true);
  632. break;
  633. default:
  634. _relays[id].report = true;
  635. relayMQTT(id);
  636. break;
  637. }
  638. }
  639. void relayMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  640. if (type == MQTT_CONNECT_EVENT) {
  641. // Send status on connect
  642. #if (HEARTBEAT_MODE == HEARTBEAT_NONE) or (not HEARTBEAT_REPORT_RELAY)
  643. relayMQTT();
  644. #endif
  645. // Subscribe to own /set topic
  646. char relay_topic[strlen(MQTT_TOPIC_RELAY) + 3];
  647. snprintf_P(relay_topic, sizeof(relay_topic), PSTR("%s/+"), MQTT_TOPIC_RELAY);
  648. mqttSubscribe(relay_topic);
  649. // Subscribe to pulse topic
  650. char pulse_topic[strlen(MQTT_TOPIC_PULSE) + 3];
  651. snprintf_P(pulse_topic, sizeof(pulse_topic), PSTR("%s/+"), MQTT_TOPIC_PULSE);
  652. mqttSubscribe(pulse_topic);
  653. #if defined(ITEAD_SONOFF_IFAN02)
  654. mqttSubscribe(MQTT_TOPIC_SPEED);
  655. #endif
  656. // Subscribe to group topics
  657. for (unsigned int i=0; i < _relays.size(); i++) {
  658. String t = getSetting("mqttGroup", i, "");
  659. if (t.length() > 0) mqttSubscribeRaw(t.c_str());
  660. }
  661. }
  662. if (type == MQTT_MESSAGE_EVENT) {
  663. String t = mqttMagnitude((char *) topic);
  664. // magnitude is relay/#/pulse
  665. if (t.startsWith(MQTT_TOPIC_PULSE)) {
  666. unsigned int id = t.substring(strlen(MQTT_TOPIC_PULSE)+1).toInt();
  667. if (id >= relayCount()) {
  668. DEBUG_MSG_P(PSTR("[RELAY] Wrong relayID (%d)\n"), id);
  669. return;
  670. }
  671. unsigned long pulse = 1000 * String(payload).toFloat();
  672. if (0 == pulse) return;
  673. if (RELAY_PULSE_NONE != _relays[id].pulse) {
  674. DEBUG_MSG_P(PSTR("[RELAY] Overriding relay #%d pulse settings\n"), id);
  675. }
  676. _relays[id].pulse_ms = pulse;
  677. _relays[id].pulse = relayStatus(id) ? RELAY_PULSE_ON : RELAY_PULSE_OFF;
  678. relayToggle(id, true, false);
  679. return;
  680. }
  681. // magnitude is relay/#
  682. if (t.startsWith(MQTT_TOPIC_RELAY)) {
  683. // Get relay ID
  684. unsigned int id = t.substring(strlen(MQTT_TOPIC_RELAY)+1).toInt();
  685. if (id >= relayCount()) {
  686. DEBUG_MSG_P(PSTR("[RELAY] Wrong relayID (%d)\n"), id);
  687. return;
  688. }
  689. // Get value
  690. unsigned char value = relayParsePayload(payload);
  691. if (value == 0xFF) return;
  692. relayStatusWrap(id, value, false);
  693. return;
  694. }
  695. // Check group topics
  696. for (unsigned int i=0; i < _relays.size(); i++) {
  697. String t = getSetting("mqttGroup", i, "");
  698. if ((t.length() > 0) && t.equals(topic)) {
  699. unsigned char value = relayParsePayload(payload);
  700. if (value == 0xFF) return;
  701. if (value < 2) {
  702. if (getSetting("mqttGroupInv", i, 0).toInt() == 1) {
  703. value = 1 - value;
  704. }
  705. }
  706. DEBUG_MSG_P(PSTR("[RELAY] Matched group topic for relayID %d\n"), i);
  707. relayStatusWrap(i, value, true);
  708. }
  709. }
  710. // Itead Sonoff IFAN02
  711. #if defined (ITEAD_SONOFF_IFAN02)
  712. if (t.startsWith(MQTT_TOPIC_SPEED)) {
  713. setSpeed(atoi(payload));
  714. }
  715. #endif
  716. }
  717. if (type == MQTT_DISCONNECT_EVENT) {
  718. for (unsigned int i=0; i < _relays.size(); i++){
  719. int reaction = getSetting("relayOnDisc", i, 0).toInt();
  720. if (1 == reaction) { // switch relay OFF
  721. DEBUG_MSG_P(PSTR("[RELAY] Reset relay (%d) due to MQTT disconnection\n"), i);
  722. relayStatusWrap(i, false, false);
  723. } else if(2 == reaction) { // switch relay ON
  724. DEBUG_MSG_P(PSTR("[RELAY] Set relay (%d) due to MQTT disconnection\n"), i);
  725. relayStatusWrap(i, true, false);
  726. }
  727. }
  728. }
  729. }
  730. void relaySetupMQTT() {
  731. mqttRegister(relayMQTTCallback);
  732. }
  733. #endif
  734. //------------------------------------------------------------------------------
  735. // InfluxDB
  736. //------------------------------------------------------------------------------
  737. #if INFLUXDB_SUPPORT
  738. void relayInfluxDB(unsigned char id) {
  739. if (id >= _relays.size()) return;
  740. idbSend(MQTT_TOPIC_RELAY, id, relayStatus(id) ? "1" : "0");
  741. }
  742. #endif
  743. //------------------------------------------------------------------------------
  744. // Settings
  745. //------------------------------------------------------------------------------
  746. #if TERMINAL_SUPPORT
  747. void _relayInitCommands() {
  748. settingsRegisterCommand(F("RELAY"), [](Embedis* e) {
  749. if (e->argc < 2) {
  750. DEBUG_MSG_P(PSTR("-ERROR: Wrong arguments\n"));
  751. return;
  752. }
  753. int id = String(e->argv[1]).toInt();
  754. if (id >= relayCount()) {
  755. DEBUG_MSG_P(PSTR("-ERROR: Wrong relayID (%d)\n"), id);
  756. return;
  757. }
  758. if (e->argc > 2) {
  759. int value = String(e->argv[2]).toInt();
  760. if (value == 2) {
  761. relayToggle(id);
  762. } else {
  763. relayStatus(id, value == 1);
  764. }
  765. }
  766. DEBUG_MSG_P(PSTR("Status: %s\n"), _relays[id].target_status ? "true" : "false");
  767. if (_relays[id].pulse != RELAY_PULSE_NONE) {
  768. DEBUG_MSG_P(PSTR("Pulse: %s\n"), (_relays[id].pulse == RELAY_PULSE_ON) ? "ON" : "OFF");
  769. DEBUG_MSG_P(PSTR("Pulse time: %d\n"), _relays[id].pulse_ms);
  770. }
  771. DEBUG_MSG_P(PSTR("+OK\n"));
  772. });
  773. }
  774. #endif // TERMINAL_SUPPORT
  775. //------------------------------------------------------------------------------
  776. // Setup
  777. //------------------------------------------------------------------------------
  778. void _relayLoop() {
  779. _relayProcess(false);
  780. _relayProcess(true);
  781. }
  782. void relaySetup() {
  783. // Dummy relays for AI Light, Magic Home LED Controller, H801, Sonoff Dual and Sonoff RF Bridge
  784. // No delay_on or off for these devices to easily allow having more than
  785. // 8 channels. This behaviour will be recovered with v2.
  786. for (unsigned char i=0; i < DUMMY_RELAY_COUNT; i++) {
  787. _relays.push_back((relay_t) {GPIO_NONE, RELAY_TYPE_NORMAL, 0, 0, 0});
  788. }
  789. // Ad-hoc relays
  790. #if RELAY1_PIN != GPIO_NONE
  791. _relays.push_back((relay_t) { RELAY1_PIN, RELAY1_TYPE, RELAY1_RESET_PIN, RELAY1_DELAY_ON, RELAY1_DELAY_OFF });
  792. #endif
  793. #if RELAY2_PIN != GPIO_NONE
  794. _relays.push_back((relay_t) { RELAY2_PIN, RELAY2_TYPE, RELAY2_RESET_PIN, RELAY2_DELAY_ON, RELAY2_DELAY_OFF });
  795. #endif
  796. #if RELAY3_PIN != GPIO_NONE
  797. _relays.push_back((relay_t) { RELAY3_PIN, RELAY3_TYPE, RELAY3_RESET_PIN, RELAY3_DELAY_ON, RELAY3_DELAY_OFF });
  798. #endif
  799. #if RELAY4_PIN != GPIO_NONE
  800. _relays.push_back((relay_t) { RELAY4_PIN, RELAY4_TYPE, RELAY4_RESET_PIN, RELAY4_DELAY_ON, RELAY4_DELAY_OFF });
  801. #endif
  802. #if RELAY5_PIN != GPIO_NONE
  803. _relays.push_back((relay_t) { RELAY5_PIN, RELAY5_TYPE, RELAY5_RESET_PIN, RELAY5_DELAY_ON, RELAY5_DELAY_OFF });
  804. #endif
  805. #if RELAY6_PIN != GPIO_NONE
  806. _relays.push_back((relay_t) { RELAY6_PIN, RELAY6_TYPE, RELAY6_RESET_PIN, RELAY6_DELAY_ON, RELAY6_DELAY_OFF });
  807. #endif
  808. #if RELAY7_PIN != GPIO_NONE
  809. _relays.push_back((relay_t) { RELAY7_PIN, RELAY7_TYPE, RELAY7_RESET_PIN, RELAY7_DELAY_ON, RELAY7_DELAY_OFF });
  810. #endif
  811. #if RELAY8_PIN != GPIO_NONE
  812. _relays.push_back((relay_t) { RELAY8_PIN, RELAY8_TYPE, RELAY8_RESET_PIN, RELAY8_DELAY_ON, RELAY8_DELAY_OFF });
  813. #endif
  814. _relayBackwards();
  815. _relayConfigure();
  816. _relayBoot();
  817. _relayLoop();
  818. #if WEB_SUPPORT
  819. relaySetupWS();
  820. #endif
  821. #if API_SUPPORT
  822. relaySetupAPI();
  823. #endif
  824. #if MQTT_SUPPORT
  825. relaySetupMQTT();
  826. #endif
  827. #if TERMINAL_SUPPORT
  828. _relayInitCommands();
  829. #endif
  830. // Main callbacks
  831. espurnaRegisterLoop(_relayLoop);
  832. espurnaRegisterReload(_relayConfigure);
  833. DEBUG_MSG_P(PSTR("[RELAY] Number of relays: %d\n"), _relays.size());
  834. }