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.

1162 lines
34 KiB

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