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.

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