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.

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