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.

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