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.

1067 lines
31 KiB

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