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.

1542 lines
45 KiB

5 years ago
5 years ago
Terminal: change command-line parser (#2247) Change the underlying command line handling: - switch to a custom parser, inspired by redis / sds - update terminalRegisterCommand signature, pass only bare minimum - clean-up `help` & `commands`. update settings `set`, `get` and `del` - allow our custom test suite to run command-line tests - clean-up Stream IO to allow us to print large things into debug stream (for example, `eeprom.dump`) - send parsing errors to the debug log As a proof of concept, introduce `TERMINAL_MQTT_SUPPORT` and `TERMINAL_WEB_API_SUPPORT` - MQTT subscribes to the `<root>/cmd/set` and sends response to the `<root>/cmd`. We can't output too much, as we don't have any large-send API. - Web API listens to the `/api/cmd?apikey=...&line=...` (or PUT, params inside the body). This one is intended as a possible replacement of the `API_SUPPORT`. Internals introduce a 'task' around the AsyncWebServerRequest object that will simulate what WiFiClient does and push data into it continuously, switching between CONT and SYS. Both are experimental. We only accept a single command and not every command is updated to use Print `ctx.output` object. We are also somewhat limited by the Print / Stream overall, perhaps I am overestimating the usefulness of Arduino compatibility to such an extent :) Web API handler can also sometimes show only part of the result, whenever the command tries to yield() by itself waiting for something. Perhaps we would need to create a custom request handler for that specific use-case.
4 years ago
Terminal: change command-line parser (#2247) Change the underlying command line handling: - switch to a custom parser, inspired by redis / sds - update terminalRegisterCommand signature, pass only bare minimum - clean-up `help` & `commands`. update settings `set`, `get` and `del` - allow our custom test suite to run command-line tests - clean-up Stream IO to allow us to print large things into debug stream (for example, `eeprom.dump`) - send parsing errors to the debug log As a proof of concept, introduce `TERMINAL_MQTT_SUPPORT` and `TERMINAL_WEB_API_SUPPORT` - MQTT subscribes to the `<root>/cmd/set` and sends response to the `<root>/cmd`. We can't output too much, as we don't have any large-send API. - Web API listens to the `/api/cmd?apikey=...&line=...` (or PUT, params inside the body). This one is intended as a possible replacement of the `API_SUPPORT`. Internals introduce a 'task' around the AsyncWebServerRequest object that will simulate what WiFiClient does and push data into it continuously, switching between CONT and SYS. Both are experimental. We only accept a single command and not every command is updated to use Print `ctx.output` object. We are also somewhat limited by the Print / Stream overall, perhaps I am overestimating the usefulness of Arduino compatibility to such an extent :) Web API handler can also sometimes show only part of the result, whenever the command tries to yield() by itself waiting for something. Perhaps we would need to create a custom request handler for that specific use-case.
4 years ago
Terminal: change command-line parser (#2247) Change the underlying command line handling: - switch to a custom parser, inspired by redis / sds - update terminalRegisterCommand signature, pass only bare minimum - clean-up `help` & `commands`. update settings `set`, `get` and `del` - allow our custom test suite to run command-line tests - clean-up Stream IO to allow us to print large things into debug stream (for example, `eeprom.dump`) - send parsing errors to the debug log As a proof of concept, introduce `TERMINAL_MQTT_SUPPORT` and `TERMINAL_WEB_API_SUPPORT` - MQTT subscribes to the `<root>/cmd/set` and sends response to the `<root>/cmd`. We can't output too much, as we don't have any large-send API. - Web API listens to the `/api/cmd?apikey=...&line=...` (or PUT, params inside the body). This one is intended as a possible replacement of the `API_SUPPORT`. Internals introduce a 'task' around the AsyncWebServerRequest object that will simulate what WiFiClient does and push data into it continuously, switching between CONT and SYS. Both are experimental. We only accept a single command and not every command is updated to use Print `ctx.output` object. We are also somewhat limited by the Print / Stream overall, perhaps I am overestimating the usefulness of Arduino compatibility to such an extent :) Web API handler can also sometimes show only part of the result, whenever the command tries to yield() by itself waiting for something. Perhaps we would need to create a custom request handler for that specific use-case.
4 years ago
Terminal: change command-line parser (#2247) Change the underlying command line handling: - switch to a custom parser, inspired by redis / sds - update terminalRegisterCommand signature, pass only bare minimum - clean-up `help` & `commands`. update settings `set`, `get` and `del` - allow our custom test suite to run command-line tests - clean-up Stream IO to allow us to print large things into debug stream (for example, `eeprom.dump`) - send parsing errors to the debug log As a proof of concept, introduce `TERMINAL_MQTT_SUPPORT` and `TERMINAL_WEB_API_SUPPORT` - MQTT subscribes to the `<root>/cmd/set` and sends response to the `<root>/cmd`. We can't output too much, as we don't have any large-send API. - Web API listens to the `/api/cmd?apikey=...&line=...` (or PUT, params inside the body). This one is intended as a possible replacement of the `API_SUPPORT`. Internals introduce a 'task' around the AsyncWebServerRequest object that will simulate what WiFiClient does and push data into it continuously, switching between CONT and SYS. Both are experimental. We only accept a single command and not every command is updated to use Print `ctx.output` object. We are also somewhat limited by the Print / Stream overall, perhaps I am overestimating the usefulness of Arduino compatibility to such an extent :) Web API handler can also sometimes show only part of the result, whenever the command tries to yield() by itself waiting for something. Perhaps we would need to create a custom request handler for that specific use-case.
4 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 "relay.h"
  6. #if RELAY_SUPPORT
  7. #include <Ticker.h>
  8. #include <ArduinoJson.h>
  9. #include <vector>
  10. #include <functional>
  11. #include <bitset>
  12. #include "api.h"
  13. #include "broker.h"
  14. #include "light.h"
  15. #include "mqtt.h"
  16. #include "rfbridge.h"
  17. #include "rpc.h"
  18. #include "rtcmem.h"
  19. #include "settings.h"
  20. #include "storage_eeprom.h"
  21. #include "tuya.h"
  22. #include "utils.h"
  23. #include "ws.h"
  24. #include "libs/BasePin.h"
  25. #include "gpio_pin.h"
  26. #include "mcp23s08_pin.h"
  27. #include "relay_config.h"
  28. class DummyPin final : public BasePin {
  29. public:
  30. DummyPin(unsigned char pin) :
  31. BasePin(pin)
  32. {}
  33. void pinMode(int8_t) override {
  34. }
  35. void digitalWrite(int8_t) override {
  36. }
  37. int digitalRead() override {
  38. return 0;
  39. }
  40. String description() const override {
  41. return F("DummyPin");
  42. }
  43. };
  44. struct relay_t {
  45. using pin_type = BasePin;
  46. // Share the same dummy pin between different relays, no need to duplicate
  47. static pin_type* DummyPinInstance;
  48. // Default to empty relay configuration, as we allow switches to exist without real GPIOs
  49. relay_t() = default;
  50. relay_t(pin_type* pin_, unsigned char type_, pin_type* reset_pin_) :
  51. pin(pin_),
  52. reset_pin(reset_pin_),
  53. type(type_)
  54. {}
  55. pin_type* pin { DummyPinInstance }; // GPIO pin for the relay
  56. pin_type* reset_pin { DummyPinInstance }; // GPIO to reset the relay if RELAY_TYPE_LATCHED
  57. unsigned char type { RELAY_TYPE_NORMAL }; // RELAY_TYPE_NORMAL, RELAY_TYPE_INVERSE, RELAY_TYPE_LATCHED or RELAY_TYPE_LATCHED_INVERSE
  58. unsigned long delay_on { 0ul }; // Delay to turn relay ON
  59. unsigned long delay_off { 0ul }; // Delay to turn relay OFF
  60. unsigned char pulse { RELAY_PULSE_NONE }; // RELAY_PULSE_NONE, RELAY_PULSE_OFF or RELAY_PULSE_ON
  61. unsigned long pulse_ms { 0ul }; // Pulse length in millis
  62. // Status variables
  63. bool current_status { false }; // Holds the current (physical) status of the relay
  64. bool target_status { false }; // Holds the target status
  65. unsigned char lock { RELAY_LOCK_DISABLED }; // Holds the value of target status, that cannot be changed afterwards. (0 for false, 1 for true, 2 to disable)
  66. unsigned long fw_start { 0ul }; // Flood window start time
  67. unsigned char fw_count { 0u }; // Number of changes within the current flood window
  68. unsigned long change_start { 0ul }; // Time when relay was scheduled to change
  69. unsigned long change_delay { 0ul }; // Delay until the next change
  70. bool report { false }; // Whether to report to own topic
  71. bool group_report { false }; // Whether to report to group topic
  72. // Helper objects
  73. Ticker pulseTicker; // Holds the pulse back timer
  74. };
  75. BasePin* relay_t::DummyPinInstance = new DummyPin(GPIO_NONE);
  76. std::vector<relay_t> _relays;
  77. bool _relayRecursive = false;
  78. size_t _relayDummy = 0;
  79. unsigned long _relay_flood_window = (1000 * RELAY_FLOOD_WINDOW);
  80. unsigned long _relay_flood_changes = RELAY_FLOOD_CHANGES;
  81. unsigned long _relay_delay_interlock;
  82. unsigned char _relay_sync_mode = RELAY_SYNC_ANY;
  83. bool _relay_sync_locked = false;
  84. Ticker _relay_save_timer;
  85. Ticker _relay_sync_timer;
  86. #if WEB_SUPPORT
  87. bool _relay_report_ws = false;
  88. #endif // WEB_SUPPORT
  89. #if MQTT_SUPPORT || API_SUPPORT
  90. String _relay_rpc_payload_on;
  91. String _relay_rpc_payload_off;
  92. String _relay_rpc_payload_toggle;
  93. #endif // MQTT_SUPPORT || API_SUPPORT
  94. // -----------------------------------------------------------------------------
  95. // UTILITY
  96. // -----------------------------------------------------------------------------
  97. bool _relayHandlePayload(unsigned char relayID, const char* payload) {
  98. auto value = relayParsePayload(payload);
  99. if (value == PayloadStatus::Unknown) return false;
  100. if (value == PayloadStatus::Off) {
  101. relayStatus(relayID, false);
  102. } else if (value == PayloadStatus::On) {
  103. relayStatus(relayID, true);
  104. } else if (value == PayloadStatus::Toggle) {
  105. relayToggle(relayID);
  106. }
  107. return true;
  108. }
  109. PayloadStatus _relayStatusInvert(PayloadStatus status) {
  110. return (status == PayloadStatus::On) ? PayloadStatus::Off : status;
  111. }
  112. PayloadStatus _relayStatusTyped(unsigned char id) {
  113. if (id >= _relays.size()) return PayloadStatus::Off;
  114. const bool status = _relays[id].current_status;
  115. return (status) ? PayloadStatus::On : PayloadStatus::Off;
  116. }
  117. void _relayLockAll() {
  118. for (auto& relay : _relays) {
  119. relay.lock = relay.target_status ? RELAY_LOCK_ON : RELAY_LOCK_OFF;
  120. }
  121. _relay_sync_locked = true;
  122. }
  123. void _relayUnlockAll() {
  124. for (auto& relay : _relays) {
  125. relay.lock = RELAY_LOCK_DISABLED;
  126. }
  127. _relay_sync_locked = false;
  128. }
  129. bool _relayStatusLock(unsigned char id, bool status) {
  130. if (_relays[id].lock != RELAY_LOCK_DISABLED) {
  131. bool lock = _relays[id].lock == RELAY_LOCK_ON;
  132. if ((lock != status) || (lock != _relays[id].target_status)) {
  133. _relays[id].target_status = lock;
  134. _relays[id].change_delay = 0;
  135. return false;
  136. }
  137. }
  138. return true;
  139. }
  140. // https://github.com/xoseperez/espurna/issues/1510#issuecomment-461894516
  141. // completely reset timing on the other relay to sync with this one
  142. // to ensure that they change state sequentially
  143. void _relaySyncRelaysDelay(unsigned char first, unsigned char second) {
  144. _relays[second].fw_start = _relays[first].change_start;
  145. _relays[second].fw_count = 1;
  146. _relays[second].change_delay = std::max({
  147. _relay_delay_interlock,
  148. _relays[first].change_delay,
  149. _relays[second].change_delay
  150. });
  151. }
  152. void _relaySyncUnlock() {
  153. bool unlock = true;
  154. bool all_off = true;
  155. for (const auto& relay : _relays) {
  156. unlock = unlock && (relay.current_status == relay.target_status);
  157. if (!unlock) break;
  158. all_off = all_off && !relay.current_status;
  159. }
  160. if (!unlock) return;
  161. auto action = []() {
  162. _relayUnlockAll();
  163. #if WEB_SUPPORT
  164. _relay_report_ws = true;
  165. #endif
  166. };
  167. if (all_off) {
  168. _relay_sync_timer.once_ms(_relay_delay_interlock, action);
  169. } else {
  170. action();
  171. }
  172. }
  173. // -----------------------------------------------------------------------------
  174. // RELAY PROVIDERS
  175. // -----------------------------------------------------------------------------
  176. void _relayProviderStatus(unsigned char id, bool status) {
  177. // Check relay ID
  178. if (id >= _relays.size()) return;
  179. // Store new current status
  180. _relays[id].current_status = status;
  181. #if RELAY_PROVIDER == RELAY_PROVIDER_RFBRIDGE
  182. rfbStatus(id, status);
  183. #endif
  184. #if RELAY_PROVIDER == RELAY_PROVIDER_DUAL
  185. // Calculate mask
  186. unsigned char mask=0;
  187. for (unsigned char i=0; i<_relays.size(); i++) {
  188. if (_relays[i].current_status) mask = mask + (1 << i);
  189. }
  190. DEBUG_MSG_P(PSTR("[RELAY] [DUAL] Sending relay mask: %d\n"), mask);
  191. // Send it to F330
  192. Serial.flush();
  193. Serial.write(0xA0);
  194. Serial.write(0x04);
  195. Serial.write(mask);
  196. Serial.write(0xA1);
  197. Serial.flush();
  198. #endif
  199. #if RELAY_PROVIDER == RELAY_PROVIDER_STM
  200. Serial.flush();
  201. Serial.write(0xA0);
  202. Serial.write(id + 1);
  203. Serial.write(status);
  204. Serial.write(0xA1 + status + id);
  205. // The serial init are not full recognized by relais board.
  206. // References: https://github.com/xoseperez/espurna/issues/1519 , https://github.com/xoseperez/espurna/issues/1130
  207. delay(100);
  208. Serial.flush();
  209. #endif
  210. #if RELAY_PROVIDER == RELAY_PROVIDER_LIGHT
  211. // Real relays
  212. size_t physical = _relays.size() - _relayDummy;
  213. // Support for a mixed of dummy and real relays
  214. // Reference: https://github.com/xoseperez/espurna/issues/1305
  215. if (id >= physical) {
  216. // If the number of dummy relays matches the number of light channels
  217. // assume each relay controls one channel.
  218. // If the number of dummy relays is the number of channels plus 1
  219. // assume the first one controls all the channels and
  220. // the rest one channel each.
  221. // Otherwise every dummy relay controls all channels.
  222. if (_relayDummy == lightChannels()) {
  223. lightState(id-physical, status);
  224. lightState(true);
  225. } else if (_relayDummy == (lightChannels() + 1u)) {
  226. if (id == physical) {
  227. lightState(status);
  228. } else {
  229. lightState(id-1-physical, status);
  230. }
  231. } else {
  232. lightState(status);
  233. }
  234. lightUpdate(true, true);
  235. return;
  236. }
  237. #endif
  238. #if (RELAY_PROVIDER == RELAY_PROVIDER_RELAY) || \
  239. (RELAY_PROVIDER == RELAY_PROVIDER_LIGHT) || \
  240. (RELAY_PROVIDER == RELAY_PROVIDER_MCP23S08)
  241. // If this is a light, all dummy relays have already been processed above
  242. // we reach here if the user has toggled a physical relay
  243. if (_relays[id].type == RELAY_TYPE_NORMAL) {
  244. _relays[id].pin->digitalWrite(status);
  245. } else if (_relays[id].type == RELAY_TYPE_INVERSE) {
  246. _relays[id].pin->digitalWrite(!status);
  247. } else if (_relays[id].type == RELAY_TYPE_LATCHED || _relays[id].type == RELAY_TYPE_LATCHED_INVERSE) {
  248. bool pulse = (_relays[id].type == RELAY_TYPE_LATCHED) ? HIGH : LOW;
  249. _relays[id].pin->digitalWrite(!pulse);
  250. if (GPIO_NONE != _relays[id].reset_pin->pin) {
  251. _relays[id].reset_pin->digitalWrite(!pulse);
  252. }
  253. if (status || (GPIO_NONE == _relays[id].reset_pin->pin)) {
  254. _relays[id].pin->digitalWrite(pulse);
  255. } else {
  256. _relays[id].reset_pin->digitalWrite(pulse);
  257. }
  258. nice_delay(RELAY_LATCHING_PULSE);
  259. _relays[id].pin->digitalWrite(!pulse);
  260. if (GPIO_NONE != _relays[id].reset_pin->pin) {
  261. _relays[id].reset_pin->digitalWrite(!pulse);
  262. }
  263. }
  264. #endif
  265. }
  266. /**
  267. * Walks the relay vector processing only those relays
  268. * that have to change to the requested mode
  269. * @bool mode Requested mode
  270. */
  271. void _relayProcess(bool mode) {
  272. bool changed = false;
  273. for (unsigned char id = 0; id < _relays.size(); id++) {
  274. bool target = _relays[id].target_status;
  275. // Only process the relays we have to change
  276. if (target == _relays[id].current_status) continue;
  277. // Only process the relays we have to change to the requested mode
  278. if (target != mode) continue;
  279. // Only process if the change delay has expired
  280. if (_relays[id].change_delay && (millis() - _relays[id].change_start < _relays[id].change_delay)) continue;
  281. // Purge existing delay in case of cancelation
  282. _relays[id].change_delay = 0;
  283. changed = true;
  284. DEBUG_MSG_P(PSTR("[RELAY] #%d set to %s\n"), id, target ? "ON" : "OFF");
  285. // Call the provider to perform the action
  286. _relayProviderStatus(id, target);
  287. // Send to Broker
  288. #if BROKER_SUPPORT
  289. StatusBroker::Publish(MQTT_TOPIC_RELAY, id, target);
  290. #endif
  291. // Send MQTT
  292. #if MQTT_SUPPORT
  293. relayMQTT(id);
  294. #endif
  295. #if WEB_SUPPORT
  296. _relay_report_ws = true;
  297. #endif
  298. if (!_relayRecursive) {
  299. relayPulse(id);
  300. // We will trigger a eeprom save only if
  301. // we care about current relay status on boot
  302. const auto boot_mode = getSetting({"relayBoot", id}, RELAY_BOOT_MODE);
  303. const bool save_eeprom = ((RELAY_BOOT_SAME == boot_mode) || (RELAY_BOOT_TOGGLE == boot_mode));
  304. _relay_save_timer.once_ms(RELAY_SAVE_DELAY, relaySave, save_eeprom);
  305. }
  306. _relays[id].report = false;
  307. _relays[id].group_report = false;
  308. }
  309. // Whenever we are using sync modes and any relay had changed the state, check if we can unlock
  310. const bool needs_unlock = ((_relay_sync_mode == RELAY_SYNC_NONE_OR_ONE) || (_relay_sync_mode == RELAY_SYNC_ONE));
  311. if (_relay_sync_locked && needs_unlock && changed) {
  312. _relaySyncUnlock();
  313. }
  314. }
  315. #if defined(ITEAD_SONOFF_IFAN02)
  316. unsigned char _relay_ifan02_speeds[] = {0, 1, 3, 5};
  317. unsigned char getSpeed() {
  318. unsigned char speed =
  319. (_relays[1].target_status ? 1 : 0) +
  320. (_relays[2].target_status ? 2 : 0) +
  321. (_relays[3].target_status ? 4 : 0);
  322. for (unsigned char i=0; i<4; i++) {
  323. if (_relay_ifan02_speeds[i] == speed) return i;
  324. }
  325. return 0;
  326. }
  327. void setSpeed(unsigned char speed) {
  328. if ((0 <= speed) & (speed <= 3)) {
  329. if (getSpeed() == speed) return;
  330. unsigned char states = _relay_ifan02_speeds[speed];
  331. for (unsigned char i=0; i<3; i++) {
  332. relayStatus(i+1, states & 1 == 1);
  333. states >>= 1;
  334. }
  335. }
  336. }
  337. #endif
  338. // -----------------------------------------------------------------------------
  339. // RELAY
  340. // -----------------------------------------------------------------------------
  341. // State persistance persistance
  342. namespace {
  343. String u32toString(uint32_t value, int base) {
  344. String result;
  345. result.reserve(32 + 2);
  346. if (base == 2) {
  347. result += "0b";
  348. } else if (base == 8) {
  349. result += "0o";
  350. } else if (base == 16) {
  351. result += "0x";
  352. }
  353. char buffer[33] = {0};
  354. ultoa(value, buffer, base);
  355. result += buffer;
  356. return result;
  357. }
  358. struct RelayMask {
  359. const String as_string;
  360. uint32_t as_u32;
  361. };
  362. RelayMask INLINE _relayMask(uint32_t mask) {
  363. return {std::move(u32toString(mask, 2)), mask};
  364. }
  365. RelayMask INLINE _relayMaskRtcmem() {
  366. return _relayMask(Rtcmem->relay);
  367. }
  368. void INLINE _relayMaskRtcmem(uint32_t mask) {
  369. Rtcmem->relay = mask;
  370. }
  371. void INLINE _relayMaskRtcmem(const RelayMask& mask) {
  372. _relayMaskRtcmem(mask.as_u32);
  373. }
  374. void INLINE _relayMaskRtcmem(const std::bitset<RelaysMax>& bitset) {
  375. _relayMaskRtcmem(bitset.to_ulong());
  376. }
  377. RelayMask INLINE _relayMaskSettings() {
  378. constexpr unsigned long defaultMask { 0ul };
  379. auto value = getSetting("relayBootMask", defaultMask);
  380. return _relayMask(value);
  381. }
  382. void INLINE _relayMaskSettings(uint32_t mask) {
  383. setSetting("relayBootMask", u32toString(mask, 2));
  384. }
  385. void INLINE _relayMaskSettings(const RelayMask& mask) {
  386. setSetting("relayBootMask", mask.as_string);
  387. }
  388. void INLINE _relayMaskSettings(const std::bitset<RelaysMax>& bitset) {
  389. _relayMaskSettings(bitset.to_ulong());
  390. }
  391. } // ns anonymous
  392. // Pulse timers (timer after ON or OFF event)
  393. void relayPulse(unsigned char id) {
  394. _relays[id].pulseTicker.detach();
  395. byte mode = _relays[id].pulse;
  396. if (mode == RELAY_PULSE_NONE) return;
  397. unsigned long ms = _relays[id].pulse_ms;
  398. if (ms == 0) return;
  399. bool status = relayStatus(id);
  400. bool pulseStatus = (mode == RELAY_PULSE_ON);
  401. if (pulseStatus != status) {
  402. DEBUG_MSG_P(PSTR("[RELAY] Scheduling relay #%d back in %lums (pulse)\n"), id, ms);
  403. _relays[id].pulseTicker.once_ms(ms, relayToggle, id);
  404. // Reconfigure after dynamic pulse
  405. _relays[id].pulse = getSetting({"relayPulse", id}, RELAY_PULSE_MODE);
  406. _relays[id].pulse_ms = 1000 * getSetting({"relayTime", id}, 0.);
  407. }
  408. }
  409. // General relay status control
  410. bool relayStatus(unsigned char id, bool status, bool report, bool group_report) {
  411. if (id == RELAY_NONE) return false;
  412. if (id >= _relays.size()) return false;
  413. if (!_relayStatusLock(id, status)) {
  414. DEBUG_MSG_P(PSTR("[RELAY] #%d is locked to %s\n"), id, _relays[id].current_status ? "ON" : "OFF");
  415. _relays[id].report = true;
  416. _relays[id].group_report = true;
  417. return false;
  418. }
  419. bool changed = false;
  420. if (_relays[id].current_status == status) {
  421. if (_relays[id].target_status != status) {
  422. DEBUG_MSG_P(PSTR("[RELAY] #%d scheduled change cancelled\n"), id);
  423. _relays[id].target_status = status;
  424. _relays[id].report = false;
  425. _relays[id].group_report = false;
  426. _relays[id].change_delay = 0;
  427. changed = true;
  428. }
  429. // For RFBridge, keep sending the message even if the status is already the required
  430. #if RELAY_PROVIDER == RELAY_PROVIDER_RFBRIDGE
  431. rfbStatus(id, status);
  432. #endif
  433. // Update the pulse counter if the relay is already in the non-normal state (#454)
  434. relayPulse(id);
  435. } else {
  436. unsigned long current_time = millis();
  437. unsigned long change_delay = status ? _relays[id].delay_on : _relays[id].delay_off;
  438. _relays[id].fw_count++;
  439. _relays[id].change_start = current_time;
  440. _relays[id].change_delay = std::max(_relays[id].change_delay, change_delay);
  441. // If current_time is off-limits the floodWindow...
  442. const auto fw_diff = current_time - _relays[id].fw_start;
  443. if (fw_diff > _relay_flood_window) {
  444. // We reset the floodWindow
  445. _relays[id].fw_start = current_time;
  446. _relays[id].fw_count = 1;
  447. // If current_time is in the floodWindow and there have been too many requests...
  448. } else if (_relays[id].fw_count >= _relay_flood_changes) {
  449. // We schedule the changes to the end of the floodWindow
  450. // unless it's already delayed beyond that point
  451. _relays[id].change_delay = std::max(change_delay, _relay_flood_window - fw_diff);
  452. // Another option is to always move it forward, starting from current time
  453. //_relays[id].fw_start = current_time;
  454. }
  455. _relays[id].target_status = status;
  456. if (report) _relays[id].report = true;
  457. if (group_report) _relays[id].group_report = true;
  458. relaySync(id);
  459. DEBUG_MSG_P(PSTR("[RELAY] #%d scheduled %s in %u ms\n"),
  460. id, status ? "ON" : "OFF", _relays[id].change_delay
  461. );
  462. changed = true;
  463. }
  464. return changed;
  465. }
  466. bool relayStatus(unsigned char id, bool status) {
  467. #if MQTT_SUPPORT
  468. return relayStatus(id, status, mqttForward(), true);
  469. #else
  470. return relayStatus(id, status, false, true);
  471. #endif
  472. }
  473. bool relayStatus(unsigned char id) {
  474. // Check that relay ID is valid
  475. if (id >= _relays.size()) return false;
  476. // Get status directly from storage
  477. return _relays[id].current_status;
  478. }
  479. bool relayStatusTarget(unsigned char id) {
  480. if (id >= _relays.size()) return false;
  481. return _relays[id].target_status;
  482. }
  483. void relaySync(unsigned char id) {
  484. // No sync if none or only one relay
  485. if (_relays.size() < 2) return;
  486. // Do not go on if we are comming from a previous sync
  487. if (_relayRecursive) return;
  488. // Flag sync mode
  489. _relayRecursive = true;
  490. bool status = _relays[id].target_status;
  491. // If RELAY_SYNC_SAME all relays should have the same state
  492. if (_relay_sync_mode == RELAY_SYNC_SAME) {
  493. for (unsigned short i=0; i<_relays.size(); i++) {
  494. if (i != id) relayStatus(i, status);
  495. }
  496. // If RELAY_SYNC_FIRST all relays should have the same state as first if first changes
  497. } else if (_relay_sync_mode == RELAY_SYNC_FIRST) {
  498. if (id == 0) {
  499. for (unsigned short i=1; i<_relays.size(); i++) {
  500. relayStatus(i, status);
  501. }
  502. }
  503. } else if ((_relay_sync_mode == RELAY_SYNC_NONE_OR_ONE) || (_relay_sync_mode == RELAY_SYNC_ONE)) {
  504. // If NONE_OR_ONE or ONE and setting ON we should set OFF all the others
  505. if (status) {
  506. if (_relay_sync_mode != RELAY_SYNC_ANY) {
  507. for (unsigned short other_id=0; other_id<_relays.size(); other_id++) {
  508. if (other_id != id) {
  509. relayStatus(other_id, false);
  510. if (relayStatus(other_id)) {
  511. _relaySyncRelaysDelay(other_id, id);
  512. }
  513. }
  514. }
  515. }
  516. // If ONLY_ONE and setting OFF we should set ON the other one
  517. } else {
  518. if (_relay_sync_mode == RELAY_SYNC_ONE) {
  519. unsigned char other_id = (id + 1) % _relays.size();
  520. _relaySyncRelaysDelay(id, other_id);
  521. relayStatus(other_id, true);
  522. }
  523. }
  524. _relayLockAll();
  525. }
  526. // Unflag sync mode
  527. _relayRecursive = false;
  528. }
  529. void relaySave(bool eeprom) {
  530. const unsigned char count = constrain(relayCount(), 0, RelaysMax);
  531. auto statuses = std::bitset<RelaysMax>(0);
  532. for (unsigned int id = 0; id < count; ++id) {
  533. statuses.set(id, relayStatus(id));
  534. }
  535. const auto mask = _relayMask(statuses.to_ulong() & 0xffffffffu);
  536. DEBUG_MSG_P(PSTR("[RELAY] Setting relay mask: %s\n"), mask.as_string.c_str());
  537. // Persist only to rtcmem, unless requested to save to the eeprom
  538. _relayMaskRtcmem(mask);
  539. // The 'eeprom' flag controls whether we are commiting this change or not.
  540. // It is useful to set it to 'false' if the relay change triggering the
  541. // save involves a relay whose boot mode is independent from current mode,
  542. // thus storing the last relay value is not absolutely necessary.
  543. // Nevertheless, we store the value in the EEPROM buffer so it will be written
  544. // on the next commit.
  545. if (eeprom) {
  546. _relayMaskSettings(mask);
  547. // We are actually enqueuing the commit so it will be
  548. // executed on the main loop, in case this is called from a system context callback
  549. eepromCommit();
  550. }
  551. }
  552. void relaySave() {
  553. relaySave(false);
  554. }
  555. void relayToggle(unsigned char id, bool report, bool group_report) {
  556. if (id >= _relays.size()) return;
  557. relayStatus(id, !relayStatus(id), report, group_report);
  558. }
  559. void relayToggle(unsigned char id) {
  560. #if MQTT_SUPPORT
  561. relayToggle(id, mqttForward(), true);
  562. #else
  563. relayToggle(id, false, true);
  564. #endif
  565. }
  566. unsigned char relayCount() {
  567. return _relays.size();
  568. }
  569. PayloadStatus relayParsePayload(const char * payload) {
  570. #if MQTT_SUPPORT || API_SUPPORT
  571. return rpcParsePayload(payload, [](const char* payload) {
  572. if (_relay_rpc_payload_off.equals(payload)) return PayloadStatus::Off;
  573. if (_relay_rpc_payload_on.equals(payload)) return PayloadStatus::On;
  574. if (_relay_rpc_payload_toggle.equals(payload)) return PayloadStatus::Toggle;
  575. return PayloadStatus::Unknown;
  576. });
  577. #else
  578. return rpcParsePayload(payload);
  579. #endif
  580. }
  581. // BACKWARDS COMPATIBILITY
  582. void _relayBackwards() {
  583. for (unsigned char id = 0; id < _relays.size(); ++id) {
  584. const settings_key_t key {"mqttGroupInv", id};
  585. if (!hasSetting(key)) continue;
  586. setSetting({"mqttGroupSync", id}, getSetting(key));
  587. delSetting(key);
  588. }
  589. }
  590. void _relayBoot() {
  591. _relayRecursive = true;
  592. const auto stored_mask = rtcmemStatus()
  593. ? _relayMaskRtcmem()
  594. : _relayMaskSettings();
  595. DEBUG_MSG_P(PSTR("[RELAY] Retrieving mask: %s\n"), stored_mask.as_string.c_str());
  596. auto mask = std::bitset<RelaysMax>(stored_mask.as_u32);
  597. // Walk the relays
  598. unsigned char lock;
  599. bool status;
  600. for (unsigned char i=0; i<relayCount(); ++i) {
  601. const auto boot_mode = getSetting({"relayBoot", i}, RELAY_BOOT_MODE);
  602. DEBUG_MSG_P(PSTR("[RELAY] Relay #%u boot mode %d\n"), i, boot_mode);
  603. status = false;
  604. lock = RELAY_LOCK_DISABLED;
  605. switch (boot_mode) {
  606. case RELAY_BOOT_SAME:
  607. status = mask.test(i);
  608. break;
  609. case RELAY_BOOT_TOGGLE:
  610. mask.flip(i);
  611. status = mask[i];
  612. break;
  613. case RELAY_BOOT_LOCKED_ON:
  614. status = true;
  615. lock = RELAY_LOCK_ON;
  616. break;
  617. case RELAY_BOOT_LOCKED_OFF:
  618. lock = RELAY_LOCK_OFF;
  619. break;
  620. case RELAY_BOOT_ON:
  621. status = true;
  622. break;
  623. case RELAY_BOOT_OFF:
  624. default:
  625. break;
  626. }
  627. _relays[i].current_status = !status;
  628. _relays[i].target_status = status;
  629. _relays[i].change_start = millis();
  630. _relays[i].change_delay = status
  631. ? _relays[i].delay_on
  632. : _relays[i].delay_off;
  633. #if RELAY_PROVIDER == RELAY_PROVIDER_STM
  634. // XXX hack for correctly restoring relay state on boot
  635. // because of broken stm relay firmware
  636. _relays[i].change_delay = 3000 + 1000 * i;
  637. #endif
  638. _relays[i].lock = lock;
  639. }
  640. _relayRecursive = false;
  641. #if TUYA_SUPPORT
  642. Tuya::tuyaSyncSwitchStatus();
  643. #endif
  644. }
  645. void _relayConfigure() {
  646. for (unsigned char i = 0, relays = _relays.size() ; (i < relays); ++i) {
  647. _relays[i].pulse = getSetting({"relayPulse", i}, RELAY_PULSE_MODE);
  648. _relays[i].pulse_ms = 1000 * getSetting({"relayTime", i}, 0.);
  649. _relays[i].delay_on = getSetting({"relayDelayOn", i}, _relayDelayOn(i));
  650. _relays[i].delay_off = getSetting({"relayDelayOff", i}, _relayDelayOff(i));
  651. // make sure pin is valid before continuing with writes
  652. if (!static_cast<bool>(*_relays[i].pin)) continue;
  653. _relays[i].pin->pinMode(OUTPUT);
  654. if (static_cast<bool>(*_relays[i].reset_pin)) {
  655. _relays[i].reset_pin->pinMode(OUTPUT);
  656. }
  657. if (_relays[i].type == RELAY_TYPE_INVERSE) {
  658. //set to high to block short opening of relay
  659. _relays[i].pin->digitalWrite(HIGH);
  660. }
  661. }
  662. _relay_flood_window = (1000 * getSetting("relayFloodTime", RELAY_FLOOD_WINDOW));
  663. _relay_flood_changes = getSetting("relayFloodChanges", RELAY_FLOOD_CHANGES);
  664. _relay_delay_interlock = getSetting("relayDelayInterlock", RELAY_DELAY_INTERLOCK);
  665. _relay_sync_mode = getSetting("relaySync", RELAY_SYNC);
  666. #if MQTT_SUPPORT || API_SUPPORT
  667. settingsProcessConfig({
  668. {_relay_rpc_payload_on, "relayPayloadOn", RELAY_MQTT_ON},
  669. {_relay_rpc_payload_off, "relayPayloadOff", RELAY_MQTT_OFF},
  670. {_relay_rpc_payload_toggle, "relayPayloadToggle", RELAY_MQTT_TOGGLE},
  671. });
  672. #endif // MQTT_SUPPORT
  673. }
  674. //------------------------------------------------------------------------------
  675. // WEBSOCKETS
  676. //------------------------------------------------------------------------------
  677. #if WEB_SUPPORT
  678. bool _relayWebSocketOnKeyCheck(const char * key, JsonVariant& value) {
  679. return (strncmp(key, "relay", 5) == 0);
  680. }
  681. void _relayWebSocketUpdate(JsonObject& root) {
  682. JsonObject& state = root.createNestedObject("relayState");
  683. state["size"] = relayCount();
  684. JsonArray& status = state.createNestedArray("status");
  685. JsonArray& lock = state.createNestedArray("lock");
  686. // Note: we use byte instead of bool to ever so slightly compress json output
  687. for (unsigned char i=0; i<relayCount(); i++) {
  688. status.add<uint8_t>(_relays[i].target_status);
  689. lock.add(_relays[i].lock);
  690. }
  691. }
  692. String _relayFriendlyName(unsigned char i) {
  693. String res = String("GPIO") + String(_relays[i].pin->pin);
  694. if (GPIO_NONE == _relays[i].pin->pin) {
  695. #if (RELAY_PROVIDER == RELAY_PROVIDER_LIGHT)
  696. uint8_t physical = _relays.size() - _relayDummy;
  697. if (i >= physical) {
  698. if (_relayDummy == lightChannels()) {
  699. res = String("CH") + String(i-physical);
  700. } else if (_relayDummy == (lightChannels() + 1u)) {
  701. if (physical == i) {
  702. res = String("Light");
  703. } else {
  704. res = String("CH") + String(i-1-physical);
  705. }
  706. } else {
  707. res = String("Light");
  708. }
  709. } else {
  710. res = String("?");
  711. }
  712. #else
  713. res = String("SW") + String(i);
  714. #endif
  715. }
  716. return res;
  717. }
  718. void _relayWebSocketSendRelays(JsonObject& root) {
  719. JsonObject& relays = root.createNestedObject("relayConfig");
  720. relays["size"] = relayCount();
  721. relays["start"] = 0;
  722. JsonArray& gpio = relays.createNestedArray("gpio");
  723. JsonArray& type = relays.createNestedArray("type");
  724. JsonArray& reset = relays.createNestedArray("reset");
  725. JsonArray& boot = relays.createNestedArray("boot");
  726. JsonArray& pulse = relays.createNestedArray("pulse");
  727. JsonArray& pulse_time = relays.createNestedArray("pulse_time");
  728. #if SCHEDULER_SUPPORT
  729. JsonArray& sch_last = relays.createNestedArray("sch_last");
  730. #endif
  731. #if MQTT_SUPPORT
  732. JsonArray& group = relays.createNestedArray("group");
  733. JsonArray& group_sync = relays.createNestedArray("group_sync");
  734. JsonArray& on_disconnect = relays.createNestedArray("on_disc");
  735. #endif
  736. for (unsigned char i=0; i<relayCount(); i++) {
  737. gpio.add(_relayFriendlyName(i));
  738. type.add(_relays[i].type);
  739. reset.add(_relays[i].reset_pin->pin);
  740. boot.add(getSetting({"relayBoot", i}, RELAY_BOOT_MODE));
  741. pulse.add(_relays[i].pulse);
  742. pulse_time.add(_relays[i].pulse_ms / 1000.0);
  743. #if SCHEDULER_SUPPORT
  744. sch_last.add(getSetting({"relayLastSch", i}, SCHEDULER_RESTORE_LAST_SCHEDULE));
  745. #endif
  746. #if MQTT_SUPPORT
  747. group.add(getSetting({"mqttGroup", i}));
  748. group_sync.add(getSetting({"mqttGroupSync", i}, 0));
  749. on_disconnect.add(getSetting({"relayOnDisc", i}, 0));
  750. #endif
  751. }
  752. }
  753. void _relayWebSocketOnVisible(JsonObject& root) {
  754. if (relayCount() == 0) return;
  755. if (relayCount() > 1) {
  756. root["multirelayVisible"] = 1;
  757. root["relaySync"] = getSetting("relaySync", RELAY_SYNC);
  758. }
  759. root["relayVisible"] = 1;
  760. }
  761. void _relayWebSocketOnConnected(JsonObject& root) {
  762. if (relayCount() == 0) return;
  763. // Per-relay configuration
  764. _relayWebSocketSendRelays(root);
  765. }
  766. void _relayWebSocketOnAction(uint32_t client_id, const char * action, JsonObject& data) {
  767. if (strcmp(action, "relay") != 0) return;
  768. if (data.containsKey("status")) {
  769. unsigned int relayID = 0;
  770. if (data.containsKey("id") && data.is<int>("id")) {
  771. relayID = data["id"];
  772. }
  773. _relayHandlePayload(relayID, data["status"]);
  774. }
  775. }
  776. void relaySetupWS() {
  777. wsRegister()
  778. .onVisible(_relayWebSocketOnVisible)
  779. .onConnected(_relayWebSocketOnConnected)
  780. .onData(_relayWebSocketUpdate)
  781. .onAction(_relayWebSocketOnAction)
  782. .onKeyCheck(_relayWebSocketOnKeyCheck);
  783. }
  784. #endif // WEB_SUPPORT
  785. //------------------------------------------------------------------------------
  786. // REST API
  787. //------------------------------------------------------------------------------
  788. #if API_SUPPORT
  789. void relaySetupAPI() {
  790. // Note that we expect a fixed number of entries.
  791. // Otherwise, underlying vector will reserve more than we need (likely, *2 of the current size)
  792. apiReserve(2u + (relayCount() * 2u));
  793. apiRegister({
  794. MQTT_TOPIC_RELAY, Api::Type::Json, ApiUnusedArg,
  795. [](const Api&, JsonObject& root) {
  796. JsonArray& relays = root.createNestedArray("relayStatus");
  797. for (unsigned char id = 0; id < relayCount(); ++id) {
  798. relays.add(_relays[id].target_status ? 1 : 0);
  799. }
  800. }
  801. });
  802. #if defined(ITEAD_SONOFF_IFAN02)
  803. apiRegister({
  804. MQTT_TOPIC_SPEED, Api::Type::Basic, ApiUnusedArg,
  805. [](const Api&, ApiBuffer& buffer) {
  806. snprintf(buffer.data, buffer.size, "%u", getSpeed());
  807. },
  808. [](const Api&, ApiBuffer& buffer) {
  809. setSpeed(atoi(buffer.data));
  810. snprintf(buffer.data, buffer.size, "%u", getSpeed());
  811. }
  812. });
  813. #endif
  814. char path[64] = {0};
  815. for (unsigned char id = 0; id < relayCount(); ++id) {
  816. sprintf_P(path, PSTR(MQTT_TOPIC_RELAY "/%u"), id);
  817. apiRegister({
  818. path, Api::Type::Basic, id,
  819. [](const Api& api, ApiBuffer& buffer) {
  820. snprintf_P(buffer.data, buffer.size, PSTR("%d"), _relays[api.arg].target_status ? 1 : 0);
  821. },
  822. [](const Api& api, ApiBuffer& buffer) {
  823. if (!_relayHandlePayload(api.arg, buffer.data)) {
  824. DEBUG_MSG_P(PSTR("[RELAY] Invalid API payload (%s)\n"), buffer.data);
  825. return;
  826. }
  827. }
  828. });
  829. sprintf_P(path, PSTR(MQTT_TOPIC_PULSE "/%u"), id);
  830. apiRegister({
  831. path, Api::Type::Basic, id,
  832. [](const Api& api, ApiBuffer& buffer) {
  833. dtostrf((double) _relays[api.arg].pulse_ms / 1000, 1, 3, buffer.data);
  834. },
  835. [](const Api& api, ApiBuffer& buffer) {
  836. unsigned long pulse = 1000 * atof(buffer.data);
  837. if (0 == pulse) {
  838. return;
  839. }
  840. if (RELAY_PULSE_NONE != _relays[api.arg].pulse) {
  841. DEBUG_MSG_P(PSTR("[RELAY] Overriding relay #%d pulse settings\n"), api.arg);
  842. }
  843. _relays[api.arg].pulse_ms = pulse;
  844. _relays[api.arg].pulse = relayStatus(api.arg)
  845. ? RELAY_PULSE_ON
  846. : RELAY_PULSE_OFF;
  847. relayToggle(api.arg, true, false);
  848. }
  849. });
  850. }
  851. }
  852. #endif // API_SUPPORT
  853. //------------------------------------------------------------------------------
  854. // MQTT
  855. //------------------------------------------------------------------------------
  856. #if MQTT_SUPPORT || API_SUPPORT
  857. const String& relayPayloadOn() {
  858. return _relay_rpc_payload_on;
  859. }
  860. const String& relayPayloadOff() {
  861. return _relay_rpc_payload_off;
  862. }
  863. const String& relayPayloadToggle() {
  864. return _relay_rpc_payload_toggle;
  865. }
  866. const char* relayPayload(PayloadStatus status) {
  867. switch (status) {
  868. case PayloadStatus::Off:
  869. return _relay_rpc_payload_off.c_str();
  870. case PayloadStatus::On:
  871. return _relay_rpc_payload_on.c_str();
  872. case PayloadStatus::Toggle:
  873. return _relay_rpc_payload_toggle.c_str();
  874. case PayloadStatus::Unknown:
  875. default:
  876. return "";
  877. }
  878. }
  879. #endif // MQTT_SUPPORT || API_SUPPORT
  880. #if MQTT_SUPPORT
  881. void _relayMQTTGroup(unsigned char id) {
  882. const String topic = getSetting({"mqttGroup", id});
  883. if (!topic.length()) return;
  884. const auto mode = getSetting({"mqttGroupSync", id}, RELAY_GROUP_SYNC_NORMAL);
  885. if (mode == RELAY_GROUP_SYNC_RECEIVEONLY) return;
  886. auto status = _relayStatusTyped(id);
  887. if (mode == RELAY_GROUP_SYNC_INVERSE) status = _relayStatusInvert(status);
  888. mqttSendRaw(topic.c_str(), relayPayload(status));
  889. }
  890. void relayMQTT(unsigned char id) {
  891. if (id >= _relays.size()) return;
  892. // Send state topic
  893. if (_relays[id].report) {
  894. _relays[id].report = false;
  895. mqttSend(MQTT_TOPIC_RELAY, id, relayPayload(_relayStatusTyped(id)));
  896. }
  897. // Check group topic
  898. if (_relays[id].group_report) {
  899. _relays[id].group_report = false;
  900. _relayMQTTGroup(id);
  901. }
  902. // Send speed for IFAN02
  903. #if defined (ITEAD_SONOFF_IFAN02)
  904. char buffer[5];
  905. snprintf(buffer, sizeof(buffer), "%u", getSpeed());
  906. mqttSend(MQTT_TOPIC_SPEED, buffer);
  907. #endif
  908. }
  909. void relayMQTT() {
  910. for (unsigned int id=0; id < _relays.size(); id++) {
  911. mqttSend(MQTT_TOPIC_RELAY, id, relayPayload(_relayStatusTyped(id)));
  912. }
  913. }
  914. void relayStatusWrap(unsigned char id, PayloadStatus value, bool is_group_topic) {
  915. #if MQTT_SUPPORT
  916. const auto forward = mqttForward();
  917. #else
  918. const auto forward = false;
  919. #endif
  920. switch (value) {
  921. case PayloadStatus::Off:
  922. relayStatus(id, false, forward, !is_group_topic);
  923. break;
  924. case PayloadStatus::On:
  925. relayStatus(id, true, forward, !is_group_topic);
  926. break;
  927. case PayloadStatus::Toggle:
  928. relayToggle(id, true, true);
  929. break;
  930. case PayloadStatus::Unknown:
  931. default:
  932. _relays[id].report = true;
  933. relayMQTT(id);
  934. break;
  935. }
  936. }
  937. void relayMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  938. if (type == MQTT_CONNECT_EVENT) {
  939. // Send status on connect
  940. #if (HEARTBEAT_MODE == HEARTBEAT_NONE) or (not HEARTBEAT_REPORT_RELAY)
  941. relayMQTT();
  942. #endif
  943. // Subscribe to own /set topic
  944. char relay_topic[strlen(MQTT_TOPIC_RELAY) + 3];
  945. snprintf_P(relay_topic, sizeof(relay_topic), PSTR("%s/+"), MQTT_TOPIC_RELAY);
  946. mqttSubscribe(relay_topic);
  947. // Subscribe to pulse topic
  948. char pulse_topic[strlen(MQTT_TOPIC_PULSE) + 3];
  949. snprintf_P(pulse_topic, sizeof(pulse_topic), PSTR("%s/+"), MQTT_TOPIC_PULSE);
  950. mqttSubscribe(pulse_topic);
  951. #if defined(ITEAD_SONOFF_IFAN02)
  952. mqttSubscribe(MQTT_TOPIC_SPEED);
  953. #endif
  954. // Subscribe to group topics
  955. for (unsigned char i=0; i < _relays.size(); i++) {
  956. const auto t = getSetting({"mqttGroup", i});
  957. if (t.length() > 0) mqttSubscribeRaw(t.c_str());
  958. }
  959. }
  960. if (type == MQTT_MESSAGE_EVENT) {
  961. String t = mqttMagnitude((char *) topic);
  962. // magnitude is relay/#/pulse
  963. if (t.startsWith(MQTT_TOPIC_PULSE)) {
  964. unsigned int id = t.substring(strlen(MQTT_TOPIC_PULSE)+1).toInt();
  965. if (id >= relayCount()) {
  966. DEBUG_MSG_P(PSTR("[RELAY] Wrong relayID (%d)\n"), id);
  967. return;
  968. }
  969. unsigned long pulse = 1000 * atof(payload);
  970. if (0 == pulse) return;
  971. if (RELAY_PULSE_NONE != _relays[id].pulse) {
  972. DEBUG_MSG_P(PSTR("[RELAY] Overriding relay #%d pulse settings\n"), id);
  973. }
  974. _relays[id].pulse_ms = pulse;
  975. _relays[id].pulse = relayStatus(id) ? RELAY_PULSE_ON : RELAY_PULSE_OFF;
  976. relayToggle(id, true, false);
  977. return;
  978. }
  979. // magnitude is relay/#
  980. if (t.startsWith(MQTT_TOPIC_RELAY)) {
  981. // Get relay ID
  982. unsigned int id = t.substring(strlen(MQTT_TOPIC_RELAY)+1).toInt();
  983. if (id >= relayCount()) {
  984. DEBUG_MSG_P(PSTR("[RELAY] Wrong relayID (%d)\n"), id);
  985. return;
  986. }
  987. // Get value
  988. auto value = relayParsePayload(payload);
  989. if (value == PayloadStatus::Unknown) return;
  990. relayStatusWrap(id, value, false);
  991. return;
  992. }
  993. // Check group topics
  994. for (unsigned char i=0; i < _relays.size(); i++) {
  995. const String t = getSetting({"mqttGroup", i});
  996. if ((t.length() > 0) && t.equals(topic)) {
  997. auto value = relayParsePayload(payload);
  998. if (value == PayloadStatus::Unknown) return;
  999. if ((value == PayloadStatus::On) || (value == PayloadStatus::Off)) {
  1000. if (getSetting({"mqttGroupSync", i}, RELAY_GROUP_SYNC_NORMAL) == RELAY_GROUP_SYNC_INVERSE) {
  1001. value = _relayStatusInvert(value);
  1002. }
  1003. }
  1004. DEBUG_MSG_P(PSTR("[RELAY] Matched group topic for relayID %d\n"), i);
  1005. relayStatusWrap(i, value, true);
  1006. }
  1007. }
  1008. // Itead Sonoff IFAN02
  1009. #if defined (ITEAD_SONOFF_IFAN02)
  1010. if (t.startsWith(MQTT_TOPIC_SPEED)) {
  1011. setSpeed(atoi(payload));
  1012. }
  1013. #endif
  1014. }
  1015. if (type == MQTT_DISCONNECT_EVENT) {
  1016. for (unsigned char i=0; i < _relays.size(); i++){
  1017. const auto reaction = getSetting({"relayOnDisc", i}, 0);
  1018. if (1 == reaction) { // switch relay OFF
  1019. DEBUG_MSG_P(PSTR("[RELAY] Reset relay (%d) due to MQTT disconnection\n"), i);
  1020. relayStatusWrap(i, PayloadStatus::Off, false);
  1021. } else if(2 == reaction) { // switch relay ON
  1022. DEBUG_MSG_P(PSTR("[RELAY] Set relay (%d) due to MQTT disconnection\n"), i);
  1023. relayStatusWrap(i, PayloadStatus::On, false);
  1024. }
  1025. }
  1026. }
  1027. }
  1028. void relaySetupMQTT() {
  1029. mqttRegister(relayMQTTCallback);
  1030. }
  1031. #endif
  1032. void _relaySetupProvider() {
  1033. // TODO: implement something like `RelayProvider tuya_provider({.setup_cb = ..., .send_cb = ...})`?
  1034. // note of the function call order! relay code is initialized before tuya's, and the easiest
  1035. // way to accomplish that is to use ctor as a way to "register" callbacks even before setup() is called
  1036. #if TUYA_SUPPORT
  1037. Tuya::tuyaSetupSwitch();
  1038. #endif
  1039. }
  1040. //------------------------------------------------------------------------------
  1041. // Settings
  1042. //------------------------------------------------------------------------------
  1043. #if TERMINAL_SUPPORT
  1044. void _relayInitCommands() {
  1045. terminalRegisterCommand(F("RELAY"), [](const terminal::CommandContext& ctx) {
  1046. if (ctx.argc < 2) {
  1047. terminalError(F("Wrong arguments"));
  1048. return;
  1049. }
  1050. int id = ctx.argv[1].toInt();
  1051. if (id >= relayCount()) {
  1052. DEBUG_MSG_P(PSTR("-ERROR: Wrong relayID (%d)\n"), id);
  1053. return;
  1054. }
  1055. if (ctx.argc > 2) {
  1056. int value = ctx.argv[2].toInt();
  1057. if (value == 2) {
  1058. relayToggle(id);
  1059. } else {
  1060. relayStatus(id, value == 1);
  1061. }
  1062. }
  1063. DEBUG_MSG_P(PSTR("Status: %s\n"), _relays[id].target_status ? "true" : "false");
  1064. if (_relays[id].pulse != RELAY_PULSE_NONE) {
  1065. DEBUG_MSG_P(PSTR("Pulse: %s\n"), (_relays[id].pulse == RELAY_PULSE_ON) ? "ON" : "OFF");
  1066. DEBUG_MSG_P(PSTR("Pulse time: %d\n"), _relays[id].pulse_ms);
  1067. }
  1068. terminalOK();
  1069. });
  1070. #if 0
  1071. terminalRegisterCommand(F("RELAY.INFO"), [](const terminal::CommandContext&) {
  1072. DEBUG_MSG_P(PSTR(" cur tgt pin type reset lock delay_on delay_off pulse pulse_ms\n"));
  1073. DEBUG_MSG_P(PSTR(" --- --- --- ---- ----- ---- ---------- ----------- ----- ----------\n"));
  1074. for (unsigned char index = 0; index < _relays.size(); ++index) {
  1075. const auto& relay = _relays.at(index);
  1076. DEBUG_MSG_P(PSTR("%3u %3s %3s %3u %4u %5u %4u %10u %11u %5u %10u\n"),
  1077. index,
  1078. relay.current_status ? "ON" : "OFF",
  1079. relay.target_status ? "ON" : "OFF",
  1080. relay.pin, relay.type, relay.reset_pin,
  1081. relay.lock,
  1082. relay.delay_on, relay.delay_off,
  1083. relay.pulse, relay.pulse_ms
  1084. );
  1085. }
  1086. });
  1087. #endif
  1088. }
  1089. #endif // TERMINAL_SUPPORT
  1090. //------------------------------------------------------------------------------
  1091. // Setup
  1092. //------------------------------------------------------------------------------
  1093. void _relayLoop() {
  1094. _relayProcess(false);
  1095. _relayProcess(true);
  1096. #if WEB_SUPPORT
  1097. if (_relay_report_ws) {
  1098. wsPost(_relayWebSocketUpdate);
  1099. _relay_report_ws = false;
  1100. }
  1101. #endif
  1102. }
  1103. // Dummy relays for virtual light switches, Sonoff Dual, Sonoff RF Bridge and Tuya
  1104. void relaySetupDummy(size_t size, bool reconfigure) {
  1105. if (size == _relayDummy) return;
  1106. const size_t new_size = ((_relays.size() - _relayDummy) + size);
  1107. if (new_size > RelaysMax) return;
  1108. _relayDummy = size;
  1109. _relays.resize(new_size);
  1110. if (reconfigure) {
  1111. _relayConfigure();
  1112. }
  1113. #if BROKER_SUPPORT
  1114. ConfigBroker::Publish("relayDummy", String(int(size)));
  1115. #endif
  1116. }
  1117. void _relaySetupAdhoc() {
  1118. size_t relays [[gnu::unused]] = 0;
  1119. #if RELAY1_PIN != GPIO_NONE
  1120. ++relays;
  1121. #endif
  1122. #if RELAY2_PIN != GPIO_NONE
  1123. ++relays;
  1124. #endif
  1125. #if RELAY3_PIN != GPIO_NONE
  1126. ++relays;
  1127. #endif
  1128. #if RELAY4_PIN != GPIO_NONE
  1129. ++relays;
  1130. #endif
  1131. #if RELAY5_PIN != GPIO_NONE
  1132. ++relays;
  1133. #endif
  1134. #if RELAY6_PIN != GPIO_NONE
  1135. ++relays;
  1136. #endif
  1137. #if RELAY7_PIN != GPIO_NONE
  1138. ++relays;
  1139. #endif
  1140. #if RELAY8_PIN != GPIO_NONE
  1141. ++relays;
  1142. #endif
  1143. _relays.reserve(relays);
  1144. #if (RELAY_PROVIDER == RELAY_PROVIDER_RELAY) || (RELAY_PROVIDER == RELAY_PROVIDER_LIGHT)
  1145. using gpio_type = GpioPin;
  1146. #elif (RELAY_PROVIDER == RELAY_PROVIDER_MCP23S08)
  1147. using gpio_type = McpGpioPin;
  1148. #else
  1149. using gpio_type = DummyPin;
  1150. #endif
  1151. for (unsigned char id = 0; id < RelaysMax; ++id) {
  1152. const auto pin = _relayPin(id);
  1153. #if (RELAY_PROVIDER == RELAY_PROVIDER_MCP23S08)
  1154. if (!mcpGpioValid(pin)) {
  1155. #else
  1156. if (!gpioValid(pin)) {
  1157. #endif
  1158. break;
  1159. }
  1160. _relays.emplace_back(
  1161. new gpio_type(pin),
  1162. _relayType(id),
  1163. new gpio_type(_relayResetPin(id))
  1164. );
  1165. }
  1166. }
  1167. void relaySetup() {
  1168. // Ad-hoc relays
  1169. _relaySetupAdhoc();
  1170. // Dummy (virtual) relays
  1171. relaySetupDummy(getSetting("relayDummy", DUMMY_RELAY_COUNT));
  1172. _relaySetupProvider();
  1173. _relayBackwards();
  1174. _relayConfigure();
  1175. _relayBoot();
  1176. _relayLoop();
  1177. #if WEB_SUPPORT
  1178. relaySetupWS();
  1179. #endif
  1180. #if API_SUPPORT
  1181. relaySetupAPI();
  1182. #endif
  1183. #if MQTT_SUPPORT
  1184. relaySetupMQTT();
  1185. #endif
  1186. #if TERMINAL_SUPPORT
  1187. _relayInitCommands();
  1188. #endif
  1189. // Main callbacks
  1190. espurnaRegisterLoop(_relayLoop);
  1191. espurnaRegisterReload(_relayConfigure);
  1192. DEBUG_MSG_P(PSTR("[RELAY] Number of relays: %d\n"), _relays.size());
  1193. }
  1194. #endif // RELAY_SUPPORT == 1