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.

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