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.

1501 lines
44 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. #if defined(EEPROM_RELAY_STATUS)
  575. {
  576. uint8_t mask = EEPROMr.read(EEPROM_RELAY_STATUS);
  577. if (mask != 0xff) {
  578. _relayMaskSettings(static_cast<uint32_t>(mask));
  579. EEPROMr.write(EEPROM_RELAY_STATUS, 0xff);
  580. eepromCommit();
  581. }
  582. }
  583. #endif
  584. for (unsigned char id = 0; id < _relays.size(); ++id) {
  585. const settings_key_t key {"mqttGroupInv", id};
  586. if (!hasSetting(key)) continue;
  587. setSetting({"mqttGroupSync", id}, getSetting(key));
  588. delSetting(key);
  589. }
  590. }
  591. void _relayBoot() {
  592. _relayRecursive = true;
  593. const auto stored_mask = rtcmemStatus()
  594. ? _relayMaskRtcmem()
  595. : _relayMaskSettings();
  596. DEBUG_MSG_P(PSTR("[RELAY] Retrieving mask: %s\n"), stored_mask.as_string.c_str());
  597. auto mask = std::bitset<RELAYS_MAX>(stored_mask.as_u32);
  598. // Walk the relays
  599. unsigned char lock;
  600. bool status;
  601. for (unsigned char i=0; i<relayCount(); ++i) {
  602. const auto boot_mode = getSetting({"relayBoot", i}, RELAY_BOOT_MODE);
  603. DEBUG_MSG_P(PSTR("[RELAY] Relay #%u boot mode %d\n"), i, boot_mode);
  604. status = false;
  605. lock = RELAY_LOCK_DISABLED;
  606. switch (boot_mode) {
  607. case RELAY_BOOT_SAME:
  608. status = mask.test(i);
  609. break;
  610. case RELAY_BOOT_TOGGLE:
  611. mask.flip(i);
  612. status = mask[i];
  613. break;
  614. case RELAY_BOOT_LOCKED_ON:
  615. status = true;
  616. lock = RELAY_LOCK_ON;
  617. break;
  618. case RELAY_BOOT_LOCKED_OFF:
  619. lock = RELAY_LOCK_OFF;
  620. break;
  621. case RELAY_BOOT_ON:
  622. status = true;
  623. break;
  624. case RELAY_BOOT_OFF:
  625. default:
  626. break;
  627. }
  628. _relays[i].current_status = !status;
  629. _relays[i].target_status = status;
  630. _relays[i].change_start = millis();
  631. _relays[i].change_delay = status
  632. ? _relays[i].delay_on
  633. : _relays[i].delay_off;
  634. #if RELAY_PROVIDER == RELAY_PROVIDER_STM
  635. // XXX hack for correctly restoring relay state on boot
  636. // because of broken stm relay firmware
  637. _relays[i].change_delay = 3000 + 1000 * i;
  638. #endif
  639. _relays[i].lock = lock;
  640. }
  641. _relayRecursive = false;
  642. #if TUYA_SUPPORT
  643. Tuya::tuyaSyncSwitchStatus();
  644. #endif
  645. }
  646. void _relayConfigure() {
  647. for (unsigned char i = 0, relays = _relays.size() ; (i < relays); ++i) {
  648. _relays[i].pulse = getSetting({"relayPulse", i}, RELAY_PULSE_MODE);
  649. _relays[i].pulse_ms = 1000 * getSetting({"relayTime", i}, 0.);
  650. _relays[i].delay_on = getSetting({"relayDelayOn", i}, _relayDelayOn(i));
  651. _relays[i].delay_off = getSetting({"relayDelayOff", i}, _relayDelayOff(i));
  652. if (GPIO_NONE == _relays[i].pin) continue;
  653. pinMode(_relays[i].pin, OUTPUT);
  654. if (GPIO_NONE != _relays[i].reset_pin) {
  655. pinMode(_relays[i].reset_pin, OUTPUT);
  656. }
  657. if (_relays[i].type == RELAY_TYPE_INVERSE) {
  658. //set to high to block short opening of relay
  659. digitalWrite(_relays[i].pin, 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);
  694. if (GPIO_NONE == _relays[i].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);
  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. char key[20];
  791. // API entry points (protected with apikey)
  792. for (unsigned int relayID=0; relayID<relayCount(); relayID++) {
  793. snprintf_P(key, sizeof(key), PSTR("%s/%d"), MQTT_TOPIC_RELAY, relayID);
  794. apiRegister(key,
  795. [relayID](char * buffer, size_t len) {
  796. snprintf_P(buffer, len, PSTR("%d"), _relays[relayID].target_status ? 1 : 0);
  797. },
  798. [relayID](const char * payload) {
  799. if (!_relayHandlePayload(relayID, payload)) {
  800. DEBUG_MSG_P(PSTR("[RELAY] Wrong payload (%s)\n"), payload);
  801. return;
  802. }
  803. }
  804. );
  805. snprintf_P(key, sizeof(key), PSTR("%s/%d"), MQTT_TOPIC_PULSE, relayID);
  806. apiRegister(key,
  807. [relayID](char * buffer, size_t len) {
  808. dtostrf((double) _relays[relayID].pulse_ms / 1000, 1, 3, buffer);
  809. },
  810. [relayID](const char * payload) {
  811. unsigned long pulse = 1000 * atof(payload);
  812. if (0 == pulse) return;
  813. if (RELAY_PULSE_NONE != _relays[relayID].pulse) {
  814. DEBUG_MSG_P(PSTR("[RELAY] Overriding relay #%d pulse settings\n"), relayID);
  815. }
  816. _relays[relayID].pulse_ms = pulse;
  817. _relays[relayID].pulse = relayStatus(relayID) ? RELAY_PULSE_ON : RELAY_PULSE_OFF;
  818. relayToggle(relayID, true, false);
  819. }
  820. );
  821. #if defined(ITEAD_SONOFF_IFAN02)
  822. apiRegister(MQTT_TOPIC_SPEED,
  823. [relayID](char * buffer, size_t len) {
  824. snprintf(buffer, len, "%u", getSpeed());
  825. },
  826. [relayID](const char * payload) {
  827. setSpeed(atoi(payload));
  828. }
  829. );
  830. #endif
  831. }
  832. }
  833. #endif // API_SUPPORT
  834. //------------------------------------------------------------------------------
  835. // MQTT
  836. //------------------------------------------------------------------------------
  837. #if MQTT_SUPPORT || API_SUPPORT
  838. const String& relayPayloadOn() {
  839. return _relay_rpc_payload_on;
  840. }
  841. const String& relayPayloadOff() {
  842. return _relay_rpc_payload_off;
  843. }
  844. const String& relayPayloadToggle() {
  845. return _relay_rpc_payload_toggle;
  846. }
  847. const char* relayPayload(PayloadStatus status) {
  848. switch (status) {
  849. case PayloadStatus::Off:
  850. return _relay_rpc_payload_off.c_str();
  851. case PayloadStatus::On:
  852. return _relay_rpc_payload_on.c_str();
  853. case PayloadStatus::Toggle:
  854. return _relay_rpc_payload_toggle.c_str();
  855. case PayloadStatus::Unknown:
  856. default:
  857. return "";
  858. }
  859. }
  860. #endif // MQTT_SUPPORT || API_SUPPORT
  861. #if MQTT_SUPPORT
  862. void _relayMQTTGroup(unsigned char id) {
  863. const String topic = getSetting({"mqttGroup", id});
  864. if (!topic.length()) return;
  865. const auto mode = getSetting({"mqttGroupSync", id}, RELAY_GROUP_SYNC_NORMAL);
  866. if (mode == RELAY_GROUP_SYNC_RECEIVEONLY) return;
  867. auto status = _relayStatusTyped(id);
  868. if (mode == RELAY_GROUP_SYNC_INVERSE) status = _relayStatusInvert(status);
  869. mqttSendRaw(topic.c_str(), relayPayload(status));
  870. }
  871. void relayMQTT(unsigned char id) {
  872. if (id >= _relays.size()) return;
  873. // Send state topic
  874. if (_relays[id].report) {
  875. _relays[id].report = false;
  876. mqttSend(MQTT_TOPIC_RELAY, id, relayPayload(_relayStatusTyped(id)));
  877. }
  878. // Check group topic
  879. if (_relays[id].group_report) {
  880. _relays[id].group_report = false;
  881. _relayMQTTGroup(id);
  882. }
  883. // Send speed for IFAN02
  884. #if defined (ITEAD_SONOFF_IFAN02)
  885. char buffer[5];
  886. snprintf(buffer, sizeof(buffer), "%u", getSpeed());
  887. mqttSend(MQTT_TOPIC_SPEED, buffer);
  888. #endif
  889. }
  890. void relayMQTT() {
  891. for (unsigned int id=0; id < _relays.size(); id++) {
  892. mqttSend(MQTT_TOPIC_RELAY, id, relayPayload(_relayStatusTyped(id)));
  893. }
  894. }
  895. void relayStatusWrap(unsigned char id, PayloadStatus value, bool is_group_topic) {
  896. #if MQTT_SUPPORT
  897. const auto forward = mqttForward();
  898. #else
  899. const auto forward = false;
  900. #endif
  901. switch (value) {
  902. case PayloadStatus::Off:
  903. relayStatus(id, false, forward, !is_group_topic);
  904. break;
  905. case PayloadStatus::On:
  906. relayStatus(id, true, forward, !is_group_topic);
  907. break;
  908. case PayloadStatus::Toggle:
  909. relayToggle(id, true, true);
  910. break;
  911. case PayloadStatus::Unknown:
  912. default:
  913. _relays[id].report = true;
  914. relayMQTT(id);
  915. break;
  916. }
  917. }
  918. void relayMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  919. if (type == MQTT_CONNECT_EVENT) {
  920. // Send status on connect
  921. #if (HEARTBEAT_MODE == HEARTBEAT_NONE) or (not HEARTBEAT_REPORT_RELAY)
  922. relayMQTT();
  923. #endif
  924. // Subscribe to own /set topic
  925. char relay_topic[strlen(MQTT_TOPIC_RELAY) + 3];
  926. snprintf_P(relay_topic, sizeof(relay_topic), PSTR("%s/+"), MQTT_TOPIC_RELAY);
  927. mqttSubscribe(relay_topic);
  928. // Subscribe to pulse topic
  929. char pulse_topic[strlen(MQTT_TOPIC_PULSE) + 3];
  930. snprintf_P(pulse_topic, sizeof(pulse_topic), PSTR("%s/+"), MQTT_TOPIC_PULSE);
  931. mqttSubscribe(pulse_topic);
  932. #if defined(ITEAD_SONOFF_IFAN02)
  933. mqttSubscribe(MQTT_TOPIC_SPEED);
  934. #endif
  935. // Subscribe to group topics
  936. for (unsigned char i=0; i < _relays.size(); i++) {
  937. const auto t = getSetting({"mqttGroup", i});
  938. if (t.length() > 0) mqttSubscribeRaw(t.c_str());
  939. }
  940. }
  941. if (type == MQTT_MESSAGE_EVENT) {
  942. String t = mqttMagnitude((char *) topic);
  943. // magnitude is relay/#/pulse
  944. if (t.startsWith(MQTT_TOPIC_PULSE)) {
  945. unsigned int id = t.substring(strlen(MQTT_TOPIC_PULSE)+1).toInt();
  946. if (id >= relayCount()) {
  947. DEBUG_MSG_P(PSTR("[RELAY] Wrong relayID (%d)\n"), id);
  948. return;
  949. }
  950. unsigned long pulse = 1000 * atof(payload);
  951. if (0 == pulse) return;
  952. if (RELAY_PULSE_NONE != _relays[id].pulse) {
  953. DEBUG_MSG_P(PSTR("[RELAY] Overriding relay #%d pulse settings\n"), id);
  954. }
  955. _relays[id].pulse_ms = pulse;
  956. _relays[id].pulse = relayStatus(id) ? RELAY_PULSE_ON : RELAY_PULSE_OFF;
  957. relayToggle(id, true, false);
  958. return;
  959. }
  960. // magnitude is relay/#
  961. if (t.startsWith(MQTT_TOPIC_RELAY)) {
  962. // Get relay ID
  963. unsigned int id = t.substring(strlen(MQTT_TOPIC_RELAY)+1).toInt();
  964. if (id >= relayCount()) {
  965. DEBUG_MSG_P(PSTR("[RELAY] Wrong relayID (%d)\n"), id);
  966. return;
  967. }
  968. // Get value
  969. auto value = relayParsePayload(payload);
  970. if (value == PayloadStatus::Unknown) return;
  971. relayStatusWrap(id, value, false);
  972. return;
  973. }
  974. // Check group topics
  975. for (unsigned char i=0; i < _relays.size(); i++) {
  976. const String t = getSetting({"mqttGroup", i});
  977. if ((t.length() > 0) && t.equals(topic)) {
  978. auto value = relayParsePayload(payload);
  979. if (value == PayloadStatus::Unknown) return;
  980. if ((value == PayloadStatus::On) || (value == PayloadStatus::Off)) {
  981. if (getSetting({"mqttGroupSync", i}, RELAY_GROUP_SYNC_NORMAL) == RELAY_GROUP_SYNC_INVERSE) {
  982. value = _relayStatusInvert(value);
  983. }
  984. }
  985. DEBUG_MSG_P(PSTR("[RELAY] Matched group topic for relayID %d\n"), i);
  986. relayStatusWrap(i, value, true);
  987. }
  988. }
  989. // Itead Sonoff IFAN02
  990. #if defined (ITEAD_SONOFF_IFAN02)
  991. if (t.startsWith(MQTT_TOPIC_SPEED)) {
  992. setSpeed(atoi(payload));
  993. }
  994. #endif
  995. }
  996. if (type == MQTT_DISCONNECT_EVENT) {
  997. for (unsigned char i=0; i < _relays.size(); i++){
  998. const auto reaction = getSetting({"relayOnDisc", i}, 0);
  999. if (1 == reaction) { // switch relay OFF
  1000. DEBUG_MSG_P(PSTR("[RELAY] Reset relay (%d) due to MQTT disconnection\n"), i);
  1001. relayStatusWrap(i, PayloadStatus::Off, false);
  1002. } else if(2 == reaction) { // switch relay ON
  1003. DEBUG_MSG_P(PSTR("[RELAY] Set relay (%d) due to MQTT disconnection\n"), i);
  1004. relayStatusWrap(i, PayloadStatus::On, false);
  1005. }
  1006. }
  1007. }
  1008. }
  1009. void relaySetupMQTT() {
  1010. mqttRegister(relayMQTTCallback);
  1011. }
  1012. #endif
  1013. void _relaySetupProvider() {
  1014. // TODO: implement something like `RelayProvider tuya_provider({.setup_cb = ..., .send_cb = ...})`?
  1015. // note of the function call order! relay code is initialized before tuya's, and the easiest
  1016. // way to accomplish that is to use ctor as a way to "register" callbacks even before setup() is called
  1017. #if TUYA_SUPPORT
  1018. Tuya::tuyaSetupSwitch();
  1019. #endif
  1020. }
  1021. //------------------------------------------------------------------------------
  1022. // Settings
  1023. //------------------------------------------------------------------------------
  1024. #if TERMINAL_SUPPORT
  1025. void _relayInitCommands() {
  1026. terminalRegisterCommand(F("RELAY"), [](const terminal::CommandContext& ctx) {
  1027. if (ctx.argc < 2) {
  1028. terminalError(F("Wrong arguments"));
  1029. return;
  1030. }
  1031. int id = ctx.argv[1].toInt();
  1032. if (id >= relayCount()) {
  1033. DEBUG_MSG_P(PSTR("-ERROR: Wrong relayID (%d)\n"), id);
  1034. return;
  1035. }
  1036. if (ctx.argc > 2) {
  1037. int value = ctx.argv[2].toInt();
  1038. if (value == 2) {
  1039. relayToggle(id);
  1040. } else {
  1041. relayStatus(id, value == 1);
  1042. }
  1043. }
  1044. DEBUG_MSG_P(PSTR("Status: %s\n"), _relays[id].target_status ? "true" : "false");
  1045. if (_relays[id].pulse != RELAY_PULSE_NONE) {
  1046. DEBUG_MSG_P(PSTR("Pulse: %s\n"), (_relays[id].pulse == RELAY_PULSE_ON) ? "ON" : "OFF");
  1047. DEBUG_MSG_P(PSTR("Pulse time: %d\n"), _relays[id].pulse_ms);
  1048. }
  1049. terminalOK();
  1050. });
  1051. #if 0
  1052. terminalRegisterCommand(F("RELAY.INFO"), [](const terminal::CommandContext&) {
  1053. DEBUG_MSG_P(PSTR(" cur tgt pin type reset lock delay_on delay_off pulse pulse_ms\n"));
  1054. DEBUG_MSG_P(PSTR(" --- --- --- ---- ----- ---- ---------- ----------- ----- ----------\n"));
  1055. for (unsigned char index = 0; index < _relays.size(); ++index) {
  1056. const auto& relay = _relays.at(index);
  1057. DEBUG_MSG_P(PSTR("%3u %3s %3s %3u %4u %5u %4u %10u %11u %5u %10u\n"),
  1058. index,
  1059. relay.current_status ? "ON" : "OFF",
  1060. relay.target_status ? "ON" : "OFF",
  1061. relay.pin, relay.type, relay.reset_pin,
  1062. relay.lock,
  1063. relay.delay_on, relay.delay_off,
  1064. relay.pulse, relay.pulse_ms
  1065. );
  1066. }
  1067. });
  1068. #endif
  1069. }
  1070. #endif // TERMINAL_SUPPORT
  1071. //------------------------------------------------------------------------------
  1072. // Setup
  1073. //------------------------------------------------------------------------------
  1074. void _relayLoop() {
  1075. _relayProcess(false);
  1076. _relayProcess(true);
  1077. #if WEB_SUPPORT
  1078. if (_relay_report_ws) {
  1079. wsPost(_relayWebSocketUpdate);
  1080. _relay_report_ws = false;
  1081. }
  1082. #endif
  1083. }
  1084. // Dummy relays for virtual light switches, Sonoff Dual, Sonoff RF Bridge and Tuya
  1085. void relaySetupDummy(size_t size, bool reconfigure) {
  1086. if (size == _relayDummy) return;
  1087. const size_t new_size = ((_relays.size() - _relayDummy) + size);
  1088. if (new_size > RELAYS_MAX) return;
  1089. _relayDummy = size;
  1090. _relays.resize(new_size);
  1091. if (reconfigure) {
  1092. _relayConfigure();
  1093. }
  1094. #if BROKER_SUPPORT
  1095. ConfigBroker::Publish("relayDummy", String(int(size)));
  1096. #endif
  1097. }
  1098. void _relaySetupAdhoc() {
  1099. size_t relays = 0;
  1100. #if RELAY1_PIN != GPIO_NONE
  1101. ++relays;
  1102. #endif
  1103. #if RELAY2_PIN != GPIO_NONE
  1104. ++relays;
  1105. #endif
  1106. #if RELAY3_PIN != GPIO_NONE
  1107. ++relays;
  1108. #endif
  1109. #if RELAY4_PIN != GPIO_NONE
  1110. ++relays;
  1111. #endif
  1112. #if RELAY5_PIN != GPIO_NONE
  1113. ++relays;
  1114. #endif
  1115. #if RELAY6_PIN != GPIO_NONE
  1116. ++relays;
  1117. #endif
  1118. #if RELAY7_PIN != GPIO_NONE
  1119. ++relays;
  1120. #endif
  1121. #if RELAY8_PIN != GPIO_NONE
  1122. ++relays;
  1123. #endif
  1124. _relays.reserve(relays);
  1125. for (unsigned char id = 0; id < relays; ++id) {
  1126. _relays.emplace_back(id);
  1127. }
  1128. }
  1129. void relaySetup() {
  1130. // Ad-hoc relays
  1131. _relaySetupAdhoc();
  1132. // Dummy (virtual) relays
  1133. relaySetupDummy(getSetting("relayDummy", DUMMY_RELAY_COUNT));
  1134. _relaySetupProvider();
  1135. _relayBackwards();
  1136. _relayConfigure();
  1137. _relayBoot();
  1138. _relayLoop();
  1139. #if WEB_SUPPORT
  1140. relaySetupWS();
  1141. #endif
  1142. #if API_SUPPORT
  1143. relaySetupAPI();
  1144. #endif
  1145. #if MQTT_SUPPORT
  1146. relaySetupMQTT();
  1147. #endif
  1148. #if TERMINAL_SUPPORT
  1149. _relayInitCommands();
  1150. #endif
  1151. // Main callbacks
  1152. espurnaRegisterLoop(_relayLoop);
  1153. espurnaRegisterReload(_relayConfigure);
  1154. DEBUG_MSG_P(PSTR("[RELAY] Number of relays: %d\n"), _relays.size());
  1155. }
  1156. #endif // RELAY_SUPPORT == 1