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.

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