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.

566 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. rfbStatus(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 TRACK_RELAY_STATUS
  128. if (relayStatus(id) != status) {
  129. #endif
  130. unsigned int floodWindowEnd = _relays[id].floodWindowStart + 1000 * RELAY_FLOOD_WINDOW;
  131. unsigned int currentTime = millis();
  132. _relays[id].floodWindowChanges++;
  133. _relays[id].scheduledStatusTime = currentTime;
  134. if (currentTime >= floodWindowEnd || currentTime < _relays[id].floodWindowStart) {
  135. _relays[id].floodWindowStart = currentTime;
  136. _relays[id].floodWindowChanges = 1;
  137. } else if (_relays[id].floodWindowChanges >= RELAY_FLOOD_CHANGES) {
  138. _relays[id].scheduledStatusTime = floodWindowEnd;
  139. }
  140. _relays[id].scheduled = true;
  141. _relays[id].scheduledStatus = status;
  142. _relays[id].scheduledReport = (report ? true : _relays[id].scheduledReport);
  143. DEBUG_MSG_P(PSTR("[RELAY] Scheduled %d => %s in %u ms\n"),
  144. id, status ? "ON" : "OFF",
  145. (_relays[id].scheduledStatusTime - currentTime));
  146. changed = true;
  147. #if TRACK_RELAY_STATUS
  148. }
  149. #endif
  150. return changed;
  151. }
  152. bool relayStatus(unsigned char id, bool status) {
  153. return relayStatus(id, status, true);
  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. String output = relayString();
  246. wsSend(output.c_str());
  247. }
  248. //------------------------------------------------------------------------------
  249. // Domoticz
  250. //------------------------------------------------------------------------------
  251. #if ENABLE_DOMOTICZ
  252. void relayDomoticzSend(unsigned int relayID) {
  253. char buffer[15];
  254. sprintf(buffer, "dczRelayIdx%d", relayID);
  255. domoticzSend(buffer, relayStatus(relayID) ? "1" : "0");
  256. }
  257. int relayFromIdx(unsigned int idx) {
  258. for (int relayID=0; relayID<relayCount(); relayID++) {
  259. if (relayToIdx(relayID) == idx) {
  260. return relayID;
  261. }
  262. }
  263. return -1;
  264. }
  265. int relayToIdx(unsigned int relayID) {
  266. char buffer[15];
  267. sprintf(buffer, "dczRelayIdx%d", relayID);
  268. return getSetting(buffer).toInt();
  269. }
  270. void relayDomoticzSetup() {
  271. mqttRegister([](unsigned int type, const char * topic, const char * payload) {
  272. String dczTopicOut = getSetting("dczTopicOut", DOMOTICZ_OUT_TOPIC);
  273. if (type == MQTT_CONNECT_EVENT) {
  274. mqttSubscribeRaw(dczTopicOut.c_str());
  275. }
  276. if (type == MQTT_MESSAGE_EVENT) {
  277. // Check topic
  278. if (dczTopicOut.equals(topic)) {
  279. // Parse response
  280. DynamicJsonBuffer jsonBuffer;
  281. JsonObject& root = jsonBuffer.parseObject((char *) payload);
  282. if (!root.success()) {
  283. DEBUG_MSG_P(PSTR("[DOMOTICZ] Error parsing data\n"));
  284. return;
  285. }
  286. // IDX
  287. unsigned long idx = root["idx"];
  288. int relayID = relayFromIdx(idx);
  289. if (relayID >= 0) {
  290. unsigned long value = root["nvalue"];
  291. DEBUG_MSG_P(PSTR("[DOMOTICZ] Received value %d for IDX %d\n"), value, idx);
  292. relayStatus(relayID, value == 1);
  293. }
  294. }
  295. }
  296. });
  297. }
  298. #endif
  299. //------------------------------------------------------------------------------
  300. // MQTT
  301. //------------------------------------------------------------------------------
  302. void relayMQTT(unsigned char id) {
  303. if (id >= _relays.size()) return;
  304. mqttSend(MQTT_TOPIC_RELAY, id, relayStatus(id) ? "1" : "0");
  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. void relayMQTT() {
  315. for (unsigned int i=0; i < _relays.size(); i++) {
  316. relayMQTT(i);
  317. }
  318. }
  319. void relayMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  320. if (type == MQTT_CONNECT_EVENT) {
  321. #if not HEARTBEAT_REPORT_RELAY
  322. relayMQTT();
  323. #endif
  324. char buffer[strlen(MQTT_TOPIC_RELAY) + 3];
  325. sprintf(buffer, "%s/+", MQTT_TOPIC_RELAY);
  326. mqttSubscribe(buffer);
  327. }
  328. if (type == MQTT_MESSAGE_EVENT) {
  329. // Match topic
  330. String t = mqttSubtopic((char *) topic);
  331. if (!t.startsWith(MQTT_TOPIC_RELAY)) return;
  332. // Get value
  333. unsigned int value = (char)payload[0] - '0';
  334. // Pulse topic
  335. if (t.endsWith("pulse")) {
  336. relayPulseMode(value, mqttForward());
  337. return;
  338. }
  339. // Get relay ID
  340. unsigned int relayID = t.substring(strlen(MQTT_TOPIC_RELAY)+1).toInt();
  341. if (relayID >= relayCount()) {
  342. DEBUG_MSG_P(PSTR("[RELAY] Wrong relayID (%d)\n"), relayID);
  343. return;
  344. }
  345. // Action to perform
  346. if (value == 2) {
  347. relayToggle(relayID);
  348. } else {
  349. relayStatus(relayID, value > 0, mqttForward());
  350. }
  351. }
  352. }
  353. void relaySetupMQTT() {
  354. mqttRegister(relayMQTTCallback);
  355. }
  356. //------------------------------------------------------------------------------
  357. // Setup
  358. //------------------------------------------------------------------------------
  359. void relaySetup() {
  360. // Dummy relays for AI Light, Magic Home LED Controller, H801,
  361. // Sonoff Dual and Sonoff RF Bridge
  362. #ifdef DUMMY_RELAY_COUNT
  363. for (unsigned char i=0; i < DUMMY_RELAY_COUNT; i++) {
  364. _relays.push_back((relay_t) {0, 0});
  365. _relays[i].scheduled = false;
  366. }
  367. #else
  368. #ifdef RELAY1_PIN
  369. _relays.push_back((relay_t) { RELAY1_PIN, RELAY1_PIN_INVERSE, RELAY1_LED });
  370. #endif
  371. #ifdef RELAY2_PIN
  372. _relays.push_back((relay_t) { RELAY2_PIN, RELAY2_PIN_INVERSE, RELAY2_LED });
  373. #endif
  374. #ifdef RELAY3_PIN
  375. _relays.push_back((relay_t) { RELAY3_PIN, RELAY3_PIN_INVERSE, RELAY3_LED });
  376. #endif
  377. #ifdef RELAY4_PIN
  378. _relays.push_back((relay_t) { RELAY4_PIN, RELAY4_PIN_INVERSE, RELAY4_LED });
  379. #endif
  380. #endif
  381. byte relayMode = getSetting("relayMode", RELAY_MODE).toInt();
  382. for (unsigned int i=0; i < _relays.size(); i++) {
  383. pinMode(_relays[i].pin, OUTPUT);
  384. if (relayMode == RELAY_MODE_OFF) relayStatus(i, false);
  385. if (relayMode == RELAY_MODE_ON) relayStatus(i, true);
  386. }
  387. if (relayMode == RELAY_MODE_SAME) relayRetrieve(false);
  388. if (relayMode == RELAY_MODE_TOOGLE) relayRetrieve(true);
  389. relayLoop();
  390. relaySetupAPI();
  391. relaySetupMQTT();
  392. #if ENABLE_DOMOTICZ
  393. relayDomoticzSetup();
  394. #endif
  395. DEBUG_MSG_P(PSTR("[RELAY] Number of relays: %d\n"), _relays.size());
  396. }
  397. void relayLoop(void) {
  398. unsigned char id;
  399. for (id = 0; id < _relays.size(); id++) {
  400. unsigned int currentTime = millis();
  401. bool status = _relays[id].scheduledStatus;
  402. #if TRACK_RELAY_STATUS
  403. if (relayStatus(id) != status && currentTime >= _relays[id].scheduledStatusTime) {
  404. #else
  405. if (_relays[id].scheduled && currentTime >= _relays[id].scheduledStatusTime) {
  406. #endif
  407. DEBUG_MSG_P(PSTR("[RELAY] %d => %s\n"), id, status ? "ON" : "OFF");
  408. relayProviderStatus(id, status);
  409. if (_relays[id].led > 0) {
  410. ledStatus(_relays[id].led - 1, status);
  411. }
  412. if (_relays[id].scheduledReport) {
  413. relayMQTT(id);
  414. }
  415. if (!recursive) {
  416. relayPulse(id);
  417. relaySync(id);
  418. relaySave();
  419. relayWS();
  420. }
  421. #if ENABLE_DOMOTICZ
  422. relayDomoticzSend(id);
  423. #endif
  424. #if ENABLE_INFLUXDB
  425. relayInfluxDB(id);
  426. #endif
  427. _relays[id].scheduled = false;
  428. _relays[id].scheduledReport = false;
  429. }
  430. }
  431. }