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.

643 lines
19 KiB

7 years ago
  1. /*
  2. ITEAD RF BRIDGE MODULE
  3. Copyright (C) 2017-2018 by Xose Pérez <xose dot perez at gmail dot com>
  4. Module key prefix: rfb (shared with RFBridge)
  5. */
  6. #ifdef ITEAD_SONOFF_RFBRIDGE
  7. #include <queue>
  8. #include <Ticker.h>
  9. #if RFB_DIRECT
  10. #include <RCSwitch.h>
  11. #endif
  12. // -----------------------------------------------------------------------------
  13. // DEFINITIONS
  14. // -----------------------------------------------------------------------------
  15. #define RF_MESSAGE_SIZE 9
  16. #define RF_MAX_MESSAGE_SIZE (112+4)
  17. #define RF_CODE_START 0xAA
  18. #define RF_CODE_ACK 0xA0
  19. #define RF_CODE_LEARN 0xA1
  20. #define RF_CODE_LEARN_KO 0xA2
  21. #define RF_CODE_LEARN_OK 0xA3
  22. #define RF_CODE_RFIN 0xA4
  23. #define RF_CODE_RFOUT 0xA5
  24. #define RF_CODE_SNIFFING_ON 0xA6
  25. #define RF_CODE_SNIFFING_OFF 0xA7
  26. #define RF_CODE_RFOUT_NEW 0xA8
  27. #define RF_CODE_LEARN_NEW 0xA9
  28. #define RF_CODE_LEARN_KO_NEW 0xAA
  29. #define RF_CODE_LEARN_OK_NEW 0xAB
  30. #define RF_CODE_RFOUT_BUCKET 0xB0
  31. #define RF_CODE_STOP 0x55
  32. // -----------------------------------------------------------------------------
  33. // GLOBALS TO THE MODULE
  34. // -----------------------------------------------------------------------------
  35. unsigned char _uartbuf[RF_MESSAGE_SIZE+3] = {0};
  36. unsigned char _uartpos = 0;
  37. unsigned char _learnId = 0;
  38. bool _learnStatus = true;
  39. bool _rfbin = false;
  40. typedef struct {
  41. byte code[RF_MESSAGE_SIZE];
  42. byte times;
  43. } rfb_message_t;
  44. static std::queue<rfb_message_t> _rfb_message_queue;
  45. Ticker _rfb_ticker;
  46. bool _rfb_ticker_active = false;
  47. #if RFB_DIRECT
  48. RCSwitch * _rfModem;
  49. bool _learning = false;
  50. #endif
  51. // -----------------------------------------------------------------------------
  52. // PRIVATES
  53. // -----------------------------------------------------------------------------
  54. /*
  55. From an hexa char array ("A220EE...") to a byte array (half the size)
  56. */
  57. static int _rfbToArray(const char * in, byte * out, int length = RF_MESSAGE_SIZE * 2) {
  58. int n = strlen(in);
  59. if (n > RF_MAX_MESSAGE_SIZE*2 || (length > 0 && n != length)) return 0;
  60. char tmp[3] = {0,0,0};
  61. n /= 2;
  62. for (unsigned char p = 0; p<n; p++) {
  63. memcpy(tmp, &in[p*2], 2);
  64. out[p] = strtol(tmp, NULL, 16);
  65. }
  66. return n;
  67. }
  68. /*
  69. From a byte array to an hexa char array ("A220EE...", double the size)
  70. */
  71. static bool _rfbToChar(byte * in, char * out, int n = RF_MESSAGE_SIZE) {
  72. for (unsigned char p = 0; p<n; p++) {
  73. sprintf_P(&out[p*2], PSTR("%02X"), in[p]);
  74. }
  75. return true;
  76. }
  77. void _rfbWebSocketOnSend(JsonObject& root) {
  78. root["rfbVisible"] = 1;
  79. root["rfbCount"] = relayCount();
  80. #if RF_RAW_SUPPORT
  81. root["rfbrawVisible"] = 1;
  82. #endif
  83. JsonArray& rfb = root.createNestedArray("rfb");
  84. for (byte id=0; id<relayCount(); id++) {
  85. for (byte status=0; status<2; status++) {
  86. JsonObject& node = rfb.createNestedObject();
  87. node["id"] = id;
  88. node["status"] = status;
  89. node["data"] = rfbRetrieve(id, status == 1);
  90. }
  91. }
  92. }
  93. void _rfbWebSocketOnAction(uint32_t client_id, const char * action, JsonObject& data) {
  94. if (strcmp(action, "rfblearn") == 0) rfbLearn(data["id"], data["status"]);
  95. if (strcmp(action, "rfbforget") == 0) rfbForget(data["id"], data["status"]);
  96. if (strcmp(action, "rfbsend") == 0) rfbStore(data["id"], data["status"], data["data"].as<const char*>());
  97. }
  98. void _rfbAck() {
  99. #if not RFB_DIRECT
  100. DEBUG_MSG_P(PSTR("[RFBRIDGE] Sending ACK\n"));
  101. Serial.println();
  102. Serial.write(RF_CODE_START);
  103. Serial.write(RF_CODE_ACK);
  104. Serial.write(RF_CODE_STOP);
  105. Serial.flush();
  106. Serial.println();
  107. #endif
  108. }
  109. void _rfbLearn() {
  110. #if RFB_DIRECT
  111. DEBUG_MSG_P(PSTR("[RFBRIDGE] Entering LEARN mode\n"));
  112. _learning = true;
  113. #else
  114. DEBUG_MSG_P(PSTR("[RFBRIDGE] Sending LEARN\n"));
  115. Serial.println();
  116. Serial.write(RF_CODE_START);
  117. Serial.write(RF_CODE_LEARN);
  118. Serial.write(RF_CODE_STOP);
  119. Serial.flush();
  120. Serial.println();
  121. #endif
  122. #if WEB_SUPPORT
  123. char buffer[100];
  124. snprintf_P(buffer, sizeof(buffer), PSTR("{\"action\": \"rfbLearn\", \"data\":{\"id\": %d, \"status\": %d}}"), _learnId, _learnStatus ? 1 : 0);
  125. wsSend(buffer);
  126. #endif
  127. }
  128. void _rfbSendRaw(const byte *message, const unsigned char n = RF_MESSAGE_SIZE) {
  129. for (unsigned char j=0; j<n; j++) {
  130. Serial.write(message[j]);
  131. }
  132. }
  133. void _rfbSend(byte * message) {
  134. #if RFB_DIRECT
  135. unsigned int protocol = message[1];
  136. unsigned int timing =
  137. (message[2] << 8) |
  138. (message[3] << 0) ;
  139. unsigned int bitlength = message[4];
  140. unsigned long rf_code =
  141. (message[5] << 24) |
  142. (message[6] << 16) |
  143. (message[7] << 8) |
  144. (message[8] << 0) ;
  145. _rfModem->setProtocol(protocol);
  146. if (timing > 0) {
  147. _rfModem->setPulseLength(timing);
  148. }
  149. _rfModem->send(rf_code, bitlength);
  150. _rfModem->resetAvailable();
  151. #else
  152. Serial.println();
  153. Serial.write(RF_CODE_START);
  154. Serial.write(RF_CODE_RFOUT);
  155. _rfbSendRaw(message);
  156. Serial.write(RF_CODE_STOP);
  157. Serial.flush();
  158. Serial.println();
  159. #endif
  160. }
  161. void _rfbSend() {
  162. // Check if there is something in the queue
  163. if (_rfb_message_queue.empty()) return;
  164. // Pop the first element
  165. rfb_message_t message = _rfb_message_queue.front();
  166. _rfb_message_queue.pop();
  167. // Send the message
  168. _rfbSend(message.code);
  169. // If it should be further sent, push it to the stack again
  170. if (message.times > 1) {
  171. message.times = message.times - 1;
  172. _rfb_message_queue.push(message);
  173. }
  174. // if there are still messages in the queue...
  175. if (_rfb_message_queue.empty()) {
  176. _rfb_ticker.detach();
  177. _rfb_ticker_active = false;
  178. }
  179. }
  180. void _rfbSend(byte * code, unsigned char times) {
  181. #if RFB_DIRECT
  182. times = 1;
  183. #endif
  184. char buffer[RF_MESSAGE_SIZE];
  185. _rfbToChar(code, buffer);
  186. DEBUG_MSG_P(PSTR("[RFBRIDGE] Enqueuing MESSAGE '%s' %d time(s)\n"), buffer, times);
  187. rfb_message_t message;
  188. memcpy(message.code, code, RF_MESSAGE_SIZE);
  189. message.times = times;
  190. _rfb_message_queue.push(message);
  191. // Enable the ticker if not running
  192. if (!_rfb_ticker_active) {
  193. _rfb_ticker_active = true;
  194. _rfb_ticker.attach_ms(RF_SEND_DELAY, _rfbSend);
  195. }
  196. }
  197. #if RF_RAW_SUPPORT
  198. void _rfbSendRawOnce(byte *code, unsigned char length) {
  199. char buffer[length*2];
  200. _rfbToChar(code, buffer, length);
  201. DEBUG_MSG_P(PSTR("[RFBRIDGE] Sending RAW MESSAGE '%s'\n"), buffer);
  202. _rfbSendRaw(code, length);
  203. }
  204. #endif // RF_RAW_SUPPORT
  205. bool _rfbMatch(char* code, unsigned char& relayID, unsigned char& value, char* buffer = NULL) {
  206. if (strlen(code) != 18) return false;
  207. bool found = false;
  208. String compareto = String(&code[12]);
  209. compareto.toUpperCase();
  210. DEBUG_MSG_P(PSTR("[RFBRIDGE] Trying to match code %s\n"), compareto.c_str());
  211. for (unsigned char i=0; i<relayCount(); i++) {
  212. String code_on = rfbRetrieve(i, true);
  213. if (code_on.length() && code_on.endsWith(compareto)) {
  214. DEBUG_MSG_P(PSTR("[RFBRIDGE] Match ON code for relay %d\n"), i);
  215. value = 1;
  216. found = true;
  217. if (buffer) strcpy(buffer, code_on.c_str());
  218. }
  219. String code_off = rfbRetrieve(i, false);
  220. if (code_off.length() && code_off.endsWith(compareto)) {
  221. DEBUG_MSG_P(PSTR("[RFBRIDGE] Match OFF code for relay %d\n"), i);
  222. if (found) value = 2;
  223. found = true;
  224. if (buffer) strcpy(buffer, code_off.c_str());
  225. }
  226. if (found) {
  227. relayID = i;
  228. return true;
  229. }
  230. }
  231. return false;
  232. }
  233. void _rfbDecode() {
  234. static unsigned long last = 0;
  235. if (millis() - last < RF_RECEIVE_DELAY) return;
  236. last = millis();
  237. byte action = _uartbuf[0];
  238. char buffer[RF_MESSAGE_SIZE * 2 + 1] = {0};
  239. DEBUG_MSG_P(PSTR("[RFBRIDGE] Action 0x%02X\n"), action);
  240. if (action == RF_CODE_LEARN_KO) {
  241. _rfbAck();
  242. DEBUG_MSG_P(PSTR("[RFBRIDGE] Learn timeout\n"));
  243. #if WEB_SUPPORT
  244. wsSend_P(PSTR("{\"action\": \"rfbTimeout\"}"));
  245. #endif
  246. }
  247. unsigned char id;
  248. unsigned char status;
  249. bool matched = false;
  250. if (action == RF_CODE_LEARN_OK || action == RF_CODE_RFIN) {
  251. _rfbAck();
  252. _rfbToChar(&_uartbuf[1], buffer);
  253. /* Look for the code, possibly replacing the code with the exact learned one on match
  254. * we want to do this on learn too to be sure that the learned code is the same if it
  255. * is equivalent
  256. */
  257. DEBUG_MSG_P(PSTR("[RFBRIDGE] Received message '%s'\n"), buffer);
  258. matched = _rfbMatch(buffer, id, status, buffer);
  259. DEBUG_MSG_P(PSTR("[RFBRIDGE] Matched message '%s'\n"), buffer);
  260. #if MQTT_SUPPORT
  261. mqttSend(MQTT_TOPIC_RFIN, buffer);
  262. #endif
  263. }
  264. if (action == RF_CODE_LEARN_OK) {
  265. DEBUG_MSG_P(PSTR("[RFBRIDGE] Learn success\n"));
  266. rfbStore(_learnId, _learnStatus, buffer);
  267. // Websocket update
  268. #if WEB_SUPPORT
  269. char wsb[100];
  270. snprintf_P(wsb, sizeof(wsb), PSTR("{\"rfb\":[{\"id\": %d, \"status\": %d, \"data\": \"%s\"}]}"), _learnId, _learnStatus ? 1 : 0, buffer);
  271. wsSend(wsb);
  272. #endif
  273. }
  274. if (action == RF_CODE_RFIN) {
  275. DEBUG_MSG_P(PSTR("[RFBRIDGE] Forward message '%s'\n"), buffer);
  276. if (matched) {
  277. _rfbin = true;
  278. if (status == 2) {
  279. relayToggle(id);
  280. } else {
  281. relayStatus(id, status == 1);
  282. }
  283. }
  284. }
  285. }
  286. void _rfbReceive() {
  287. #if RFB_DIRECT
  288. static long learn_start = 0;
  289. if (!_learning && learn_start) {
  290. learn_start = 0;
  291. }
  292. if (_learning) {
  293. if (!learn_start) {
  294. DEBUG_MSG_P(PSTR("[RFBRIDGE] arming learn timeout\n"));
  295. learn_start = millis();
  296. }
  297. if (learn_start > 0 && millis() - learn_start > RF_LEARN_TIMEOUT) {
  298. DEBUG_MSG_P(PSTR("[RFBRIDGE] learn timeout triggered\n"));
  299. memset(_uartbuf, 0, sizeof(_uartbuf));
  300. _uartbuf[0] = RF_CODE_LEARN_KO;
  301. _rfbDecode();
  302. _learning = false;
  303. }
  304. }
  305. if (_rfModem->available()) {
  306. static unsigned long last = 0;
  307. if (millis() - last > RF_DEBOUNCE) {
  308. last = millis();
  309. unsigned long rf_code = _rfModem->getReceivedValue();
  310. if ( rf_code > 0) {
  311. DEBUG_MSG_P(PSTR("[RFBRIDGE] Received code: %08X\n"), rf_code);
  312. unsigned int timing = _rfModem->getReceivedDelay();
  313. memset(_uartbuf, 0, sizeof(_uartbuf));
  314. unsigned char *msgbuf = _uartbuf + 1;
  315. _uartbuf[0] = _learning ? RF_CODE_LEARN_OK: RF_CODE_RFIN;
  316. msgbuf[0] = 0xC0;
  317. msgbuf[1] = _rfModem->getReceivedProtocol();
  318. msgbuf[2] = timing >> 8;
  319. msgbuf[3] = timing >> 0;
  320. msgbuf[4] = _rfModem->getReceivedBitlength();
  321. msgbuf[5] = rf_code >> 24;
  322. msgbuf[6] = rf_code >> 16;
  323. msgbuf[7] = rf_code >> 8;
  324. msgbuf[8] = rf_code >> 0;
  325. _rfbDecode();
  326. _learning = false;
  327. }
  328. }
  329. _rfModem->resetAvailable();
  330. }
  331. #else
  332. static bool receiving = false;
  333. while (Serial.available()) {
  334. yield();
  335. byte c = Serial.read();
  336. //DEBUG_MSG_P(PSTR("[RFBRIDGE] Received 0x%02X\n"), c);
  337. if (receiving) {
  338. if (c == RF_CODE_STOP && (_uartpos == 1 || _uartpos == RF_MESSAGE_SIZE + 1)) {
  339. _rfbDecode();
  340. receiving = false;
  341. } else if (_uartpos <= RF_MESSAGE_SIZE) {
  342. _uartbuf[_uartpos++] = c;
  343. } else {
  344. // wrong message, should have received a RF_CODE_STOP
  345. receiving = false;
  346. }
  347. } else if (c == RF_CODE_START) {
  348. _uartpos = 0;
  349. receiving = true;
  350. }
  351. }
  352. #endif
  353. }
  354. bool _rfbCompare(const char * code1, const char * code2) {
  355. return strcmp(&code1[12], &code2[12]) == 0;
  356. }
  357. bool _rfbSameOnOff(unsigned char id) {
  358. return _rfbCompare(rfbRetrieve(id, true).c_str(), rfbRetrieve(id, false).c_str());
  359. }
  360. #if MQTT_SUPPORT
  361. void _rfbMqttCallback(unsigned int type, const char * topic, const char * payload) {
  362. if (type == MQTT_CONNECT_EVENT) {
  363. char buffer[strlen(MQTT_TOPIC_RFLEARN) + 3];
  364. snprintf_P(buffer, sizeof(buffer), PSTR("%s/+"), MQTT_TOPIC_RFLEARN);
  365. mqttSubscribe(buffer);
  366. mqttSubscribe(MQTT_TOPIC_RFOUT);
  367. #if RF_RAW_SUPPORT
  368. mqttSubscribe(MQTT_TOPIC_RFRAW);
  369. #endif
  370. }
  371. if (type == MQTT_MESSAGE_EVENT) {
  372. // Match topic
  373. String t = mqttMagnitude((char *) topic);
  374. // Check if should go into learn mode
  375. if (t.startsWith(MQTT_TOPIC_RFLEARN)) {
  376. _learnId = t.substring(strlen(MQTT_TOPIC_RFLEARN)+1).toInt();
  377. if (_learnId >= relayCount()) {
  378. DEBUG_MSG_P(PSTR("[RFBRIDGE] Wrong learnID (%d)\n"), _learnId);
  379. return;
  380. }
  381. _learnStatus = (char)payload[0] != '0';
  382. _rfbLearn();
  383. return;
  384. }
  385. bool isRFOut = t.equals(MQTT_TOPIC_RFOUT);
  386. #if RF_RAW_SUPPORT
  387. bool isRFRaw = !isRFOut && t.equals(MQTT_TOPIC_RFRAW);
  388. #else
  389. bool isRFRaw = false;
  390. #endif
  391. if (isRFOut || isRFRaw) {
  392. // The payload may be a code in HEX format ([0-9A-Z]{18}) or
  393. // the code comma the number of times to transmit it.
  394. char * tok = strtok((char *) payload, ",");
  395. // Check if a switch is linked to that message
  396. unsigned char id;
  397. unsigned char status = 0;
  398. if (_rfbMatch(tok, id, status)) {
  399. if (status == 2) {
  400. relayToggle(id);
  401. } else {
  402. relayStatus(id, status == 1);
  403. }
  404. return;
  405. }
  406. #if RF_RAW_SUPPORT
  407. byte message[RF_MAX_MESSAGE_SIZE];
  408. int len = _rfbToArray(tok, message, 0);
  409. if ((len > 0) && (isRFRaw || len != RF_MESSAGE_SIZE)) {
  410. _rfbSendRawOnce(message, len);
  411. } else {
  412. tok = strtok(NULL, ",");
  413. byte times = (tok != NULL) ? atoi(tok) : 1;
  414. _rfbSend(message, times);
  415. }
  416. #else // RF_RAW_SUPPORT
  417. byte message[RF_MESSAGE_SIZE];
  418. if (_rfbToArray(tok, message)) {
  419. tok = strtok(NULL, ",");
  420. byte times = (tok != NULL) ? atoi(tok) : 1;
  421. _rfbSend(message, times);
  422. }
  423. #endif // RF_RAW_SUPPORT
  424. }
  425. }
  426. }
  427. #endif
  428. bool _rfbKeyCheck(const char * key) {
  429. return (strncmp(key, "rfb", 3) == 0);
  430. }
  431. // -----------------------------------------------------------------------------
  432. // PUBLIC
  433. // -----------------------------------------------------------------------------
  434. void rfbStore(unsigned char id, bool status, const char * code) {
  435. DEBUG_MSG_P(PSTR("[RFBRIDGE] Storing %d-%s => '%s'\n"), id, status ? "ON" : "OFF", code);
  436. char key[8] = {0};
  437. snprintf_P(key, sizeof(key), PSTR("rfb%s%d"), status ? "ON" : "OFF", id);
  438. setSetting(key, code);
  439. }
  440. String rfbRetrieve(unsigned char id, bool status) {
  441. char key[8] = {0};
  442. snprintf_P(key, sizeof(key), PSTR("rfb%s%d"), status ? "ON" : "OFF", id);
  443. return getSetting(key);
  444. }
  445. void rfbStatus(unsigned char id, bool status) {
  446. String value = rfbRetrieve(id, status);
  447. if (value.length() > 0) {
  448. bool same = _rfbSameOnOff(id);
  449. #if RF_RAW_SUPPORT
  450. byte message[RF_MAX_MESSAGE_SIZE];
  451. int len = _rfbToArray(value.c_str(), message, 0);
  452. if (len == RF_MESSAGE_SIZE && // probably a standard msg
  453. (message[0] != RF_CODE_START || // raw would start with 0xAA
  454. message[1] != RF_CODE_RFOUT_BUCKET || // followed by 0xB0,
  455. message[2] + 4 != len || // needs a valid length,
  456. message[len-1] != RF_CODE_STOP)) { // and finish with 0x55
  457. if (!_rfbin) {
  458. unsigned char times = same ? 1 : RF_SEND_TIMES;
  459. _rfbSend(message, times);
  460. }
  461. } else {
  462. _rfbSendRawOnce(message, len); // send a raw message
  463. }
  464. #else // RF_RAW_SUPPORT
  465. if (!_rfbin) {
  466. byte message[RF_MESSAGE_SIZE];
  467. _rfbToArray(value.c_str(), message);
  468. unsigned char times = same ? 1 : RF_SEND_TIMES;
  469. _rfbSend(message, times);
  470. }
  471. #endif // RF_RAW_SUPPORT
  472. }
  473. _rfbin = false;
  474. }
  475. void rfbLearn(unsigned char id, bool status) {
  476. _learnId = id;
  477. _learnStatus = status;
  478. _rfbLearn();
  479. }
  480. void rfbForget(unsigned char id, bool status) {
  481. char key[8] = {0};
  482. snprintf_P(key, sizeof(key), PSTR("rfb%s%d"), status ? "ON" : "OFF", id);
  483. delSetting(key);
  484. // Websocket update
  485. #if WEB_SUPPORT
  486. char wsb[100];
  487. snprintf_P(wsb, sizeof(wsb), PSTR("{\"rfb\":[{\"id\": %d, \"status\": %d, \"data\": \"\"}]}"), id, status ? 1 : 0);
  488. wsSend(wsb);
  489. #endif
  490. }
  491. // -----------------------------------------------------------------------------
  492. // SETUP & LOOP
  493. // -----------------------------------------------------------------------------
  494. void rfbSetup() {
  495. #if MQTT_SUPPORT
  496. mqttRegister(_rfbMqttCallback);
  497. #endif
  498. #if WEB_SUPPORT
  499. wsOnSendRegister(_rfbWebSocketOnSend);
  500. wsOnActionRegister(_rfbWebSocketOnAction);
  501. #endif
  502. #if RFB_DIRECT
  503. _rfModem = new RCSwitch();
  504. _rfModem->enableReceive(RFB_RX_PIN);
  505. _rfModem->enableTransmit(RFB_TX_PIN);
  506. _rfModem->setRepeatTransmit(6);
  507. DEBUG_MSG_P(PSTR("[RFBRIDGE] RF receiver on GPIO %u\n"), RFB_RX_PIN);
  508. DEBUG_MSG_P(PSTR("[RFBRIDGE] RF transmitter on GPIO %u\n"), RFB_TX_PIN);
  509. #endif
  510. // Key Check
  511. settingsRegisterKeyCheck(_rfbKeyCheck);
  512. // Register loop
  513. espurnaRegisterLoop(rfbLoop);
  514. }
  515. void rfbLoop() {
  516. _rfbReceive();
  517. }
  518. #endif