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.

512 lines
14 KiB

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