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.

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