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.

472 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. EEPROM.write(0, 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. sprintf(buffer, "%s/pulse%s", MQTT_RELAY_TOPIC, mqttSetter.c_str());
  292. mqttSubscribe(buffer);
  293. }
  294. if (type == MQTT_MESSAGE_EVENT) {
  295. // Match topic
  296. String t = String(topic + mqttTopicRootLength());
  297. if (!t.startsWith(MQTT_RELAY_TOPIC)) return;
  298. if (!t.endsWith(mqttSetter)) return;
  299. // Get value
  300. unsigned int value = (char)payload[0] - '0';
  301. // Pulse topic
  302. if (t.indexOf("pulse") > 0) {
  303. relayPulseMode(value, !sameSetGet);
  304. return;
  305. }
  306. // Get relay ID
  307. unsigned int relayID = topic[strlen(topic) - mqttSetter.length() - 1] - '0';
  308. if (relayID >= relayCount()) {
  309. DEBUG_MSG("[RELAY] Wrong relayID (%d)\n", relayID);
  310. return;
  311. }
  312. // Action to perform
  313. if (value == 2) {
  314. relayToggle(relayID);
  315. } else {
  316. relayStatus(relayID, value > 0, !sameSetGet);
  317. }
  318. }
  319. }
  320. void relaySetupMQTT() {
  321. mqttRegister(relayMQTTCallback);
  322. }
  323. //------------------------------------------------------------------------------
  324. // Setup
  325. //------------------------------------------------------------------------------
  326. void relaySetup() {
  327. #ifdef SONOFF_DUAL
  328. // Two dummy relays for the dual
  329. _relays.push_back((relay_t) {0, 0});
  330. _relays.push_back((relay_t) {0, 0});
  331. #else
  332. #ifdef RELAY1_PIN
  333. _relays.push_back((relay_t) { RELAY1_PIN, RELAY1_PIN_INVERSE });
  334. #endif
  335. #ifdef RELAY2_PIN
  336. _relays.push_back((relay_t) { RELAY2_PIN, RELAY2_PIN_INVERSE });
  337. #endif
  338. #ifdef RELAY3_PIN
  339. _relays.push_back((relay_t) { RELAY3_PIN, RELAY3_PIN_INVERSE });
  340. #endif
  341. #ifdef RELAY4_PIN
  342. _relays.push_back((relay_t) { RELAY4_PIN, RELAY4_PIN_INVERSE });
  343. #endif
  344. #endif
  345. EEPROM.begin(4096);
  346. byte relayMode = getSetting("relayMode", RELAY_MODE).toInt();
  347. for (unsigned int i=0; i < _relays.size(); i++) {
  348. pinMode(_relays[i].pin, OUTPUT);
  349. if (relayMode == RELAY_MODE_OFF) relayStatus(i, false);
  350. if (relayMode == RELAY_MODE_ON) relayStatus(i, true);
  351. }
  352. if (relayMode == RELAY_MODE_SAME) relayRetrieve(false);
  353. if (relayMode == RELAY_MODE_TOOGLE) relayRetrieve(true);
  354. relaySetupAPI();
  355. relaySetupMQTT();
  356. #if ENABLE_DOMOTICZ
  357. relayDomoticzSetup();
  358. #endif
  359. DEBUG_MSG("[RELAY] Number of relays: %d\n", _relays.size());
  360. }