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.

478 lines
13 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 int floodWindowStart;
  15. unsigned char floodWindowChanges;
  16. unsigned int scheduledStatusTime;
  17. bool scheduledStatus;
  18. bool scheduledReport;
  19. Ticker pulseTicker;
  20. } relay_t;
  21. std::vector<relay_t> _relays;
  22. bool recursive = false;
  23. #if RELAY_PROVIDER == RELAY_PROVIDER_DUAL
  24. unsigned char _dual_status = 0;
  25. #endif
  26. // -----------------------------------------------------------------------------
  27. // RELAY PROVIDERS
  28. // -----------------------------------------------------------------------------
  29. void relayProviderStatus(unsigned char id, bool status) {
  30. if (id >= _relays.size()) return;
  31. #if RELAY_PROVIDER == RELAY_PROVIDER_DUAL
  32. _dual_status ^= (1 << id);
  33. Serial.flush();
  34. Serial.write(0xA0);
  35. Serial.write(0x04);
  36. Serial.write(_dual_status);
  37. Serial.write(0xA1);
  38. Serial.flush();
  39. #endif
  40. #if RELAY_PROVIDER == RELAY_PROVIDER_LIGHT
  41. lightState(status);
  42. #endif
  43. #if RELAY_PROVIDER == RELAY_PROVIDER_RELAY
  44. digitalWrite(_relays[id].pin, _relays[id].reverse ? !status : status);
  45. #endif
  46. }
  47. bool relayProviderStatus(unsigned char id) {
  48. if (id >= _relays.size()) return false;
  49. #if RELAY_PROVIDER == RELAY_PROVIDER_DUAL
  50. return ((_dual_status & (1 << id)) > 0);
  51. #endif
  52. #if RELAY_PROVIDER == RELAY_PROVIDER_LIGHT
  53. return lightState();
  54. #endif
  55. #if RELAY_PROVIDER == RELAY_PROVIDER_RELAY
  56. bool status = (digitalRead(_relays[id].pin) == HIGH);
  57. return _relays[id].reverse ? !status : status;
  58. #endif
  59. }
  60. // -----------------------------------------------------------------------------
  61. // RELAY
  62. // -----------------------------------------------------------------------------
  63. String relayString() {
  64. DynamicJsonBuffer jsonBuffer;
  65. JsonObject& root = jsonBuffer.createObject();
  66. JsonArray& relay = root.createNestedArray("relayStatus");
  67. for (unsigned char i=0; i<relayCount(); i++) {
  68. relay.add(relayStatus(i));
  69. }
  70. String output;
  71. root.printTo(output);
  72. return output;
  73. }
  74. bool relayStatus(unsigned char id) {
  75. return relayProviderStatus(id);
  76. }
  77. void relayPulse(unsigned char id) {
  78. byte relayPulseMode = getSetting("relayPulseMode", RELAY_PULSE_MODE).toInt();
  79. if (relayPulseMode == RELAY_PULSE_NONE) return;
  80. long relayPulseTime = 1000.0 * getSetting("relayPulseTime", RELAY_PULSE_TIME).toFloat();
  81. if (relayPulseTime == 0) return;
  82. bool status = relayStatus(id);
  83. bool pulseStatus = (relayPulseMode == RELAY_PULSE_ON);
  84. if (pulseStatus == status) {
  85. _relays[id].pulseTicker.detach();
  86. return;
  87. }
  88. _relays[id].pulseTicker.once_ms(relayPulseTime, relayToggle, id);
  89. }
  90. unsigned int relayPulseMode() {
  91. unsigned int value = getSetting("relayPulseMode", RELAY_PULSE_MODE).toInt();
  92. return value;
  93. }
  94. void relayPulseMode(unsigned int value, bool report) {
  95. setSetting("relayPulseMode", value);
  96. /*
  97. if (report) {
  98. char topic[strlen(MQTT_TOPIC_RELAY) + 10];
  99. sprintf(topic, "%s/pulse", MQTT_TOPIC_RELAY);
  100. char value[2];
  101. sprintf(value, "%d", value);
  102. mqttSend(topic, value);
  103. }
  104. */
  105. char message[20];
  106. sprintf(message, "{\"relayPulseMode\": %d}", value);
  107. wsSend(message);
  108. }
  109. void relayPulseMode(unsigned int value) {
  110. relayPulseMode(value, true);
  111. }
  112. void relayPulseToggle() {
  113. unsigned int value = relayPulseMode();
  114. value = (value == RELAY_PULSE_NONE) ? RELAY_PULSE_OFF : RELAY_PULSE_NONE;
  115. relayPulseMode(value);
  116. }
  117. bool relayStatus(unsigned char id, bool status, bool report) {
  118. if (id >= _relays.size()) return false;
  119. bool changed = false;
  120. if (relayStatus(id) != status) {
  121. unsigned int floodWindowEnd = _relays[id].floodWindowStart + 1000 * RELAY_FLOOD_WINDOW;
  122. unsigned int currentTime = millis();
  123. _relays[id].floodWindowChanges++;
  124. _relays[id].scheduledStatusTime = currentTime;
  125. if (currentTime >= floodWindowEnd || currentTime < _relays[id].floodWindowStart) {
  126. _relays[id].floodWindowStart = currentTime;
  127. _relays[id].floodWindowChanges = 1;
  128. } else if (_relays[id].floodWindowChanges >= RELAY_FLOOD_CHANGES) {
  129. _relays[id].scheduledStatusTime = floodWindowEnd;
  130. }
  131. _relays[id].scheduledStatus = status;
  132. _relays[id].scheduledReport = (report ? true : _relays[id].scheduledReport);
  133. DEBUG_MSG_P(PSTR("[RELAY] Scheduled %d => %s in %u ms\n"),
  134. id, status ? "ON" : "OFF",
  135. (_relays[id].scheduledStatusTime - currentTime));
  136. changed = true;
  137. }
  138. return changed;
  139. }
  140. bool relayStatus(unsigned char id, bool status) {
  141. return relayStatus(id, status, true);
  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. String output = relayString();
  234. wsSend(output.c_str());
  235. }
  236. //------------------------------------------------------------------------------
  237. // MQTT
  238. //------------------------------------------------------------------------------
  239. void relayMQTT(unsigned char id) {
  240. if (id >= _relays.size()) return;
  241. mqttSend(MQTT_TOPIC_RELAY, id, relayStatus(id) ? "1" : "0");
  242. }
  243. #if ENABLE_INFLUXDB
  244. void relayInfluxDB(unsigned char id) {
  245. if (id >= _relays.size()) return;
  246. char buffer[10];
  247. sprintf(buffer, "%s,id=%d", MQTT_TOPIC_RELAY, id);
  248. influxDBSend(buffer, relayStatus(id) ? "1" : "0");
  249. }
  250. #endif
  251. void relayMQTT() {
  252. for (unsigned int i=0; i < _relays.size(); i++) {
  253. relayMQTT(i);
  254. }
  255. }
  256. void relayMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  257. if (type == MQTT_CONNECT_EVENT) {
  258. #if not HEARTBEAT_REPORT_RELAY
  259. relayMQTT();
  260. #endif
  261. char buffer[strlen(MQTT_TOPIC_RELAY) + 3];
  262. sprintf(buffer, "%s/+", MQTT_TOPIC_RELAY);
  263. mqttSubscribe(buffer);
  264. }
  265. if (type == MQTT_MESSAGE_EVENT) {
  266. // Match topic
  267. String t = mqttSubtopic((char *) topic);
  268. if (!t.startsWith(MQTT_TOPIC_RELAY)) return;
  269. // Get value
  270. unsigned int value = (char)payload[0] - '0';
  271. // Pulse topic
  272. if (t.endsWith("pulse")) {
  273. relayPulseMode(value, mqttForward());
  274. return;
  275. }
  276. // Get relay ID
  277. unsigned int relayID = t.substring(strlen(MQTT_TOPIC_RELAY)+1).toInt();
  278. if (relayID >= relayCount()) {
  279. DEBUG_MSG_P(PSTR("[RELAY] Wrong relayID (%d)\n"), relayID);
  280. return;
  281. }
  282. // Action to perform
  283. if (value == 2) {
  284. relayToggle(relayID);
  285. } else {
  286. relayStatus(relayID, value > 0, mqttForward());
  287. }
  288. }
  289. }
  290. void relaySetupMQTT() {
  291. mqttRegister(relayMQTTCallback);
  292. }
  293. //------------------------------------------------------------------------------
  294. // Setup
  295. //------------------------------------------------------------------------------
  296. void relaySetup() {
  297. #if defined(SONOFF_DUAL)
  298. // Two dummy relays for the dual
  299. _relays.push_back((relay_t) {0, 0});
  300. _relays.push_back((relay_t) {0, 0});
  301. #elif defined(AI_LIGHT) | defined(LED_CONTROLLER) | defined(H801_LED_CONTROLLER)
  302. // One dummy relay for the AI Thinker Light & Magic Home and H801 led controllers
  303. _relays.push_back((relay_t) {0, 0});
  304. #else
  305. #ifdef RELAY1_PIN
  306. _relays.push_back((relay_t) { RELAY1_PIN, RELAY1_PIN_INVERSE, RELAY1_LED });
  307. #endif
  308. #ifdef RELAY2_PIN
  309. _relays.push_back((relay_t) { RELAY2_PIN, RELAY2_PIN_INVERSE, RELAY2_LED });
  310. #endif
  311. #ifdef RELAY3_PIN
  312. _relays.push_back((relay_t) { RELAY3_PIN, RELAY3_PIN_INVERSE, RELAY3_LED });
  313. #endif
  314. #ifdef RELAY4_PIN
  315. _relays.push_back((relay_t) { RELAY4_PIN, RELAY4_PIN_INVERSE, RELAY4_LED });
  316. #endif
  317. #endif
  318. byte relayMode = getSetting("relayMode", RELAY_MODE).toInt();
  319. for (unsigned int i=0; i < _relays.size(); i++) {
  320. pinMode(_relays[i].pin, OUTPUT);
  321. if (relayMode == RELAY_MODE_OFF) relayStatus(i, false);
  322. if (relayMode == RELAY_MODE_ON) relayStatus(i, true);
  323. }
  324. if (relayMode == RELAY_MODE_SAME) relayRetrieve(false);
  325. if (relayMode == RELAY_MODE_TOOGLE) relayRetrieve(true);
  326. relayLoop();
  327. relaySetupAPI();
  328. relaySetupMQTT();
  329. DEBUG_MSG_P(PSTR("[RELAY] Number of relays: %d\n"), _relays.size());
  330. }
  331. void relayLoop(void) {
  332. unsigned char id;
  333. for (id = 0; id < _relays.size(); id++) {
  334. unsigned int currentTime = millis();
  335. bool status = _relays[id].scheduledStatus;
  336. if (relayStatus(id) != status && currentTime >= _relays[id].scheduledStatusTime) {
  337. DEBUG_MSG_P(PSTR("[RELAY] %d => %s\n"), id, status ? "ON" : "OFF");
  338. relayProviderStatus(id, status);
  339. if (_relays[id].led > 0) {
  340. ledStatus(_relays[id].led - 1, status);
  341. }
  342. if (_relays[id].scheduledReport) {
  343. relayMQTT(id);
  344. }
  345. if (!recursive) {
  346. relayPulse(id);
  347. relaySync(id);
  348. relaySave();
  349. relayWS();
  350. }
  351. #if ENABLE_DOMOTICZ
  352. relayDomoticzSend(id);
  353. #endif
  354. #if ENABLE_INFLUXDB
  355. relayInfluxDB(id);
  356. #endif
  357. _relays[id].scheduledReport = false;
  358. }
  359. }
  360. }