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.

476 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(0, 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(0) : EEPROM.read(0);
  168. for (unsigned int i=0; i < _relays.size(); i++) {
  169. relayStatus(i, ((mask & bit) == bit));
  170. bit += bit;
  171. }
  172. if (invert) {
  173. relaySave();
  174. }
  175. recursive = false;
  176. }
  177. void relayToggle(unsigned char id) {
  178. if (id >= _relays.size()) return;
  179. relayStatus(id, !relayStatus(id));
  180. }
  181. unsigned char relayCount() {
  182. return _relays.size();
  183. }
  184. //------------------------------------------------------------------------------
  185. // REST API
  186. //------------------------------------------------------------------------------
  187. void relaySetupAPI() {
  188. // API entry points (protected with apikey)
  189. for (unsigned int relayID=0; relayID<relayCount(); relayID++) {
  190. char url[15];
  191. sprintf(url, "/api/relay/%d", relayID);
  192. char key[10];
  193. sprintf(key, "relay%d", relayID);
  194. apiRegister(url, key,
  195. [relayID](char * buffer, size_t len) {
  196. snprintf(buffer, len, "%d", relayStatus(relayID) ? 1 : 0);
  197. },
  198. [relayID](const char * payload) {
  199. unsigned int value = payload[0] - '0';
  200. if (value == 2) {
  201. relayToggle(relayID);
  202. } else {
  203. relayStatus(relayID, value == 1);
  204. }
  205. });
  206. }
  207. }
  208. //------------------------------------------------------------------------------
  209. // WebSockets
  210. //------------------------------------------------------------------------------
  211. void relayWS() {
  212. String output = relayString();
  213. wsSend(output.c_str());
  214. }
  215. //------------------------------------------------------------------------------
  216. // Domoticz
  217. //------------------------------------------------------------------------------
  218. #if ENABLE_DOMOTICZ
  219. void relayDomoticzSend(unsigned int relayID) {
  220. char buffer[15];
  221. sprintf(buffer, "dczRelayIdx%d", relayID);
  222. domoticzSend(buffer, relayStatus(relayID) ? "1" : "0");
  223. }
  224. int relayFromIdx(unsigned int idx) {
  225. for (int relayID=0; relayID<relayCount(); relayID++) {
  226. if (relayToIdx(relayID) == idx) {
  227. return relayID;
  228. }
  229. }
  230. return -1;
  231. }
  232. int relayToIdx(unsigned int relayID) {
  233. char buffer[15];
  234. sprintf(buffer, "dczRelayIdx%d", relayID);
  235. return getSetting(buffer).toInt();
  236. }
  237. void relayDomoticzSetup() {
  238. mqttRegister([](unsigned int type, const char * topic, const char * payload) {
  239. String dczTopicOut = getSetting("dczTopicOut", DOMOTICZ_OUT_TOPIC);
  240. if (type == MQTT_CONNECT_EVENT) {
  241. mqttSubscribeRaw(dczTopicOut.c_str());
  242. }
  243. if (type == MQTT_MESSAGE_EVENT) {
  244. // Check topic
  245. if (dczTopicOut.equals(topic)) {
  246. // Parse response
  247. DynamicJsonBuffer jsonBuffer;
  248. JsonObject& root = jsonBuffer.parseObject((char *) payload);
  249. if (!root.success()) {
  250. DEBUG_MSG("[DOMOTICZ] Error parsing data\n");
  251. return;
  252. }
  253. // IDX
  254. unsigned long idx = root["idx"];
  255. int relayID = relayFromIdx(idx);
  256. if (relayID >= 0) {
  257. unsigned long value = root["nvalue"];
  258. DEBUG_MSG("[DOMOTICZ] Received value %d for IDX %d\n", value, idx);
  259. relayStatus(relayID, value == 1);
  260. }
  261. }
  262. }
  263. });
  264. }
  265. #endif
  266. //------------------------------------------------------------------------------
  267. // MQTT
  268. //------------------------------------------------------------------------------
  269. void relayMQTT(unsigned char id) {
  270. if (id >= _relays.size()) return;
  271. String mqttGetter = getSetting("mqttGetter", MQTT_USE_GETTER);
  272. char buffer[strlen(MQTT_RELAY_TOPIC) + mqttGetter.length() + 3];
  273. sprintf(buffer, "%s/%d%s", MQTT_RELAY_TOPIC, id, mqttGetter.c_str());
  274. mqttSend(buffer, relayStatus(id) ? "1" : "0");
  275. }
  276. void relayMQTT() {
  277. for (unsigned int i=0; i < _relays.size(); i++) {
  278. relayMQTT(i);
  279. }
  280. }
  281. void relayMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  282. String mqttSetter = getSetting("mqttSetter", MQTT_USE_SETTER);
  283. String mqttGetter = getSetting("mqttGetter", MQTT_USE_GETTER);
  284. bool sameSetGet = mqttGetter.compareTo(mqttSetter) == 0;
  285. if (type == MQTT_CONNECT_EVENT) {
  286. relayMQTT();
  287. char buffer[strlen(MQTT_RELAY_TOPIC) + mqttSetter.length() + 10];
  288. sprintf(buffer, "%s/+%s", MQTT_RELAY_TOPIC, mqttSetter.c_str());
  289. mqttSubscribe(buffer);
  290. sprintf(buffer, "%s/pulse%s", MQTT_RELAY_TOPIC, mqttSetter.c_str());
  291. mqttSubscribe(buffer);
  292. }
  293. if (type == MQTT_MESSAGE_EVENT) {
  294. // Match topic
  295. String t = String(topic + mqttTopicRootLength());
  296. if (!t.startsWith(MQTT_RELAY_TOPIC)) return;
  297. if (!t.endsWith(mqttSetter)) return;
  298. // Get value
  299. unsigned int value = (char)payload[0] - '0';
  300. // Pulse topic
  301. if (t.indexOf("pulse") > 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. <<<<<<< HEAD
  352. if (relayMode == RELAY_MODE_SAME) relayRetrieve();
  353. =======
  354. if (relayMode == RELAY_MODE_SAME) relayRetrieve(false);
  355. if (relayMode == RELAY_MODE_TOOGLE) relayRetrieve(true);
  356. >>>>>>> Enable revert state mode
  357. relaySetupAPI();
  358. relaySetupMQTT();
  359. #if ENABLE_DOMOTICZ
  360. relayDomoticzSetup();
  361. #endif
  362. DEBUG_MSG("[RELAY] Number of relays: %d\n", _relays.size());
  363. }