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.

517 lines
14 KiB

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