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.

610 lines
17 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. */
  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 bitlength = message[4];
  136. unsigned long rf_code =
  137. (message[5] << 24) |
  138. (message[6] << 16) |
  139. (message[7] << 8) |
  140. (message[8] << 0) ;
  141. _rfModem->setProtocol(protocol);
  142. _rfModem->send(rf_code, bitlength);
  143. #else
  144. Serial.println();
  145. Serial.write(RF_CODE_START);
  146. Serial.write(RF_CODE_RFOUT);
  147. _rfbSendRaw(message);
  148. Serial.write(RF_CODE_STOP);
  149. Serial.flush();
  150. Serial.println();
  151. #endif
  152. }
  153. void _rfbSend() {
  154. // Check if there is something in the queue
  155. if (_rfb_message_queue.empty()) return;
  156. // Pop the first element
  157. rfb_message_t message = _rfb_message_queue.front();
  158. _rfb_message_queue.pop();
  159. // Send the message
  160. _rfbSend(message.code);
  161. // If it should be further sent, push it to the stack again
  162. if (message.times > 1) {
  163. message.times = message.times - 1;
  164. _rfb_message_queue.push(message);
  165. }
  166. // if there are still messages in the queue...
  167. if (_rfb_message_queue.empty()) {
  168. _rfb_ticker.detach();
  169. _rfb_ticker_active = false;
  170. }
  171. }
  172. void _rfbSend(byte * code, unsigned char times) {
  173. char buffer[RF_MESSAGE_SIZE];
  174. _rfbToChar(code, buffer);
  175. DEBUG_MSG_P(PSTR("[RFBRIDGE] Enqueuing MESSAGE '%s' %d time(s)\n"), buffer, times);
  176. rfb_message_t message;
  177. memcpy(message.code, code, RF_MESSAGE_SIZE);
  178. message.times = times;
  179. _rfb_message_queue.push(message);
  180. // Enable the ticker if not running
  181. if (!_rfb_ticker_active) {
  182. _rfb_ticker_active = true;
  183. _rfb_ticker.attach_ms(RF_SEND_DELAY, _rfbSend);
  184. }
  185. }
  186. #if RF_RAW_SUPPORT
  187. void _rfbSendRawOnce(byte *code, unsigned char length) {
  188. char buffer[length*2];
  189. _rfbToChar(code, buffer, length);
  190. DEBUG_MSG_P(PSTR("[RFBRIDGE] Sending RAW MESSAGE '%s'\n"), buffer);
  191. _rfbSendRaw(code, length);
  192. }
  193. #endif // RF_RAW_SUPPORT
  194. bool _rfbMatch(char * code, unsigned char& relayID, unsigned char& value) {
  195. if (strlen(code) != 18) return false;
  196. bool found = false;
  197. String compareto = String(&code[12]);
  198. compareto.toUpperCase();
  199. DEBUG_MSG_P(PSTR("[RFBRIDGE] Trying to match code %s\n"), compareto.c_str());
  200. for (unsigned char i=0; i<relayCount(); i++) {
  201. String code_on = rfbRetrieve(i, true);
  202. if (code_on.length() && code_on.endsWith(compareto)) {
  203. DEBUG_MSG_P(PSTR("[RFBRIDGE] Match ON code for relay %d\n"), i);
  204. value = 1;
  205. found = true;
  206. }
  207. String code_off = rfbRetrieve(i, false);
  208. if (code_off.length() && code_off.endsWith(compareto)) {
  209. DEBUG_MSG_P(PSTR("[RFBRIDGE] Match OFF code for relay %d\n"), i);
  210. if (found) value = 2;
  211. found = true;
  212. }
  213. if (found) {
  214. relayID = i;
  215. return true;
  216. }
  217. }
  218. return false;
  219. }
  220. void _rfbDecode() {
  221. static unsigned long last = 0;
  222. if (millis() - last < RF_RECEIVE_DELAY) return;
  223. last = millis();
  224. byte action = _uartbuf[0];
  225. char buffer[RF_MESSAGE_SIZE * 2 + 1] = {0};
  226. DEBUG_MSG_P(PSTR("[RFBRIDGE] Action 0x%02X\n"), action);
  227. if (action == RF_CODE_LEARN_KO) {
  228. _rfbAck();
  229. DEBUG_MSG_P(PSTR("[RFBRIDGE] Learn timeout\n"));
  230. #if WEB_SUPPORT
  231. wsSend_P(PSTR("{\"action\": \"rfbTimeout\"}"));
  232. #endif
  233. }
  234. if (action == RF_CODE_LEARN_OK || action == RF_CODE_RFIN) {
  235. #if MQTT_SUPPORT
  236. _rfbToChar(&_uartbuf[1], buffer);
  237. mqttSend(MQTT_TOPIC_RFIN, buffer);
  238. #endif
  239. _rfbAck();
  240. }
  241. if (action == RF_CODE_LEARN_OK) {
  242. DEBUG_MSG_P(PSTR("[RFBRIDGE] Learn success\n"));
  243. rfbStore(_learnId, _learnStatus, buffer);
  244. // Websocket update
  245. #if WEB_SUPPORT
  246. char wsb[100];
  247. snprintf_P(wsb, sizeof(wsb), PSTR("{\"rfb\":[{\"id\": %d, \"status\": %d, \"data\": \"%s\"}]}"), _learnId, _learnStatus ? 1 : 0, buffer);
  248. wsSend(wsb);
  249. #endif
  250. }
  251. if (action == RF_CODE_RFIN) {
  252. DEBUG_MSG_P(PSTR("[RFBRIDGE] Forward message '%s'\n"), buffer);
  253. // Look for the code
  254. unsigned char id;
  255. unsigned char status = 0;
  256. if (_rfbMatch(buffer, id, status)) {
  257. _rfbin = true;
  258. if (status == 2) {
  259. relayToggle(id);
  260. } else {
  261. relayStatus(id, status == 1);
  262. }
  263. }
  264. }
  265. }
  266. void _rfbReceive() {
  267. #if RFB_DIRECT
  268. static long learn_start = 0;
  269. if (!_learning && learn_start) {
  270. learn_start = 0;
  271. }
  272. if (_learning) {
  273. if (!learn_start) {
  274. DEBUG_MSG_P(PSTR("[RFBRIDGE] arming learn timeout\n"));
  275. learn_start = millis();
  276. }
  277. if (learn_start > 0 && millis() - learn_start > RF_LEARN_TIMEOUT) {
  278. DEBUG_MSG_P(PSTR("[RFBRIDGE] learn timeout triggered\n"));
  279. memset(_uartbuf, 0, sizeof(_uartbuf));
  280. _uartbuf[0] = RF_CODE_LEARN_KO;
  281. _rfbDecode();
  282. _learning = false;
  283. }
  284. }
  285. if (_rfModem->available()) {
  286. static unsigned long last = 0;
  287. if (millis() - last > RF_DEBOUNCE) {
  288. last = millis();
  289. unsigned long rf_code = _rfModem->getReceivedValue();
  290. if ( rf_code > 0) {
  291. DEBUG_MSG_P(PSTR("[RFBRIDGE] Received code: %08X\n"), rf_code);
  292. memset(_uartbuf, 0, sizeof(_uartbuf));
  293. unsigned char *msgbuf = _uartbuf + 1;
  294. _uartbuf[0] = _learning ? RF_CODE_LEARN_OK: RF_CODE_RFIN;
  295. msgbuf[0] = 0xC0;
  296. msgbuf[1] = _rfModem->getReceivedProtocol();
  297. msgbuf[4] = _rfModem->getReceivedBitlength();
  298. msgbuf[5] = rf_code >> 24;
  299. msgbuf[6] = rf_code >> 16;
  300. msgbuf[7] = rf_code >> 8;
  301. msgbuf[8] = rf_code >> 0;
  302. _rfbDecode();
  303. _learning = false;
  304. }
  305. }
  306. _rfModem->resetAvailable();
  307. }
  308. #else
  309. static bool receiving = false;
  310. while (Serial.available()) {
  311. yield();
  312. byte c = Serial.read();
  313. //DEBUG_MSG_P(PSTR("[RFBRIDGE] Received 0x%02X\n"), c);
  314. if (receiving) {
  315. if (c == RF_CODE_STOP && (_uartpos == 1 || _uartpos == RF_MESSAGE_SIZE + 1)) {
  316. _rfbDecode();
  317. receiving = false;
  318. } else if (_uartpos <= RF_MESSAGE_SIZE) {
  319. _uartbuf[_uartpos++] = c;
  320. } else {
  321. // wrong message, should have received a RF_CODE_STOP
  322. receiving = false;
  323. }
  324. } else if (c == RF_CODE_START) {
  325. _uartpos = 0;
  326. receiving = true;
  327. }
  328. }
  329. #endif
  330. }
  331. bool _rfbCompare(const char * code1, const char * code2) {
  332. return strcmp(&code1[12], &code2[12]) == 0;
  333. }
  334. bool _rfbSameOnOff(unsigned char id) {
  335. return _rfbCompare(rfbRetrieve(id, true).c_str(), rfbRetrieve(id, false).c_str());
  336. }
  337. #if MQTT_SUPPORT
  338. void _rfbMqttCallback(unsigned int type, const char * topic, const char * payload) {
  339. if (type == MQTT_CONNECT_EVENT) {
  340. char buffer[strlen(MQTT_TOPIC_RFLEARN) + 3];
  341. snprintf_P(buffer, sizeof(buffer), PSTR("%s/+"), MQTT_TOPIC_RFLEARN);
  342. mqttSubscribe(buffer);
  343. mqttSubscribe(MQTT_TOPIC_RFOUT);
  344. #if RF_RAW_SUPPORT
  345. mqttSubscribe(MQTT_TOPIC_RFRAW);
  346. #endif
  347. }
  348. if (type == MQTT_MESSAGE_EVENT) {
  349. // Match topic
  350. String t = mqttMagnitude((char *) topic);
  351. // Check if should go into learn mode
  352. if (t.startsWith(MQTT_TOPIC_RFLEARN)) {
  353. _learnId = t.substring(strlen(MQTT_TOPIC_RFLEARN)+1).toInt();
  354. if (_learnId >= relayCount()) {
  355. DEBUG_MSG_P(PSTR("[RFBRIDGE] Wrong learnID (%d)\n"), _learnId);
  356. return;
  357. }
  358. _learnStatus = (char)payload[0] != '0';
  359. _rfbLearn();
  360. return;
  361. }
  362. bool isRFOut = t.equals(MQTT_TOPIC_RFOUT);
  363. #if RF_RAW_SUPPORT
  364. bool isRFRaw = !isRFOut && t.equals(MQTT_TOPIC_RFRAW);
  365. #else
  366. bool isRFRaw = false;
  367. #endif
  368. if (isRFOut || isRFRaw) {
  369. // The payload may be a code in HEX format ([0-9A-Z]{18}) or
  370. // the code comma the number of times to transmit it.
  371. char * tok = strtok((char *) payload, ",");
  372. // Check if a switch is linked to that message
  373. unsigned char id;
  374. unsigned char status = 0;
  375. if (_rfbMatch(tok, id, status)) {
  376. if (status == 2) {
  377. relayToggle(id);
  378. } else {
  379. relayStatus(id, status == 1);
  380. }
  381. return;
  382. }
  383. #if RF_RAW_SUPPORT
  384. byte message[RF_MAX_MESSAGE_SIZE];
  385. int len = _rfbToArray(tok, message, 0);
  386. if ((len > 0) && (isRFRaw || len != RF_MESSAGE_SIZE)) {
  387. _rfbSendRawOnce(message, len);
  388. } else {
  389. tok = strtok(NULL, ",");
  390. byte times = (tok != NULL) ? atoi(tok) : 1;
  391. _rfbSend(message, times);
  392. }
  393. #else // RF_RAW_SUPPORT
  394. byte message[RF_MESSAGE_SIZE];
  395. if (_rfbToArray(tok, message)) {
  396. tok = strtok(NULL, ",");
  397. byte times = (tok != NULL) ? atoi(tok) : 1;
  398. _rfbSend(message, times);
  399. }
  400. #endif // RF_RAW_SUPPORT
  401. }
  402. }
  403. }
  404. #endif
  405. // -----------------------------------------------------------------------------
  406. // PUBLIC
  407. // -----------------------------------------------------------------------------
  408. void rfbStore(unsigned char id, bool status, const char * code) {
  409. DEBUG_MSG_P(PSTR("[RFBRIDGE] Storing %d-%s => '%s'\n"), id, status ? "ON" : "OFF", code);
  410. char key[8] = {0};
  411. snprintf_P(key, sizeof(key), PSTR("rfb%s%d"), status ? "ON" : "OFF", id);
  412. setSetting(key, code);
  413. }
  414. String rfbRetrieve(unsigned char id, bool status) {
  415. char key[8] = {0};
  416. snprintf_P(key, sizeof(key), PSTR("rfb%s%d"), status ? "ON" : "OFF", id);
  417. return getSetting(key);
  418. }
  419. void rfbStatus(unsigned char id, bool status) {
  420. String value = rfbRetrieve(id, status);
  421. if (value.length() > 0) {
  422. bool same = _rfbSameOnOff(id);
  423. #if RF_RAW_SUPPORT
  424. byte message[RF_MAX_MESSAGE_SIZE];
  425. int len = _rfbToArray(value.c_str(), message, 0);
  426. if (len == RF_MESSAGE_SIZE && // probably a standard msg
  427. (message[0] != RF_CODE_START || // raw would start with 0xAA
  428. message[1] != RF_CODE_RFOUT_BUCKET || // followed by 0xB0,
  429. message[2] + 4 != len || // needs a valid length,
  430. message[len-1] != RF_CODE_STOP)) { // and finish with 0x55
  431. if (!_rfbin) {
  432. unsigned char times = same ? 1 : RF_SEND_TIMES;
  433. _rfbSend(message, times);
  434. }
  435. } else {
  436. _rfbSendRawOnce(message, len); // send a raw message
  437. }
  438. #else // RF_RAW_SUPPORT
  439. if (!_rfbin) {
  440. byte message[RF_MESSAGE_SIZE];
  441. _rfbToArray(value.c_str(), message);
  442. unsigned char times = same ? 1 : RF_SEND_TIMES;
  443. _rfbSend(message, times);
  444. }
  445. #endif // RF_RAW_SUPPORT
  446. }
  447. _rfbin = false;
  448. }
  449. void rfbLearn(unsigned char id, bool status) {
  450. _learnId = id;
  451. _learnStatus = status;
  452. _rfbLearn();
  453. }
  454. void rfbForget(unsigned char id, bool status) {
  455. char key[8] = {0};
  456. snprintf_P(key, sizeof(key), PSTR("rfb%s%d"), status ? "ON" : "OFF", id);
  457. delSetting(key);
  458. // Websocket update
  459. #if WEB_SUPPORT
  460. char wsb[100];
  461. snprintf_P(wsb, sizeof(wsb), PSTR("{\"rfb\":[{\"id\": %d, \"status\": %d, \"data\": \"\"}]}"), id, status ? 1 : 0);
  462. wsSend(wsb);
  463. #endif
  464. }
  465. // -----------------------------------------------------------------------------
  466. // SETUP & LOOP
  467. // -----------------------------------------------------------------------------
  468. void rfbSetup() {
  469. #if MQTT_SUPPORT
  470. mqttRegister(_rfbMqttCallback);
  471. #endif
  472. #if WEB_SUPPORT
  473. wsOnSendRegister(_rfbWebSocketOnSend);
  474. wsOnActionRegister(_rfbWebSocketOnAction);
  475. #endif
  476. #if RFB_DIRECT
  477. _rfModem = new RCSwitch();
  478. _rfModem->enableReceive(RFB_RX_PIN);
  479. _rfModem->enableTransmit(RFB_TX_PIN);
  480. DEBUG_MSG_P(PSTR("[RFBRIDGE] RF receiver on GPIO %u\n"), RFB_RX_PIN);
  481. DEBUG_MSG_P(PSTR("[RFBRIDGE] RF transmitter on GPIO %u\n"), RFB_TX_PIN);
  482. #endif
  483. // Register loop
  484. espurnaRegisterLoop(rfbLoop);
  485. }
  486. void rfbLoop() {
  487. _rfbReceive();
  488. }
  489. #endif