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.

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