signal.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  1. /* Copyright (C) 2022-2023 Salvatore Sanfilippo -- All Rights Reserved
  2. * See the LICENSE file for information about the license. */
  3. #include "app.h"
  4. bool decode_signal(RawSamplesBuffer *s, uint64_t len, ProtoViewMsgInfo *info);
  5. /* =============================================================================
  6. * Raw signal detection
  7. * ===========================================================================*/
  8. /* Return the time difference between a and b, always >= 0 since
  9. * the absolute value is returned. */
  10. uint32_t duration_delta(uint32_t a, uint32_t b) {
  11. return a > b ? a - b : b - a;
  12. }
  13. /* Reset the current signal, so that a new one can be detected. */
  14. void reset_current_signal(ProtoViewApp *app) {
  15. app->signal_bestlen = 0;
  16. app->signal_offset = 0;
  17. app->signal_decoded = false;
  18. raw_samples_reset(DetectedSamples);
  19. raw_samples_reset(RawSamples);
  20. free_msg_info(app->msg_info);
  21. app->msg_info = NULL;
  22. }
  23. /* This function starts scanning samples at offset idx looking for the
  24. * longest run of pulses, either high or low, that are not much different
  25. * from each other, for a maximum of three duration classes.
  26. * So for instance 50 successive pulses that are roughly long 340us or 670us
  27. * will be sensed as a coherent signal (example: 312, 361, 700, 334, 667, ...)
  28. *
  29. * The classes are counted separtely for high and low signals (RF on / off)
  30. * because many devices tend to have different pulse lenghts depending on
  31. * the level of the pulse.
  32. *
  33. * For instance Oregon2 sensors, in the case of protocol 2.1 will send
  34. * pulses of ~400us (RF on) VS ~580us (RF off). */
  35. #define SEARCH_CLASSES 3
  36. uint32_t search_coherent_signal(RawSamplesBuffer *s, uint32_t idx) {
  37. struct {
  38. uint32_t dur[2]; /* dur[0] = low, dur[1] = high */
  39. uint32_t count[2]; /* Associated observed frequency. */
  40. } classes[SEARCH_CLASSES];
  41. memset(classes,0,sizeof(classes));
  42. uint32_t minlen = 30, maxlen = 4000; /* Depends on data rate, here we
  43. allow for high and low. */
  44. uint32_t len = 0; /* Observed len of coherent samples. */
  45. s->short_pulse_dur = 0;
  46. for (uint32_t j = idx; j < idx+500; j++) {
  47. bool level;
  48. uint32_t dur;
  49. raw_samples_get(s, j, &level, &dur);
  50. if (dur < minlen || dur > maxlen) break; /* return. */
  51. /* Let's see if it matches a class we already have or if we
  52. * can populate a new (yet empty) class. */
  53. uint32_t k;
  54. for (k = 0; k < SEARCH_CLASSES; k++) {
  55. if (classes[k].count[level] == 0) {
  56. classes[k].dur[level] = dur;
  57. classes[k].count[level] = 1;
  58. break; /* Sample accepted. */
  59. } else {
  60. uint32_t classavg = classes[k].dur[level];
  61. uint32_t count = classes[k].count[level];
  62. uint32_t delta = duration_delta(dur,classavg);
  63. /* Is the difference in duration between this signal and
  64. * the class we are inspecting less than a given percentage?
  65. * If so, accept this signal. */
  66. if (delta < classavg/5) { /* 100%/5 = 20%. */
  67. /* It is useful to compute the average of the class
  68. * we are observing. We know how many samples we got so
  69. * far, so we can recompute the average easily.
  70. * By always having a better estimate of the pulse len
  71. * we can avoid missing next samples in case the first
  72. * observed samples are too off. */
  73. classavg = ((classavg * count) + dur) / (count+1);
  74. classes[k].dur[level] = classavg;
  75. classes[k].count[level]++;
  76. break; /* Sample accepted. */
  77. }
  78. }
  79. }
  80. if (k == SEARCH_CLASSES) break; /* No match, return. */
  81. /* If we are here, we accepted this sample. Try with the next
  82. * one. */
  83. len++;
  84. }
  85. /* Update the buffer setting the shortest pulse we found
  86. * among the three classes. This will be used when scaling
  87. * for visualization. */
  88. uint32_t short_dur[2] = {0,0};
  89. for (int j = 0; j < SEARCH_CLASSES; j++) {
  90. for (int level = 0; level < 2; level++) {
  91. if (classes[j].dur[level] == 0) continue;
  92. if (classes[j].count[level] < 3) continue;
  93. if (short_dur[level] == 0 ||
  94. short_dur[level] > classes[j].dur[level])
  95. {
  96. short_dur[level] = classes[j].dur[level];
  97. }
  98. }
  99. }
  100. /* Use the average between high and low short pulses duration.
  101. * Often they are a bit different, and using the average is more robust
  102. * when we do decoding sampling at short_pulse_dur intervals. */
  103. if (short_dur[0] == 0) short_dur[0] = short_dur[1];
  104. if (short_dur[1] == 0) short_dur[1] = short_dur[0];
  105. s->short_pulse_dur = (short_dur[0]+short_dur[1])/2;
  106. return len;
  107. }
  108. /* Called when we detect a message. Just blinks when the message was
  109. * not decoded. Vibrates, too, when the message was correctly decoded. */
  110. void notify_signal_detected(ProtoViewApp *app, bool decoded) {
  111. static const NotificationSequence decoded_seq = {
  112. &message_vibro_on,
  113. &message_green_255,
  114. &message_delay_50,
  115. &message_green_0,
  116. &message_vibro_off,
  117. NULL
  118. };
  119. static const NotificationSequence unknown_seq = {
  120. &message_red_255,
  121. &message_delay_50,
  122. &message_red_0,
  123. NULL
  124. };
  125. if (decoded)
  126. notification_message(app->notification, &decoded_seq);
  127. else
  128. notification_message(app->notification, &unknown_seq);
  129. }
  130. /* Search the buffer with the stored signal (last N samples received)
  131. * in order to find a coherent signal. If a signal that does not appear to
  132. * be just noise is found, it is set in DetectedSamples global signal
  133. * buffer, that is what is rendered on the screen. */
  134. void scan_for_signal(ProtoViewApp *app) {
  135. /* We need to work on a copy: the RawSamples buffer is populated
  136. * by the background thread receiving data. */
  137. RawSamplesBuffer *copy = raw_samples_alloc();
  138. raw_samples_copy(copy,RawSamples);
  139. /* Try to seek on data that looks to have a regular high low high low
  140. * pattern. */
  141. uint32_t minlen = 18; /* Min run of coherent samples. With less
  142. than a few samples it's very easy to
  143. mistake noise for signal. */
  144. uint32_t i = 0;
  145. while (i < copy->total-1) {
  146. uint32_t thislen = search_coherent_signal(copy,i);
  147. /* For messages that are long enough, attempt decoding. */
  148. if (thislen > minlen) {
  149. /* Allocate the message information that some decoder may
  150. * fill, in case it is able to decode a message. */
  151. ProtoViewMsgInfo *info = malloc(sizeof(ProtoViewMsgInfo));
  152. init_msg_info(info,app);
  153. info->short_pulse_dur = copy->short_pulse_dur;
  154. uint32_t saved_idx = copy->idx; /* Save index, see later. */
  155. /* decode_signal() expects the detected signal to start
  156. * from index zero .*/
  157. raw_samples_center(copy,i);
  158. bool decoded = decode_signal(copy,thislen,info);
  159. copy->idx = saved_idx; /* Restore the index as we are scanning
  160. the signal in the loop. */
  161. /* Accept this signal as the new signal if either it's longer
  162. * than the previous undecoded one, or the previous one was
  163. * unknown and this is decoded. */
  164. if ((thislen > app->signal_bestlen && app->signal_decoded == false)
  165. || (app->signal_decoded == false && decoded))
  166. {
  167. free_msg_info(app->msg_info);
  168. app->msg_info = info;
  169. app->signal_bestlen = thislen;
  170. app->signal_decoded = decoded;
  171. raw_samples_copy(DetectedSamples,copy);
  172. raw_samples_center(DetectedSamples,i);
  173. FURI_LOG_E(TAG, "===> Displayed sample updated (%d samples %lu us)",
  174. (int)thislen, DetectedSamples->short_pulse_dur);
  175. adjust_raw_view_scale(app,DetectedSamples->short_pulse_dur);
  176. notify_signal_detected(app,decoded);
  177. } else {
  178. /* If the structure was not filled, discard it. Otherwise
  179. * now the owner is app->msg_info. */
  180. free_msg_info(info);
  181. }
  182. }
  183. i += thislen ? thislen : 1;
  184. }
  185. raw_samples_free(copy);
  186. }
  187. /* =============================================================================
  188. * Decoding
  189. *
  190. * The following code will translates the raw singals as received by
  191. * the CC1101 into logical signals: a bitmap of 0s and 1s sampled at
  192. * the detected data clock interval.
  193. *
  194. * Then the converted signal is passed to the protocols decoders, that look
  195. * for protocol-specific information. We stop at the first decoder that is
  196. * able to decode the data, so protocols here should be registered in
  197. * order of complexity and specificity, with the generic ones at the end.
  198. * ===========================================================================*/
  199. /* Set the 'bitpos' bit to value 'val', in the specified bitmap
  200. * 'b' of len 'blen'.
  201. * Out of range bits will silently be discarded. */
  202. void bitmap_set(uint8_t *b, uint32_t blen, uint32_t bitpos, bool val) {
  203. uint32_t byte = bitpos/8;
  204. uint32_t bit = 7-(bitpos&7);
  205. if (byte >= blen) return;
  206. if (val)
  207. b[byte] |= 1<<bit;
  208. else
  209. b[byte] &= ~(1<<bit);
  210. }
  211. /* Get the bit 'bitpos' of the bitmap 'b' of 'blen' bytes.
  212. * Out of range bits return false (not bit set). */
  213. bool bitmap_get(uint8_t *b, uint32_t blen, uint32_t bitpos) {
  214. uint32_t byte = bitpos/8;
  215. uint32_t bit = 7-(bitpos&7);
  216. if (byte >= blen) return 0;
  217. return (b[byte] & (1<<bit)) != 0;
  218. }
  219. /* Copy 'count' bits from the bitmap 's' of 'slen' total bytes, to the
  220. * bitmap 'd' of 'dlen' total bytes. The bits are copied starting from
  221. * offset 'soff' of the source bitmap to the offset 'doff' of the
  222. * destination bitmap. */
  223. void bitmap_copy(uint8_t *d, uint32_t dlen, uint32_t doff,
  224. uint8_t *s, uint32_t slen, uint32_t soff,
  225. uint32_t count)
  226. {
  227. /* If we are byte-aligned in both source and destination, use a fast
  228. * path for the number of bytes we can consume this way. */
  229. if ((doff & 7) == 0 && (soff & 7) == 0) {
  230. uint32_t didx = doff/8;
  231. uint32_t sidx = soff/8;
  232. while(count > 8 && didx < dlen && sidx < slen) {
  233. d[didx++] = s[sidx++];
  234. count -= 8;
  235. }
  236. doff = didx * 8;
  237. soff = sidx * 8;
  238. /* Note that if we entered this path, the count at the end
  239. * of the loop will be < 8. */
  240. }
  241. /* Copy the bits needed to reach an offset where we can copy
  242. * two half bytes of src to a full byte of destination. */
  243. while(count > 8 && (doff&7) != 0) {
  244. bool bit = bitmap_get(s,slen,soff++);
  245. bitmap_set(d,dlen,doff++,bit);
  246. count--;
  247. }
  248. /* If we are here and count > 8, we have an offset that is byte aligned
  249. * to the destination bitmap, but not aligned to the source bitmap.
  250. * We can copy fast enough by shifting each two bytes of the original
  251. * bitmap.
  252. *
  253. * This is how it works:
  254. *
  255. * dst:
  256. * +--------+--------+--------+
  257. * | 0 | 1 | 2 |
  258. * | | | | <- data to fill
  259. * +--------+--------+--------+
  260. * ^
  261. * |
  262. * doff = 8
  263. *
  264. * src:
  265. * +--------+--------+--------+
  266. * | 0 | 1 | 2 |
  267. * |hellowor|ld!HELLO|WORLDS!!| <- data to copy
  268. * +--------+--------+--------+
  269. * ^
  270. * |
  271. * soff = 11
  272. *
  273. * skew = 11%8 = 3
  274. * each destination byte in dst will receive:
  275. *
  276. * dst[doff/8] = (src[soff/8] << skew) | (src[soff/8+1] >> (8-skew))
  277. *
  278. * dstbyte = doff/8 = 8/8 = 1
  279. * srcbyte = soff/8 = 11/8 = 1
  280. *
  281. * so dst[1] will get:
  282. * src[1] << 3, that is "ld!HELLO" << 3 = "HELLO..."
  283. * xored with
  284. * src[2] << 5, that is "WORLDS!!" >> 5 = ".....WOR"
  285. * That is "HELLOWOR"
  286. */
  287. if (count > 8) {
  288. uint8_t skew = soff % 8; /* Don't worry, compiler will optimize. */
  289. uint32_t didx = doff/8;
  290. uint32_t sidx = soff/8;
  291. while(count > 8 && didx < dlen && sidx < slen) {
  292. d[didx] = ((s[sidx] << skew) |
  293. (s[sidx+1] >> (8-skew)));
  294. sidx++;
  295. didx++;
  296. soff += 8;
  297. doff += 8;
  298. count -= 8;
  299. }
  300. }
  301. /* Here count is guaranteed to be < 8.
  302. * Copy the final bits bit by bit. */
  303. while(count) {
  304. bool bit = bitmap_get(s,slen,soff++);
  305. bitmap_set(d,dlen,doff++,bit);
  306. count--;
  307. }
  308. }
  309. /* We decode bits assuming the first bit we receive is the MSB
  310. * (see bitmap_set/get functions). Certain devices send data
  311. * encoded in the reverse way. */
  312. void bitmap_reverse_bytes(uint8_t *p, uint32_t len) {
  313. for (uint32_t j = 0; j < len; j++) {
  314. uint32_t b = p[j];
  315. /* Step 1: swap the two nibbles: 12345678 -> 56781234 */
  316. b = (b&0xf0)>>4 | (b&0x0f)<<4;
  317. /* Step 2: swap adjacent pairs : 56781234 -> 78563412 */
  318. b = (b&0xcc)>>2 | (b&0x33)<<2;
  319. /* Step 3: swap adjacent bits : 78563412 -> 87654321 */
  320. b = (b&0xaa)>>1 | (b&0x55)<<1;
  321. p[j] = b;
  322. }
  323. }
  324. /* Return true if the specified sequence of bits, provided as a string in the
  325. * form "11010110..." is found in the 'b' bitmap of 'blen' bits at 'bitpos'
  326. * position. */
  327. bool bitmap_match_bits(uint8_t *b, uint32_t blen, uint32_t bitpos, const char *bits) {
  328. for (size_t j = 0; bits[j]; j++) {
  329. bool expected = (bits[j] == '1') ? true : false;
  330. if (bitmap_get(b,blen,bitpos+j) != expected) return false;
  331. }
  332. return true;
  333. }
  334. /* Search for the specified bit sequence (see bitmap_match_bits() for details)
  335. * in the bitmap 'b' of 'blen' bytes, looking forward at most 'maxbits' ahead.
  336. * Returns the offset (in bits) of the match, or BITMAP_SEEK_NOT_FOUND if not
  337. * found.
  338. *
  339. * Note: there are better algorithms, such as Boyer-Moore. Here we hope that
  340. * for the kind of patterns we search we'll have a lot of early stops so
  341. * we use a vanilla approach. */
  342. uint32_t bitmap_seek_bits(uint8_t *b, uint32_t blen, uint32_t startpos, uint32_t maxbits, const char *bits) {
  343. uint32_t endpos = startpos+blen*8;
  344. uint32_t end2 = startpos+maxbits;
  345. if (end2 < endpos) endpos = end2;
  346. for (uint32_t j = startpos; j < endpos; j++)
  347. if (bitmap_match_bits(b,blen,j,bits)) return j;
  348. return BITMAP_SEEK_NOT_FOUND;
  349. }
  350. /* Set the pattern 'pat' into the bitmap 'b' of max length 'blen' bytes,
  351. * starting from the specified offset.
  352. *
  353. * The pattern is given as a string of 0s and 1s characters, like "01101001".
  354. * This function is useful in order to set the test vectors in the protocol
  355. * decoders, to see if the decoding works regardless of the fact we are able
  356. * to actually receive a given signal. */
  357. void bitmap_set_pattern(uint8_t *b, uint32_t blen, uint32_t off, const char *pat) {
  358. uint32_t i = 0;
  359. while(pat[i]) {
  360. bitmap_set(b,blen,i+off,pat[i] == '1');
  361. i++;
  362. }
  363. }
  364. /* Take the raw signal and turn it into a sequence of bits inside the
  365. * buffer 'b'. Note that such 0s and 1s are NOT the actual data in the
  366. * signal, but is just a low level representation of the line code. Basically
  367. * if the short pulse we find in the signal is 320us, we convert high and
  368. * low levels in the raw sample in this way:
  369. *
  370. * If for instance we see a high level lasting ~600 us, we will add
  371. * two 1s bit. If then the signal goes down for 330us, we will add one zero,
  372. * and so forth. So for each period of high and low we find the closest
  373. * multiple and set the relevant number of bits.
  374. *
  375. * In case of a short pulse of 320us detected, 320*2 is the closest to a
  376. * high pulse of 600us, so 2 bits will be set.
  377. *
  378. * In other terms what this function does is sampling the signal at
  379. * fixed 'rate' intervals.
  380. *
  381. * This representation makes it simple to decode the signal at a higher
  382. * level later, translating it from Marshal coding or other line codes
  383. * to the actual bits/bytes.
  384. *
  385. * The 'idx' argument marks the detected signal start index into the
  386. * raw samples buffer. The 'count' tells the function how many raw
  387. * samples to convert into bits. The function returns the number of
  388. * bits set into the buffer 'b'. The 'rate' argument, in microseconds, is
  389. * the detected short-pulse duration. We expect the line code to be
  390. * meaningful when interpreted at multiples of 'rate'. */
  391. uint32_t convert_signal_to_bits(uint8_t *b, uint32_t blen, RawSamplesBuffer *s, uint32_t idx, uint32_t count, uint32_t rate) {
  392. if (rate == 0) return 0; /* We can't perform the conversion. */
  393. uint32_t bitpos = 0;
  394. for (uint32_t j = 0; j < count; j++) {
  395. uint32_t dur;
  396. bool level;
  397. raw_samples_get(s, j+idx, &level, &dur);
  398. uint32_t numbits = dur / rate; /* full bits that surely fit. */
  399. uint32_t rest = dur % rate; /* How much we are left with. */
  400. if (rest > rate/2) numbits++; /* There is another one. */
  401. /* Limit how much a single sample can spawn. There are likely no
  402. * protocols doing such long pulses when the rate is low. */
  403. if (numbits > 1024) numbits = 1024;
  404. if (0) /* Super verbose, so not under the DEBUG_MSG define. */
  405. FURI_LOG_E(TAG, "%lu converted into %lu (%d) bits",
  406. dur,numbits,(int)level);
  407. /* If the signal is too short, let's claim it an interference
  408. * and ignore it completely. */
  409. if (numbits == 0) continue;
  410. while(numbits--) bitmap_set(b,blen,bitpos++,level);
  411. }
  412. return bitpos;
  413. }
  414. /* This function converts the line code used to the final data representation.
  415. * The representation is put inside 'buf', for up to 'buflen' bytes of total
  416. * data. For instance in order to convert manchester you can use "10" and "01"
  417. * as zero and one patterns. However this function does not handle differential
  418. * encodings. See below for convert_from_diff_manchester().
  419. *
  420. * The function returns the number of bits converted. It will stop as soon
  421. * as it finds a pattern that does not match zero or one patterns, or when
  422. * the end of the bitmap pointed by 'bits' is reached (the length is
  423. * specified in bytes by the caller, via the 'len' parameters).
  424. *
  425. * The decoding starts at the specified offset (in bits) 'off'. */
  426. uint32_t convert_from_line_code(uint8_t *buf, uint64_t buflen, uint8_t *bits, uint32_t len, uint32_t off, const char *zero_pattern, const char *one_pattern)
  427. {
  428. uint32_t decoded = 0; /* Number of bits extracted. */
  429. len *= 8; /* Convert bytes to bits. */
  430. while(off < len) {
  431. bool bitval;
  432. if (bitmap_match_bits(bits,len,off,zero_pattern)) {
  433. bitval = false;
  434. off += strlen(zero_pattern);
  435. } else if (bitmap_match_bits(bits,len,off,one_pattern)) {
  436. bitval = true;
  437. off += strlen(one_pattern);
  438. } else {
  439. break;
  440. }
  441. bitmap_set(buf,buflen,decoded++,bitval);
  442. if (decoded/8 == buflen) break; /* No space left on target buffer. */
  443. }
  444. return decoded;
  445. }
  446. /* Convert the differential Manchester code to bits. This is similar to
  447. * convert_from_line_code() but specific for Manchester. The user must
  448. * supply the value of the previous symbol before this stream, since
  449. * in differential codings the next bits depend on the previous one.
  450. *
  451. * Parameters and return values are like convert_from_line_code(). */
  452. uint32_t convert_from_diff_manchester(uint8_t *buf, uint64_t buflen, uint8_t *bits, uint32_t len, uint32_t off, bool previous)
  453. {
  454. uint32_t decoded = 0;
  455. len *= 8; /* Conver to bits. */
  456. for (uint32_t j = off; j < len; j += 2) {
  457. bool b0 = bitmap_get(bits,len,j);
  458. bool b1 = bitmap_get(bits,len,j+1);
  459. if (b0 == previous) break; /* Each new bit must switch value. */
  460. bitmap_set(buf,buflen,decoded++,b0 == b1);
  461. previous = b1;
  462. if (decoded/8 == buflen) break; /* No space left on target buffer. */
  463. }
  464. return decoded;
  465. }
  466. /* Supported protocols go here, with the relevant implementation inside
  467. * protocols/<name>.c */
  468. extern ProtoViewDecoder Oregon2Decoder;
  469. extern ProtoViewDecoder B4B1Decoder;
  470. extern ProtoViewDecoder RenaultTPMSDecoder;
  471. extern ProtoViewDecoder ToyotaTPMSDecoder;
  472. extern ProtoViewDecoder SchraderTPMSDecoder;
  473. extern ProtoViewDecoder SchraderEG53MA4TPMSDecoder;
  474. extern ProtoViewDecoder CitroenTPMSDecoder;
  475. extern ProtoViewDecoder FordTPMSDecoder;
  476. extern ProtoViewDecoder KeeloqDecoder;
  477. ProtoViewDecoder *Decoders[] = {
  478. &Oregon2Decoder, /* Oregon sensors v2.1 protocol. */
  479. &B4B1Decoder, /* PT, SC, ... 24 bits remotes. */
  480. &RenaultTPMSDecoder, /* Renault TPMS. */
  481. &ToyotaTPMSDecoder, /* Toyota TPMS. */
  482. &SchraderTPMSDecoder, /* Schrader TPMS. */
  483. &SchraderEG53MA4TPMSDecoder, /* Schrader EG53MA4 TPMS. */
  484. &CitroenTPMSDecoder, /* Citroen TPMS. */
  485. &FordTPMSDecoder, /* Ford TPMS. */
  486. &KeeloqDecoder, /* Keeloq remote. */
  487. NULL
  488. };
  489. /* Free the message info and allocated data. */
  490. void free_msg_info(ProtoViewMsgInfo *i) {
  491. if (i == NULL) return;
  492. fieldset_free(i->fieldset);
  493. free(i->bits);
  494. free(i);
  495. }
  496. /* Reset the message info structure before passing it to the decoding
  497. * functions. */
  498. void init_msg_info(ProtoViewMsgInfo *i, ProtoViewApp *app) {
  499. UNUSED(app);
  500. memset(i,0,sizeof(ProtoViewMsgInfo));
  501. i->bits = NULL;
  502. i->fieldset = fieldset_new();
  503. }
  504. /* This function is called when a new signal is detected. It converts it
  505. * to a bitstream, and the calls the protocol specific functions for
  506. * decoding. If the signal was decoded correctly by some protocol, true
  507. * is returned. Otherwise false is returned. */
  508. bool decode_signal(RawSamplesBuffer *s, uint64_t len, ProtoViewMsgInfo *info) {
  509. uint32_t bitmap_bits_size = 4096*8;
  510. uint32_t bitmap_size = bitmap_bits_size/8;
  511. /* We call the decoders with an offset a few samples before the actual
  512. * signal detected and for a len of a few bits after its end. */
  513. uint32_t before_samples = 32;
  514. uint32_t after_samples = 100;
  515. uint8_t *bitmap = malloc(bitmap_size);
  516. uint32_t bits = convert_signal_to_bits(bitmap,bitmap_size,s,-before_samples,len+before_samples+after_samples,s->short_pulse_dur);
  517. if (DEBUG_MSG) { /* Useful for debugging purposes. Don't remove. */
  518. char *str = malloc(1024);
  519. uint32_t j;
  520. for (j = 0; j < bits && j < 1023; j++) {
  521. str[j] = bitmap_get(bitmap,bitmap_size,j) ? '1' : '0';
  522. }
  523. str[j] = 0;
  524. FURI_LOG_E(TAG, "%lu bits sampled: %s", bits, str);
  525. free(str);
  526. }
  527. /* Try all the decoders available. */
  528. int j = 0;
  529. bool decoded = false;
  530. while(Decoders[j]) {
  531. uint32_t start_time = furi_get_tick();
  532. decoded = Decoders[j]->decode(bitmap,bitmap_size,bits,info);
  533. uint32_t delta = furi_get_tick() - start_time;
  534. FURI_LOG_E(TAG, "Decoder %s took %lu ms",
  535. Decoders[j]->name, (unsigned long)delta);
  536. if (decoded) {
  537. info->decoder = Decoders[j];
  538. break;
  539. }
  540. j++;
  541. }
  542. if (!decoded) {
  543. FURI_LOG_E(TAG, "No decoding possible");
  544. } else {
  545. FURI_LOG_E(TAG, "+++ Decoded %s", info->decoder->name);
  546. /* The message was correctly decoded: fill the info structure
  547. * with the decoded signal. The decoder may not implement offset/len
  548. * filling of the structure. In such case we have no info and
  549. * pulses_count will be set to zero. */
  550. if (info->pulses_count) {
  551. info->bits_bytes = (info->pulses_count+7)/8; // Round to full byte.
  552. info->bits = malloc(info->bits_bytes);
  553. bitmap_copy(info->bits,info->bits_bytes,0,
  554. bitmap,bitmap_size,info->start_off,
  555. info->pulses_count);
  556. }
  557. }
  558. free(bitmap);
  559. return decoded;
  560. }