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.

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