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.

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