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.

1100 lines
33 KiB

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