signal.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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. void decode_signal(RawSamplesBuffer *s, uint64_t len);
  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. /* This function starts scanning samples at offset idx looking for the
  14. * longest run of pulses, either high or low, that are not much different
  15. * from each other, for a maximum of three duration classes.
  16. * So for instance 50 successive pulses that are roughly long 340us or 670us
  17. * will be sensed as a coherent signal (example: 312, 361, 700, 334, 667, ...)
  18. *
  19. * The classes are counted separtely for high and low signals (RF on / off)
  20. * because many devices tend to have different pulse lenghts depending on
  21. * the level of the pulse.
  22. *
  23. * For instance Oregon2 sensors, in the case of protocol 2.1 will send
  24. * pulses of ~400us (RF on) VS ~580us (RF off). */
  25. #define SEARCH_CLASSES 3
  26. uint32_t search_coherent_signal(RawSamplesBuffer *s, uint32_t idx) {
  27. struct {
  28. uint32_t dur[2]; /* dur[0] = low, dur[1] = high */
  29. uint32_t count[2]; /* Associated observed frequency. */
  30. } classes[SEARCH_CLASSES];
  31. memset(classes,0,sizeof(classes));
  32. uint32_t minlen = 40, maxlen = 4000; /* Depends on data rate, here we
  33. allow for high and low. */
  34. uint32_t len = 0; /* Observed len of coherent samples. */
  35. s->short_pulse_dur = 0;
  36. for (uint32_t j = idx; j < idx+500; j++) {
  37. bool level;
  38. uint32_t dur;
  39. raw_samples_get(s, j, &level, &dur);
  40. if (dur < minlen || dur > maxlen) break; /* return. */
  41. /* Let's see if it matches a class we already have or if we
  42. * can populate a new (yet empty) class. */
  43. uint32_t k;
  44. for (k = 0; k < SEARCH_CLASSES; k++) {
  45. if (classes[k].count[level] == 0) {
  46. classes[k].dur[level] = dur;
  47. classes[k].count[level] = 1;
  48. break; /* Sample accepted. */
  49. } else {
  50. uint32_t classavg = classes[k].dur[level];
  51. uint32_t count = classes[k].count[level];
  52. uint32_t delta = duration_delta(dur,classavg);
  53. /* Is the difference in duration between this signal and
  54. * the class we are inspecting less than a given percentage?
  55. * If so, accept this signal. */
  56. if (delta < classavg/8) { /* 100%/8 = 12%. */
  57. /* It is useful to compute the average of the class
  58. * we are observing. We know how many samples we got so
  59. * far, so we can recompute the average easily.
  60. * By always having a better estimate of the pulse len
  61. * we can avoid missing next samples in case the first
  62. * observed samples are too off. */
  63. classavg = ((classavg * count) + dur) / (count+1);
  64. classes[k].dur[level] = classavg;
  65. classes[k].count[level]++;
  66. break; /* Sample accepted. */
  67. }
  68. }
  69. }
  70. if (k == SEARCH_CLASSES) break; /* No match, return. */
  71. /* If we are here, we accepted this sample. Try with the next
  72. * one. */
  73. len++;
  74. }
  75. /* Update the buffer setting the shortest pulse we found
  76. * among the three classes. This will be used when scaling
  77. * for visualization. */
  78. uint32_t short_dur[2] = {0,0};
  79. for (int j = 0; j < SEARCH_CLASSES; j++) {
  80. for (int level = 0; level < 2; level++) {
  81. if (classes[j].dur[level] == 0) continue;
  82. if (classes[j].count[level] < 3) continue;
  83. if (short_dur[level] == 0 ||
  84. short_dur[level] > classes[j].dur[level])
  85. {
  86. short_dur[level] = classes[j].dur[level];
  87. }
  88. }
  89. }
  90. /* Use the average between high and low short pulses duration.
  91. * Often they are a bit different, and using the average is more robust
  92. * when we do decoding sampling at short_pulse_dur intervals. */
  93. if (short_dur[0] == 0) short_dur[0] = short_dur[1];
  94. if (short_dur[1] == 0) short_dur[1] = short_dur[0];
  95. s->short_pulse_dur = (short_dur[0]+short_dur[1])/2;
  96. return len;
  97. }
  98. /* Search the buffer with the stored signal (last N samples received)
  99. * in order to find a coherent signal. If a signal that does not appear to
  100. * be just noise is found, it is set in DetectedSamples global signal
  101. * buffer, that is what is rendered on the screen. */
  102. void scan_for_signal(ProtoViewApp *app) {
  103. /* We need to work on a copy: the RawSamples buffer is populated
  104. * by the background thread receiving data. */
  105. RawSamplesBuffer *copy = raw_samples_alloc();
  106. raw_samples_copy(copy,RawSamples);
  107. /* Try to seek on data that looks to have a regular high low high low
  108. * pattern. */
  109. uint32_t minlen = 13; /* Min run of coherent samples. Up to
  110. 12 samples it's very easy to mistake
  111. noise for signal. */
  112. uint32_t i = 0;
  113. while (i < copy->total-1) {
  114. uint32_t thislen = search_coherent_signal(copy,i);
  115. if (thislen > minlen && thislen > app->signal_bestlen) {
  116. app->signal_bestlen = thislen;
  117. raw_samples_copy(DetectedSamples,copy);
  118. DetectedSamples->idx = (DetectedSamples->idx+i)%
  119. DetectedSamples->total;
  120. FURI_LOG_E(TAG, "Displayed sample updated (%d samples %lu us)",
  121. (int)thislen, DetectedSamples->short_pulse_dur);
  122. decode_signal(DetectedSamples,thislen);
  123. }
  124. i += thislen ? thislen : 1;
  125. }
  126. raw_samples_free(copy);
  127. }
  128. /* =============================================================================
  129. * Decoding
  130. *
  131. * The following code will translates the raw singals as received by
  132. * the CC1101 into logical signals: a bitmap of 0s and 1s sampled at
  133. * the detected data clock interval.
  134. *
  135. * Then the converted signal is passed to the protocols decoders, that look
  136. * for protocol-specific information. We stop at the first decoder that is
  137. * able to decode the data, so protocols here should be registered in
  138. * order of complexity and specificity, with the generic ones at the end.
  139. * ===========================================================================*/
  140. /* Set the 'bitpos' bit to value 'val', in the specified bitmap
  141. * 'b' of len 'blen'.
  142. * Out of range bits will silently be discarded. */
  143. void bitmap_set(uint8_t *b, uint32_t blen, uint32_t bitpos, bool val) {
  144. uint32_t byte = bitpos/8;
  145. uint32_t bit = bitpos&7;
  146. if (byte >= blen) return;
  147. if (val)
  148. b[byte] |= 1<<bit;
  149. else
  150. b[byte] &= ~(1<<bit);
  151. }
  152. /* Get the bit 'bitpos' of the bitmap 'b' of 'blen' bytes.
  153. * Out of range bits return false (not bit set). */
  154. bool bitmap_get(uint8_t *b, uint32_t blen, uint32_t bitpos) {
  155. uint32_t byte = bitpos/8;
  156. uint32_t bit = bitpos&7;
  157. if (byte >= blen) return 0;
  158. return (b[byte] & (1<<bit)) != 0;
  159. }
  160. /* Return true if the specified sequence of bits, provided as a string in the
  161. * form "11010110..." is found in the 'b' bitmap of 'blen' bits at 'bitpos'
  162. * position. */
  163. bool bitmap_match_bits(uint8_t *b, uint32_t blen, uint32_t bitpos, const char *bits) {
  164. size_t l = strlen(bits);
  165. for (size_t j = 0; j < l; j++) {
  166. bool expected = (bits[j] == '1') ? true : false;
  167. if (bitmap_get(b,blen,bitpos+j) != expected) return false;
  168. }
  169. return true;
  170. }
  171. /* Search for the specified bit sequence (see bitmap_match_bits() for details)
  172. * in the bitmap 'b' of 'blen' bytes. Returns the offset (in bits) of the
  173. * match, or BITMAP_SEEK_NOT_FOUND if not found.
  174. *
  175. * Note: there are better algorithms, such as Boyer-Moore. Here we hope that
  176. * for the kind of patterns we search we'll have a lot of early stops so
  177. * we use a vanilla approach. */
  178. uint32_t bitmap_seek_bits(uint8_t *b, uint32_t blen, uint32_t startpos, const char *bits) {
  179. uint32_t endpos = blen*8;
  180. for (uint32_t j = startpos; j < endpos; j++)
  181. if (bitmap_match_bits(b,blen,j,bits)) return j;
  182. return BITMAP_SEEK_NOT_FOUND;
  183. }
  184. /* Take the raw signal and turn it into a sequence of bits inside the
  185. * buffer 'b'. Note that such 0s and 1s are NOT the actual data in the
  186. * signal, but is just a low level representation of the line code. Basically
  187. * if the short pulse we find in the signal is 320us, we convert high and
  188. * low levels in the raw sample in this way:
  189. *
  190. * If for instance we see a high level lasting ~600 us, we will add
  191. * two 1s bit. If then the signal goes down for 330us, we will add one zero,
  192. * and so forth. So for each period of high and low we find the closest
  193. * multiple and set the relevant number of bits.
  194. *
  195. * In case of a short pulse of 320us detected, 320*2 is the closest to a
  196. * high pulse of 600us, so 2 bits will be set.
  197. *
  198. * In other terms what this function does is sampling the signal at
  199. * fixed 'rate' intervals.
  200. *
  201. * This representation makes it simple to decode the signal at a higher
  202. * level later, translating it from Marshal coding or other line codes
  203. * to the actual bits/bytes.
  204. *
  205. * The 'idx' argument marks the detected signal start index into the
  206. * raw samples buffer. The 'count' tells the function how many raw
  207. * samples to convert into bits. The function returns the number of
  208. * bits set into the buffer 'b'. The 'rate' argument, in microseconds, is
  209. * the detected short-pulse duration. We expect the line code to be
  210. * meaningful when interpreted at multiples of 'rate'. */
  211. uint32_t convert_signal_to_bits(uint8_t *b, uint32_t blen, RawSamplesBuffer *s, uint32_t idx, uint32_t count, uint32_t rate) {
  212. if (rate == 0) return 0; /* We can't perform the conversion. */
  213. uint32_t bitpos = 0;
  214. for (uint32_t j = 0; j < count; j++) {
  215. uint32_t dur;
  216. bool level;
  217. raw_samples_get(s, j+idx, &level, &dur);
  218. uint32_t numbits = dur / rate; /* full bits that surely fit. */
  219. uint32_t rest = dur % rate; /* How much we are left with. */
  220. if (rest > rate/2) numbits++; /* There is another one. */
  221. FURI_LOG_E(TAG, "%lu converted into %lu (%d) bits", dur,numbits,(int)level);
  222. /* If the signal is too short, let's claim it an interference
  223. * and ignore it completely. */
  224. if (numbits == 0) continue;
  225. while(numbits--) bitmap_set(b,blen,bitpos++,level);
  226. }
  227. return bitpos;
  228. }
  229. /* This function converts the line code used to the final data representation.
  230. * The representation is put inside 'buf', for up to 'buflen' bytes of total
  231. * data. For instance in order to convert manchester I can use "10" and "01"
  232. * as zero and one patterns. It is possible to use "?" inside patterns in
  233. * order to skip certain bits. For instance certain devices encode data twice,
  234. * with each bit encoded in manchester encoding and then in its reversed
  235. * representation. In such a case I could use "10??" and "01??".
  236. *
  237. * The function returns the number of bits converted. It will stop as soon
  238. * as it finds a pattern that does not match zero or one patterns. The
  239. * decoding starts at the specified offset 'off'. */
  240. 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)
  241. {
  242. uint32_t decoded = 0; /* Number of bits extracted. */
  243. while(off < len) {
  244. bool level;
  245. if (bitmap_match_bits(bits,len,off,zero_pattern)) {
  246. level = true;
  247. off += strlen(zero_pattern);
  248. } else if (bitmap_match_bits(bits,len,off,one_pattern)) {
  249. level = false;
  250. off += strlen(zero_pattern);
  251. } else {
  252. break;
  253. }
  254. bitmap_set(buf,buflen,decoded++,level);
  255. if (decoded/8 == buflen) break; /* No space left on target buffer. */
  256. }
  257. return decoded;
  258. }
  259. /* Supported protocols go here, with the relevant implementation inside
  260. * protocols/<name>.c */
  261. extern ProtoViewDecoder Oregon2Decoder;
  262. extern ProtoViewDecoder B4B1Decoder;
  263. ProtoViewDecoder *Decoders[] = {
  264. &Oregon2Decoder, /* Oregon sensors v2.1 protocol. */
  265. &B4B1Decoder, /* PT, SC, ... 24 bits remotes. */
  266. NULL
  267. };
  268. /* Reset the message info structure before passing it to the decoding
  269. * functions. */
  270. void initialize_msg_info(ProtoViewMsgInfo *i) {
  271. memset(i,0,sizeof(ProtoViewMsgInfo));
  272. }
  273. /* This function is called when a new signal is detected. It converts it
  274. * to a bitstream, and the calls the protocol specific functions for
  275. * decoding. */
  276. void decode_signal(RawSamplesBuffer *s, uint64_t len) {
  277. uint32_t bitmap_bits_size = 4096*8;
  278. uint32_t bitmap_size = bitmap_bits_size/8;
  279. /* We call the decoders with an offset a few bits before the actual
  280. * signal detected and for a len of a few bits after its end. */
  281. uint32_t before_after_bits = 2;
  282. uint8_t *bitmap = malloc(bitmap_size);
  283. uint32_t bits = convert_signal_to_bits(bitmap,bitmap_size,s,-before_after_bits,len+before_after_bits*2,s->short_pulse_dur);
  284. if (DEBUG_MSG) { /* Useful for debugging purposes. Don't remove. */
  285. char *str = malloc(1024);
  286. uint32_t j;
  287. for (j = 0; j < bits && j < 1023; j++) {
  288. str[j] = bitmap_get(bitmap,bitmap_size,j) ? '1' : '0';
  289. }
  290. str[j] = 0;
  291. FURI_LOG_E(TAG, "%lu bits decoded: %s", bits, str);
  292. free(str);
  293. }
  294. /* Try all the decoders available. */
  295. int j = 0;
  296. ProtoViewMsgInfo info;
  297. initialize_msg_info(&info);
  298. while(Decoders[j]) {
  299. FURI_LOG_E(TAG, "Calling decoder %s", Decoders[j]->name);
  300. ProtoViewMsgInfo info;
  301. if (Decoders[j]->decode(bitmap,bits,&info)) {
  302. FURI_LOG_E(TAG, "Message detected by %s", Decoders[j]->name);
  303. break;
  304. }
  305. j++;
  306. }
  307. if (Decoders[j] == NULL) {
  308. FURI_LOG_E(TAG, "No decoding possible");
  309. } else {
  310. FURI_LOG_E(TAG, "Decoded %s, raw=%s",
  311. info.name, info.raw);
  312. }
  313. free(bitmap);
  314. }