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.

373 lines
10 KiB

  1. /*
  2. ITEAD RF BRIDGE MODULE
  3. Copyright (C) 2017 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #ifdef ITEAD_SONOFF_RFBRIDGE
  6. // -----------------------------------------------------------------------------
  7. // DEFINITIONS
  8. // -----------------------------------------------------------------------------
  9. #define RF_MESSAGE_SIZE 9
  10. #define RF_CODE_START 0xAA
  11. #define RF_CODE_ACK 0xA0
  12. #define RF_CODE_LEARN 0xA1
  13. #define RF_CODE_LEARN_KO 0xA2
  14. #define RF_CODE_LEARN_OK 0xA3
  15. #define RF_CODE_RFIN 0xA4
  16. #define RF_CODE_RFOUT 0xA5
  17. #define RF_CODE_STOP 0x55
  18. // -----------------------------------------------------------------------------
  19. // GLOBALS TO THE MODULE
  20. // -----------------------------------------------------------------------------
  21. unsigned char _uartbuf[RF_MESSAGE_SIZE+3] = {0};
  22. unsigned char _uartpos = 0;
  23. unsigned char _learnId = 0;
  24. bool _learnStatus = true;
  25. bool _rfbin = false;
  26. // -----------------------------------------------------------------------------
  27. // PRIVATES
  28. // -----------------------------------------------------------------------------
  29. void _rfbWebSocketOnSend(JsonObject& root) {
  30. root["rfbVisible"] = 1;
  31. root["rfbCount"] = relayCount();
  32. JsonArray& rfb = root.createNestedArray("rfb");
  33. for (byte id=0; id<relayCount(); id++) {
  34. for (byte status=0; status<2; status++) {
  35. JsonObject& node = rfb.createNestedObject();
  36. node["id"] = id;
  37. node["status"] = status;
  38. node["data"] = rfbRetrieve(id, status == 1);
  39. }
  40. }
  41. }
  42. void _rfbWebSocketOnAction(const char * action, JsonObject& data) {
  43. if (strcmp(action, "rfblearn") == 0) rfbLearn(data["id"], data["status"]);
  44. if (strcmp(action, "rfbforget") == 0) rfbForget(data["id"], data["status"]);
  45. if (strcmp(action, "rfbsend") == 0) rfbStore(data["id"], data["status"], data["data"].as<const char*>());
  46. }
  47. void _rfbAck() {
  48. DEBUG_MSG_P(PSTR("[RFBRIDGE] Sending ACK\n"));
  49. Serial.println();
  50. Serial.write(RF_CODE_START);
  51. Serial.write(RF_CODE_ACK);
  52. Serial.write(RF_CODE_STOP);
  53. Serial.flush();
  54. Serial.println();
  55. }
  56. void _rfbLearn() {
  57. DEBUG_MSG_P(PSTR("[RFBRIDGE] Sending LEARN\n"));
  58. Serial.println();
  59. Serial.write(RF_CODE_START);
  60. Serial.write(RF_CODE_LEARN);
  61. Serial.write(RF_CODE_STOP);
  62. Serial.flush();
  63. Serial.println();
  64. #if WEB_SUPPORT
  65. char buffer[100];
  66. snprintf_P(buffer, sizeof(buffer), PSTR("{\"action\": \"rfbLearn\", \"data\":{\"id\": %d, \"status\": %d}}"), _learnId, _learnStatus ? 1 : 0);
  67. wsSend(buffer);
  68. #endif
  69. }
  70. void _rfbSend(byte * message) {
  71. Serial.println();
  72. Serial.write(RF_CODE_START);
  73. Serial.write(RF_CODE_RFOUT);
  74. for (unsigned char j=0; j<RF_MESSAGE_SIZE; j++) {
  75. Serial.write(message[j]);
  76. }
  77. Serial.write(RF_CODE_STOP);
  78. Serial.flush();
  79. Serial.println();
  80. }
  81. void _rfbSend(byte * message, int times) {
  82. char buffer[RF_MESSAGE_SIZE];
  83. _rfbToChar(message, buffer);
  84. DEBUG_MSG_P(PSTR("[RFBRIDGE] Sending MESSAGE '%s' %d time(s)\n"), buffer, times);
  85. for (int i=0; i<times; i++) {
  86. if (i>0) {
  87. unsigned long start = millis();
  88. while (millis() - start < RF_SEND_DELAY) delay(1);
  89. }
  90. _rfbSend(message);
  91. }
  92. }
  93. void _rfbDecode() {
  94. static unsigned long last = 0;
  95. if (millis() - last < RF_RECEIVE_DELAY) return;
  96. last = millis();
  97. byte action = _uartbuf[0];
  98. char buffer[RF_MESSAGE_SIZE * 2 + 1] = {0};
  99. DEBUG_MSG_P(PSTR("[RFBRIDGE] Action 0x%02X\n"), action);
  100. if (action == RF_CODE_LEARN_KO) {
  101. _rfbAck();
  102. DEBUG_MSG_P(PSTR("[RFBRIDGE] Learn timeout\n"));
  103. #if WEB_SUPPORT
  104. wsSend_P(PSTR("{\"action\": \"rfbTimeout\"}"));
  105. #endif
  106. }
  107. if (action == RF_CODE_LEARN_OK || action == RF_CODE_RFIN) {
  108. #if MQTT_SUPPORT
  109. _rfbToChar(&_uartbuf[1], buffer);
  110. mqttSend(MQTT_TOPIC_RFIN, buffer);
  111. #endif
  112. _rfbAck();
  113. }
  114. if (action == RF_CODE_LEARN_OK) {
  115. DEBUG_MSG_P(PSTR("[RFBRIDGE] Learn success\n"));
  116. rfbStore(_learnId, _learnStatus, buffer);
  117. // Websocket update
  118. #if WEB_SUPPORT
  119. char wsb[100];
  120. snprintf_P(wsb, sizeof(wsb), PSTR("{\"rfb\":[{\"id\": %d, \"status\": %d, \"data\": \"%s\"}]}"), _learnId, _learnStatus ? 1 : 0, buffer);
  121. wsSend(wsb);
  122. #endif
  123. }
  124. if (action == RF_CODE_RFIN) {
  125. DEBUG_MSG_P(PSTR("[RFBRIDGE] Forward message '%s'\n"), buffer);
  126. // Look for the code
  127. unsigned char id;
  128. unsigned char status = 0;
  129. bool found = false;
  130. for (id=0; id<relayCount(); id++) {
  131. String code_on = rfbRetrieve(id, true);
  132. if (code_on.length() && code_on.endsWith(&buffer[12])) {
  133. DEBUG_MSG_P(PSTR("[RFBRIDGE] Match ON code for relay %d\n"), id);
  134. status = 1;
  135. found = true;
  136. }
  137. String code_off = rfbRetrieve(id, false);
  138. if (code_off.length() && code_off.endsWith(&buffer[12])) {
  139. DEBUG_MSG_P(PSTR("[RFBRIDGE] Match OFF code for relay %d\n"), id);
  140. if (found) status = 2;
  141. found = true;
  142. }
  143. if (found) {
  144. _rfbin = true;
  145. if (status == 2) {
  146. relayToggle(id);
  147. } else {
  148. relayStatus(id, status == 1);
  149. }
  150. break;
  151. }
  152. }
  153. }
  154. }
  155. void _rfbReceive() {
  156. static bool receiving = false;
  157. while (Serial.available()) {
  158. yield();
  159. byte c = Serial.read();
  160. //DEBUG_MSG_P(PSTR("[RFBRIDGE] Received 0x%02X\n"), c);
  161. if (receiving) {
  162. if (c == RF_CODE_STOP) {
  163. _rfbDecode();
  164. receiving = false;
  165. } else {
  166. _uartbuf[_uartpos++] = c;
  167. }
  168. } else if (c == RF_CODE_START) {
  169. _uartpos = 0;
  170. receiving = true;
  171. }
  172. }
  173. }
  174. bool _rfbCompare(const char * code1, const char * code2) {
  175. return strcmp(&code1[12], &code2[12]) == 0;
  176. }
  177. bool _rfbSameOnOff(unsigned char id) {
  178. return _rfbCompare(rfbRetrieve(id, true).c_str(), rfbRetrieve(id, false).c_str());
  179. }
  180. /*
  181. From an hexa char array ("A220EE...") to a byte array (half the size)
  182. */
  183. bool _rfbToArray(const char * in, byte * out) {
  184. if (strlen(in) != RF_MESSAGE_SIZE * 2) return false;
  185. char tmp[3] = {0};
  186. for (unsigned char p = 0; p<RF_MESSAGE_SIZE; p++) {
  187. memcpy(tmp, &in[p*2], 2);
  188. out[p] = strtol(tmp, NULL, 16);
  189. }
  190. return true;
  191. }
  192. /*
  193. From a byte array to an hexa char array ("A220EE...", double the size)
  194. */
  195. bool _rfbToChar(byte * in, char * out) {
  196. for (unsigned char p = 0; p<RF_MESSAGE_SIZE; p++) {
  197. sprintf_P(&out[p*2], PSTR("%02X"), in[p]);
  198. }
  199. return true;
  200. }
  201. #if MQTT_SUPPORT
  202. void _rfbMqttCallback(unsigned int type, const char * topic, const char * payload) {
  203. if (type == MQTT_CONNECT_EVENT) {
  204. char buffer[strlen(MQTT_TOPIC_RFLEARN) + 3];
  205. snprintf_P(buffer, sizeof(buffer), PSTR("%s/+"), MQTT_TOPIC_RFLEARN);
  206. mqttSubscribe(buffer);
  207. mqttSubscribe(MQTT_TOPIC_RFOUT);
  208. }
  209. if (type == MQTT_MESSAGE_EVENT) {
  210. // Match topic
  211. String t = mqttSubtopic((char *) topic);
  212. // Check if should go into learn mode
  213. if (t.startsWith(MQTT_TOPIC_RFLEARN)) {
  214. _learnId = t.substring(strlen(MQTT_TOPIC_RFLEARN)+1).toInt();
  215. if (_learnId >= relayCount()) {
  216. DEBUG_MSG_P(PSTR("[RFBRIDGE] Wrong learnID (%d)\n"), _learnId);
  217. return;
  218. }
  219. _learnStatus = (char)payload[0] != '0';
  220. _rfbLearn();
  221. }
  222. if (t.equals(MQTT_TOPIC_RFOUT)) {
  223. // The payload may be a code in HEX format ([0-9A-Z]{18}) or
  224. // the code comma the number of times to transmit it.
  225. byte message[RF_MESSAGE_SIZE];
  226. char * tok = strtok((char *) payload, ",");
  227. if (_rfbToArray(tok, message)) {
  228. tok = strtok(NULL, ",");
  229. byte times = (tok != NULL) ? atoi(tok) : 1;
  230. _rfbSend(message, times);
  231. }
  232. }
  233. }
  234. }
  235. #endif
  236. // -----------------------------------------------------------------------------
  237. // PUBLIC
  238. // -----------------------------------------------------------------------------
  239. void rfbStore(unsigned char id, bool status, const char * code) {
  240. DEBUG_MSG_P(PSTR("[RFBRIDGE] Storing %d-%s => '%s'\n"), id, status ? "ON" : "OFF", code);
  241. char key[8] = {0};
  242. snprintf_P(key, sizeof(key), PSTR("rfb%s%d"), status ? "ON" : "OFF", id);
  243. setSetting(key, code);
  244. }
  245. String rfbRetrieve(unsigned char id, bool status) {
  246. char key[8] = {0};
  247. snprintf_P(key, sizeof(key), PSTR("rfb%s%d"), status ? "ON" : "OFF", id);
  248. return getSetting(key);
  249. }
  250. void rfbStatus(unsigned char id, bool status) {
  251. String value = rfbRetrieve(id, status);
  252. if (value.length() > 0) {
  253. bool same = _rfbSameOnOff(id);
  254. byte message[RF_MESSAGE_SIZE];
  255. _rfbToArray(value.c_str(), message);
  256. unsigned char times = RF_SEND_TIMES;
  257. if (same) times = _rfbin ? 0 : 1;
  258. _rfbSend(message, times);
  259. }
  260. }
  261. void rfbLearn(unsigned char id, bool status) {
  262. _learnId = id;
  263. _learnStatus = status;
  264. _rfbLearn();
  265. }
  266. void rfbForget(unsigned char id, bool status) {
  267. char key[8] = {0};
  268. snprintf_P(key, sizeof(key), PSTR("rfb%s%d"), status ? "ON" : "OFF", id);
  269. delSetting(key);
  270. // Websocket update
  271. #if WEB_SUPPORT
  272. char wsb[100];
  273. snprintf_P(wsb, sizeof(wsb), PSTR("{\"rfb\":[{\"id\": %d, \"status\": %d, \"data\": \"\"}]}"), id, status ? 1 : 0);
  274. wsSend(wsb);
  275. #endif
  276. }
  277. // -----------------------------------------------------------------------------
  278. // SETUP & LOOP
  279. // -----------------------------------------------------------------------------
  280. void rfbSetup() {
  281. #if MQTT_SUPPORT
  282. mqttRegister(_rfbMqttCallback);
  283. #endif
  284. #if WEB_SUPPORT
  285. wsOnSendRegister(_rfbWebSocketOnSend);
  286. wsOnActionRegister(_rfbWebSocketOnAction);
  287. #endif
  288. }
  289. void rfbLoop() {
  290. _rfbReceive();
  291. }
  292. #endif