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.

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