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.

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