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.

1107 lines
33 KiB

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