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.

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