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.

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