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.

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