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.

1127 lines
33 KiB

5 years ago
  1. /*
  2. RELAY MODULE
  3. Copyright (C) 2016-2019 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. // The serial init are not full recognized by relais board.
  66. // References: https://github.com/xoseperez/espurna/issues/1519 , https://github.com/xoseperez/espurna/issues/1130
  67. delay(100);
  68. Serial.flush();
  69. #endif
  70. #if RELAY_PROVIDER == RELAY_PROVIDER_LIGHT
  71. // Real relays
  72. uint8_t physical = _relays.size() - DUMMY_RELAY_COUNT;
  73. // Support for a mixed of dummy and real relays
  74. // Reference: https://github.com/xoseperez/espurna/issues/1305
  75. if (id >= physical) {
  76. // If the number of dummy relays matches the number of light channels
  77. // assume each relay controls one channel.
  78. // If the number of dummy relays is the number of channels plus 1
  79. // assume the first one controls all the channels and
  80. // the rest one channel each.
  81. // Otherwise every dummy relay controls all channels.
  82. if (DUMMY_RELAY_COUNT == lightChannels()) {
  83. lightState(id-physical, status);
  84. lightState(true);
  85. } else if (DUMMY_RELAY_COUNT == (lightChannels() + 1u)) {
  86. if (id == physical) {
  87. lightState(status);
  88. } else {
  89. lightState(id-1-physical, status);
  90. }
  91. } else {
  92. lightState(status);
  93. }
  94. lightUpdate(true, true);
  95. return;
  96. }
  97. #endif
  98. #if (RELAY_PROVIDER == RELAY_PROVIDER_RELAY) || (RELAY_PROVIDER == RELAY_PROVIDER_LIGHT)
  99. // If this is a light, all dummy relays have already been processed above
  100. // we reach here if the user has toggled a physical relay
  101. if (_relays[id].type == RELAY_TYPE_NORMAL) {
  102. digitalWrite(_relays[id].pin, status);
  103. } else if (_relays[id].type == RELAY_TYPE_INVERSE) {
  104. digitalWrite(_relays[id].pin, !status);
  105. } else if (_relays[id].type == RELAY_TYPE_LATCHED || _relays[id].type == RELAY_TYPE_LATCHED_INVERSE) {
  106. bool pulse = RELAY_TYPE_LATCHED ? HIGH : LOW;
  107. digitalWrite(_relays[id].pin, !pulse);
  108. if (GPIO_NONE != _relays[id].reset_pin) digitalWrite(_relays[id].reset_pin, !pulse);
  109. if (status || (GPIO_NONE == _relays[id].reset_pin)) {
  110. digitalWrite(_relays[id].pin, pulse);
  111. } else {
  112. digitalWrite(_relays[id].reset_pin, pulse);
  113. }
  114. nice_delay(RELAY_LATCHING_PULSE);
  115. digitalWrite(_relays[id].pin, !pulse);
  116. if (GPIO_NONE != _relays[id].reset_pin) digitalWrite(_relays[id].reset_pin, !pulse);
  117. }
  118. #endif
  119. }
  120. /**
  121. * Walks the relay vector processing only those relays
  122. * that have to change to the requested mode
  123. * @bool mode Requested mode
  124. */
  125. void _relayProcess(bool mode) {
  126. unsigned long current_time = millis();
  127. for (unsigned char id = 0; id < _relays.size(); id++) {
  128. bool target = _relays[id].target_status;
  129. // Only process the relays we have to change
  130. if (target == _relays[id].current_status) continue;
  131. // Only process the relays we have to change to the requested mode
  132. if (target != mode) continue;
  133. // Only process if the change_time has arrived
  134. if (current_time < _relays[id].change_time) continue;
  135. DEBUG_MSG_P(PSTR("[RELAY] #%d set to %s\n"), id, target ? "ON" : "OFF");
  136. // Call the provider to perform the action
  137. _relayProviderStatus(id, target);
  138. // Send to Broker
  139. #if BROKER_SUPPORT
  140. brokerPublish(BROKER_MSG_TYPE_STATUS, MQTT_TOPIC_RELAY, id, target ? "1" : "0");
  141. #endif
  142. // Send MQTT
  143. #if MQTT_SUPPORT
  144. relayMQTT(id);
  145. #endif
  146. if (!_relayRecursive) {
  147. relayPulse(id);
  148. // We will trigger a eeprom save only if
  149. // we care about current relay status on boot
  150. unsigned char boot_mode = getSetting("relayBoot", id, RELAY_BOOT_MODE).toInt();
  151. bool save_eeprom = ((RELAY_BOOT_SAME == boot_mode) || (RELAY_BOOT_TOGGLE == boot_mode));
  152. _relaySaveTicker.once_ms(RELAY_SAVE_DELAY, relaySave, save_eeprom);
  153. #if WEB_SUPPORT
  154. wsSend(_relayWebSocketUpdate);
  155. #endif
  156. }
  157. _relays[id].report = false;
  158. _relays[id].group_report = false;
  159. }
  160. }
  161. #if defined(ITEAD_SONOFF_IFAN02)
  162. unsigned char _relay_ifan02_speeds[] = {0, 1, 3, 5};
  163. unsigned char getSpeed() {
  164. unsigned char speed =
  165. (_relays[1].target_status ? 1 : 0) +
  166. (_relays[2].target_status ? 2 : 0) +
  167. (_relays[3].target_status ? 4 : 0);
  168. for (unsigned char i=0; i<4; i++) {
  169. if (_relay_ifan02_speeds[i] == speed) return i;
  170. }
  171. return 0;
  172. }
  173. void setSpeed(unsigned char speed) {
  174. if ((0 <= speed) & (speed <= 3)) {
  175. if (getSpeed() == speed) return;
  176. unsigned char states = _relay_ifan02_speeds[speed];
  177. for (unsigned char i=0; i<3; i++) {
  178. relayStatus(i+1, states & 1 == 1);
  179. states >>= 1;
  180. }
  181. }
  182. }
  183. #endif
  184. // -----------------------------------------------------------------------------
  185. // RELAY
  186. // -----------------------------------------------------------------------------
  187. void _relayMaskRtcmem(uint32_t mask) {
  188. Rtcmem->relay = mask;
  189. }
  190. uint32_t _relayMaskRtcmem() {
  191. return Rtcmem->relay;
  192. }
  193. void relayPulse(unsigned char id) {
  194. _relays[id].pulseTicker.detach();
  195. byte mode = _relays[id].pulse;
  196. if (mode == RELAY_PULSE_NONE) return;
  197. unsigned long ms = _relays[id].pulse_ms;
  198. if (ms == 0) return;
  199. bool status = relayStatus(id);
  200. bool pulseStatus = (mode == RELAY_PULSE_ON);
  201. if (pulseStatus != status) {
  202. DEBUG_MSG_P(PSTR("[RELAY] Scheduling relay #%d back in %lums (pulse)\n"), id, ms);
  203. _relays[id].pulseTicker.once_ms(ms, relayToggle, id);
  204. // Reconfigure after dynamic pulse
  205. _relays[id].pulse = getSetting("relayPulse", id, RELAY_PULSE_MODE).toInt();
  206. _relays[id].pulse_ms = 1000 * getSetting("relayTime", id, RELAY_PULSE_MODE).toFloat();
  207. }
  208. }
  209. bool relayStatus(unsigned char id, bool status, bool report, bool group_report) {
  210. if (id >= _relays.size()) return false;
  211. bool changed = false;
  212. if (_relays[id].current_status == status) {
  213. if (_relays[id].target_status != status) {
  214. DEBUG_MSG_P(PSTR("[RELAY] #%d scheduled change cancelled\n"), id);
  215. _relays[id].target_status = status;
  216. _relays[id].report = false;
  217. _relays[id].group_report = false;
  218. changed = true;
  219. }
  220. // For RFBridge, keep sending the message even if the status is already the required
  221. #if RELAY_PROVIDER == RELAY_PROVIDER_RFBRIDGE
  222. rfbStatus(id, status);
  223. #endif
  224. // Update the pulse counter if the relay is already in the non-normal state (#454)
  225. relayPulse(id);
  226. } else {
  227. unsigned long current_time = millis();
  228. unsigned long fw_end = _relays[id].fw_start + 1000 * RELAY_FLOOD_WINDOW;
  229. unsigned long delay = status ? _relays[id].delay_on : _relays[id].delay_off;
  230. _relays[id].fw_count++;
  231. _relays[id].change_time = current_time + delay;
  232. // If current_time is off-limits the floodWindow...
  233. if (current_time < _relays[id].fw_start || fw_end <= current_time) {
  234. // We reset the floodWindow
  235. _relays[id].fw_start = current_time;
  236. _relays[id].fw_count = 1;
  237. // If current_time is in the floodWindow and there have been too many requests...
  238. } else if (_relays[id].fw_count >= RELAY_FLOOD_CHANGES) {
  239. // We schedule the changes to the end of the floodWindow
  240. // unless it's already delayed beyond that point
  241. if (fw_end - delay > current_time) {
  242. _relays[id].change_time = fw_end;
  243. }
  244. }
  245. _relays[id].target_status = status;
  246. if (report) _relays[id].report = true;
  247. if (group_report) _relays[id].group_report = true;
  248. relaySync(id);
  249. DEBUG_MSG_P(PSTR("[RELAY] #%d scheduled %s in %u ms\n"),
  250. id, status ? "ON" : "OFF",
  251. (_relays[id].change_time - current_time));
  252. changed = true;
  253. }
  254. return changed;
  255. }
  256. bool relayStatus(unsigned char id, bool status) {
  257. return relayStatus(id, status, mqttForward(), true);
  258. }
  259. bool relayStatus(unsigned char id) {
  260. // Check relay ID
  261. if (id >= _relays.size()) return false;
  262. // Get status from storage
  263. return _relays[id].current_status;
  264. }
  265. void relaySync(unsigned char id) {
  266. // No sync if none or only one relay
  267. if (_relays.size() < 2) return;
  268. // Do not go on if we are comming from a previous sync
  269. if (_relayRecursive) return;
  270. // Flag sync mode
  271. _relayRecursive = true;
  272. byte relaySync = getSetting("relaySync", RELAY_SYNC).toInt();
  273. bool status = _relays[id].target_status;
  274. // If RELAY_SYNC_SAME all relays should have the same state
  275. if (relaySync == RELAY_SYNC_SAME) {
  276. for (unsigned short i=0; i<_relays.size(); i++) {
  277. if (i != id) relayStatus(i, status);
  278. }
  279. // If RELAY_SYNC_FIRST all relays should have the same state as first if first changes
  280. } else if (relaySync == RELAY_SYNC_FIRST) {
  281. if (id == 0) {
  282. for (unsigned short i=1; i<_relays.size(); i++) {
  283. relayStatus(i, status);
  284. }
  285. }
  286. // If NONE_OR_ONE or ONE and setting ON we should set OFF all the others
  287. } else if (status) {
  288. if (relaySync != RELAY_SYNC_ANY) {
  289. for (unsigned short i=0; i<_relays.size(); i++) {
  290. if (i != id) relayStatus(i, false);
  291. }
  292. }
  293. // If ONLY_ONE and setting OFF we should set ON the other one
  294. } else {
  295. if (relaySync == RELAY_SYNC_ONE) {
  296. unsigned char i = (id + 1) % _relays.size();
  297. relayStatus(i, true);
  298. }
  299. }
  300. // Unflag sync mode
  301. _relayRecursive = false;
  302. }
  303. void relaySave(bool eeprom) {
  304. auto mask = std::bitset<RELAY_SAVE_MASK_MAX>(0);
  305. unsigned char count = relayCount();
  306. if (count > RELAY_SAVE_MASK_MAX) count = RELAY_SAVE_MASK_MAX;
  307. for (unsigned int i=0; i < count; ++i) {
  308. mask.set(i, relayStatus(i));
  309. }
  310. const uint32_t mask_value = mask.to_ulong();
  311. DEBUG_MSG_P(PSTR("[RELAY] Setting relay mask: %u\n"), mask_value);
  312. // Persist only to rtcmem, unless requested to save to the eeprom
  313. _relayMaskRtcmem(mask_value);
  314. // The 'eeprom' 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 (eeprom) {
  321. EEPROMr.write(EEPROM_RELAY_STATUS, mask_value);
  322. // We are actually enqueuing the commit so it will be
  323. // executed on the main loop, in case this is called from a system context callback
  324. eepromCommit();
  325. }
  326. }
  327. void relaySave() {
  328. relaySave(false);
  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, mqttForward(), 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. for (unsigned int i=0; i<_relays.size(); i++) {
  369. if (!hasSetting("mqttGroupInv", i)) continue;
  370. setSetting("mqttGroupSync", i, getSetting("mqttGroupInv", i));
  371. delSetting("mqttGroupInv", i);
  372. }
  373. }
  374. void _relayBoot() {
  375. _relayRecursive = true;
  376. bool trigger_save = false;
  377. uint32_t stored_mask = 0;
  378. if (rtcmemStatus()) {
  379. stored_mask = _relayMaskRtcmem();
  380. } else {
  381. stored_mask = EEPROMr.read(EEPROM_RELAY_STATUS);
  382. }
  383. DEBUG_MSG_P(PSTR("[RELAY] Retrieving mask: %u\n"), stored_mask);
  384. auto mask = std::bitset<RELAY_SAVE_MASK_MAX>(stored_mask);
  385. // Walk the relays
  386. bool status;
  387. for (unsigned char i=0; i<relayCount(); ++i) {
  388. unsigned char boot_mode = getSetting("relayBoot", i, RELAY_BOOT_MODE).toInt();
  389. DEBUG_MSG_P(PSTR("[RELAY] Relay #%u boot mode %u\n"), i, boot_mode);
  390. status = false;
  391. switch (boot_mode) {
  392. case RELAY_BOOT_SAME:
  393. if (i < 8) {
  394. status = mask.test(i);
  395. }
  396. break;
  397. case RELAY_BOOT_TOGGLE:
  398. if (i < 8) {
  399. status = !mask[i];
  400. mask.flip(i);
  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. }
  419. // Save if there is any relay in the RELAY_BOOT_TOGGLE mode
  420. if (trigger_save) {
  421. _relayMaskRtcmem(mask.to_ulong());
  422. EEPROMr.write(EEPROM_RELAY_STATUS, mask.to_ulong());
  423. eepromCommit();
  424. }
  425. _relayRecursive = false;
  426. }
  427. void _relayConfigure() {
  428. for (unsigned int i=0; i<_relays.size(); i++) {
  429. _relays[i].pulse = getSetting("relayPulse", i, RELAY_PULSE_MODE).toInt();
  430. _relays[i].pulse_ms = 1000 * getSetting("relayTime", i, RELAY_PULSE_MODE).toFloat();
  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. }
  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<uint8_t>(_relays[i].target_status);
  453. }
  454. }
  455. String _relayFriendlyName(unsigned char i) {
  456. String res = String("GPIO") + String(_relays[i].pin);
  457. if (GPIO_NONE == _relays[i].pin) {
  458. #if (RELAY_PROVIDER == RELAY_PROVIDER_LIGHT)
  459. uint8_t physical = _relays.size() - DUMMY_RELAY_COUNT;
  460. if (i >= physical) {
  461. if (DUMMY_RELAY_COUNT == lightChannels()) {
  462. res = String("CH") + String(i-physical);
  463. } else if (DUMMY_RELAY_COUNT == (lightChannels() + 1u)) {
  464. if (physical == i) {
  465. res = String("Light");
  466. } else {
  467. res = String("CH") + String(i-1-physical);
  468. }
  469. } else {
  470. res = String("Light");
  471. }
  472. } else {
  473. res = String("?");
  474. }
  475. #else
  476. res = String("SW") + String(i);
  477. #endif
  478. }
  479. return res;
  480. }
  481. void _relayWebSocketSendRelays() {
  482. DynamicJsonBuffer jsonBuffer;
  483. JsonObject& root = jsonBuffer.createObject();
  484. JsonObject& relays = root.createNestedObject("relayConfig");
  485. relays["size"] = relayCount();
  486. relays["start"] = 0;
  487. JsonArray& gpio = relays.createNestedArray("gpio");
  488. JsonArray& type = relays.createNestedArray("type");
  489. JsonArray& reset = relays.createNestedArray("reset");
  490. JsonArray& boot = relays.createNestedArray("boot");
  491. JsonArray& pulse = relays.createNestedArray("pulse");
  492. JsonArray& pulse_time = relays.createNestedArray("pulse_time");
  493. #if MQTT_SUPPORT
  494. JsonArray& group = relays.createNestedArray("group");
  495. JsonArray& group_sync = relays.createNestedArray("group_sync");
  496. JsonArray& on_disconnect = relays.createNestedArray("on_disc");
  497. #endif
  498. for (unsigned char i=0; i<relayCount(); i++) {
  499. gpio.add(_relayFriendlyName(i));
  500. type.add(_relays[i].type);
  501. reset.add(_relays[i].reset_pin);
  502. boot.add(getSetting("relayBoot", i, RELAY_BOOT_MODE).toInt());
  503. pulse.add(_relays[i].pulse);
  504. pulse_time.add(_relays[i].pulse_ms / 1000.0);
  505. #if MQTT_SUPPORT
  506. group.add(getSetting("mqttGroup", i, ""));
  507. group_sync.add(getSetting("mqttGroupSync", i, 0).toInt());
  508. on_disconnect.add(getSetting("relayOnDisc", i, 0).toInt());
  509. #endif
  510. }
  511. wsSend(root);
  512. }
  513. void _relayWebSocketOnStart(JsonObject& root) {
  514. if (relayCount() == 0) return;
  515. // Per-relay configuration
  516. _relayWebSocketSendRelays();
  517. // Statuses
  518. _relayWebSocketUpdate(root);
  519. // Options
  520. if (relayCount() > 1) {
  521. root["multirelayVisible"] = 1;
  522. root["relaySync"] = getSetting("relaySync", RELAY_SYNC);
  523. }
  524. root["relayVisible"] = 1;
  525. }
  526. void _relayWebSocketOnAction(uint32_t client_id, const char * action, JsonObject& data) {
  527. if (strcmp(action, "relay") != 0) return;
  528. if (data.containsKey("status")) {
  529. unsigned char value = relayParsePayload(data["status"]);
  530. if (value == 3) {
  531. wsSend(_relayWebSocketUpdate);
  532. } else if (value < 3) {
  533. unsigned int relayID = 0;
  534. if (data.containsKey("id")) {
  535. String value = data["id"];
  536. relayID = value.toInt();
  537. }
  538. // Action to perform
  539. if (value == 0) {
  540. relayStatus(relayID, false);
  541. } else if (value == 1) {
  542. relayStatus(relayID, true);
  543. } else if (value == 2) {
  544. relayToggle(relayID);
  545. }
  546. }
  547. }
  548. }
  549. void relaySetupWS() {
  550. wsOnSendRegister(_relayWebSocketOnStart);
  551. wsOnActionRegister(_relayWebSocketOnAction);
  552. wsOnReceiveRegister(_relayWebSocketOnReceive);
  553. }
  554. #endif // WEB_SUPPORT
  555. //------------------------------------------------------------------------------
  556. // REST API
  557. //------------------------------------------------------------------------------
  558. #if API_SUPPORT
  559. void relaySetupAPI() {
  560. char key[20];
  561. // API entry points (protected with apikey)
  562. for (unsigned int relayID=0; relayID<relayCount(); relayID++) {
  563. snprintf_P(key, sizeof(key), PSTR("%s/%d"), MQTT_TOPIC_RELAY, relayID);
  564. apiRegister(key,
  565. [relayID](char * buffer, size_t len) {
  566. snprintf_P(buffer, len, PSTR("%d"), _relays[relayID].target_status ? 1 : 0);
  567. },
  568. [relayID](const char * payload) {
  569. unsigned char value = relayParsePayload(payload);
  570. if (value == 0xFF) {
  571. DEBUG_MSG_P(PSTR("[RELAY] Wrong payload (%s)\n"), payload);
  572. return;
  573. }
  574. if (value == 0) {
  575. relayStatus(relayID, false);
  576. } else if (value == 1) {
  577. relayStatus(relayID, true);
  578. } else if (value == 2) {
  579. relayToggle(relayID);
  580. }
  581. }
  582. );
  583. snprintf_P(key, sizeof(key), PSTR("%s/%d"), MQTT_TOPIC_PULSE, relayID);
  584. apiRegister(key,
  585. [relayID](char * buffer, size_t len) {
  586. dtostrf((double) _relays[relayID].pulse_ms / 1000, 1-len, 3, buffer);
  587. },
  588. [relayID](const char * payload) {
  589. unsigned long pulse = 1000 * String(payload).toFloat();
  590. if (0 == pulse) return;
  591. if (RELAY_PULSE_NONE != _relays[relayID].pulse) {
  592. DEBUG_MSG_P(PSTR("[RELAY] Overriding relay #%d pulse settings\n"), relayID);
  593. }
  594. _relays[relayID].pulse_ms = pulse;
  595. _relays[relayID].pulse = relayStatus(relayID) ? RELAY_PULSE_ON : RELAY_PULSE_OFF;
  596. relayToggle(relayID, true, false);
  597. }
  598. );
  599. #if defined(ITEAD_SONOFF_IFAN02)
  600. apiRegister(MQTT_TOPIC_SPEED,
  601. [relayID](char * buffer, size_t len) {
  602. snprintf(buffer, len, "%u", getSpeed());
  603. },
  604. [relayID](const char * payload) {
  605. setSpeed(atoi(payload));
  606. }
  607. );
  608. #endif
  609. }
  610. }
  611. #endif // API_SUPPORT
  612. //------------------------------------------------------------------------------
  613. // MQTT
  614. //------------------------------------------------------------------------------
  615. #if MQTT_SUPPORT
  616. void _relayMQTTGroup(unsigned char id) {
  617. String topic = getSetting("mqttGroup", id, "");
  618. if (!topic.length()) return;
  619. unsigned char mode = getSetting("mqttGroupSync", id, RELAY_GROUP_SYNC_NORMAL).toInt();
  620. if (mode == RELAY_GROUP_SYNC_RECEIVEONLY) return;
  621. bool status = relayStatus(id);
  622. if (mode == RELAY_GROUP_SYNC_INVERSE) status = !status;
  623. mqttSendRaw(topic.c_str(), status ? RELAY_MQTT_ON : RELAY_MQTT_OFF);
  624. }
  625. void relayMQTT(unsigned char id) {
  626. if (id >= _relays.size()) return;
  627. // Send state topic
  628. if (_relays[id].report) {
  629. _relays[id].report = false;
  630. mqttSend(MQTT_TOPIC_RELAY, id, _relays[id].current_status ? RELAY_MQTT_ON : RELAY_MQTT_OFF);
  631. }
  632. // Check group topic
  633. if (_relays[id].group_report) {
  634. _relays[id].group_report = false;
  635. _relayMQTTGroup(id);
  636. }
  637. // Send speed for IFAN02
  638. #if defined (ITEAD_SONOFF_IFAN02)
  639. char buffer[5];
  640. snprintf(buffer, sizeof(buffer), "%u", getSpeed());
  641. mqttSend(MQTT_TOPIC_SPEED, buffer);
  642. #endif
  643. }
  644. void relayMQTT() {
  645. for (unsigned int id=0; id < _relays.size(); id++) {
  646. mqttSend(MQTT_TOPIC_RELAY, id, _relays[id].current_status ? RELAY_MQTT_ON : RELAY_MQTT_OFF);
  647. }
  648. }
  649. void relayStatusWrap(unsigned char id, unsigned char value, bool is_group_topic) {
  650. switch (value) {
  651. case 0:
  652. relayStatus(id, false, mqttForward(), !is_group_topic);
  653. break;
  654. case 1:
  655. relayStatus(id, true, mqttForward(), !is_group_topic);
  656. break;
  657. case 2:
  658. relayToggle(id, true, true);
  659. break;
  660. default:
  661. _relays[id].report = true;
  662. relayMQTT(id);
  663. break;
  664. }
  665. }
  666. void relayMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  667. if (type == MQTT_CONNECT_EVENT) {
  668. // Send status on connect
  669. #if (HEARTBEAT_MODE == HEARTBEAT_NONE) or (not HEARTBEAT_REPORT_RELAY)
  670. relayMQTT();
  671. #endif
  672. // Subscribe to own /set topic
  673. char relay_topic[strlen(MQTT_TOPIC_RELAY) + 3];
  674. snprintf_P(relay_topic, sizeof(relay_topic), PSTR("%s/+"), MQTT_TOPIC_RELAY);
  675. mqttSubscribe(relay_topic);
  676. // Subscribe to pulse topic
  677. char pulse_topic[strlen(MQTT_TOPIC_PULSE) + 3];
  678. snprintf_P(pulse_topic, sizeof(pulse_topic), PSTR("%s/+"), MQTT_TOPIC_PULSE);
  679. mqttSubscribe(pulse_topic);
  680. #if defined(ITEAD_SONOFF_IFAN02)
  681. mqttSubscribe(MQTT_TOPIC_SPEED);
  682. #endif
  683. // Subscribe to group topics
  684. for (unsigned int i=0; i < _relays.size(); i++) {
  685. String t = getSetting("mqttGroup", i, "");
  686. if (t.length() > 0) mqttSubscribeRaw(t.c_str());
  687. }
  688. }
  689. if (type == MQTT_MESSAGE_EVENT) {
  690. String t = mqttMagnitude((char *) topic);
  691. // magnitude is relay/#/pulse
  692. if (t.startsWith(MQTT_TOPIC_PULSE)) {
  693. unsigned int id = t.substring(strlen(MQTT_TOPIC_PULSE)+1).toInt();
  694. if (id >= relayCount()) {
  695. DEBUG_MSG_P(PSTR("[RELAY] Wrong relayID (%d)\n"), id);
  696. return;
  697. }
  698. unsigned long pulse = 1000 * String(payload).toFloat();
  699. if (0 == pulse) return;
  700. if (RELAY_PULSE_NONE != _relays[id].pulse) {
  701. DEBUG_MSG_P(PSTR("[RELAY] Overriding relay #%d pulse settings\n"), id);
  702. }
  703. _relays[id].pulse_ms = pulse;
  704. _relays[id].pulse = relayStatus(id) ? RELAY_PULSE_ON : RELAY_PULSE_OFF;
  705. relayToggle(id, true, false);
  706. return;
  707. }
  708. // magnitude is relay/#
  709. if (t.startsWith(MQTT_TOPIC_RELAY)) {
  710. // Get relay ID
  711. unsigned int id = t.substring(strlen(MQTT_TOPIC_RELAY)+1).toInt();
  712. if (id >= relayCount()) {
  713. DEBUG_MSG_P(PSTR("[RELAY] Wrong relayID (%d)\n"), id);
  714. return;
  715. }
  716. // Get value
  717. unsigned char value = relayParsePayload(payload);
  718. if (value == 0xFF) return;
  719. relayStatusWrap(id, value, false);
  720. return;
  721. }
  722. // Check group topics
  723. for (unsigned int i=0; i < _relays.size(); i++) {
  724. String t = getSetting("mqttGroup", i, "");
  725. if ((t.length() > 0) && t.equals(topic)) {
  726. unsigned char value = relayParsePayload(payload);
  727. if (value == 0xFF) return;
  728. if (value < 2) {
  729. if (getSetting("mqttGroupSync", i, RELAY_GROUP_SYNC_NORMAL).toInt() == RELAY_GROUP_SYNC_INVERSE) {
  730. value = 1 - value;
  731. }
  732. }
  733. DEBUG_MSG_P(PSTR("[RELAY] Matched group topic for relayID %d\n"), i);
  734. relayStatusWrap(i, value, true);
  735. }
  736. }
  737. // Itead Sonoff IFAN02
  738. #if defined (ITEAD_SONOFF_IFAN02)
  739. if (t.startsWith(MQTT_TOPIC_SPEED)) {
  740. setSpeed(atoi(payload));
  741. }
  742. #endif
  743. }
  744. if (type == MQTT_DISCONNECT_EVENT) {
  745. for (unsigned int i=0; i < _relays.size(); i++){
  746. int reaction = getSetting("relayOnDisc", i, 0).toInt();
  747. if (1 == reaction) { // switch relay OFF
  748. DEBUG_MSG_P(PSTR("[RELAY] Reset relay (%d) due to MQTT disconnection\n"), i);
  749. relayStatusWrap(i, false, false);
  750. } else if(2 == reaction) { // switch relay ON
  751. DEBUG_MSG_P(PSTR("[RELAY] Set relay (%d) due to MQTT disconnection\n"), i);
  752. relayStatusWrap(i, true, false);
  753. }
  754. }
  755. }
  756. }
  757. void relaySetupMQTT() {
  758. mqttRegister(relayMQTTCallback);
  759. }
  760. #endif
  761. //------------------------------------------------------------------------------
  762. // Settings
  763. //------------------------------------------------------------------------------
  764. #if TERMINAL_SUPPORT
  765. void _relayInitCommands() {
  766. terminalRegisterCommand(F("RELAY"), [](Embedis* e) {
  767. if (e->argc < 2) {
  768. terminalError(F("Wrong arguments"));
  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. terminalOK();
  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. }