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

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