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.

1032 lines
30 KiB

6 years ago
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. wsOnAfterParseRegister(_relayConfigure);
  507. }
  508. #endif // WEB_SUPPORT
  509. //------------------------------------------------------------------------------
  510. // REST API
  511. //------------------------------------------------------------------------------
  512. #if API_SUPPORT
  513. void relaySetupAPI() {
  514. char key[20];
  515. // API entry points (protected with apikey)
  516. for (unsigned int relayID=0; relayID<relayCount(); relayID++) {
  517. snprintf_P(key, sizeof(key), PSTR("%s/%d"), MQTT_TOPIC_RELAY, relayID);
  518. apiRegister(key,
  519. [relayID](char * buffer, size_t len) {
  520. snprintf_P(buffer, len, PSTR("%d"), _relays[relayID].target_status ? 1 : 0);
  521. },
  522. [relayID](const char * payload) {
  523. unsigned char value = relayParsePayload(payload);
  524. if (value == 0xFF) {
  525. DEBUG_MSG_P(PSTR("[RELAY] Wrong payload (%s)\n"), payload);
  526. return;
  527. }
  528. if (value == 0) {
  529. relayStatus(relayID, false);
  530. } else if (value == 1) {
  531. relayStatus(relayID, true);
  532. } else if (value == 2) {
  533. relayToggle(relayID);
  534. }
  535. }
  536. );
  537. snprintf_P(key, sizeof(key), PSTR("%s/%d"), MQTT_TOPIC_PULSE, relayID);
  538. apiRegister(key,
  539. [relayID](char * buffer, size_t len) {
  540. dtostrf((double) _relays[relayID].pulse_ms / 1000, 1-len, 3, buffer);
  541. },
  542. [relayID](const char * payload) {
  543. unsigned long pulse = 1000 * String(payload).toFloat();
  544. if (0 == pulse) return;
  545. if (RELAY_PULSE_NONE != _relays[relayID].pulse) {
  546. DEBUG_MSG_P(PSTR("[RELAY] Overriding relay #%d pulse settings\n"), relayID);
  547. }
  548. _relays[relayID].pulse_ms = pulse;
  549. _relays[relayID].pulse = relayStatus(relayID) ? RELAY_PULSE_ON : RELAY_PULSE_OFF;
  550. relayToggle(relayID, true, false);
  551. }
  552. );
  553. #if defined(ITEAD_SONOFF_IFAN02)
  554. apiRegister(MQTT_TOPIC_SPEED,
  555. [relayID](char * buffer, size_t len) {
  556. snprintf(buffer, len, "%u", getSpeed());
  557. },
  558. [relayID](const char * payload) {
  559. setSpeed(atoi(payload));
  560. }
  561. );
  562. #endif
  563. }
  564. }
  565. #endif // API_SUPPORT
  566. //------------------------------------------------------------------------------
  567. // MQTT
  568. //------------------------------------------------------------------------------
  569. #if MQTT_SUPPORT
  570. void relayMQTT(unsigned char id) {
  571. if (id >= _relays.size()) return;
  572. // Send state topic
  573. if (_relays[id].report) {
  574. _relays[id].report = false;
  575. mqttSend(MQTT_TOPIC_RELAY, id, _relays[id].current_status ? RELAY_MQTT_ON : RELAY_MQTT_OFF);
  576. }
  577. // Check group topic
  578. if (_relays[id].group_report) {
  579. _relays[id].group_report = false;
  580. String t = getSetting("mqttGroup", id, "");
  581. if (t.length() > 0) {
  582. bool status = relayStatus(id);
  583. if (getSetting("mqttGroupInv", id, 0).toInt() == 1) status = !status;
  584. mqttSendRaw(t.c_str(), status ? RELAY_MQTT_ON : RELAY_MQTT_OFF);
  585. }
  586. }
  587. // Send speed for IFAN02
  588. #if defined (ITEAD_SONOFF_IFAN02)
  589. char buffer[5];
  590. snprintf(buffer, sizeof(buffer), "%u", getSpeed());
  591. mqttSend(MQTT_TOPIC_SPEED, buffer);
  592. #endif
  593. }
  594. void relayMQTT() {
  595. for (unsigned int id=0; id < _relays.size(); id++) {
  596. mqttSend(MQTT_TOPIC_RELAY, id, _relays[id].current_status ? RELAY_MQTT_ON : RELAY_MQTT_OFF);
  597. }
  598. }
  599. void relayStatusWrap(unsigned char id, unsigned char value, bool is_group_topic) {
  600. switch (value) {
  601. case 0:
  602. relayStatus(id, false, mqttForward(), !is_group_topic);
  603. break;
  604. case 1:
  605. relayStatus(id, true, mqttForward(), !is_group_topic);
  606. break;
  607. case 2:
  608. relayToggle(id, true, true);
  609. break;
  610. default:
  611. _relays[id].report = true;
  612. relayMQTT(id);
  613. break;
  614. }
  615. }
  616. void relayMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  617. if (type == MQTT_CONNECT_EVENT) {
  618. // Send status on connect
  619. #if not HEARTBEAT_REPORT_RELAY
  620. relayMQTT();
  621. #endif
  622. // Subscribe to own /set topic
  623. char relay_topic[strlen(MQTT_TOPIC_RELAY) + 3];
  624. snprintf_P(relay_topic, sizeof(relay_topic), PSTR("%s/+"), MQTT_TOPIC_RELAY);
  625. mqttSubscribe(relay_topic);
  626. // Subscribe to pulse topic
  627. char pulse_topic[strlen(MQTT_TOPIC_PULSE) + 3];
  628. snprintf_P(pulse_topic, sizeof(pulse_topic), PSTR("%s/+"), MQTT_TOPIC_PULSE);
  629. mqttSubscribe(pulse_topic);
  630. #if defined(ITEAD_SONOFF_IFAN02)
  631. mqttSubscribe(MQTT_TOPIC_SPEED);
  632. #endif
  633. // Subscribe to group topics
  634. for (unsigned int i=0; i < _relays.size(); i++) {
  635. String t = getSetting("mqttGroup", i, "");
  636. if (t.length() > 0) mqttSubscribeRaw(t.c_str());
  637. }
  638. }
  639. if (type == MQTT_MESSAGE_EVENT) {
  640. String t = mqttMagnitude((char *) topic);
  641. // magnitude is relay/#/pulse
  642. if (t.startsWith(MQTT_TOPIC_PULSE)) {
  643. unsigned int id = t.substring(strlen(MQTT_TOPIC_PULSE)+1).toInt();
  644. if (id >= relayCount()) {
  645. DEBUG_MSG_P(PSTR("[RELAY] Wrong relayID (%d)\n"), id);
  646. return;
  647. }
  648. unsigned long pulse = 1000 * String(payload).toFloat();
  649. if (0 == pulse) return;
  650. if (RELAY_PULSE_NONE != _relays[id].pulse) {
  651. DEBUG_MSG_P(PSTR("[RELAY] Overriding relay #%d pulse settings\n"), id);
  652. }
  653. _relays[id].pulse_ms = pulse;
  654. _relays[id].pulse = relayStatus(id) ? RELAY_PULSE_ON : RELAY_PULSE_OFF;
  655. relayToggle(id, true, false);
  656. return;
  657. }
  658. // magnitude is relay/#
  659. if (t.startsWith(MQTT_TOPIC_RELAY)) {
  660. // Get relay ID
  661. unsigned int id = t.substring(strlen(MQTT_TOPIC_RELAY)+1).toInt();
  662. if (id >= relayCount()) {
  663. DEBUG_MSG_P(PSTR("[RELAY] Wrong relayID (%d)\n"), id);
  664. return;
  665. }
  666. // Get value
  667. unsigned char value = relayParsePayload(payload);
  668. if (value == 0xFF) return;
  669. relayStatusWrap(id, value, false);
  670. return;
  671. }
  672. // Check group topics
  673. for (unsigned int i=0; i < _relays.size(); i++) {
  674. String t = getSetting("mqttGroup", i, "");
  675. if ((t.length() > 0) && t.equals(topic)) {
  676. unsigned char value = relayParsePayload(payload);
  677. if (value == 0xFF) return;
  678. if (value < 2) {
  679. if (getSetting("mqttGroupInv", i, 0).toInt() == 1) {
  680. value = 1 - value;
  681. }
  682. }
  683. DEBUG_MSG_P(PSTR("[RELAY] Matched group topic for relayID %d\n"), i);
  684. relayStatusWrap(i, value, true);
  685. }
  686. }
  687. // Itead Sonoff IFAN02
  688. #if defined (ITEAD_SONOFF_IFAN02)
  689. if (t.startsWith(MQTT_TOPIC_SPEED)) {
  690. setSpeed(atoi(payload));
  691. }
  692. #endif
  693. }
  694. if (type == MQTT_DISCONNECT_EVENT) {
  695. for (unsigned int i=0; i < _relays.size(); i++){
  696. int reaction = getSetting("rlyOnDisc", i, 0).toInt();
  697. if (1 == reaction) { // switch relay OFF
  698. DEBUG_MSG_P(PSTR("[RELAY] Reset relay (%d) due to MQTT disconnection\n"), i);
  699. relayStatusWrap(i, false, false);
  700. } else if(2 == reaction) { // switch relay ON
  701. DEBUG_MSG_P(PSTR("[RELAY] Set relay (%d) due to MQTT disconnection\n"), i);
  702. relayStatusWrap(i, true, false);
  703. }
  704. }
  705. }
  706. }
  707. void relaySetupMQTT() {
  708. mqttRegister(relayMQTTCallback);
  709. }
  710. #endif
  711. //------------------------------------------------------------------------------
  712. // InfluxDB
  713. //------------------------------------------------------------------------------
  714. #if INFLUXDB_SUPPORT
  715. void relayInfluxDB(unsigned char id) {
  716. if (id >= _relays.size()) return;
  717. idbSend(MQTT_TOPIC_RELAY, id, relayStatus(id) ? "1" : "0");
  718. }
  719. #endif
  720. //------------------------------------------------------------------------------
  721. // Settings
  722. //------------------------------------------------------------------------------
  723. #if TERMINAL_SUPPORT
  724. void _relayInitCommands() {
  725. settingsRegisterCommand(F("RELAY"), [](Embedis* e) {
  726. if (e->argc < 2) {
  727. DEBUG_MSG_P(PSTR("-ERROR: Wrong arguments\n"));
  728. return;
  729. }
  730. int id = String(e->argv[1]).toInt();
  731. if (id >= relayCount()) {
  732. DEBUG_MSG_P(PSTR("-ERROR: Wrong relayID (%d)\n"), id);
  733. return;
  734. }
  735. if (e->argc > 2) {
  736. int value = String(e->argv[2]).toInt();
  737. if (value == 2) {
  738. relayToggle(id);
  739. } else {
  740. relayStatus(id, value == 1);
  741. }
  742. }
  743. DEBUG_MSG_P(PSTR("Status: %s\n"), _relays[id].target_status ? "true" : "false");
  744. if (_relays[id].pulse != RELAY_PULSE_NONE) {
  745. DEBUG_MSG_P(PSTR("Pulse: %s\n"), (_relays[id].pulse == RELAY_PULSE_ON) ? "ON" : "OFF");
  746. DEBUG_MSG_P(PSTR("Pulse time: %d\n"), _relays[id].pulse_ms);
  747. }
  748. DEBUG_MSG_P(PSTR("+OK\n"));
  749. });
  750. }
  751. #endif // TERMINAL_SUPPORT
  752. //------------------------------------------------------------------------------
  753. // Setup
  754. //------------------------------------------------------------------------------
  755. void _relayLoop() {
  756. _relayProcess(false);
  757. _relayProcess(true);
  758. }
  759. void relaySetup() {
  760. _relayBackwards();
  761. _relayConfigure();
  762. _relayBoot();
  763. _relayLoop();
  764. settingsRegisterKeyCheck(_relayKeyCheck);
  765. espurnaRegisterLoop(_relayLoop);
  766. #if WEB_SUPPORT
  767. relaySetupWS();
  768. #endif
  769. #if API_SUPPORT
  770. relaySetupAPI();
  771. #endif
  772. #if MQTT_SUPPORT
  773. relaySetupMQTT();
  774. #endif
  775. #if TERMINAL_SUPPORT
  776. _relayInitCommands();
  777. #endif
  778. }