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.

1495 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. void relaySync(unsigned char id) {
  471. // No sync if none or only one relay
  472. if (_relays.size() < 2) return;
  473. // Do not go on if we are comming from a previous sync
  474. if (_relayRecursive) return;
  475. // Flag sync mode
  476. _relayRecursive = true;
  477. bool status = _relays[id].target_status;
  478. // If RELAY_SYNC_SAME all relays should have the same state
  479. if (_relay_sync_mode == RELAY_SYNC_SAME) {
  480. for (unsigned short i=0; i<_relays.size(); i++) {
  481. if (i != id) relayStatus(i, status);
  482. }
  483. // If RELAY_SYNC_FIRST all relays should have the same state as first if first changes
  484. } else if (_relay_sync_mode == RELAY_SYNC_FIRST) {
  485. if (id == 0) {
  486. for (unsigned short i=1; i<_relays.size(); i++) {
  487. relayStatus(i, status);
  488. }
  489. }
  490. } else if ((_relay_sync_mode == RELAY_SYNC_NONE_OR_ONE) || (_relay_sync_mode == RELAY_SYNC_ONE)) {
  491. // If NONE_OR_ONE or ONE and setting ON we should set OFF all the others
  492. if (status) {
  493. if (_relay_sync_mode != RELAY_SYNC_ANY) {
  494. for (unsigned short other_id=0; other_id<_relays.size(); other_id++) {
  495. if (other_id != id) {
  496. relayStatus(other_id, false);
  497. if (relayStatus(other_id)) {
  498. _relaySyncRelaysDelay(other_id, id);
  499. }
  500. }
  501. }
  502. }
  503. // If ONLY_ONE and setting OFF we should set ON the other one
  504. } else {
  505. if (_relay_sync_mode == RELAY_SYNC_ONE) {
  506. unsigned char other_id = (id + 1) % _relays.size();
  507. _relaySyncRelaysDelay(id, other_id);
  508. relayStatus(other_id, true);
  509. }
  510. }
  511. _relayLockAll();
  512. }
  513. // Unflag sync mode
  514. _relayRecursive = false;
  515. }
  516. void relaySave(bool eeprom) {
  517. const unsigned char count = constrain(relayCount(), 0, RELAYS_MAX);
  518. auto statuses = std::bitset<RELAYS_MAX>(0);
  519. for (unsigned int id = 0; id < count; ++id) {
  520. statuses.set(id, relayStatus(id));
  521. }
  522. const auto mask = _relayMask(statuses.to_ulong() & 0xffffffffu);
  523. DEBUG_MSG_P(PSTR("[RELAY] Setting relay mask: %s\n"), mask.as_string.c_str());
  524. // Persist only to rtcmem, unless requested to save to the eeprom
  525. _relayMaskRtcmem(mask);
  526. // The 'eeprom' flag controls whether we are commiting this change or not.
  527. // It is useful to set it to 'false' if the relay change triggering the
  528. // save involves a relay whose boot mode is independent from current mode,
  529. // thus storing the last relay value is not absolutely necessary.
  530. // Nevertheless, we store the value in the EEPROM buffer so it will be written
  531. // on the next commit.
  532. if (eeprom) {
  533. _relayMaskSettings(mask);
  534. // We are actually enqueuing the commit so it will be
  535. // executed on the main loop, in case this is called from a system context callback
  536. eepromCommit();
  537. }
  538. }
  539. void relaySave() {
  540. relaySave(false);
  541. }
  542. void relayToggle(unsigned char id, bool report, bool group_report) {
  543. if (id >= _relays.size()) return;
  544. relayStatus(id, !relayStatus(id), report, group_report);
  545. }
  546. void relayToggle(unsigned char id) {
  547. #if MQTT_SUPPORT
  548. relayToggle(id, mqttForward(), true);
  549. #else
  550. relayToggle(id, false, true);
  551. #endif
  552. }
  553. unsigned char relayCount() {
  554. return _relays.size();
  555. }
  556. PayloadStatus relayParsePayload(const char * payload) {
  557. #if MQTT_SUPPORT || API_SUPPORT
  558. return rpcParsePayload(payload, [](const char* payload) {
  559. if (_relay_rpc_payload_off.equals(payload)) return PayloadStatus::Off;
  560. if (_relay_rpc_payload_on.equals(payload)) return PayloadStatus::On;
  561. if (_relay_rpc_payload_toggle.equals(payload)) return PayloadStatus::Toggle;
  562. return PayloadStatus::Unknown;
  563. });
  564. #else
  565. return rpcParsePayload(payload);
  566. #endif
  567. }
  568. // BACKWARDS COMPATIBILITY
  569. void _relayBackwards() {
  570. #if defined(EEPROM_RELAY_STATUS)
  571. {
  572. uint8_t mask = EEPROMr.read(EEPROM_RELAY_STATUS);
  573. if (mask != 0xff) {
  574. _relayMaskSettings(static_cast<uint32_t>(mask));
  575. EEPROMr.write(EEPROM_RELAY_STATUS, 0xff);
  576. eepromCommit();
  577. }
  578. }
  579. #endif
  580. for (unsigned char id = 0; id < _relays.size(); ++id) {
  581. const settings_key_t key {"mqttGroupInv", id};
  582. if (!hasSetting(key)) continue;
  583. setSetting({"mqttGroupSync", id}, getSetting(key));
  584. delSetting(key);
  585. }
  586. }
  587. void _relayBoot() {
  588. _relayRecursive = true;
  589. const auto stored_mask = rtcmemStatus()
  590. ? _relayMaskRtcmem()
  591. : _relayMaskSettings();
  592. DEBUG_MSG_P(PSTR("[RELAY] Retrieving mask: %s\n"), stored_mask.as_string.c_str());
  593. auto mask = std::bitset<RELAYS_MAX>(stored_mask.as_u32);
  594. // Walk the relays
  595. unsigned char lock;
  596. bool status;
  597. for (unsigned char i=0; i<relayCount(); ++i) {
  598. const auto boot_mode = getSetting({"relayBoot", i}, RELAY_BOOT_MODE);
  599. DEBUG_MSG_P(PSTR("[RELAY] Relay #%u boot mode %d\n"), i, boot_mode);
  600. status = false;
  601. lock = RELAY_LOCK_DISABLED;
  602. switch (boot_mode) {
  603. case RELAY_BOOT_SAME:
  604. status = mask.test(i);
  605. break;
  606. case RELAY_BOOT_TOGGLE:
  607. mask.flip(i);
  608. status = mask[i];
  609. break;
  610. case RELAY_BOOT_LOCKED_ON:
  611. status = true;
  612. lock = RELAY_LOCK_ON;
  613. break;
  614. case RELAY_BOOT_LOCKED_OFF:
  615. lock = RELAY_LOCK_OFF;
  616. break;
  617. case RELAY_BOOT_ON:
  618. status = true;
  619. break;
  620. case RELAY_BOOT_OFF:
  621. default:
  622. break;
  623. }
  624. _relays[i].current_status = !status;
  625. _relays[i].target_status = status;
  626. _relays[i].change_start = millis();
  627. _relays[i].change_delay = status
  628. ? _relays[i].delay_on
  629. : _relays[i].delay_off;
  630. #if RELAY_PROVIDER == RELAY_PROVIDER_STM
  631. // XXX hack for correctly restoring relay state on boot
  632. // because of broken stm relay firmware
  633. _relays[i].change_delay = 3000 + 1000 * i;
  634. #endif
  635. _relays[i].lock = lock;
  636. }
  637. _relayRecursive = false;
  638. #if TUYA_SUPPORT
  639. Tuya::tuyaSyncSwitchStatus();
  640. #endif
  641. }
  642. void _relayConfigure() {
  643. for (unsigned char i = 0, relays = _relays.size() ; (i < relays); ++i) {
  644. _relays[i].pulse = getSetting({"relayPulse", i}, RELAY_PULSE_MODE);
  645. _relays[i].pulse_ms = 1000 * getSetting({"relayTime", i}, 0.);
  646. _relays[i].delay_on = getSetting({"relayDelayOn", i}, _relayDelayOn(i));
  647. _relays[i].delay_off = getSetting({"relayDelayOff", i}, _relayDelayOff(i));
  648. if (GPIO_NONE == _relays[i].pin) continue;
  649. pinMode(_relays[i].pin, OUTPUT);
  650. if (GPIO_NONE != _relays[i].reset_pin) {
  651. pinMode(_relays[i].reset_pin, OUTPUT);
  652. }
  653. if (_relays[i].type == RELAY_TYPE_INVERSE) {
  654. //set to high to block short opening of relay
  655. digitalWrite(_relays[i].pin, HIGH);
  656. }
  657. }
  658. _relay_flood_window = (1000 * getSetting("relayFloodTime", RELAY_FLOOD_WINDOW));
  659. _relay_flood_changes = getSetting("relayFloodChanges", RELAY_FLOOD_CHANGES);
  660. _relay_delay_interlock = getSetting("relayDelayInterlock", RELAY_DELAY_INTERLOCK);
  661. _relay_sync_mode = getSetting("relaySync", RELAY_SYNC);
  662. #if MQTT_SUPPORT || API_SUPPORT
  663. settingsProcessConfig({
  664. {_relay_rpc_payload_on, "relayPayloadOn", RELAY_MQTT_ON},
  665. {_relay_rpc_payload_off, "relayPayloadOff", RELAY_MQTT_OFF},
  666. {_relay_rpc_payload_toggle, "relayPayloadToggle", RELAY_MQTT_TOGGLE},
  667. });
  668. #endif // MQTT_SUPPORT
  669. }
  670. //------------------------------------------------------------------------------
  671. // WEBSOCKETS
  672. //------------------------------------------------------------------------------
  673. #if WEB_SUPPORT
  674. bool _relayWebSocketOnKeyCheck(const char * key, JsonVariant& value) {
  675. return (strncmp(key, "relay", 5) == 0);
  676. }
  677. void _relayWebSocketUpdate(JsonObject& root) {
  678. JsonObject& state = root.createNestedObject("relayState");
  679. state["size"] = relayCount();
  680. JsonArray& status = state.createNestedArray("status");
  681. JsonArray& lock = state.createNestedArray("lock");
  682. for (unsigned char i=0; i<relayCount(); i++) {
  683. status.add<uint8_t>(_relays[i].target_status);
  684. lock.add(_relays[i].lock);
  685. }
  686. }
  687. String _relayFriendlyName(unsigned char i) {
  688. String res = String("GPIO") + String(_relays[i].pin);
  689. if (GPIO_NONE == _relays[i].pin) {
  690. #if (RELAY_PROVIDER == RELAY_PROVIDER_LIGHT)
  691. uint8_t physical = _relays.size() - _relayDummy;
  692. if (i >= physical) {
  693. if (_relayDummy == lightChannels()) {
  694. res = String("CH") + String(i-physical);
  695. } else if (_relayDummy == (lightChannels() + 1u)) {
  696. if (physical == i) {
  697. res = String("Light");
  698. } else {
  699. res = String("CH") + String(i-1-physical);
  700. }
  701. } else {
  702. res = String("Light");
  703. }
  704. } else {
  705. res = String("?");
  706. }
  707. #else
  708. res = String("SW") + String(i);
  709. #endif
  710. }
  711. return res;
  712. }
  713. void _relayWebSocketSendRelays(JsonObject& root) {
  714. JsonObject& relays = root.createNestedObject("relayConfig");
  715. relays["size"] = relayCount();
  716. relays["start"] = 0;
  717. JsonArray& gpio = relays.createNestedArray("gpio");
  718. JsonArray& type = relays.createNestedArray("type");
  719. JsonArray& reset = relays.createNestedArray("reset");
  720. JsonArray& boot = relays.createNestedArray("boot");
  721. JsonArray& pulse = relays.createNestedArray("pulse");
  722. JsonArray& pulse_time = relays.createNestedArray("pulse_time");
  723. #if SCHEDULER_SUPPORT
  724. JsonArray& sch_last = relays.createNestedArray("sch_last");
  725. #endif
  726. #if MQTT_SUPPORT
  727. JsonArray& group = relays.createNestedArray("group");
  728. JsonArray& group_sync = relays.createNestedArray("group_sync");
  729. JsonArray& on_disconnect = relays.createNestedArray("on_disc");
  730. #endif
  731. for (unsigned char i=0; i<relayCount(); i++) {
  732. gpio.add(_relayFriendlyName(i));
  733. type.add(_relays[i].type);
  734. reset.add(_relays[i].reset_pin);
  735. boot.add(getSetting({"relayBoot", i}, RELAY_BOOT_MODE));
  736. pulse.add(_relays[i].pulse);
  737. pulse_time.add(_relays[i].pulse_ms / 1000.0);
  738. #if SCHEDULER_SUPPORT
  739. sch_last.add(getSetting({"relayLastSch", i}, SCHEDULER_RESTORE_LAST_SCHEDULE));
  740. #endif
  741. #if MQTT_SUPPORT
  742. group.add(getSetting({"mqttGroup", i}));
  743. group_sync.add(getSetting({"mqttGroupSync", i}, 0));
  744. on_disconnect.add(getSetting({"relayOnDisc", i}, 0));
  745. #endif
  746. }
  747. }
  748. void _relayWebSocketOnVisible(JsonObject& root) {
  749. if (relayCount() == 0) return;
  750. if (relayCount() > 1) {
  751. root["multirelayVisible"] = 1;
  752. root["relaySync"] = getSetting("relaySync", RELAY_SYNC);
  753. }
  754. root["relayVisible"] = 1;
  755. }
  756. void _relayWebSocketOnConnected(JsonObject& root) {
  757. if (relayCount() == 0) return;
  758. // Per-relay configuration
  759. _relayWebSocketSendRelays(root);
  760. }
  761. void _relayWebSocketOnAction(uint32_t client_id, const char * action, JsonObject& data) {
  762. if (strcmp(action, "relay") != 0) return;
  763. if (data.containsKey("status")) {
  764. unsigned int relayID = 0;
  765. if (data.containsKey("id") && data.is<int>("id")) {
  766. relayID = data["id"];
  767. }
  768. _relayHandlePayload(relayID, data["status"]);
  769. }
  770. }
  771. void relaySetupWS() {
  772. wsRegister()
  773. .onVisible(_relayWebSocketOnVisible)
  774. .onConnected(_relayWebSocketOnConnected)
  775. .onData(_relayWebSocketUpdate)
  776. .onAction(_relayWebSocketOnAction)
  777. .onKeyCheck(_relayWebSocketOnKeyCheck);
  778. }
  779. #endif // WEB_SUPPORT
  780. //------------------------------------------------------------------------------
  781. // REST API
  782. //------------------------------------------------------------------------------
  783. #if API_SUPPORT
  784. void relaySetupAPI() {
  785. char key[20];
  786. // API entry points (protected with apikey)
  787. for (unsigned int relayID=0; relayID<relayCount(); relayID++) {
  788. snprintf_P(key, sizeof(key), PSTR("%s/%d"), MQTT_TOPIC_RELAY, relayID);
  789. apiRegister(key,
  790. [relayID](char * buffer, size_t len) {
  791. snprintf_P(buffer, len, PSTR("%d"), _relays[relayID].target_status ? 1 : 0);
  792. },
  793. [relayID](const char * payload) {
  794. if (!_relayHandlePayload(relayID, payload)) {
  795. DEBUG_MSG_P(PSTR("[RELAY] Wrong payload (%s)\n"), payload);
  796. return;
  797. }
  798. }
  799. );
  800. snprintf_P(key, sizeof(key), PSTR("%s/%d"), MQTT_TOPIC_PULSE, relayID);
  801. apiRegister(key,
  802. [relayID](char * buffer, size_t len) {
  803. dtostrf((double) _relays[relayID].pulse_ms / 1000, 1, 3, buffer);
  804. },
  805. [relayID](const char * payload) {
  806. unsigned long pulse = 1000 * atof(payload);
  807. if (0 == pulse) return;
  808. if (RELAY_PULSE_NONE != _relays[relayID].pulse) {
  809. DEBUG_MSG_P(PSTR("[RELAY] Overriding relay #%d pulse settings\n"), relayID);
  810. }
  811. _relays[relayID].pulse_ms = pulse;
  812. _relays[relayID].pulse = relayStatus(relayID) ? RELAY_PULSE_ON : RELAY_PULSE_OFF;
  813. relayToggle(relayID, true, false);
  814. }
  815. );
  816. #if defined(ITEAD_SONOFF_IFAN02)
  817. apiRegister(MQTT_TOPIC_SPEED,
  818. [relayID](char * buffer, size_t len) {
  819. snprintf(buffer, len, "%u", getSpeed());
  820. },
  821. [relayID](const char * payload) {
  822. setSpeed(atoi(payload));
  823. }
  824. );
  825. #endif
  826. }
  827. }
  828. #endif // API_SUPPORT
  829. //------------------------------------------------------------------------------
  830. // MQTT
  831. //------------------------------------------------------------------------------
  832. #if MQTT_SUPPORT || API_SUPPORT
  833. const String& relayPayloadOn() {
  834. return _relay_rpc_payload_on;
  835. }
  836. const String& relayPayloadOff() {
  837. return _relay_rpc_payload_off;
  838. }
  839. const String& relayPayloadToggle() {
  840. return _relay_rpc_payload_toggle;
  841. }
  842. const char* relayPayload(PayloadStatus status) {
  843. switch (status) {
  844. case PayloadStatus::Off:
  845. return _relay_rpc_payload_off.c_str();
  846. case PayloadStatus::On:
  847. return _relay_rpc_payload_on.c_str();
  848. case PayloadStatus::Toggle:
  849. return _relay_rpc_payload_toggle.c_str();
  850. case PayloadStatus::Unknown:
  851. default:
  852. return "";
  853. }
  854. }
  855. #endif // MQTT_SUPPORT || API_SUPPORT
  856. #if MQTT_SUPPORT
  857. void _relayMQTTGroup(unsigned char id) {
  858. const String topic = getSetting({"mqttGroup", id});
  859. if (!topic.length()) return;
  860. const auto mode = getSetting({"mqttGroupSync", id}, RELAY_GROUP_SYNC_NORMAL);
  861. if (mode == RELAY_GROUP_SYNC_RECEIVEONLY) return;
  862. auto status = _relayStatusTyped(id);
  863. if (mode == RELAY_GROUP_SYNC_INVERSE) status = _relayStatusInvert(status);
  864. mqttSendRaw(topic.c_str(), relayPayload(status));
  865. }
  866. void relayMQTT(unsigned char id) {
  867. if (id >= _relays.size()) return;
  868. // Send state topic
  869. if (_relays[id].report) {
  870. _relays[id].report = false;
  871. mqttSend(MQTT_TOPIC_RELAY, id, relayPayload(_relayStatusTyped(id)));
  872. }
  873. // Check group topic
  874. if (_relays[id].group_report) {
  875. _relays[id].group_report = false;
  876. _relayMQTTGroup(id);
  877. }
  878. // Send speed for IFAN02
  879. #if defined (ITEAD_SONOFF_IFAN02)
  880. char buffer[5];
  881. snprintf(buffer, sizeof(buffer), "%u", getSpeed());
  882. mqttSend(MQTT_TOPIC_SPEED, buffer);
  883. #endif
  884. }
  885. void relayMQTT() {
  886. for (unsigned int id=0; id < _relays.size(); id++) {
  887. mqttSend(MQTT_TOPIC_RELAY, id, relayPayload(_relayStatusTyped(id)));
  888. }
  889. }
  890. void relayStatusWrap(unsigned char id, PayloadStatus value, bool is_group_topic) {
  891. #if MQTT_SUPPORT
  892. const auto forward = mqttForward();
  893. #else
  894. const auto forward = false;
  895. #endif
  896. switch (value) {
  897. case PayloadStatus::Off:
  898. relayStatus(id, false, forward, !is_group_topic);
  899. break;
  900. case PayloadStatus::On:
  901. relayStatus(id, true, forward, !is_group_topic);
  902. break;
  903. case PayloadStatus::Toggle:
  904. relayToggle(id, true, true);
  905. break;
  906. case PayloadStatus::Unknown:
  907. default:
  908. _relays[id].report = true;
  909. relayMQTT(id);
  910. break;
  911. }
  912. }
  913. void relayMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  914. if (type == MQTT_CONNECT_EVENT) {
  915. // Send status on connect
  916. #if (HEARTBEAT_MODE == HEARTBEAT_NONE) or (not HEARTBEAT_REPORT_RELAY)
  917. relayMQTT();
  918. #endif
  919. // Subscribe to own /set topic
  920. char relay_topic[strlen(MQTT_TOPIC_RELAY) + 3];
  921. snprintf_P(relay_topic, sizeof(relay_topic), PSTR("%s/+"), MQTT_TOPIC_RELAY);
  922. mqttSubscribe(relay_topic);
  923. // Subscribe to pulse topic
  924. char pulse_topic[strlen(MQTT_TOPIC_PULSE) + 3];
  925. snprintf_P(pulse_topic, sizeof(pulse_topic), PSTR("%s/+"), MQTT_TOPIC_PULSE);
  926. mqttSubscribe(pulse_topic);
  927. #if defined(ITEAD_SONOFF_IFAN02)
  928. mqttSubscribe(MQTT_TOPIC_SPEED);
  929. #endif
  930. // Subscribe to group topics
  931. for (unsigned char i=0; i < _relays.size(); i++) {
  932. const auto t = getSetting({"mqttGroup", i});
  933. if (t.length() > 0) mqttSubscribeRaw(t.c_str());
  934. }
  935. }
  936. if (type == MQTT_MESSAGE_EVENT) {
  937. String t = mqttMagnitude((char *) topic);
  938. // magnitude is relay/#/pulse
  939. if (t.startsWith(MQTT_TOPIC_PULSE)) {
  940. unsigned int id = t.substring(strlen(MQTT_TOPIC_PULSE)+1).toInt();
  941. if (id >= relayCount()) {
  942. DEBUG_MSG_P(PSTR("[RELAY] Wrong relayID (%d)\n"), id);
  943. return;
  944. }
  945. unsigned long pulse = 1000 * atof(payload);
  946. if (0 == pulse) return;
  947. if (RELAY_PULSE_NONE != _relays[id].pulse) {
  948. DEBUG_MSG_P(PSTR("[RELAY] Overriding relay #%d pulse settings\n"), id);
  949. }
  950. _relays[id].pulse_ms = pulse;
  951. _relays[id].pulse = relayStatus(id) ? RELAY_PULSE_ON : RELAY_PULSE_OFF;
  952. relayToggle(id, true, false);
  953. return;
  954. }
  955. // magnitude is relay/#
  956. if (t.startsWith(MQTT_TOPIC_RELAY)) {
  957. // Get relay ID
  958. unsigned int id = t.substring(strlen(MQTT_TOPIC_RELAY)+1).toInt();
  959. if (id >= relayCount()) {
  960. DEBUG_MSG_P(PSTR("[RELAY] Wrong relayID (%d)\n"), id);
  961. return;
  962. }
  963. // Get value
  964. auto value = relayParsePayload(payload);
  965. if (value == PayloadStatus::Unknown) return;
  966. relayStatusWrap(id, value, false);
  967. return;
  968. }
  969. // Check group topics
  970. for (unsigned char i=0; i < _relays.size(); i++) {
  971. const String t = getSetting({"mqttGroup", i});
  972. if ((t.length() > 0) && t.equals(topic)) {
  973. auto value = relayParsePayload(payload);
  974. if (value == PayloadStatus::Unknown) return;
  975. if ((value == PayloadStatus::On) || (value == PayloadStatus::Off)) {
  976. if (getSetting({"mqttGroupSync", i}, RELAY_GROUP_SYNC_NORMAL) == RELAY_GROUP_SYNC_INVERSE) {
  977. value = _relayStatusInvert(value);
  978. }
  979. }
  980. DEBUG_MSG_P(PSTR("[RELAY] Matched group topic for relayID %d\n"), i);
  981. relayStatusWrap(i, value, true);
  982. }
  983. }
  984. // Itead Sonoff IFAN02
  985. #if defined (ITEAD_SONOFF_IFAN02)
  986. if (t.startsWith(MQTT_TOPIC_SPEED)) {
  987. setSpeed(atoi(payload));
  988. }
  989. #endif
  990. }
  991. if (type == MQTT_DISCONNECT_EVENT) {
  992. for (unsigned char i=0; i < _relays.size(); i++){
  993. const auto reaction = getSetting({"relayOnDisc", i}, 0);
  994. if (1 == reaction) { // switch relay OFF
  995. DEBUG_MSG_P(PSTR("[RELAY] Reset relay (%d) due to MQTT disconnection\n"), i);
  996. relayStatusWrap(i, PayloadStatus::Off, false);
  997. } else if(2 == reaction) { // switch relay ON
  998. DEBUG_MSG_P(PSTR("[RELAY] Set relay (%d) due to MQTT disconnection\n"), i);
  999. relayStatusWrap(i, PayloadStatus::On, false);
  1000. }
  1001. }
  1002. }
  1003. }
  1004. void relaySetupMQTT() {
  1005. mqttRegister(relayMQTTCallback);
  1006. }
  1007. #endif
  1008. void _relaySetupProvider() {
  1009. // TODO: implement something like `RelayProvider tuya_provider({.setup_cb = ..., .send_cb = ...})`?
  1010. // note of the function call order! relay code is initialized before tuya's, and the easiest
  1011. // way to accomplish that is to use ctor as a way to "register" callbacks even before setup() is called
  1012. #if TUYA_SUPPORT
  1013. Tuya::tuyaSetupSwitch();
  1014. #endif
  1015. }
  1016. //------------------------------------------------------------------------------
  1017. // Settings
  1018. //------------------------------------------------------------------------------
  1019. #if TERMINAL_SUPPORT
  1020. void _relayInitCommands() {
  1021. terminalRegisterCommand(F("RELAY"), [](const terminal::CommandContext& ctx) {
  1022. if (ctx.argc < 2) {
  1023. terminalError(F("Wrong arguments"));
  1024. return;
  1025. }
  1026. int id = ctx.argv[1].toInt();
  1027. if (id >= relayCount()) {
  1028. DEBUG_MSG_P(PSTR("-ERROR: Wrong relayID (%d)\n"), id);
  1029. return;
  1030. }
  1031. if (ctx.argc > 2) {
  1032. int value = ctx.argv[2].toInt();
  1033. if (value == 2) {
  1034. relayToggle(id);
  1035. } else {
  1036. relayStatus(id, value == 1);
  1037. }
  1038. }
  1039. DEBUG_MSG_P(PSTR("Status: %s\n"), _relays[id].target_status ? "true" : "false");
  1040. if (_relays[id].pulse != RELAY_PULSE_NONE) {
  1041. DEBUG_MSG_P(PSTR("Pulse: %s\n"), (_relays[id].pulse == RELAY_PULSE_ON) ? "ON" : "OFF");
  1042. DEBUG_MSG_P(PSTR("Pulse time: %d\n"), _relays[id].pulse_ms);
  1043. }
  1044. terminalOK();
  1045. });
  1046. #if 0
  1047. terminalRegisterCommand(F("RELAY.INFO"), [](const terminal::CommandContext&) {
  1048. DEBUG_MSG_P(PSTR(" cur tgt pin type reset lock delay_on delay_off pulse pulse_ms\n"));
  1049. DEBUG_MSG_P(PSTR(" --- --- --- ---- ----- ---- ---------- ----------- ----- ----------\n"));
  1050. for (unsigned char index = 0; index < _relays.size(); ++index) {
  1051. const auto& relay = _relays.at(index);
  1052. DEBUG_MSG_P(PSTR("%3u %3s %3s %3u %4u %5u %4u %10u %11u %5u %10u\n"),
  1053. index,
  1054. relay.current_status ? "ON" : "OFF",
  1055. relay.target_status ? "ON" : "OFF",
  1056. relay.pin, relay.type, relay.reset_pin,
  1057. relay.lock,
  1058. relay.delay_on, relay.delay_off,
  1059. relay.pulse, relay.pulse_ms
  1060. );
  1061. }
  1062. });
  1063. #endif
  1064. }
  1065. #endif // TERMINAL_SUPPORT
  1066. //------------------------------------------------------------------------------
  1067. // Setup
  1068. //------------------------------------------------------------------------------
  1069. void _relayLoop() {
  1070. _relayProcess(false);
  1071. _relayProcess(true);
  1072. #if WEB_SUPPORT
  1073. if (_relay_report_ws) {
  1074. wsPost(_relayWebSocketUpdate);
  1075. _relay_report_ws = false;
  1076. }
  1077. #endif
  1078. }
  1079. // Dummy relays for virtual light switches, Sonoff Dual, Sonoff RF Bridge and Tuya
  1080. void relaySetupDummy(size_t size, bool reconfigure) {
  1081. if (size == _relayDummy) return;
  1082. const size_t new_size = ((_relays.size() - _relayDummy) + size);
  1083. if (new_size > RELAYS_MAX) return;
  1084. _relayDummy = size;
  1085. _relays.resize(new_size);
  1086. if (reconfigure) {
  1087. _relayConfigure();
  1088. }
  1089. #if BROKER_SUPPORT
  1090. ConfigBroker::Publish("relayDummy", String(int(size)));
  1091. #endif
  1092. }
  1093. void _relaySetupAdhoc() {
  1094. size_t relays = 0;
  1095. #if RELAY1_PIN != GPIO_NONE
  1096. ++relays;
  1097. #endif
  1098. #if RELAY2_PIN != GPIO_NONE
  1099. ++relays;
  1100. #endif
  1101. #if RELAY3_PIN != GPIO_NONE
  1102. ++relays;
  1103. #endif
  1104. #if RELAY4_PIN != GPIO_NONE
  1105. ++relays;
  1106. #endif
  1107. #if RELAY5_PIN != GPIO_NONE
  1108. ++relays;
  1109. #endif
  1110. #if RELAY6_PIN != GPIO_NONE
  1111. ++relays;
  1112. #endif
  1113. #if RELAY7_PIN != GPIO_NONE
  1114. ++relays;
  1115. #endif
  1116. #if RELAY8_PIN != GPIO_NONE
  1117. ++relays;
  1118. #endif
  1119. _relays.reserve(relays);
  1120. for (unsigned char id = 0; id < relays; ++id) {
  1121. _relays.emplace_back(id);
  1122. }
  1123. }
  1124. void relaySetup() {
  1125. // Ad-hoc relays
  1126. _relaySetupAdhoc();
  1127. // Dummy (virtual) relays
  1128. relaySetupDummy(getSetting("relayDummy", DUMMY_RELAY_COUNT));
  1129. _relaySetupProvider();
  1130. _relayBackwards();
  1131. _relayConfigure();
  1132. _relayBoot();
  1133. _relayLoop();
  1134. #if WEB_SUPPORT
  1135. relaySetupWS();
  1136. #endif
  1137. #if API_SUPPORT
  1138. relaySetupAPI();
  1139. #endif
  1140. #if MQTT_SUPPORT
  1141. relaySetupMQTT();
  1142. #endif
  1143. #if TERMINAL_SUPPORT
  1144. _relayInitCommands();
  1145. #endif
  1146. // Main callbacks
  1147. espurnaRegisterLoop(_relayLoop);
  1148. espurnaRegisterReload(_relayConfigure);
  1149. DEBUG_MSG_P(PSTR("[RELAY] Number of relays: %d\n"), _relays.size());
  1150. }
  1151. #endif // RELAY_SUPPORT == 1