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.

1022 lines
30 KiB

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