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.

514 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 <queue>
  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. static std::queue<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.empty()) return;
  129. // Pop the first element
  130. rfb_message_t message = _rfb_message_queue.front();
  131. _rfb_message_queue.pop();
  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(message);
  138. }
  139. // if there are still messages in the queue...
  140. if (!_rfb_message_queue.empty()) {
  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(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. return;
  286. }
  287. bool isRFOut = t.equals(MQTT_TOPIC_RFOUT);
  288. #if RF_RAW_SUPPORT
  289. bool isRFRaw = !isRFOut && t.equals(MQTT_TOPIC_RFRAW);
  290. #else
  291. bool isRFRaw = false;
  292. #endif
  293. if (isRFOut || isRFRaw) {
  294. // The payload may be a code in HEX format ([0-9A-Z]{18}) or
  295. // the code comma the number of times to transmit it.
  296. char * tok = strtok((char *) payload, ",");
  297. // Check if a switch is linked to that message
  298. unsigned char id;
  299. unsigned char status = 0;
  300. if (_rfbMatch(tok, id, status)) {
  301. if (status == 2) {
  302. relayToggle(id);
  303. } else {
  304. relayStatus(id, status == 1);
  305. }
  306. return;
  307. }
  308. #if RF_RAW_SUPPORT
  309. byte message[RF_MAX_MESSAGE_SIZE];
  310. int len = _rfbToArray(tok, message, 0);
  311. if ((len > 0) && (isRFRaw || len != RF_MESSAGE_SIZE)) {
  312. _rfbSendRawOnce(message, len);
  313. } else {
  314. tok = strtok(NULL, ",");
  315. byte times = (tok != NULL) ? atoi(tok) : 1;
  316. _rfbSend(message, times);
  317. }
  318. #else // RF_RAW_SUPPORT
  319. byte message[RF_MESSAGE_SIZE];
  320. if (_rfbToArray(tok, message)) {
  321. tok = strtok(NULL, ",");
  322. byte times = (tok != NULL) ? atoi(tok) : 1;
  323. _rfbSend(message, times);
  324. }
  325. #endif // RF_RAW_SUPPORT
  326. }
  327. }
  328. }
  329. #endif
  330. // -----------------------------------------------------------------------------
  331. // PUBLIC
  332. // -----------------------------------------------------------------------------
  333. void rfbStore(unsigned char id, bool status, const char * code) {
  334. DEBUG_MSG_P(PSTR("[RFBRIDGE] Storing %d-%s => '%s'\n"), id, status ? "ON" : "OFF", code);
  335. char key[8] = {0};
  336. snprintf_P(key, sizeof(key), PSTR("rfb%s%d"), status ? "ON" : "OFF", id);
  337. setSetting(key, code);
  338. }
  339. String rfbRetrieve(unsigned char id, bool status) {
  340. char key[8] = {0};
  341. snprintf_P(key, sizeof(key), PSTR("rfb%s%d"), status ? "ON" : "OFF", id);
  342. return getSetting(key);
  343. }
  344. void rfbStatus(unsigned char id, bool status) {
  345. String value = rfbRetrieve(id, status);
  346. if (value.length() > 0) {
  347. bool same = _rfbSameOnOff(id);
  348. #if RF_RAW_SUPPORT
  349. byte message[RF_MAX_MESSAGE_SIZE];
  350. int len = _rfbToArray(value.c_str(), message, 0);
  351. if (len == RF_MESSAGE_SIZE && // probably a standard msg
  352. (message[0] != RF_CODE_START || // raw would start with 0xAA
  353. message[1] != RF_CODE_RFOUT_BUCKET || // followed by 0xB0,
  354. message[2] + 4 != len || // needs a valid length,
  355. message[len-1] != RF_CODE_STOP)) { // and finish with 0x55
  356. unsigned char times = RF_SEND_TIMES;
  357. if (same) times = _rfbin ? 0 : 1;
  358. _rfbSend(message, times);
  359. } else {
  360. _rfbSendRawOnce(message, len); // send a raw message
  361. }
  362. #else // RF_RAW_SUPPORT
  363. byte message[RF_MESSAGE_SIZE];
  364. _rfbToArray(value.c_str(), message);
  365. unsigned char times = RF_SEND_TIMES;
  366. if (same) times = _rfbin ? 0 : 1;
  367. _rfbSend(message, times);
  368. #endif // RF_RAW_SUPPORT
  369. }
  370. }
  371. void rfbLearn(unsigned char id, bool status) {
  372. _learnId = id;
  373. _learnStatus = status;
  374. _rfbLearn();
  375. }
  376. void rfbForget(unsigned char id, bool status) {
  377. char key[8] = {0};
  378. snprintf_P(key, sizeof(key), PSTR("rfb%s%d"), status ? "ON" : "OFF", id);
  379. delSetting(key);
  380. // Websocket update
  381. #if WEB_SUPPORT
  382. char wsb[100];
  383. snprintf_P(wsb, sizeof(wsb), PSTR("{\"rfb\":[{\"id\": %d, \"status\": %d, \"data\": \"\"}]}"), id, status ? 1 : 0);
  384. wsSend(wsb);
  385. #endif
  386. }
  387. // -----------------------------------------------------------------------------
  388. // SETUP & LOOP
  389. // -----------------------------------------------------------------------------
  390. void rfbSetup() {
  391. #if MQTT_SUPPORT
  392. mqttRegister(_rfbMqttCallback);
  393. #endif
  394. #if WEB_SUPPORT
  395. wsOnSendRegister(_rfbWebSocketOnSend);
  396. wsOnActionRegister(_rfbWebSocketOnAction);
  397. #endif
  398. }
  399. void rfbLoop() {
  400. _rfbReceive();
  401. }
  402. #endif