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.

548 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 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. // Domoticz
  238. //------------------------------------------------------------------------------
  239. #if ENABLE_DOMOTICZ
  240. void relayDomoticzSend(unsigned int relayID) {
  241. char buffer[15];
  242. sprintf(buffer, "dczRelayIdx%d", relayID);
  243. domoticzSend(buffer, relayStatus(relayID) ? "1" : "0");
  244. }
  245. int relayFromIdx(unsigned int idx) {
  246. for (int relayID=0; relayID<relayCount(); relayID++) {
  247. if (relayToIdx(relayID) == idx) {
  248. return relayID;
  249. }
  250. }
  251. return -1;
  252. }
  253. int relayToIdx(unsigned int relayID) {
  254. char buffer[15];
  255. sprintf(buffer, "dczRelayIdx%d", relayID);
  256. return getSetting(buffer).toInt();
  257. }
  258. void relayDomoticzSetup() {
  259. mqttRegister([](unsigned int type, const char * topic, const char * payload) {
  260. String dczTopicOut = getSetting("dczTopicOut", DOMOTICZ_OUT_TOPIC);
  261. if (type == MQTT_CONNECT_EVENT) {
  262. mqttSubscribeRaw(dczTopicOut.c_str());
  263. }
  264. if (type == MQTT_MESSAGE_EVENT) {
  265. // Check topic
  266. if (dczTopicOut.equals(topic)) {
  267. // Parse response
  268. DynamicJsonBuffer jsonBuffer;
  269. JsonObject& root = jsonBuffer.parseObject((char *) payload);
  270. if (!root.success()) {
  271. DEBUG_MSG_P(PSTR("[DOMOTICZ] Error parsing data\n"));
  272. return;
  273. }
  274. // IDX
  275. unsigned long idx = root["idx"];
  276. int relayID = relayFromIdx(idx);
  277. if (relayID >= 0) {
  278. unsigned long value = root["nvalue"];
  279. DEBUG_MSG_P(PSTR("[DOMOTICZ] Received value %d for IDX %d\n"), value, idx);
  280. relayStatus(relayID, value == 1);
  281. }
  282. }
  283. }
  284. });
  285. }
  286. #endif
  287. //------------------------------------------------------------------------------
  288. // MQTT
  289. //------------------------------------------------------------------------------
  290. void relayMQTT(unsigned char id) {
  291. if (id >= _relays.size()) return;
  292. mqttSend(MQTT_TOPIC_RELAY, id, relayStatus(id) ? "1" : "0");
  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. void relayMQTT() {
  303. for (unsigned int i=0; i < _relays.size(); i++) {
  304. relayMQTT(i);
  305. }
  306. }
  307. void relayMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  308. if (type == MQTT_CONNECT_EVENT) {
  309. #if not MQTT_REPORT_RELAY
  310. relayMQTT();
  311. #endif
  312. char buffer[strlen(MQTT_TOPIC_RELAY) + 3];
  313. sprintf(buffer, "%s/+", MQTT_TOPIC_RELAY);
  314. mqttSubscribe(buffer);
  315. }
  316. if (type == MQTT_MESSAGE_EVENT) {
  317. // Match topic
  318. String t = mqttSubtopic((char *) topic);
  319. if (!t.startsWith(MQTT_TOPIC_RELAY)) return;
  320. // Get value
  321. unsigned int value = (char)payload[0] - '0';
  322. // Pulse topic
  323. if (t.endsWith("pulse")) {
  324. relayPulseMode(value, mqttForward());
  325. return;
  326. }
  327. // Get relay ID
  328. unsigned int relayID = t.substring(strlen(MQTT_TOPIC_RELAY)+1).toInt();
  329. if (relayID >= relayCount()) {
  330. DEBUG_MSG_P(PSTR("[RELAY] Wrong relayID (%d)\n"), relayID);
  331. return;
  332. }
  333. // Action to perform
  334. if (value == 2) {
  335. relayToggle(relayID);
  336. } else {
  337. relayStatus(relayID, value > 0, mqttForward());
  338. }
  339. }
  340. }
  341. void relaySetupMQTT() {
  342. mqttRegister(relayMQTTCallback);
  343. }
  344. //------------------------------------------------------------------------------
  345. // Setup
  346. //------------------------------------------------------------------------------
  347. void relaySetup() {
  348. #if defined(SONOFF_DUAL)
  349. // Two dummy relays for the dual
  350. _relays.push_back((relay_t) {0, 0});
  351. _relays.push_back((relay_t) {0, 0});
  352. #elif defined(AI_LIGHT) | defined(LED_CONTROLLER) | defined(H801_LED_CONTROLLER)
  353. // One dummy relay for the AI Thinker Light & Magic Home and H801 led controllers
  354. _relays.push_back((relay_t) {0, 0});
  355. #else
  356. #ifdef RELAY1_PIN
  357. _relays.push_back((relay_t) { RELAY1_PIN, RELAY1_PIN_INVERSE, RELAY1_LED });
  358. #endif
  359. #ifdef RELAY2_PIN
  360. _relays.push_back((relay_t) { RELAY2_PIN, RELAY2_PIN_INVERSE, RELAY2_LED });
  361. #endif
  362. #ifdef RELAY3_PIN
  363. _relays.push_back((relay_t) { RELAY3_PIN, RELAY3_PIN_INVERSE, RELAY3_LED });
  364. #endif
  365. #ifdef RELAY4_PIN
  366. _relays.push_back((relay_t) { RELAY4_PIN, RELAY4_PIN_INVERSE, RELAY4_LED });
  367. #endif
  368. #endif
  369. byte relayMode = getSetting("relayMode", RELAY_MODE).toInt();
  370. for (unsigned int i=0; i < _relays.size(); i++) {
  371. pinMode(_relays[i].pin, OUTPUT);
  372. if (relayMode == RELAY_MODE_OFF) relayStatus(i, false);
  373. if (relayMode == RELAY_MODE_ON) relayStatus(i, true);
  374. }
  375. if (relayMode == RELAY_MODE_SAME) relayRetrieve(false);
  376. if (relayMode == RELAY_MODE_TOOGLE) relayRetrieve(true);
  377. relayLoop();
  378. relaySetupAPI();
  379. relaySetupMQTT();
  380. #if ENABLE_DOMOTICZ
  381. relayDomoticzSetup();
  382. #endif
  383. DEBUG_MSG_P(PSTR("[RELAY] Number of relays: %d\n"), _relays.size());
  384. }
  385. void relayLoop(void) {
  386. unsigned char id;
  387. for (id = 0; id < _relays.size(); id++) {
  388. unsigned int currentTime = millis();
  389. bool status = _relays[id].scheduledStatus;
  390. if (relayStatus(id) != status && currentTime >= _relays[id].scheduledStatusTime) {
  391. DEBUG_MSG_P(PSTR("[RELAY] %d => %s\n"), id, status ? "ON" : "OFF");
  392. relayProviderStatus(id, status);
  393. if (_relays[id].led > 0) {
  394. ledStatus(_relays[id].led - 1, status);
  395. }
  396. if (_relays[id].scheduledReport) relayMQTT(id);
  397. if (!recursive) {
  398. relayPulse(id);
  399. relaySync(id);
  400. relaySave();
  401. relayWS();
  402. }
  403. #if ENABLE_DOMOTICZ
  404. relayDomoticzSend(id);
  405. #endif
  406. #if ENABLE_INFLUXDB
  407. relayInfluxDB(id);
  408. #endif
  409. _relays[id].scheduledReport = false;
  410. }
  411. }
  412. }