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.

634 lines
18 KiB

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