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.

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