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.

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