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.

1034 lines
30 KiB

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