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.

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