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.

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