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.

724 lines
20 KiB

  1. /*
  2. RELAY MODULE
  3. Copyright (C) 2016-2017 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #include <EEPROM.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;
  14. unsigned char reset_pin;
  15. unsigned char led;
  16. unsigned long delay_on;
  17. unsigned long delay_off;
  18. // Status variables
  19. bool current_status;
  20. bool target_status;
  21. unsigned int fw_start;
  22. unsigned char fw_count;
  23. unsigned int change_time;
  24. bool report;
  25. bool group_report;
  26. // Helping objects
  27. Ticker pulseTicker;
  28. } relay_t;
  29. std::vector<relay_t> _relays;
  30. bool recursive = false;
  31. Ticker _relaySaveTicker;
  32. // -----------------------------------------------------------------------------
  33. // RELAY PROVIDERS
  34. // -----------------------------------------------------------------------------
  35. #if RELAY_PROVIDER == RELAY_PROVIDER_DUAL
  36. #endif
  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=_relays.size()-1; i>=0; i-- ) {
  49. mask <<= 1;
  50. if (_relays[i].current_status) mask++;
  51. }
  52. // Send it to EFM88
  53. Serial.flush();
  54. Serial.write(0xA0);
  55. Serial.write(0x04);
  56. Serial.write(mask);
  57. Serial.write(0xA1);
  58. Serial.flush();
  59. #endif
  60. #if RELAY_PROVIDER == RELAY_PROVIDER_LIGHT
  61. lightState(status);
  62. lightUpdate(true, true);
  63. #endif
  64. #if RELAY_PROVIDER == RELAY_PROVIDER_RELAY
  65. if (_relays[id].type == RELAY_TYPE_NORMAL) {
  66. digitalWrite(_relays[id].pin, status);
  67. } else if (_relays[id].type == RELAY_TYPE_INVERSE) {
  68. digitalWrite(_relays[id].pin, !status);
  69. } else if (_relays[id].type == RELAY_TYPE_LATCHED) {
  70. digitalWrite(_relays[id].pin, LOW);
  71. digitalWrite(_relays[id].reset_pin, LOW);
  72. if (status) {
  73. digitalWrite(_relays[id].pin, HIGH);
  74. } else {
  75. digitalWrite(_relays[id].reset_pin, HIGH);
  76. }
  77. delay(RELAY_LATCHING_PULSE);
  78. digitalWrite(_relays[id].pin, LOW);
  79. digitalWrite(_relays[id].reset_pin, LOW);
  80. }
  81. #endif
  82. }
  83. // -----------------------------------------------------------------------------
  84. // RELAY
  85. // -----------------------------------------------------------------------------
  86. void relayPulse(unsigned char id) {
  87. byte relayPulseMode = getSetting("relayPulseMode", RELAY_PULSE_MODE).toInt();
  88. if (relayPulseMode == RELAY_PULSE_NONE) return;
  89. long relayPulseTime = 1000.0 * getSetting("relayPulseTime", RELAY_PULSE_TIME).toFloat();
  90. if (relayPulseTime == 0) return;
  91. bool status = relayStatus(id);
  92. bool pulseStatus = (relayPulseMode == RELAY_PULSE_ON);
  93. if (pulseStatus == status) {
  94. _relays[id].pulseTicker.detach();
  95. return;
  96. }
  97. _relays[id].pulseTicker.once_ms(relayPulseTime, relayToggle, id);
  98. }
  99. unsigned int relayPulseMode() {
  100. unsigned int value = getSetting("relayPulseMode", RELAY_PULSE_MODE).toInt();
  101. return value;
  102. }
  103. void relayPulseMode(unsigned int value) {
  104. setSetting("relayPulseMode", value);
  105. #if WEB_SUPPORT
  106. char message[20];
  107. snprintf_P(message, sizeof(message), PSTR("{\"relayPulseMode\": %d}"), value);
  108. wsSend(message);
  109. #endif
  110. }
  111. void relayPulseToggle() {
  112. unsigned int value = relayPulseMode();
  113. value = (value == RELAY_PULSE_NONE) ? RELAY_PULSE_OFF : RELAY_PULSE_NONE;
  114. relayPulseMode(value);
  115. }
  116. bool relayStatus(unsigned char id, bool status, bool report, bool group_report) {
  117. if (id >= _relays.size()) return false;
  118. bool changed = false;
  119. if (_relays[id].current_status == status) {
  120. if (_relays[id].target_status != status) {
  121. DEBUG_MSG_P(PSTR("[RELAY] #%d scheduled change cancelled\n"), id);
  122. _relays[id].target_status = status;
  123. _relays[id].report = false;
  124. _relays[id].group_report = false;
  125. changed = true;
  126. }
  127. } else {
  128. unsigned int current_time = millis();
  129. unsigned int fw_end = _relays[id].fw_start + 1000 * RELAY_FLOOD_WINDOW;
  130. unsigned long delay = status ? _relays[id].delay_on : _relays[id].delay_off;
  131. _relays[id].fw_count++;
  132. _relays[id].change_time = current_time + delay;
  133. // If current_time is off-limits the floodWindow...
  134. if (current_time < _relays[id].fw_start || fw_end <= current_time) {
  135. // We reset the floodWindow
  136. _relays[id].fw_start = current_time;
  137. _relays[id].fw_count = 1;
  138. // If current_time is in the floodWindow and there have been too many requests...
  139. } else if (_relays[id].fw_count >= RELAY_FLOOD_CHANGES) {
  140. // We schedule the changes to the end of the floodWindow
  141. // unless it's already delayed beyond that point
  142. if (fw_end - delay > current_time) {
  143. _relays[id].change_time = fw_end;
  144. }
  145. }
  146. _relays[id].target_status = status;
  147. if (report) _relays[id].report = true;
  148. if (group_report) _relays[id].group_report = true;
  149. DEBUG_MSG_P(PSTR("[RELAY] #%d scheduled %s in %u ms\n"),
  150. id, status ? "ON" : "OFF",
  151. (_relays[id].change_time - current_time));
  152. changed = true;
  153. }
  154. return changed;
  155. }
  156. bool relayStatus(unsigned char id, bool status) {
  157. return relayStatus(id, status, true, true);
  158. }
  159. bool relayStatus(unsigned char id) {
  160. // Check relay ID
  161. if (id >= _relays.size()) return false;
  162. // GEt status from storage
  163. return _relays[id].current_status;
  164. }
  165. void relaySync(unsigned char id) {
  166. if (_relays.size() > 1) {
  167. recursive = true;
  168. byte relaySync = getSetting("relaySync", RELAY_SYNC).toInt();
  169. bool status = relayStatus(id);
  170. // If RELAY_SYNC_SAME all relays should have the same state
  171. if (relaySync == RELAY_SYNC_SAME) {
  172. for (unsigned short i=0; i<_relays.size(); i++) {
  173. if (i != id) relayStatus(i, status);
  174. }
  175. // If NONE_OR_ONE or ONE and setting ON we should set OFF all the others
  176. } else if (status) {
  177. if (relaySync != RELAY_SYNC_ANY) {
  178. for (unsigned short i=0; i<_relays.size(); i++) {
  179. if (i != id) relayStatus(i, false);
  180. }
  181. }
  182. // If ONLY_ONE and setting OFF we should set ON the other one
  183. } else {
  184. if (relaySync == RELAY_SYNC_ONE) {
  185. unsigned char i = (id + 1) % _relays.size();
  186. relayStatus(i, true);
  187. }
  188. }
  189. recursive = false;
  190. }
  191. }
  192. void relaySave() {
  193. unsigned char bit = 1;
  194. unsigned char mask = 0;
  195. for (unsigned int i=0; i < _relays.size(); i++) {
  196. if (relayStatus(i)) mask += bit;
  197. bit += bit;
  198. }
  199. EEPROM.write(EEPROM_RELAY_STATUS, mask);
  200. DEBUG_MSG_P(PSTR("[RELAY] Saving mask: %d\n"), mask);
  201. EEPROM.commit();
  202. }
  203. void relayRetrieve(bool invert) {
  204. recursive = true;
  205. unsigned char bit = 1;
  206. unsigned char mask = invert ? ~EEPROM.read(EEPROM_RELAY_STATUS) : EEPROM.read(EEPROM_RELAY_STATUS);
  207. DEBUG_MSG_P(PSTR("[RELAY] Retrieving mask: %d\n"), mask);
  208. for (unsigned int id=0; id < _relays.size(); id++) {
  209. _relays[id].target_status = ((mask & bit) == bit);
  210. _relays[id].report = true;
  211. _relays[id].group_report = false; // Don't do group report on start
  212. bit += bit;
  213. }
  214. if (invert) {
  215. EEPROM.write(EEPROM_RELAY_STATUS, mask);
  216. EEPROM.commit();
  217. }
  218. recursive = false;
  219. }
  220. void relayToggle(unsigned char id, bool report, bool group_report) {
  221. if (id >= _relays.size()) return;
  222. relayStatus(id, !relayStatus(id), report, group_report);
  223. }
  224. void relayToggle(unsigned char id) {
  225. relayToggle(id, true, true);
  226. }
  227. unsigned char relayCount() {
  228. return _relays.size();
  229. }
  230. unsigned char relayParsePayload(const char * payload) {
  231. // Payload could be "OFF", "ON", "TOGGLE"
  232. // or its number equivalents: 0, 1 or 2
  233. // trim payload
  234. char * p = ltrim((char *)payload);
  235. // to lower
  236. for (unsigned char i=0; i<strlen(p); i++) {
  237. p[i] = tolower(p[i]);
  238. }
  239. unsigned int value;
  240. if (strcmp(p, "off") == 0) {
  241. value = 0;
  242. } else if (strcmp(p, "on") == 0) {
  243. value = 1;
  244. } else if (strcmp(p, "toggle") == 0) {
  245. value = 2;
  246. } else if (strcmp(p, "query") == 0) {
  247. value = 3;
  248. } else {
  249. value = p[0] - '0';
  250. }
  251. if (0 <= value && value <=3) return value;
  252. return 0xFF;
  253. }
  254. //------------------------------------------------------------------------------
  255. // WEBSOCKETS
  256. //------------------------------------------------------------------------------
  257. #if WEB_SUPPORT
  258. void _relayWebSocketUpdate() {
  259. DynamicJsonBuffer jsonBuffer;
  260. JsonObject& root = jsonBuffer.createObject();
  261. // Statuses
  262. JsonArray& relay = root.createNestedArray("relayStatus");
  263. for (unsigned char relayID=0; relayID<relayCount(); relayID++) {
  264. relay.add(relayStatus(relayID));
  265. }
  266. String output;
  267. root.printTo(output);
  268. wsSend((char *) output.c_str());
  269. }
  270. void _relayWebSocketOnSend(JsonObject& root) {
  271. // Statuses
  272. JsonArray& relay = root.createNestedArray("relayStatus");
  273. for (unsigned char relayID=0; relayID<relayCount(); relayID++) {
  274. relay.add(relayStatus(relayID));
  275. }
  276. // Configuration
  277. root["relayMode"] = getSetting("relayMode", RELAY_MODE);
  278. root["relayPulseMode"] = getSetting("relayPulseMode", RELAY_PULSE_MODE);
  279. root["relayPulseTime"] = getSetting("relayPulseTime", RELAY_PULSE_TIME).toFloat();
  280. if (relayCount() > 1) {
  281. root["multirelayVisible"] = 1;
  282. root["relaySync"] = getSetting("relaySync", RELAY_SYNC);
  283. }
  284. // Group topics
  285. #if MQTT_SUPPORT
  286. JsonArray& groups = root.createNestedArray("relayGroups");
  287. for (unsigned char i=0; i<relayCount(); i++) {
  288. JsonObject& group = groups.createNestedObject();
  289. group["mqttGroup"] = getSetting("mqttGroup", i, "");
  290. group["mqttGroupInv"] = getSetting("mqttGroupInv", i, 0).toInt() == 1;
  291. }
  292. #endif
  293. }
  294. void _relayWebSocketOnAction(const char * action, JsonObject& data) {
  295. if (strcmp(action, "relay") != 0) return;
  296. if (data.containsKey("status")) {
  297. unsigned char value = relayParsePayload(data["status"]);
  298. if (value == 3) {
  299. _relayWebSocketUpdate();
  300. } else if (value < 3) {
  301. unsigned int relayID = 0;
  302. if (data.containsKey("id")) {
  303. String value = data["id"];
  304. relayID = value.toInt();
  305. }
  306. // Action to perform
  307. if (value == 0) {
  308. relayStatus(relayID, false);
  309. } else if (value == 1) {
  310. relayStatus(relayID, true);
  311. } else if (value == 2) {
  312. relayToggle(relayID);
  313. }
  314. }
  315. }
  316. }
  317. void relaySetupWS() {
  318. wsOnSendRegister(_relayWebSocketOnSend);
  319. wsOnActionRegister(_relayWebSocketOnAction);
  320. }
  321. #endif // WEB_SUPPORT
  322. //------------------------------------------------------------------------------
  323. // REST API
  324. //------------------------------------------------------------------------------
  325. #if WEB_SUPPORT
  326. void relaySetupAPI() {
  327. // API entry points (protected with apikey)
  328. for (unsigned int relayID=0; relayID<relayCount(); relayID++) {
  329. char url[15];
  330. snprintf_P(url, sizeof(url), PSTR("%s/%d"), MQTT_TOPIC_RELAY, relayID);
  331. char key[10];
  332. snprintf_P(key, sizeof(key), PSTR("%s%d"), MQTT_TOPIC_RELAY, relayID);
  333. apiRegister(url, key,
  334. [relayID](char * buffer, size_t len) {
  335. snprintf_P(buffer, len, PSTR("%d"), relayStatus(relayID) ? 1 : 0);
  336. },
  337. [relayID](const char * payload) {
  338. unsigned char value = relayParsePayload(payload);
  339. if (value == 0xFF) {
  340. DEBUG_MSG_P(PSTR("[RELAY] Wrong payload (%s)\n"), payload);
  341. return;
  342. }
  343. if (value == 0) {
  344. relayStatus(relayID, false);
  345. } else if (value == 1) {
  346. relayStatus(relayID, true);
  347. } else if (value == 2) {
  348. relayToggle(relayID);
  349. }
  350. }
  351. );
  352. }
  353. }
  354. #endif // WEB_SUPPORT
  355. //------------------------------------------------------------------------------
  356. // MQTT
  357. //------------------------------------------------------------------------------
  358. #if MQTT_SUPPORT
  359. void relayMQTT(unsigned char id) {
  360. if (id >= _relays.size()) return;
  361. // Send state topic
  362. if (_relays[id].report) {
  363. _relays[id].report = false;
  364. mqttSend(MQTT_TOPIC_RELAY, id, _relays[id].current_status ? "1" : "0");
  365. }
  366. // Check group topic
  367. if (_relays[id].group_report) {
  368. _relays[id].group_report = false;
  369. String t = getSetting("mqttGroup", id, "");
  370. if (t.length() > 0) {
  371. bool status = relayStatus(id);
  372. if (getSetting("mqttGroupInv", id, 0).toInt() == 1) status = !status;
  373. mqttSendRaw(t.c_str(), status ? "1" : "0");
  374. }
  375. }
  376. }
  377. void relayMQTT() {
  378. for (unsigned int id=0; id < _relays.size(); id++) {
  379. mqttSend(MQTT_TOPIC_RELAY, id, _relays[id].current_status ? "1" : "0");
  380. }
  381. }
  382. void relayMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  383. if (type == MQTT_CONNECT_EVENT) {
  384. // Send status on connect
  385. #if not HEARTBEAT_REPORT_RELAY
  386. relayMQTT();
  387. #endif
  388. // Subscribe to own /set topic
  389. char buffer[strlen(MQTT_TOPIC_RELAY) + 3];
  390. snprintf_P(buffer, sizeof(buffer), PSTR("%s/+"), MQTT_TOPIC_RELAY);
  391. mqttSubscribe(buffer);
  392. // Subscribe to group topics
  393. for (unsigned int i=0; i < _relays.size(); i++) {
  394. String t = getSetting("mqttGroup", i, "");
  395. if (t.length() > 0) mqttSubscribeRaw(t.c_str());
  396. }
  397. }
  398. if (type == MQTT_MESSAGE_EVENT) {
  399. // Get relay
  400. unsigned int relayID;
  401. bool is_group_topic = false;
  402. // Get value
  403. unsigned char value = relayParsePayload(payload);
  404. if (value == 0xFF) {
  405. DEBUG_MSG_P(PSTR("[RELAY] Wrong payload (%s)\n"), payload);
  406. return;
  407. }
  408. // Check group topics
  409. for (unsigned int i=0; i < _relays.size(); i++) {
  410. String t = getSetting("mqttGroup", i, "");
  411. if (t.equals(topic)) {
  412. is_group_topic = true;
  413. relayID = i;
  414. if (getSetting("mqttGroupInv", relayID, 0).toInt() == 1) {
  415. if (value < 2) value = 1 - value;
  416. }
  417. DEBUG_MSG_P(PSTR("[RELAY] Matched group topic for relayID %d\n"), relayID);
  418. break;
  419. }
  420. }
  421. // Not group topic, look for own topic
  422. if (!is_group_topic) {
  423. // Match topic
  424. String t = mqttSubtopic((char *) topic);
  425. if (!t.startsWith(MQTT_TOPIC_RELAY)) return;
  426. // Pulse topic
  427. if (t.endsWith("pulse")) {
  428. relayPulseMode(value);
  429. return;
  430. }
  431. // Get relay ID
  432. relayID = t.substring(strlen(MQTT_TOPIC_RELAY)+1).toInt();
  433. if (relayID >= relayCount()) {
  434. DEBUG_MSG_P(PSTR("[RELAY] Wrong relayID (%d)\n"), relayID);
  435. return;
  436. }
  437. }
  438. // Action to perform
  439. if (value == 0) {
  440. relayStatus(relayID, false, mqttForward(), !is_group_topic);
  441. } else if (value == 1) {
  442. relayStatus(relayID, true, mqttForward(), !is_group_topic);
  443. } else if (value == 2) {
  444. relayToggle(relayID, true, true);
  445. }
  446. }
  447. }
  448. void relaySetupMQTT() {
  449. mqttRegister(relayMQTTCallback);
  450. }
  451. #endif
  452. //------------------------------------------------------------------------------
  453. // InfluxDB
  454. //------------------------------------------------------------------------------
  455. #if INFLUXDB_SUPPORT
  456. void relayInfluxDB(unsigned char id) {
  457. if (id >= _relays.size()) return;
  458. char buffer[10];
  459. snprintf_P(buffer, sizeof(buffer), PSTR("%s,id=%d"), MQTT_TOPIC_RELAY, id);
  460. idbSend(buffer, relayStatus(id) ? "1" : "0");
  461. }
  462. #endif
  463. //------------------------------------------------------------------------------
  464. // Setup
  465. //------------------------------------------------------------------------------
  466. void relaySetup() {
  467. // Dummy relays for AI Light, Magic Home LED Controller, H801,
  468. // Sonoff Dual and Sonoff RF Bridge
  469. #ifdef DUMMY_RELAY_COUNT
  470. for (unsigned char i=0; i < DUMMY_RELAY_COUNT; i++) {
  471. _relays.push_back((relay_t) {0, RELAY_TYPE_NORMAL});
  472. }
  473. #else
  474. #ifdef RELAY1_PIN
  475. _relays.push_back((relay_t) { RELAY1_PIN, RELAY1_TYPE, RELAY1_RESET_PIN, RELAY1_LED, RELAY1_DELAY_ON, RELAY1_DELAY_OFF });
  476. #endif
  477. #ifdef RELAY2_PIN
  478. _relays.push_back((relay_t) { RELAY2_PIN, RELAY2_TYPE, RELAY2_RESET_PIN, RELAY2_LED, RELAY2_DELAY_ON, RELAY2_DELAY_OFF });
  479. #endif
  480. #ifdef RELAY3_PIN
  481. _relays.push_back((relay_t) { RELAY3_PIN, RELAY3_TYPE, RELAY3_RESET_PIN, RELAY3_LED, RELAY3_DELAY_ON, RELAY3_DELAY_OFF });
  482. #endif
  483. #ifdef RELAY4_PIN
  484. _relays.push_back((relay_t) { RELAY4_PIN, RELAY4_TYPE, RELAY4_RESET_PIN, RELAY4_LED, RELAY4_DELAY_ON, RELAY4_DELAY_OFF });
  485. #endif
  486. #endif
  487. byte relayMode = getSetting("relayMode", RELAY_MODE).toInt();
  488. for (unsigned int i=0; i < _relays.size(); i++) {
  489. pinMode(_relays[i].pin, OUTPUT);
  490. if (relayMode == RELAY_MODE_OFF) relayStatus(i, false);
  491. if (relayMode == RELAY_MODE_ON) relayStatus(i, true);
  492. }
  493. if (relayMode == RELAY_MODE_SAME) relayRetrieve(false);
  494. if (relayMode == RELAY_MODE_TOOGLE) relayRetrieve(true);
  495. relayLoop();
  496. #if WEB_SUPPORT
  497. relaySetupAPI();
  498. relaySetupWS();
  499. #endif
  500. #if MQTT_SUPPORT
  501. relaySetupMQTT();
  502. #endif
  503. DEBUG_MSG_P(PSTR("[RELAY] Number of relays: %d\n"), _relays.size());
  504. }
  505. void relayLoop(void) {
  506. unsigned char id;
  507. for (id = 0; id < _relays.size(); id++) {
  508. unsigned int current_time = millis();
  509. bool status = _relays[id].target_status;
  510. if ((_relays[id].current_status != status)
  511. && (current_time >= _relays[id].change_time)) {
  512. DEBUG_MSG_P(PSTR("[RELAY] #%d set to %s\n"), id, status ? "ON" : "OFF");
  513. // Call the provider to perform the action
  514. _relayProviderStatus(id, status);
  515. // Change the binded LED if any
  516. if (_relays[id].led > 0) {
  517. ledStatus(_relays[id].led - 1, status);
  518. }
  519. // Send MQTT
  520. #if MQTT_SUPPORT
  521. relayMQTT(id);
  522. #endif
  523. if (!recursive) {
  524. relayPulse(id);
  525. relaySync(id);
  526. _relaySaveTicker.once_ms(RELAY_SAVE_DELAY, relaySave);
  527. #if WEB_SUPPORT
  528. _relayWebSocketUpdate();
  529. #endif
  530. }
  531. #if DOMOTICZ_SUPPORT
  532. domoticzSendRelay(id);
  533. #endif
  534. #if INFLUXDB_SUPPORT
  535. relayInfluxDB(id);
  536. #endif
  537. _relays[id].report = false;
  538. _relays[id].group_report = false;
  539. }
  540. }
  541. }