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.

513 lines
14 KiB

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