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.

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