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.

357 lines
9.8 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. _rfbToChar(&_uartbuf[1], buffer);
  109. mqttSend(MQTT_TOPIC_RFIN, buffer);
  110. _rfbAck();
  111. }
  112. if (action == RF_CODE_LEARN_OK) {
  113. DEBUG_MSG_P(PSTR("[RFBRIDGE] Learn success\n"));
  114. rfbStore(_learnId, _learnStatus, buffer);
  115. // Websocket update
  116. #if WEB_SUPPORT
  117. char wsb[100];
  118. snprintf_P(wsb, sizeof(wsb), PSTR("{\"rfb\":[{\"id\": %d, \"status\": %d, \"data\": \"%s\"}]}"), _learnId, _learnStatus ? 1 : 0, buffer);
  119. wsSend(wsb);
  120. #endif
  121. }
  122. if (action == RF_CODE_RFIN) {
  123. DEBUG_MSG_P(PSTR("[RFBRIDGE] Forward message '%s'\n"), buffer);
  124. // Look for the code
  125. unsigned char id, status;
  126. bool found = false;
  127. for (id=0; id<relayCount(); id++) {
  128. String code_on = rfbRetrieve(id, true);
  129. String code_off = rfbRetrieve(id, false);
  130. if (code_on.length() && code_off.length()) {
  131. if (code_on.endsWith(&buffer[12])) {
  132. found = true;
  133. status = 1;
  134. }
  135. if (code_off.endsWith(&buffer[12])) {
  136. found = true;
  137. if (status == 1) status = 2;
  138. }
  139. }
  140. if (found) break;
  141. }
  142. if (found) {
  143. _rfbin = true;
  144. if (status == 2) {
  145. relayToggle(id);
  146. } else {
  147. relayStatus(id, status == 1);
  148. }
  149. }
  150. }
  151. }
  152. void _rfbReceive() {
  153. static bool receiving = false;
  154. while (Serial.available()) {
  155. yield();
  156. byte c = Serial.read();
  157. //DEBUG_MSG_P(PSTR("[RFBRIDGE] Received 0x%02X\n"), c);
  158. if (receiving) {
  159. if (c == RF_CODE_STOP) {
  160. _rfbDecode();
  161. receiving = false;
  162. } else {
  163. _uartbuf[_uartpos++] = c;
  164. }
  165. } else if (c == RF_CODE_START) {
  166. _uartpos = 0;
  167. receiving = true;
  168. }
  169. }
  170. }
  171. bool _rfbCompare(const char * code1, const char * code2) {
  172. return strcmp(&code1[12], &code2[12]) == 0;
  173. }
  174. bool _rfbSameOnOff(unsigned char id) {
  175. return _rfbCompare(rfbRetrieve(id, true).c_str(), rfbRetrieve(id, false).c_str());
  176. }
  177. /*
  178. From an hexa char array ("A220EE...") to a byte array (half the size)
  179. */
  180. bool _rfbToArray(const char * in, byte * out) {
  181. if (strlen(in) != RF_MESSAGE_SIZE * 2) return false;
  182. char tmp[3] = {0};
  183. for (unsigned char p = 0; p<RF_MESSAGE_SIZE; p++) {
  184. memcpy(tmp, &in[p*2], 2);
  185. out[p] = strtol(tmp, NULL, 16);
  186. }
  187. return true;
  188. }
  189. /*
  190. From a byte array to an hexa char array ("A220EE...", double the size)
  191. */
  192. bool _rfbToChar(byte * in, char * out) {
  193. for (unsigned char p = 0; p<RF_MESSAGE_SIZE; p++) {
  194. sprintf_P(&out[p*2], PSTR("%02X"), in[p]);
  195. }
  196. return true;
  197. }
  198. void _rfbMqttCallback(unsigned int type, const char * topic, const char * payload) {
  199. if (type == MQTT_CONNECT_EVENT) {
  200. char buffer[strlen(MQTT_TOPIC_RFLEARN) + 3];
  201. snprintf_P(buffer, sizeof(buffer), PSTR("%s/+"), MQTT_TOPIC_RFLEARN);
  202. mqttSubscribe(buffer);
  203. mqttSubscribe(MQTT_TOPIC_RFOUT);
  204. }
  205. if (type == MQTT_MESSAGE_EVENT) {
  206. // Match topic
  207. String t = mqttSubtopic((char *) topic);
  208. // Check if should go into learn mode
  209. if (t.startsWith(MQTT_TOPIC_RFLEARN)) {
  210. _learnId = t.substring(strlen(MQTT_TOPIC_RFLEARN)+1).toInt();
  211. if (_learnId >= relayCount()) {
  212. DEBUG_MSG_P(PSTR("[RFBRIDGE] Wrong learnID (%d)\n"), _learnId);
  213. return;
  214. }
  215. _learnStatus = (char)payload[0] != '0';
  216. _rfbLearn();
  217. }
  218. if (t.equals(MQTT_TOPIC_RFOUT)) {
  219. // The payload may be a code in HEX format ([0-9A-Z]{18}) or
  220. // the code comma the number of times to transmit it.
  221. byte message[RF_MESSAGE_SIZE];
  222. char * tok = strtok((char *) payload, ",");
  223. if (_rfbToArray(tok, message)) {
  224. tok = strtok(NULL, ",");
  225. byte times = (tok != NULL) ? atoi(tok) : 1;
  226. _rfbSend(message, times);
  227. }
  228. }
  229. }
  230. }
  231. // -----------------------------------------------------------------------------
  232. // PUBLIC
  233. // -----------------------------------------------------------------------------
  234. void rfbStore(unsigned char id, bool status, const char * code) {
  235. DEBUG_MSG_P(PSTR("[RFBRIDGE] Storing %d-%s => '%s'\n"), id, status ? "ON" : "OFF", code);
  236. char key[8] = {0};
  237. snprintf_P(key, sizeof(key), PSTR("rfb%s%d"), status ? "ON" : "OFF", id);
  238. setSetting(key, code);
  239. }
  240. String rfbRetrieve(unsigned char id, bool status) {
  241. char key[8] = {0};
  242. snprintf_P(key, sizeof(key), PSTR("rfb%s%d"), status ? "ON" : "OFF", id);
  243. return getSetting(key);
  244. }
  245. void rfbStatus(unsigned char id, bool status) {
  246. String value = rfbRetrieve(id, status);
  247. if (value.length() > 0) {
  248. bool same = _rfbSameOnOff(id);
  249. byte message[RF_MESSAGE_SIZE];
  250. _rfbToArray(value.c_str(), message);
  251. unsigned char times = RF_SEND_TIMES;
  252. if (same) times = _rfbin ? 0 : 1;
  253. _rfbSend(message, times);
  254. }
  255. }
  256. void rfbLearn(unsigned char id, bool status) {
  257. _learnId = id;
  258. _learnStatus = status;
  259. _rfbLearn();
  260. }
  261. void rfbForget(unsigned char id, bool status) {
  262. char key[8] = {0};
  263. snprintf_P(key, sizeof(key), PSTR("rfb%s%d"), status ? "ON" : "OFF", id);
  264. delSetting(key);
  265. // Websocket update
  266. #if WEB_SUPPORT
  267. char wsb[100];
  268. snprintf_P(wsb, sizeof(wsb), PSTR("{\"rfb\":[{\"id\": %d, \"status\": %d, \"data\": \"\"}]}"), id, status ? 1 : 0);
  269. wsSend(wsb);
  270. #endif
  271. }
  272. // -----------------------------------------------------------------------------
  273. // SETUP & LOOP
  274. // -----------------------------------------------------------------------------
  275. void rfbSetup() {
  276. mqttRegister(_rfbMqttCallback);
  277. #if WEB_SUPPORT
  278. wsOnSendRegister(_rfbWebSocketOnSend);
  279. wsOnActionRegister(_rfbWebSocketOnAction);
  280. #endif
  281. }
  282. void rfbLoop() {
  283. _rfbReceive();
  284. }
  285. #endif