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.

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