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.

513 lines
14 KiB

  1. /*
  2. ITEAD RF BRIDGE MODULE
  3. Copyright (C) 2017-2018 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #ifdef ITEAD_SONOFF_RFBRIDGE
  6. #include <vector>
  7. #include <Ticker.h>
  8. // -----------------------------------------------------------------------------
  9. // DEFINITIONS
  10. // -----------------------------------------------------------------------------
  11. #define RF_MESSAGE_SIZE 9
  12. #define RF_MAX_MESSAGE_SIZE (112+4)
  13. #define RF_CODE_START 0xAA
  14. #define RF_CODE_ACK 0xA0
  15. #define RF_CODE_LEARN 0xA1
  16. #define RF_CODE_LEARN_KO 0xA2
  17. #define RF_CODE_LEARN_OK 0xA3
  18. #define RF_CODE_RFIN 0xA4
  19. #define RF_CODE_RFOUT 0xA5
  20. #define RF_CODE_SNIFFING_ON 0xA6
  21. #define RF_CODE_SNIFFING_OFF 0xA7
  22. #define RF_CODE_RFOUT_NEW 0xA8
  23. #define RF_CODE_LEARN_NEW 0xA9
  24. #define RF_CODE_LEARN_KO_NEW 0xAA
  25. #define RF_CODE_LEARN_OK_NEW 0xAB
  26. #define RF_CODE_RFOUT_BUCKET 0xB0
  27. #define RF_CODE_STOP 0x55
  28. // -----------------------------------------------------------------------------
  29. // GLOBALS TO THE MODULE
  30. // -----------------------------------------------------------------------------
  31. unsigned char _uartbuf[RF_MESSAGE_SIZE+3] = {0};
  32. unsigned char _uartpos = 0;
  33. unsigned char _learnId = 0;
  34. bool _learnStatus = true;
  35. bool _rfbin = false;
  36. typedef struct {
  37. byte code[RF_MESSAGE_SIZE];
  38. byte times;
  39. } rfb_message_t;
  40. std::vector<rfb_message_t> _rfb_message_queue;
  41. Ticker _rfbTicker;
  42. // -----------------------------------------------------------------------------
  43. // PRIVATES
  44. // -----------------------------------------------------------------------------
  45. /*
  46. From an hexa char array ("A220EE...") to a byte array (half the size)
  47. */
  48. static int _rfbToArray(const char * in, byte * out, int length = RF_MESSAGE_SIZE * 2) {
  49. int n = strlen(in);
  50. if (n > RF_MAX_MESSAGE_SIZE*2 || (length > 0 && n != length)) return 0;
  51. char tmp[3] = {0,0,0};
  52. n /= 2;
  53. for (unsigned char p = 0; p<n; p++) {
  54. memcpy(tmp, &in[p*2], 2);
  55. out[p] = strtol(tmp, NULL, 16);
  56. }
  57. return n;
  58. }
  59. /*
  60. From a byte array to an hexa char array ("A220EE...", double the size)
  61. */
  62. static bool _rfbToChar(byte * in, char * out, int n = RF_MESSAGE_SIZE) {
  63. for (unsigned char p = 0; p<n; p++) {
  64. sprintf_P(&out[p*2], PSTR("%02X"), in[p]);
  65. }
  66. return true;
  67. }
  68. void _rfbWebSocketOnSend(JsonObject& root) {
  69. root["rfbVisible"] = 1;
  70. root["rfbCount"] = relayCount();
  71. #if RF_RAW_SUPPORT
  72. root["rfbrawVisible"] = 1;
  73. #endif
  74. JsonArray& rfb = root.createNestedArray("rfb");
  75. for (byte id=0; id<relayCount(); id++) {
  76. for (byte status=0; status<2; status++) {
  77. JsonObject& node = rfb.createNestedObject();
  78. node["id"] = id;
  79. node["status"] = status;
  80. node["data"] = rfbRetrieve(id, status == 1);
  81. }
  82. }
  83. }
  84. void _rfbWebSocketOnAction(uint32_t client_id, const char * action, JsonObject& data) {
  85. if (strcmp(action, "rfblearn") == 0) rfbLearn(data["id"], data["status"]);
  86. if (strcmp(action, "rfbforget") == 0) rfbForget(data["id"], data["status"]);
  87. if (strcmp(action, "rfbsend") == 0) rfbStore(data["id"], data["status"], data["data"].as<const char*>());
  88. }
  89. void _rfbAck() {
  90. DEBUG_MSG_P(PSTR("[RFBRIDGE] Sending ACK\n"));
  91. Serial.println();
  92. Serial.write(RF_CODE_START);
  93. Serial.write(RF_CODE_ACK);
  94. Serial.write(RF_CODE_STOP);
  95. Serial.flush();
  96. Serial.println();
  97. }
  98. void _rfbLearn() {
  99. DEBUG_MSG_P(PSTR("[RFBRIDGE] Sending LEARN\n"));
  100. Serial.println();
  101. Serial.write(RF_CODE_START);
  102. Serial.write(RF_CODE_LEARN);
  103. Serial.write(RF_CODE_STOP);
  104. Serial.flush();
  105. Serial.println();
  106. #if WEB_SUPPORT
  107. char buffer[100];
  108. snprintf_P(buffer, sizeof(buffer), PSTR("{\"action\": \"rfbLearn\", \"data\":{\"id\": %d, \"status\": %d}}"), _learnId, _learnStatus ? 1 : 0);
  109. wsSend(buffer);
  110. #endif
  111. }
  112. void _rfbSendRaw(const byte *message, const unsigned char n = RF_MESSAGE_SIZE) {
  113. for (unsigned char j=0; j<n; j++) {
  114. Serial.write(message[j]);
  115. }
  116. }
  117. void _rfbSend(byte * message) {
  118. Serial.println();
  119. Serial.write(RF_CODE_START);
  120. Serial.write(RF_CODE_RFOUT);
  121. _rfbSendRaw(message);
  122. Serial.write(RF_CODE_STOP);
  123. Serial.flush();
  124. Serial.println();
  125. }
  126. void _rfbSend() {
  127. // Check if there is something in the queue
  128. if (_rfb_message_queue.size() == 0) return;
  129. // Pop the first element
  130. rfb_message_t message = _rfb_message_queue.front();
  131. _rfb_message_queue.erase(_rfb_message_queue.begin());
  132. // Send the message
  133. _rfbSend(message.code);
  134. // If it should be further sent, push it to the stack again
  135. if (message.times > 1) {
  136. message.times = message.times - 1;
  137. _rfb_message_queue.push_back(message);
  138. }
  139. // if there are still messages in the queue...
  140. if (_rfb_message_queue.size() > 0) {
  141. _rfbTicker.once_ms(RF_SEND_DELAY, _rfbSend);
  142. }
  143. }
  144. void _rfbSend(byte * code, int times) {
  145. char buffer[RF_MESSAGE_SIZE];
  146. _rfbToChar(code, buffer);
  147. DEBUG_MSG_P(PSTR("[RFBRIDGE] Sending MESSAGE '%s' %d time(s)\n"), buffer, times);
  148. rfb_message_t message;
  149. memcpy(message.code, code, RF_MESSAGE_SIZE);
  150. message.times = times;
  151. _rfb_message_queue.push_back(message);
  152. _rfbSend();
  153. }
  154. #if RF_RAW_SUPPORT
  155. void _rfbSendRawOnce(byte *code, int length) {
  156. char buffer[length*2];
  157. _rfbToChar(code, buffer, length);
  158. DEBUG_MSG_P(PSTR("[RFBRIDGE] Sending RAW MESSAGE '%s'\n"), buffer);
  159. _rfbSendRaw(code, length);
  160. }
  161. #endif // RF_RAW_SUPPORT
  162. bool _rfbMatch(char * code, unsigned char& relayID, unsigned char& value) {
  163. if (strlen(code) != 18) return false;
  164. bool found = false;
  165. String compareto = String(&code[12]);
  166. compareto.toUpperCase();
  167. DEBUG_MSG_P(PSTR("[RFBRIDGE] Trying to match code %s\n"), compareto.c_str());
  168. for (unsigned char i=0; i<relayCount(); i++) {
  169. String code_on = rfbRetrieve(i, true);
  170. if (code_on.length() && code_on.endsWith(compareto)) {
  171. DEBUG_MSG_P(PSTR("[RFBRIDGE] Match ON code for relay %d\n"), i);
  172. value = 1;
  173. found = true;
  174. }
  175. String code_off = rfbRetrieve(i, false);
  176. if (code_off.length() && code_off.endsWith(compareto)) {
  177. DEBUG_MSG_P(PSTR("[RFBRIDGE] Match OFF code for relay %d\n"), i);
  178. if (found) value = 2;
  179. found = true;
  180. }
  181. if (found) {
  182. relayID = i;
  183. return true;
  184. }
  185. }
  186. return false;
  187. }
  188. void _rfbDecode() {
  189. static unsigned long last = 0;
  190. if (millis() - last < RF_RECEIVE_DELAY) return;
  191. last = millis();
  192. byte action = _uartbuf[0];
  193. char buffer[RF_MESSAGE_SIZE * 2 + 1] = {0};
  194. DEBUG_MSG_P(PSTR("[RFBRIDGE] Action 0x%02X\n"), action);
  195. if (action == RF_CODE_LEARN_KO) {
  196. _rfbAck();
  197. DEBUG_MSG_P(PSTR("[RFBRIDGE] Learn timeout\n"));
  198. #if WEB_SUPPORT
  199. wsSend_P(PSTR("{\"action\": \"rfbTimeout\"}"));
  200. #endif
  201. }
  202. if (action == RF_CODE_LEARN_OK || action == RF_CODE_RFIN) {
  203. #if MQTT_SUPPORT
  204. _rfbToChar(&_uartbuf[1], buffer);
  205. mqttSend(MQTT_TOPIC_RFIN, buffer);
  206. #endif
  207. _rfbAck();
  208. }
  209. if (action == RF_CODE_LEARN_OK) {
  210. DEBUG_MSG_P(PSTR("[RFBRIDGE] Learn success\n"));
  211. rfbStore(_learnId, _learnStatus, buffer);
  212. // Websocket update
  213. #if WEB_SUPPORT
  214. char wsb[100];
  215. snprintf_P(wsb, sizeof(wsb), PSTR("{\"rfb\":[{\"id\": %d, \"status\": %d, \"data\": \"%s\"}]}"), _learnId, _learnStatus ? 1 : 0, buffer);
  216. wsSend(wsb);
  217. #endif
  218. }
  219. if (action == RF_CODE_RFIN) {
  220. DEBUG_MSG_P(PSTR("[RFBRIDGE] Forward message '%s'\n"), buffer);
  221. // Look for the code
  222. unsigned char id;
  223. unsigned char status = 0;
  224. if (_rfbMatch(buffer, id, status)) {
  225. _rfbin = true;
  226. if (status == 2) {
  227. relayToggle(id);
  228. } else {
  229. relayStatus(id, status == 1);
  230. }
  231. }
  232. }
  233. }
  234. void _rfbReceive() {
  235. static bool receiving = false;
  236. while (Serial.available()) {
  237. yield();
  238. byte c = Serial.read();
  239. //DEBUG_MSG_P(PSTR("[RFBRIDGE] Received 0x%02X\n"), c);
  240. if (receiving) {
  241. if (c == RF_CODE_STOP && (_uartpos == 1 || _uartpos == 10)) {
  242. _rfbDecode();
  243. receiving = false;
  244. } else if (_uartpos < 10) {
  245. _uartbuf[_uartpos++] = c;
  246. } else {
  247. // wrong message, should have received a RF_CODE_STOP
  248. receiving = false;
  249. }
  250. } else if (c == RF_CODE_START) {
  251. _uartpos = 0;
  252. receiving = true;
  253. }
  254. }
  255. }
  256. bool _rfbCompare(const char * code1, const char * code2) {
  257. return strcmp(&code1[12], &code2[12]) == 0;
  258. }
  259. bool _rfbSameOnOff(unsigned char id) {
  260. return _rfbCompare(rfbRetrieve(id, true).c_str(), rfbRetrieve(id, false).c_str());
  261. }
  262. #if MQTT_SUPPORT
  263. void _rfbMqttCallback(unsigned int type, const char * topic, const char * payload) {
  264. if (type == MQTT_CONNECT_EVENT) {
  265. char buffer[strlen(MQTT_TOPIC_RFLEARN) + 3];
  266. snprintf_P(buffer, sizeof(buffer), PSTR("%s/+"), MQTT_TOPIC_RFLEARN);
  267. mqttSubscribe(buffer);
  268. mqttSubscribe(MQTT_TOPIC_RFOUT);
  269. #if RF_RAW_SUPPORT
  270. mqttSubscribe(MQTT_TOPIC_RFRAW);
  271. #endif
  272. }
  273. if (type == MQTT_MESSAGE_EVENT) {
  274. // Match topic
  275. String t = mqttTopicKey((char *) topic);
  276. // Check if should go into learn mode
  277. if (t.startsWith(MQTT_TOPIC_RFLEARN)) {
  278. _learnId = t.substring(strlen(MQTT_TOPIC_RFLEARN)+1).toInt();
  279. if (_learnId >= relayCount()) {
  280. DEBUG_MSG_P(PSTR("[RFBRIDGE] Wrong learnID (%d)\n"), _learnId);
  281. return;
  282. }
  283. _learnStatus = (char)payload[0] != '0';
  284. _rfbLearn();
  285. }
  286. bool isRFOut = t.equals(MQTT_TOPIC_RFOUT);
  287. #if RF_RAW_SUPPORT
  288. bool isRFRaw = !isRFOut && t.equals(MQTT_TOPIC_RFRAW);
  289. #else
  290. bool isRFRaw = false;
  291. #endif
  292. if (isRFOut || isRFRaw) {
  293. // The payload may be a code in HEX format ([0-9A-Z]{18}) or
  294. // the code comma the number of times to transmit it.
  295. char * tok = strtok((char *) payload, ",");
  296. // Check if a switch is linked to that message
  297. unsigned char id;
  298. unsigned char status = 0;
  299. if (_rfbMatch(tok, id, status)) {
  300. if (status == 2) {
  301. relayToggle(id);
  302. } else {
  303. relayStatus(id, status == 1);
  304. }
  305. return;
  306. }
  307. #if RF_RAW_SUPPORT
  308. byte message[RF_MAX_MESSAGE_SIZE];
  309. int len = _rfbToArray(tok, message, 0);
  310. if ((len > 0) && (isRFRaw || len != RF_MESSAGE_SIZE)) {
  311. _rfbSendRawOnce(message, len);
  312. } else {
  313. tok = strtok(NULL, ",");
  314. byte times = (tok != NULL) ? atoi(tok) : 1;
  315. _rfbSend(message, times);
  316. }
  317. #else // RF_RAW_SUPPORT
  318. byte message[RF_MESSAGE_SIZE];
  319. if (_rfbToArray(tok, message)) {
  320. tok = strtok(NULL, ",");
  321. byte times = (tok != NULL) ? atoi(tok) : 1;
  322. _rfbSend(message, times);
  323. }
  324. #endif // RF_RAW_SUPPORT
  325. }
  326. }
  327. }
  328. #endif
  329. // -----------------------------------------------------------------------------
  330. // PUBLIC
  331. // -----------------------------------------------------------------------------
  332. void rfbStore(unsigned char id, bool status, const char * code) {
  333. DEBUG_MSG_P(PSTR("[RFBRIDGE] Storing %d-%s => '%s'\n"), id, status ? "ON" : "OFF", code);
  334. char key[8] = {0};
  335. snprintf_P(key, sizeof(key), PSTR("rfb%s%d"), status ? "ON" : "OFF", id);
  336. setSetting(key, code);
  337. }
  338. String rfbRetrieve(unsigned char id, bool status) {
  339. char key[8] = {0};
  340. snprintf_P(key, sizeof(key), PSTR("rfb%s%d"), status ? "ON" : "OFF", id);
  341. return getSetting(key);
  342. }
  343. void rfbStatus(unsigned char id, bool status) {
  344. String value = rfbRetrieve(id, status);
  345. if (value.length() > 0) {
  346. bool same = _rfbSameOnOff(id);
  347. #if RF_RAW_SUPPORT
  348. byte message[RF_MAX_MESSAGE_SIZE];
  349. int len = _rfbToArray(value.c_str(), message, 0);
  350. if (len == RF_MESSAGE_SIZE && // probably a standard msg
  351. (message[0] != RF_CODE_START || // raw would start with 0xAA
  352. message[1] != RF_CODE_RFOUT_BUCKET || // followed by 0xB0,
  353. message[2] + 4 != len || // needs a valid length,
  354. message[len-1] != RF_CODE_STOP)) { // and finish with 0x55
  355. unsigned char times = RF_SEND_TIMES;
  356. if (same) times = _rfbin ? 0 : 1;
  357. _rfbSend(message, times);
  358. } else {
  359. _rfbSendRawOnce(message, len); // send a raw message
  360. }
  361. #else // RF_RAW_SUPPORT
  362. byte message[RF_MESSAGE_SIZE];
  363. _rfbToArray(value.c_str(), message);
  364. unsigned char times = RF_SEND_TIMES;
  365. if (same) times = _rfbin ? 0 : 1;
  366. _rfbSend(message, times);
  367. #endif // RF_RAW_SUPPORT
  368. }
  369. }
  370. void rfbLearn(unsigned char id, bool status) {
  371. _learnId = id;
  372. _learnStatus = status;
  373. _rfbLearn();
  374. }
  375. void rfbForget(unsigned char id, bool status) {
  376. char key[8] = {0};
  377. snprintf_P(key, sizeof(key), PSTR("rfb%s%d"), status ? "ON" : "OFF", id);
  378. delSetting(key);
  379. // Websocket update
  380. #if WEB_SUPPORT
  381. char wsb[100];
  382. snprintf_P(wsb, sizeof(wsb), PSTR("{\"rfb\":[{\"id\": %d, \"status\": %d, \"data\": \"\"}]}"), id, status ? 1 : 0);
  383. wsSend(wsb);
  384. #endif
  385. }
  386. // -----------------------------------------------------------------------------
  387. // SETUP & LOOP
  388. // -----------------------------------------------------------------------------
  389. void rfbSetup() {
  390. #if MQTT_SUPPORT
  391. mqttRegister(_rfbMqttCallback);
  392. #endif
  393. #if WEB_SUPPORT
  394. wsOnSendRegister(_rfbWebSocketOnSend);
  395. wsOnActionRegister(_rfbWebSocketOnAction);
  396. #endif
  397. }
  398. void rfbLoop() {
  399. _rfbReceive();
  400. }
  401. #endif