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.

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