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.

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