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.

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