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.

1118 lines
33 KiB

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