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.

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