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.

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