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.

462 lines
12 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. } relay_t;
  14. std::vector<relay_t> _relays;
  15. #ifdef SONOFF_DUAL
  16. unsigned char dualRelayStatus = 0;
  17. #endif
  18. Ticker pulseTicker;
  19. bool recursive = false;
  20. // -----------------------------------------------------------------------------
  21. // RELAY
  22. // -----------------------------------------------------------------------------
  23. String relayString() {
  24. DynamicJsonBuffer jsonBuffer;
  25. JsonObject& root = jsonBuffer.createObject();
  26. JsonArray& relay = root.createNestedArray("relayStatus");
  27. for (unsigned char i=0; i<relayCount(); i++) {
  28. relay.add(relayStatus(i));
  29. }
  30. String output;
  31. root.printTo(output);
  32. return output;
  33. }
  34. bool relayStatus(unsigned char id) {
  35. #ifdef SONOFF_DUAL
  36. if (id >= 2) return false;
  37. return ((dualRelayStatus & (1 << id)) > 0);
  38. #else
  39. if (id >= _relays.size()) return false;
  40. bool status = (digitalRead(_relays[id].pin) == HIGH);
  41. return _relays[id].reverse ? !status : status;
  42. #endif
  43. }
  44. void relayPulse(unsigned char id) {
  45. byte relayPulseMode = getSetting("relayPulseMode", RELAY_PULSE_MODE).toInt();
  46. if (relayPulseMode == RELAY_PULSE_NONE) return;
  47. bool status = relayStatus(id);
  48. bool pulseStatus = (relayPulseMode == RELAY_PULSE_ON);
  49. if (pulseStatus == status) {
  50. pulseTicker.detach();
  51. return;
  52. }
  53. pulseTicker.once(
  54. getSetting("relayPulseTime", RELAY_PULSE_TIME).toInt(),
  55. relayToggle,
  56. id
  57. );
  58. }
  59. unsigned int relayPulseMode() {
  60. unsigned int value = getSetting("relayPulseMode", RELAY_PULSE_MODE).toInt();
  61. return value;
  62. }
  63. void relayPulseMode(unsigned int value, bool report) {
  64. setSetting("relayPulseMode", value);
  65. /*
  66. if (report) {
  67. String mqttGetter = getSetting("mqttGetter", MQTT_USE_GETTER);
  68. char topic[strlen(MQTT_RELAY_TOPIC) + mqttGetter.length() + 10];
  69. sprintf(topic, "%s/pulse%s", MQTT_RELAY_TOPIC, mqttGetter.c_str());
  70. char value[2];
  71. sprintf(value, "%d", value);
  72. mqttSend(topic, value);
  73. }
  74. */
  75. char message[20];
  76. sprintf(message, "{\"relayPulseMode\": %d}", value);
  77. wsSend(message);
  78. }
  79. void relayPulseMode(unsigned int value) {
  80. relayPulseMode(value, true);
  81. }
  82. void relayPulseToggle() {
  83. unsigned int value = relayPulseMode();
  84. value = (value == RELAY_PULSE_NONE) ? RELAY_PULSE_OFF : RELAY_PULSE_NONE;
  85. relayPulseMode(value);
  86. }
  87. bool relayStatus(unsigned char id, bool status, bool report) {
  88. if (id >= _relays.size()) return false;
  89. bool changed = false;
  90. if (relayStatus(id) != status) {
  91. DEBUG_MSG("[RELAY] %d => %s\n", id, status ? "ON" : "OFF");
  92. changed = true;
  93. #ifdef SONOFF_DUAL
  94. dualRelayStatus ^= (1 << id);
  95. Serial.flush();
  96. Serial.write(0xA0);
  97. Serial.write(0x04);
  98. Serial.write(dualRelayStatus);
  99. Serial.write(0xA1);
  100. Serial.flush();
  101. #else
  102. digitalWrite(_relays[id].pin, _relays[id].reverse ? !status : status);
  103. #endif
  104. if (report) relayMQTT(id);
  105. if (!recursive) {
  106. relayPulse(id);
  107. relaySync(id);
  108. relaySave();
  109. relayWS();
  110. }
  111. #ifdef ENABLE_DOMOTICZ
  112. relayDomoticzSend(id);
  113. #endif
  114. }
  115. return changed;
  116. }
  117. bool relayStatus(unsigned char id, bool status) {
  118. return relayStatus(id, status, true);
  119. }
  120. void relaySync(unsigned char id) {
  121. if (_relays.size() > 1) {
  122. recursive = true;
  123. byte relaySync = getSetting("relaySync", RELAY_SYNC).toInt();
  124. bool status = relayStatus(id);
  125. // If RELAY_SYNC_SAME all relays should have the same state
  126. if (relaySync == RELAY_SYNC_SAME) {
  127. for (unsigned short i=0; i<_relays.size(); i++) {
  128. if (i != id) relayStatus(i, status);
  129. }
  130. // If NONE_OR_ONE or ONE and setting ON we should set OFF all the others
  131. } else if (status) {
  132. if (relaySync != RELAY_SYNC_ANY) {
  133. for (unsigned short i=0; i<_relays.size(); i++) {
  134. if (i != id) relayStatus(i, false);
  135. }
  136. }
  137. // If ONLY_ONE and setting OFF we should set ON the other one
  138. } else {
  139. if (relaySync == RELAY_SYNC_ONE) {
  140. unsigned char i = (id + 1) % _relays.size();
  141. relayStatus(i, true);
  142. }
  143. }
  144. recursive = false;
  145. }
  146. }
  147. void relaySave() {
  148. unsigned char bit = 1;
  149. unsigned char mask = 0;
  150. for (unsigned int i=0; i < _relays.size(); i++) {
  151. if (relayStatus(i)) mask += bit;
  152. bit += bit;
  153. }
  154. EEPROM.write(EEPROM_RELAY_STATUS, mask);
  155. EEPROM.commit();
  156. }
  157. void relayRetrieve(bool invert) {
  158. recursive = true;
  159. unsigned char bit = 1;
  160. unsigned char mask = invert ? ~EEPROM.read(EEPROM_RELAY_STATUS) : EEPROM.read(EEPROM_RELAY_STATUS);
  161. for (unsigned int i=0; i < _relays.size(); i++) {
  162. relayStatus(i, ((mask & bit) == bit));
  163. bit += bit;
  164. }
  165. if (invert) {
  166. EEPROM.write(EEPROM_RELAY_STATUS, mask);
  167. EEPROM.commit();
  168. }
  169. recursive = false;
  170. }
  171. void relayToggle(unsigned char id) {
  172. if (id >= _relays.size()) return;
  173. relayStatus(id, !relayStatus(id));
  174. }
  175. unsigned char relayCount() {
  176. return _relays.size();
  177. }
  178. //------------------------------------------------------------------------------
  179. // REST API
  180. //------------------------------------------------------------------------------
  181. void relaySetupAPI() {
  182. // API entry points (protected with apikey)
  183. for (unsigned int relayID=0; relayID<relayCount(); relayID++) {
  184. char url[15];
  185. sprintf(url, "/api/relay/%d", relayID);
  186. char key[10];
  187. sprintf(key, "relay%d", relayID);
  188. apiRegister(url, key,
  189. [relayID](char * buffer, size_t len) {
  190. snprintf(buffer, len, "%d", relayStatus(relayID) ? 1 : 0);
  191. },
  192. [relayID](const char * payload) {
  193. unsigned int value = payload[0] - '0';
  194. if (value == 2) {
  195. relayToggle(relayID);
  196. } else {
  197. relayStatus(relayID, value == 1);
  198. }
  199. }
  200. );
  201. }
  202. }
  203. //------------------------------------------------------------------------------
  204. // WebSockets
  205. //------------------------------------------------------------------------------
  206. void relayWS() {
  207. String output = relayString();
  208. wsSend(output.c_str());
  209. }
  210. //------------------------------------------------------------------------------
  211. // Domoticz
  212. //------------------------------------------------------------------------------
  213. #if ENABLE_DOMOTICZ
  214. void relayDomoticzSend(unsigned int relayID) {
  215. char buffer[15];
  216. sprintf(buffer, "dczRelayIdx%d", relayID);
  217. domoticzSend(buffer, relayStatus(relayID) ? "1" : "0");
  218. }
  219. int relayFromIdx(unsigned int idx) {
  220. for (int relayID=0; relayID<relayCount(); relayID++) {
  221. if (relayToIdx(relayID) == idx) {
  222. return relayID;
  223. }
  224. }
  225. return -1;
  226. }
  227. int relayToIdx(unsigned int relayID) {
  228. char buffer[15];
  229. sprintf(buffer, "dczRelayIdx%d", relayID);
  230. return getSetting(buffer).toInt();
  231. }
  232. void relayDomoticzSetup() {
  233. mqttRegister([](unsigned int type, const char * topic, const char * payload) {
  234. String dczTopicOut = getSetting("dczTopicOut", DOMOTICZ_OUT_TOPIC);
  235. if (type == MQTT_CONNECT_EVENT) {
  236. mqttSubscribeRaw(dczTopicOut.c_str());
  237. }
  238. if (type == MQTT_MESSAGE_EVENT) {
  239. // Check topic
  240. if (dczTopicOut.equals(topic)) {
  241. // Parse response
  242. DynamicJsonBuffer jsonBuffer;
  243. JsonObject& root = jsonBuffer.parseObject((char *) payload);
  244. if (!root.success()) {
  245. DEBUG_MSG("[DOMOTICZ] Error parsing data\n");
  246. return;
  247. }
  248. // IDX
  249. unsigned long idx = root["idx"];
  250. int relayID = relayFromIdx(idx);
  251. if (relayID >= 0) {
  252. unsigned long value = root["nvalue"];
  253. DEBUG_MSG("[DOMOTICZ] Received value %d for IDX %d\n", value, idx);
  254. relayStatus(relayID, value == 1);
  255. }
  256. }
  257. }
  258. });
  259. }
  260. #endif
  261. //------------------------------------------------------------------------------
  262. // MQTT
  263. //------------------------------------------------------------------------------
  264. void relayMQTT(unsigned char id) {
  265. if (id >= _relays.size()) return;
  266. String mqttGetter = getSetting("mqttGetter", MQTT_USE_GETTER);
  267. char buffer[strlen(MQTT_RELAY_TOPIC) + mqttGetter.length() + 3];
  268. sprintf(buffer, "%s/%d%s", MQTT_RELAY_TOPIC, id, mqttGetter.c_str());
  269. mqttSend(buffer, relayStatus(id) ? "1" : "0");
  270. }
  271. void relayMQTT() {
  272. for (unsigned int i=0; i < _relays.size(); i++) {
  273. relayMQTT(i);
  274. }
  275. }
  276. void relayMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  277. String mqttSetter = getSetting("mqttSetter", MQTT_USE_SETTER);
  278. String mqttGetter = getSetting("mqttGetter", MQTT_USE_GETTER);
  279. bool sameSetGet = mqttGetter.compareTo(mqttSetter) == 0;
  280. if (type == MQTT_CONNECT_EVENT) {
  281. relayMQTT();
  282. char buffer[strlen(MQTT_RELAY_TOPIC) + mqttSetter.length() + 10];
  283. sprintf(buffer, "%s/+%s", MQTT_RELAY_TOPIC, mqttSetter.c_str());
  284. mqttSubscribe(buffer);
  285. }
  286. if (type == MQTT_MESSAGE_EVENT) {
  287. // Match topic
  288. char * t = mqttSubtopic((char *) topic);
  289. if (strncmp(t, MQTT_RELAY_TOPIC, strlen(MQTT_RELAY_TOPIC)) != 0) return;
  290. int len = mqttSetter.length();
  291. if (strncmp(t + strlen(t) - len, mqttSetter.c_str(), len) != 0) return;
  292. // Get value
  293. unsigned int value = (char)payload[0] - '0';
  294. // Pulse topic
  295. if (strncmp(t + strlen(MQTT_RELAY_TOPIC) + 1, "pulse", 5) == 0) {
  296. relayPulseMode(value, !sameSetGet);
  297. return;
  298. }
  299. // Get relay ID
  300. unsigned int relayID = topic[strlen(topic) - mqttSetter.length() - 1] - '0';
  301. if (relayID >= relayCount()) {
  302. DEBUG_MSG("[RELAY] Wrong relayID (%d)\n", relayID);
  303. return;
  304. }
  305. // Action to perform
  306. if (value == 2) {
  307. relayToggle(relayID);
  308. } else {
  309. relayStatus(relayID, value > 0, !sameSetGet);
  310. }
  311. }
  312. }
  313. void relaySetupMQTT() {
  314. mqttRegister(relayMQTTCallback);
  315. }
  316. //------------------------------------------------------------------------------
  317. // Setup
  318. //------------------------------------------------------------------------------
  319. void relaySetup() {
  320. #ifdef SONOFF_DUAL
  321. // Two dummy relays for the dual
  322. _relays.push_back((relay_t) {0, 0});
  323. _relays.push_back((relay_t) {0, 0});
  324. #else
  325. #ifdef RELAY1_PIN
  326. _relays.push_back((relay_t) { RELAY1_PIN, RELAY1_PIN_INVERSE });
  327. #endif
  328. #ifdef RELAY2_PIN
  329. _relays.push_back((relay_t) { RELAY2_PIN, RELAY2_PIN_INVERSE });
  330. #endif
  331. #ifdef RELAY3_PIN
  332. _relays.push_back((relay_t) { RELAY3_PIN, RELAY3_PIN_INVERSE });
  333. #endif
  334. #ifdef RELAY4_PIN
  335. _relays.push_back((relay_t) { RELAY4_PIN, RELAY4_PIN_INVERSE });
  336. #endif
  337. #endif
  338. EEPROM.begin(4096);
  339. byte relayMode = getSetting("relayMode", RELAY_MODE).toInt();
  340. for (unsigned int i=0; i < _relays.size(); i++) {
  341. pinMode(_relays[i].pin, OUTPUT);
  342. if (relayMode == RELAY_MODE_OFF) relayStatus(i, false);
  343. if (relayMode == RELAY_MODE_ON) relayStatus(i, true);
  344. }
  345. if (relayMode == RELAY_MODE_SAME) relayRetrieve(false);
  346. if (relayMode == RELAY_MODE_TOOGLE) relayRetrieve(true);
  347. relaySetupAPI();
  348. relaySetupMQTT();
  349. #if ENABLE_DOMOTICZ
  350. relayDomoticzSetup();
  351. #endif
  352. DEBUG_MSG("[RELAY] Number of relays: %d\n", _relays.size());
  353. }