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.

732 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. if (relayCount() == 0) return;
  276. root["relayVisible"] = 1;
  277. // Statuses
  278. JsonArray& relay = root.createNestedArray("relayStatus");
  279. for (unsigned char relayID=0; relayID<relayCount(); relayID++) {
  280. relay.add(relayStatus(relayID));
  281. }
  282. // Configuration
  283. root["relayMode"] = getSetting("relayMode", RELAY_MODE);
  284. root["relayPulseMode"] = getSetting("relayPulseMode", RELAY_PULSE_MODE);
  285. root["relayPulseTime"] = getSetting("relayPulseTime", RELAY_PULSE_TIME).toFloat();
  286. if (relayCount() > 1) {
  287. root["multirelayVisible"] = 1;
  288. root["relaySync"] = getSetting("relaySync", RELAY_SYNC);
  289. }
  290. // Group topics
  291. #if MQTT_SUPPORT
  292. JsonArray& groups = root.createNestedArray("relayGroups");
  293. for (unsigned char i=0; i<relayCount(); i++) {
  294. JsonObject& group = groups.createNestedObject();
  295. group["mqttGroup"] = getSetting("mqttGroup", i, "");
  296. group["mqttGroupInv"] = getSetting("mqttGroupInv", i, 0).toInt() == 1;
  297. }
  298. #endif
  299. }
  300. void _relayWebSocketOnAction(const char * action, JsonObject& data) {
  301. if (strcmp(action, "relay") != 0) return;
  302. if (data.containsKey("status")) {
  303. unsigned char value = relayParsePayload(data["status"]);
  304. if (value == 3) {
  305. _relayWebSocketUpdate();
  306. } else if (value < 3) {
  307. unsigned int relayID = 0;
  308. if (data.containsKey("id")) {
  309. String value = data["id"];
  310. relayID = value.toInt();
  311. }
  312. // Action to perform
  313. if (value == 0) {
  314. relayStatus(relayID, false);
  315. } else if (value == 1) {
  316. relayStatus(relayID, true);
  317. } else if (value == 2) {
  318. relayToggle(relayID);
  319. }
  320. }
  321. }
  322. }
  323. void relaySetupWS() {
  324. wsOnSendRegister(_relayWebSocketOnSend);
  325. wsOnActionRegister(_relayWebSocketOnAction);
  326. }
  327. #endif // WEB_SUPPORT
  328. //------------------------------------------------------------------------------
  329. // REST API
  330. //------------------------------------------------------------------------------
  331. #if WEB_SUPPORT
  332. void relaySetupAPI() {
  333. // API entry points (protected with apikey)
  334. for (unsigned int relayID=0; relayID<relayCount(); relayID++) {
  335. char url[15];
  336. snprintf_P(url, sizeof(url), PSTR("%s/%d"), MQTT_TOPIC_RELAY, relayID);
  337. char key[10];
  338. snprintf_P(key, sizeof(key), PSTR("%s%d"), MQTT_TOPIC_RELAY, relayID);
  339. apiRegister(url, key,
  340. [relayID](char * buffer, size_t len) {
  341. snprintf_P(buffer, len, PSTR("%d"), relayStatus(relayID) ? 1 : 0);
  342. },
  343. [relayID](const char * payload) {
  344. unsigned char value = relayParsePayload(payload);
  345. if (value == 0xFF) {
  346. DEBUG_MSG_P(PSTR("[RELAY] Wrong payload (%s)\n"), payload);
  347. return;
  348. }
  349. if (value == 0) {
  350. relayStatus(relayID, false);
  351. } else if (value == 1) {
  352. relayStatus(relayID, true);
  353. } else if (value == 2) {
  354. relayToggle(relayID);
  355. }
  356. }
  357. );
  358. }
  359. }
  360. #endif // WEB_SUPPORT
  361. //------------------------------------------------------------------------------
  362. // MQTT
  363. //------------------------------------------------------------------------------
  364. #if MQTT_SUPPORT
  365. void relayMQTT(unsigned char id) {
  366. if (id >= _relays.size()) return;
  367. // Send state topic
  368. if (_relays[id].report) {
  369. _relays[id].report = false;
  370. mqttSend(MQTT_TOPIC_RELAY, id, _relays[id].current_status ? "1" : "0");
  371. }
  372. // Check group topic
  373. if (_relays[id].group_report) {
  374. _relays[id].group_report = false;
  375. String t = getSetting("mqttGroup", id, "");
  376. if (t.length() > 0) {
  377. bool status = relayStatus(id);
  378. if (getSetting("mqttGroupInv", id, 0).toInt() == 1) status = !status;
  379. mqttSendRaw(t.c_str(), status ? "1" : "0");
  380. }
  381. }
  382. }
  383. void relayMQTT() {
  384. for (unsigned int id=0; id < _relays.size(); id++) {
  385. mqttSend(MQTT_TOPIC_RELAY, id, _relays[id].current_status ? "1" : "0");
  386. }
  387. }
  388. void relayMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  389. if (type == MQTT_CONNECT_EVENT) {
  390. // Send status on connect
  391. #if not HEARTBEAT_REPORT_RELAY
  392. relayMQTT();
  393. #endif
  394. // Subscribe to own /set topic
  395. char buffer[strlen(MQTT_TOPIC_RELAY) + 3];
  396. snprintf_P(buffer, sizeof(buffer), PSTR("%s/+"), MQTT_TOPIC_RELAY);
  397. mqttSubscribe(buffer);
  398. // Subscribe to group topics
  399. for (unsigned int i=0; i < _relays.size(); i++) {
  400. String t = getSetting("mqttGroup", i, "");
  401. if (t.length() > 0) mqttSubscribeRaw(t.c_str());
  402. }
  403. }
  404. if (type == MQTT_MESSAGE_EVENT) {
  405. // Get relay
  406. unsigned int relayID;
  407. bool is_group_topic = false;
  408. // Get value
  409. unsigned char value = relayParsePayload(payload);
  410. if (value == 0xFF) {
  411. DEBUG_MSG_P(PSTR("[RELAY] Wrong payload (%s)\n"), payload);
  412. return;
  413. }
  414. // Check group topics
  415. for (unsigned int i=0; i < _relays.size(); i++) {
  416. String t = getSetting("mqttGroup", i, "");
  417. if (t.equals(topic)) {
  418. is_group_topic = true;
  419. relayID = i;
  420. if (getSetting("mqttGroupInv", relayID, 0).toInt() == 1) {
  421. if (value < 2) value = 1 - value;
  422. }
  423. DEBUG_MSG_P(PSTR("[RELAY] Matched group topic for relayID %d\n"), relayID);
  424. break;
  425. }
  426. }
  427. // Not group topic, look for own topic
  428. if (!is_group_topic) {
  429. // Match topic
  430. String t = mqttSubtopic((char *) topic);
  431. if (!t.startsWith(MQTT_TOPIC_RELAY)) return;
  432. // Pulse topic
  433. if (t.endsWith("pulse")) {
  434. relayPulseMode(value);
  435. return;
  436. }
  437. // Get relay ID
  438. relayID = t.substring(strlen(MQTT_TOPIC_RELAY)+1).toInt();
  439. if (relayID >= relayCount()) {
  440. DEBUG_MSG_P(PSTR("[RELAY] Wrong relayID (%d)\n"), relayID);
  441. return;
  442. }
  443. }
  444. // Action to perform
  445. if (value == 0) {
  446. relayStatus(relayID, false, mqttForward(), !is_group_topic);
  447. } else if (value == 1) {
  448. relayStatus(relayID, true, mqttForward(), !is_group_topic);
  449. } else if (value == 2) {
  450. relayToggle(relayID, true, true);
  451. }
  452. }
  453. }
  454. void relaySetupMQTT() {
  455. mqttRegister(relayMQTTCallback);
  456. }
  457. #endif
  458. //------------------------------------------------------------------------------
  459. // InfluxDB
  460. //------------------------------------------------------------------------------
  461. #if INFLUXDB_SUPPORT
  462. void relayInfluxDB(unsigned char id) {
  463. if (id >= _relays.size()) return;
  464. char buffer[10];
  465. snprintf_P(buffer, sizeof(buffer), PSTR("%s,id=%d"), MQTT_TOPIC_RELAY, id);
  466. idbSend(buffer, relayStatus(id) ? "1" : "0");
  467. }
  468. #endif
  469. //------------------------------------------------------------------------------
  470. // Setup
  471. //------------------------------------------------------------------------------
  472. void relaySetup() {
  473. // Dummy relays for AI Light, Magic Home LED Controller, H801,
  474. // Sonoff Dual and Sonoff RF Bridge
  475. #ifdef DUMMY_RELAY_COUNT
  476. for (unsigned char i=0; i < DUMMY_RELAY_COUNT; i++) {
  477. _relays.push_back((relay_t) {0, RELAY_TYPE_NORMAL});
  478. }
  479. #else
  480. #ifdef RELAY1_PIN
  481. _relays.push_back((relay_t) { RELAY1_PIN, RELAY1_TYPE, RELAY1_RESET_PIN, RELAY1_LED, RELAY1_DELAY_ON, RELAY1_DELAY_OFF });
  482. #endif
  483. #ifdef RELAY2_PIN
  484. _relays.push_back((relay_t) { RELAY2_PIN, RELAY2_TYPE, RELAY2_RESET_PIN, RELAY2_LED, RELAY2_DELAY_ON, RELAY2_DELAY_OFF });
  485. #endif
  486. #ifdef RELAY3_PIN
  487. _relays.push_back((relay_t) { RELAY3_PIN, RELAY3_TYPE, RELAY3_RESET_PIN, RELAY3_LED, RELAY3_DELAY_ON, RELAY3_DELAY_OFF });
  488. #endif
  489. #ifdef RELAY4_PIN
  490. _relays.push_back((relay_t) { RELAY4_PIN, RELAY4_TYPE, RELAY4_RESET_PIN, RELAY4_LED, RELAY4_DELAY_ON, RELAY4_DELAY_OFF });
  491. #endif
  492. #endif
  493. byte relayMode = getSetting("relayMode", RELAY_MODE).toInt();
  494. for (unsigned int i=0; i < _relays.size(); i++) {
  495. pinMode(_relays[i].pin, OUTPUT);
  496. if (relayMode == RELAY_MODE_OFF) relayStatus(i, false);
  497. if (relayMode == RELAY_MODE_ON) relayStatus(i, true);
  498. }
  499. if (relayMode == RELAY_MODE_SAME) relayRetrieve(false);
  500. if (relayMode == RELAY_MODE_TOOGLE) relayRetrieve(true);
  501. relayLoop();
  502. #if WEB_SUPPORT
  503. relaySetupAPI();
  504. relaySetupWS();
  505. #endif
  506. #if MQTT_SUPPORT
  507. relaySetupMQTT();
  508. #endif
  509. DEBUG_MSG_P(PSTR("[RELAY] Number of relays: %d\n"), _relays.size());
  510. }
  511. void relayLoop(void) {
  512. unsigned char id;
  513. for (id = 0; id < _relays.size(); id++) {
  514. unsigned int current_time = millis();
  515. bool status = _relays[id].target_status;
  516. if ((_relays[id].current_status != status)
  517. && (current_time >= _relays[id].change_time)) {
  518. DEBUG_MSG_P(PSTR("[RELAY] #%d set to %s\n"), id, status ? "ON" : "OFF");
  519. // Call the provider to perform the action
  520. _relayProviderStatus(id, status);
  521. // Change the binded LED if any
  522. if (_relays[id].led > 0) {
  523. ledStatus(_relays[id].led - 1, status);
  524. }
  525. // Send MQTT
  526. #if MQTT_SUPPORT
  527. relayMQTT(id);
  528. #endif
  529. if (!_relayRecursive) {
  530. relayPulse(id);
  531. _relaySaveTicker.once_ms(RELAY_SAVE_DELAY, relaySave);
  532. #if WEB_SUPPORT
  533. _relayWebSocketUpdate();
  534. #endif
  535. }
  536. #if DOMOTICZ_SUPPORT
  537. domoticzSendRelay(id);
  538. #endif
  539. #if INFLUXDB_SUPPORT
  540. relayInfluxDB(id);
  541. #endif
  542. _relays[id].report = false;
  543. _relays[id].group_report = false;
  544. }
  545. }
  546. }