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.

461 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. // WebSockets
  204. //------------------------------------------------------------------------------
  205. void relayWS() {
  206. String output = relayString();
  207. wsSend(output.c_str());
  208. }
  209. //------------------------------------------------------------------------------
  210. // Domoticz
  211. //------------------------------------------------------------------------------
  212. #if ENABLE_DOMOTICZ
  213. void relayDomoticzSend(unsigned int relayID) {
  214. char buffer[15];
  215. sprintf(buffer, "dczRelayIdx%d", relayID);
  216. domoticzSend(buffer, relayStatus(relayID) ? "1" : "0");
  217. }
  218. int relayFromIdx(unsigned int idx) {
  219. for (int relayID=0; relayID<relayCount(); relayID++) {
  220. if (relayToIdx(relayID) == idx) {
  221. return relayID;
  222. }
  223. }
  224. return -1;
  225. }
  226. int relayToIdx(unsigned int relayID) {
  227. char buffer[15];
  228. sprintf(buffer, "dczRelayIdx%d", relayID);
  229. return getSetting(buffer).toInt();
  230. }
  231. void relayDomoticzSetup() {
  232. mqttRegister([](unsigned int type, const char * topic, const char * payload) {
  233. String dczTopicOut = getSetting("dczTopicOut", DOMOTICZ_OUT_TOPIC);
  234. if (type == MQTT_CONNECT_EVENT) {
  235. mqttSubscribeRaw(dczTopicOut.c_str());
  236. }
  237. if (type == MQTT_MESSAGE_EVENT) {
  238. // Check topic
  239. if (dczTopicOut.equals(topic)) {
  240. // Parse response
  241. DynamicJsonBuffer jsonBuffer;
  242. JsonObject& root = jsonBuffer.parseObject((char *) payload);
  243. if (!root.success()) {
  244. DEBUG_MSG("[DOMOTICZ] Error parsing data\n");
  245. return;
  246. }
  247. // IDX
  248. unsigned long idx = root["idx"];
  249. int relayID = relayFromIdx(idx);
  250. if (relayID >= 0) {
  251. unsigned long value = root["nvalue"];
  252. DEBUG_MSG("[DOMOTICZ] Received value %d for IDX %d\n", value, idx);
  253. relayStatus(relayID, value == 1);
  254. }
  255. }
  256. }
  257. });
  258. }
  259. #endif
  260. //------------------------------------------------------------------------------
  261. // MQTT
  262. //------------------------------------------------------------------------------
  263. void relayMQTT(unsigned char id) {
  264. if (id >= _relays.size()) return;
  265. String mqttGetter = getSetting("mqttGetter", MQTT_USE_GETTER);
  266. char buffer[strlen(MQTT_RELAY_TOPIC) + mqttGetter.length() + 3];
  267. sprintf(buffer, "%s/%d%s", MQTT_RELAY_TOPIC, id, mqttGetter.c_str());
  268. mqttSend(buffer, relayStatus(id) ? "1" : "0");
  269. }
  270. void relayMQTT() {
  271. for (unsigned int i=0; i < _relays.size(); i++) {
  272. relayMQTT(i);
  273. }
  274. }
  275. void relayMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  276. String mqttSetter = getSetting("mqttSetter", MQTT_USE_SETTER);
  277. String mqttGetter = getSetting("mqttGetter", MQTT_USE_GETTER);
  278. bool sameSetGet = mqttGetter.compareTo(mqttSetter) == 0;
  279. if (type == MQTT_CONNECT_EVENT) {
  280. relayMQTT();
  281. char buffer[strlen(MQTT_RELAY_TOPIC) + mqttSetter.length() + 10];
  282. sprintf(buffer, "%s/+%s", MQTT_RELAY_TOPIC, mqttSetter.c_str());
  283. mqttSubscribe(buffer);
  284. }
  285. if (type == MQTT_MESSAGE_EVENT) {
  286. // Match topic
  287. char * t = mqttSubtopic((char *) topic);
  288. if (strncmp(t, MQTT_RELAY_TOPIC, strlen(MQTT_RELAY_TOPIC)) != 0) return;
  289. int len = mqttSetter.length();
  290. if (strncmp(t + strlen(t) - len, mqttSetter.c_str(), len) != 0) return;
  291. // Get value
  292. unsigned int value = (char)payload[0] - '0';
  293. // Pulse topic
  294. if (strncmp(t + strlen(MQTT_RELAY_TOPIC) + 1, "pulse", 5) == 0) {
  295. relayPulseMode(value, !sameSetGet);
  296. return;
  297. }
  298. // Get relay ID
  299. unsigned int relayID = topic[strlen(topic) - mqttSetter.length() - 1] - '0';
  300. if (relayID >= relayCount()) {
  301. DEBUG_MSG("[RELAY] Wrong relayID (%d)\n", relayID);
  302. return;
  303. }
  304. // Action to perform
  305. if (value == 2) {
  306. relayToggle(relayID);
  307. } else {
  308. relayStatus(relayID, value > 0, !sameSetGet);
  309. }
  310. }
  311. }
  312. void relaySetupMQTT() {
  313. mqttRegister(relayMQTTCallback);
  314. }
  315. //------------------------------------------------------------------------------
  316. // Setup
  317. //------------------------------------------------------------------------------
  318. void relaySetup() {
  319. #ifdef SONOFF_DUAL
  320. // Two dummy relays for the dual
  321. _relays.push_back((relay_t) {0, 0});
  322. _relays.push_back((relay_t) {0, 0});
  323. #else
  324. #ifdef RELAY1_PIN
  325. _relays.push_back((relay_t) { RELAY1_PIN, RELAY1_PIN_INVERSE });
  326. #endif
  327. #ifdef RELAY2_PIN
  328. _relays.push_back((relay_t) { RELAY2_PIN, RELAY2_PIN_INVERSE });
  329. #endif
  330. #ifdef RELAY3_PIN
  331. _relays.push_back((relay_t) { RELAY3_PIN, RELAY3_PIN_INVERSE });
  332. #endif
  333. #ifdef RELAY4_PIN
  334. _relays.push_back((relay_t) { RELAY4_PIN, RELAY4_PIN_INVERSE });
  335. #endif
  336. #endif
  337. EEPROM.begin(4096);
  338. byte relayMode = getSetting("relayMode", RELAY_MODE).toInt();
  339. for (unsigned int i=0; i < _relays.size(); i++) {
  340. pinMode(_relays[i].pin, OUTPUT);
  341. if (relayMode == RELAY_MODE_OFF) relayStatus(i, false);
  342. if (relayMode == RELAY_MODE_ON) relayStatus(i, true);
  343. }
  344. if (relayMode == RELAY_MODE_SAME) relayRetrieve(false);
  345. if (relayMode == RELAY_MODE_TOOGLE) relayRetrieve(true);
  346. relaySetupAPI();
  347. relaySetupMQTT();
  348. #if ENABLE_DOMOTICZ
  349. relayDomoticzSetup();
  350. #endif
  351. DEBUG_MSG("[RELAY] Number of relays: %d\n", _relays.size());
  352. }