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.

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