]> git.zerfleddert.de Git - proxmark3-svn/blob - common/lfdemod.c
58221546b24da9ce67c6aa60495f325d6a911ec1
[proxmark3-svn] / common / lfdemod.c
1 //-----------------------------------------------------------------------------
2 // Copyright (C) 2014
3 //
4 // This code is licensed to you under the terms of the GNU GPL, version 2 or,
5 // at your option, any later version. See the LICENSE.txt file for the text of
6 // the license.
7 //-----------------------------------------------------------------------------
8 // Low frequency demod/decode commands
9 //-----------------------------------------------------------------------------
10
11 #include <stdlib.h>
12 #include <string.h>
13 #include "lfdemod.h"
14 uint8_t justNoise(uint8_t *BitStream, size_t size)
15 {
16 static const uint8_t THRESHOLD = 123;
17 //test samples are not just noise
18 uint8_t justNoise1 = 1;
19 for(size_t idx=0; idx < size && justNoise1 ;idx++){
20 justNoise1 = BitStream[idx] < THRESHOLD;
21 }
22 return justNoise1;
23 }
24
25 //by marshmellow
26 //get high and low values of a wave with passed in fuzz factor. also return noise test = 1 for passed or 0 for only noise
27 int getHiLo(uint8_t *BitStream, size_t size, int *high, int *low, uint8_t fuzzHi, uint8_t fuzzLo)
28 {
29 *high=0;
30 *low=255;
31 // get high and low thresholds
32 for (size_t i=0; i < size; i++){
33 if (BitStream[i] > *high) *high = BitStream[i];
34 if (BitStream[i] < *low) *low = BitStream[i];
35 }
36 if (*high < 123) return -1; // just noise
37 *high = ((*high-128)*fuzzHi + 12800)/100;
38 *low = ((*low-128)*fuzzLo + 12800)/100;
39 return 1;
40 }
41
42 // by marshmellow
43 // pass bits to be tested in bits, length bits passed in bitLen, and parity type (even=0 | odd=1) in pType
44 // returns 1 if passed
45 uint8_t parityTest(uint32_t bits, uint8_t bitLen, uint8_t pType)
46 {
47 uint8_t ans = 0;
48 for (uint8_t i = 0; i < bitLen; i++){
49 ans ^= ((bits >> i) & 1);
50 }
51 //PrintAndLog("DEBUG: ans: %d, ptype: %d",ans,pType);
52 return (ans == pType);
53 }
54
55 //by marshmellow
56 //search for given preamble in given BitStream and return success=1 or fail=0 and startIndex and length
57 uint8_t preambleSearch(uint8_t *BitStream, uint8_t *preamble, size_t pLen, size_t *size, size_t *startIdx)
58 {
59 uint8_t foundCnt=0;
60 for (int idx=0; idx < *size - pLen; idx++){
61 if (memcmp(BitStream+idx, preamble, pLen) == 0){
62 //first index found
63 foundCnt++;
64 if (foundCnt == 1){
65 *startIdx = idx;
66 }
67 if (foundCnt == 2){
68 *size = idx - *startIdx;
69 return 1;
70 }
71 }
72 }
73 return 0;
74 }
75
76 //by marshmellow
77 //takes 1s and 0s and searches for EM410x format - output EM ID
78 uint8_t Em410xDecode(uint8_t *BitStream, size_t *size, size_t *startIdx, uint32_t *hi, uint64_t *lo)
79 {
80 //no arguments needed - built this way in case we want this to be a direct call from "data " cmds in the future
81 // otherwise could be a void with no arguments
82 //set defaults
83 uint32_t i = 0;
84 if (BitStream[1]>1) return 0; //allow only 1s and 0s
85
86 // 111111111 bit pattern represent start of frame
87 // include 0 in front to help get start pos
88 uint8_t preamble[] = {0,1,1,1,1,1,1,1,1,1};
89 uint32_t idx = 0;
90 uint32_t parityBits = 0;
91 uint8_t errChk = 0;
92 uint8_t FmtLen = 10;
93 *startIdx = 0;
94 errChk = preambleSearch(BitStream, preamble, sizeof(preamble), size, startIdx);
95 if (errChk == 0 || *size < 64) return 0;
96 if (*size > 64) FmtLen = 22;
97 *startIdx += 1; //get rid of 0 from preamble
98 idx = *startIdx + 9;
99 for (i=0; i<FmtLen; i++){ //loop through 10 or 22 sets of 5 bits (50-10p = 40 bits or 88 bits)
100 parityBits = bytebits_to_byte(BitStream+(i*5)+idx,5);
101 //check even parity - quit if failed
102 if (parityTest(parityBits, 5, 0) == 0) return 0;
103 //set uint64 with ID from BitStream
104 for (uint8_t ii=0; ii<4; ii++){
105 *hi = (*hi << 1) | (*lo >> 63);
106 *lo = (*lo << 1) | (BitStream[(i*5)+ii+idx]);
107 }
108 }
109 if (errChk != 0) return 1;
110 //skip last 5 bit parity test for simplicity.
111 // *size = 64 | 128;
112 return 0;
113 }
114
115 // demodulates strong heavily clipped samples
116 int cleanAskRawDemod(uint8_t *BinStream, size_t *size, int clk, int invert, int high, int low)
117 {
118 size_t bitCnt=0, smplCnt=0, errCnt=0;
119 uint8_t waveHigh = 0;
120 //PrintAndLog("clk: %d", clk);
121 for (size_t i=0; i < *size; i++){
122 if (BinStream[i] >= high && waveHigh){
123 smplCnt++;
124 } else if (BinStream[i] <= low && !waveHigh){
125 smplCnt++;
126 } else { //transition
127 if ((BinStream[i] >= high && !waveHigh) || (BinStream[i] <= low && waveHigh)){
128 if (smplCnt > clk-(clk/4)-1) { //full clock
129 if (smplCnt > clk + (clk/4)+1) { //too many samples
130 errCnt++;
131 BinStream[bitCnt++]=7;
132 } else if (waveHigh) {
133 BinStream[bitCnt++] = invert;
134 BinStream[bitCnt++] = invert;
135 } else if (!waveHigh) {
136 BinStream[bitCnt++] = invert ^ 1;
137 BinStream[bitCnt++] = invert ^ 1;
138 }
139 waveHigh ^= 1;
140 smplCnt = 0;
141 } else if (smplCnt > (clk/2) - (clk/4)-1) {
142 if (waveHigh) {
143 BinStream[bitCnt++] = invert;
144 } else if (!waveHigh) {
145 BinStream[bitCnt++] = invert ^ 1;
146 }
147 waveHigh ^= 1;
148 smplCnt = 0;
149 } else if (!bitCnt) {
150 //first bit
151 waveHigh = (BinStream[i] >= high);
152 smplCnt = 1;
153 } else {
154 smplCnt++;
155 //transition bit oops
156 }
157 } else { //haven't hit new high or new low yet
158 smplCnt++;
159 }
160 }
161 }
162 *size = bitCnt;
163 return errCnt;
164 }
165
166 //by marshmellow
167 //takes 3 arguments - clock, invert, maxErr as integers
168 //attempts to demodulate ask while decoding manchester
169 //prints binary found and saves in graphbuffer for further commands
170 int askmandemod(uint8_t *BinStream, size_t *size, int *clk, int *invert, int maxErr)
171 {
172 size_t i;
173 int start = DetectASKClock(BinStream, *size, clk, maxErr); //clock default
174 if (*clk==0 || start < 0) return -3;
175 if (*invert != 1) *invert=0;
176 uint8_t initLoopMax = 255;
177 if (initLoopMax > *size) initLoopMax = *size;
178 // Detect high and lows
179 // 25% fuzz in case highs and lows aren't clipped [marshmellow]
180 int high, low;
181 if (getHiLo(BinStream, initLoopMax, &high, &low, 75, 75) < 1) return -2; //just noise
182
183 // if clean clipped waves detected run alternate demod
184 if (DetectCleanAskWave(BinStream, *size, high, low)) {
185 cleanAskRawDemod(BinStream, size, *clk, *invert, high, low);
186 return manrawdecode(BinStream, size);
187 }
188
189 // PrintAndLog("DEBUG - valid high: %d - valid low: %d",high,low);
190 int lastBit; //set first clock check
191 uint16_t bitnum = 0; //output counter
192 uint8_t tol = 0; //clock tolerance adjust - waves will be accepted as within the clock if they fall + or - this value + clock from last valid wave
193 if (*clk <= 32) tol=1; //clock tolerance may not be needed anymore currently set to + or - 1 but could be increased for poor waves or removed entirely
194 uint16_t errCnt = 0, MaxBits = 512;
195 lastBit = start - *clk;
196 for (i = start; i < *size; ++i) {
197 if ((BinStream[i] >= high) && ((i-lastBit) > (*clk-tol))){
198 //high found and we are expecting a bar
199 lastBit += *clk;
200 BinStream[bitnum++] = *invert;
201 } else if ((BinStream[i] <= low) && ((i-lastBit) > (*clk-tol))){
202 //low found and we are expecting a bar
203 lastBit += *clk;
204 BinStream[bitnum++] = *invert ^ 1;
205 } else if ((i-lastBit)>(*clk+tol)){
206 //should have hit a high or low based on clock!!
207 //PrintAndLog("DEBUG - no wave in expected area - location: %d, expected: %d-%d, lastBit: %d - resetting search",i,(lastBit+(clk-((int)(tol)))),(lastBit+(clk+((int)(tol)))),lastBit);
208 if (bitnum > 0) {
209 BinStream[bitnum++] = 7;
210 errCnt++;
211 }
212 lastBit += *clk;//skip over error
213 }
214 if (bitnum >= MaxBits) break;
215 }
216 *size = bitnum;
217 return errCnt;
218 }
219
220 //by marshmellow
221 //encode binary data into binary manchester
222 int ManchesterEncode(uint8_t *BitStream, size_t size)
223 {
224 size_t modIdx=20000, i=0;
225 if (size>modIdx) return -1;
226 for (size_t idx=0; idx < size; idx++){
227 BitStream[idx+modIdx++] = BitStream[idx];
228 BitStream[idx+modIdx++] = BitStream[idx]^1;
229 }
230 for (; i<(size*2); i++){
231 BitStream[i] = BitStream[i+20000];
232 }
233 return i;
234 }
235
236 //by marshmellow
237 //take 10 and 01 and manchester decode
238 //run through 2 times and take least errCnt
239 int manrawdecode(uint8_t * BitStream, size_t *size)
240 {
241 uint16_t bitnum=0, MaxBits = 512, errCnt = 0;
242 size_t i, ii;
243 uint16_t bestErr = 1000, bestRun = 0;
244 if (size == 0) return -1;
245 //find correct start position [alignment]
246 for (ii=0;ii<2;++ii){
247 for (i=ii; i<*size-2; i+=2)
248 if (BitStream[i]==BitStream[i+1])
249 errCnt++;
250
251 if (bestErr>errCnt){
252 bestErr=errCnt;
253 bestRun=ii;
254 }
255 errCnt=0;
256 }
257 //decode
258 for (i=bestRun; i < *size-2; i+=2){
259 if(BitStream[i] == 1 && (BitStream[i+1] == 0)){
260 BitStream[bitnum++]=0;
261 } else if((BitStream[i] == 0) && BitStream[i+1] == 1){
262 BitStream[bitnum++]=1;
263 } else {
264 BitStream[bitnum++]=7;
265 }
266 if(bitnum>MaxBits) break;
267 }
268 *size=bitnum;
269 return bestErr;
270 }
271
272 //by marshmellow
273 //take 01 or 10 = 1 and 11 or 00 = 0
274 //check for phase errors - should never have 111 or 000 should be 01001011 or 10110100 for 1010
275 //decodes biphase or if inverted it is AKA conditional dephase encoding AKA differential manchester encoding
276 int BiphaseRawDecode(uint8_t *BitStream, size_t *size, int offset, int invert)
277 {
278 uint16_t bitnum = 0;
279 uint16_t errCnt = 0;
280 size_t i = offset;
281 uint16_t MaxBits=512;
282 //if not enough samples - error
283 if (*size < 51) return -1;
284 //check for phase change faults - skip one sample if faulty
285 uint8_t offsetA = 1, offsetB = 1;
286 for (; i<48; i+=2){
287 if (BitStream[i+1]==BitStream[i+2]) offsetA=0;
288 if (BitStream[i+2]==BitStream[i+3]) offsetB=0;
289 }
290 if (!offsetA && offsetB) offset++;
291 for (i=offset; i<*size-3; i+=2){
292 //check for phase error
293 if (BitStream[i+1]==BitStream[i+2]) {
294 BitStream[bitnum++]=7;
295 errCnt++;
296 }
297 if((BitStream[i]==1 && BitStream[i+1]==0) || (BitStream[i]==0 && BitStream[i+1]==1)){
298 BitStream[bitnum++]=1^invert;
299 } else if((BitStream[i]==0 && BitStream[i+1]==0) || (BitStream[i]==1 && BitStream[i+1]==1)){
300 BitStream[bitnum++]=invert;
301 } else {
302 BitStream[bitnum++]=7;
303 errCnt++;
304 }
305 if(bitnum>MaxBits) break;
306 }
307 *size=bitnum;
308 return errCnt;
309 }
310
311 //by marshmellow
312 void askAmp(uint8_t *BitStream, size_t size)
313 {
314 int shift = 127;
315 int shiftedVal=0;
316 for(size_t i = 1; i<size; i++){
317 if (BitStream[i]-BitStream[i-1]>=30) //large jump up
318 shift=127;
319 else if(BitStream[i]-BitStream[i-1]<=-20) //large jump down
320 shift=-127;
321
322 shiftedVal=BitStream[i]+shift;
323
324 if (shiftedVal>255)
325 shiftedVal=255;
326 else if (shiftedVal<0)
327 shiftedVal=0;
328 BitStream[i-1] = shiftedVal;
329 }
330 return;
331 }
332
333 //by marshmellow
334 //takes 3 arguments - clock, invert and maxErr as integers
335 //attempts to demodulate ask only
336 int askrawdemod(uint8_t *BinStream, size_t *size, int *clk, int *invert, int maxErr, uint8_t amp)
337 {
338 if (*size==0) return -1;
339 int start = DetectASKClock(BinStream, *size, clk, maxErr); //clock default
340 if (*clk==0 || start < 0) return -1;
341 if (*invert != 1) *invert = 0;
342 if (amp==1) askAmp(BinStream, *size);
343
344 uint8_t initLoopMax = 255;
345 if (initLoopMax > *size) initLoopMax = *size;
346 // Detect high and lows
347 //25% clip in case highs and lows aren't clipped [marshmellow]
348 int high, low;
349 if (getHiLo(BinStream, initLoopMax, &high, &low, 75, 75) < 1)
350 return -1; //just noise
351
352 // if clean clipped waves detected run alternate demod
353 if (DetectCleanAskWave(BinStream, *size, high, low))
354 return cleanAskRawDemod(BinStream, size, *clk, *invert, high, low);
355
356 int lastBit; //set first clock check - can go negative
357 size_t i, errCnt = 0, bitnum = 0; //output counter
358 uint8_t midBit = 0;
359 size_t MaxBits = 1024;
360 lastBit = start - *clk;
361
362 for (i = start; i < *size; ++i) {
363 if (i - lastBit > *clk){
364 if (BinStream[i] >= high) {
365 BinStream[bitnum++] = *invert;
366 } else if (BinStream[i] <= low) {
367 BinStream[bitnum++] = *invert ^ 1;
368 } else {
369 if (bitnum > 0) {
370 BinStream[bitnum++]=7;
371 errCnt++;
372 }
373 }
374 midBit = 0;
375 lastBit += *clk;
376 } else if (i-lastBit > (*clk/2) && midBit == 0){
377 if (BinStream[i] >= high) {
378 BinStream[bitnum++] = *invert;
379 } else if (BinStream[i] <= low) {
380 BinStream[bitnum++] = *invert ^ 1;
381 } else {
382
383 BinStream[bitnum] = BinStream[bitnum-1];
384 bitnum++;
385 }
386 midBit = 1;
387 }
388 if (bitnum >= MaxBits) break;
389 }
390 *size = bitnum;
391 return errCnt;
392 }
393
394 // demod gProxIIDemod
395 // error returns as -x
396 // success returns start position in BitStream
397 // BitStream must contain previously askrawdemod and biphasedemoded data
398 int gProxII_Demod(uint8_t BitStream[], size_t *size)
399 {
400 size_t startIdx=0;
401 uint8_t preamble[] = {1,1,1,1,1,0};
402
403 uint8_t errChk = preambleSearch(BitStream, preamble, sizeof(preamble), size, &startIdx);
404 if (errChk == 0) return -3; //preamble not found
405 if (*size != 96) return -2; //should have found 96 bits
406 //check first 6 spacer bits to verify format
407 if (!BitStream[startIdx+5] && !BitStream[startIdx+10] && !BitStream[startIdx+15] && !BitStream[startIdx+20] && !BitStream[startIdx+25] && !BitStream[startIdx+30]){
408 //confirmed proper separator bits found
409 //return start position
410 return (int) startIdx;
411 }
412 return -5;
413 }
414
415 //translate wave to 11111100000 (1 for each short wave 0 for each long wave)
416 size_t fsk_wave_demod(uint8_t * dest, size_t size, uint8_t fchigh, uint8_t fclow)
417 {
418 size_t last_transition = 0;
419 size_t idx = 1;
420 //uint32_t maxVal=0;
421 if (fchigh==0) fchigh=10;
422 if (fclow==0) fclow=8;
423 //set the threshold close to 0 (graph) or 128 std to avoid static
424 uint8_t threshold_value = 123;
425
426 // sync to first lo-hi transition, and threshold
427
428 // Need to threshold first sample
429
430 if(dest[0] < threshold_value) dest[0] = 0;
431 else dest[0] = 1;
432
433 size_t numBits = 0;
434 // count cycles between consecutive lo-hi transitions, there should be either 8 (fc/8)
435 // or 10 (fc/10) cycles but in practice due to noise etc we may end up with with anywhere
436 // between 7 to 11 cycles so fuzz it by treat anything <9 as 8 and anything else as 10
437 for(idx = 1; idx < size; idx++) {
438 // threshold current value
439
440 if (dest[idx] < threshold_value) dest[idx] = 0;
441 else dest[idx] = 1;
442
443 // Check for 0->1 transition
444 if (dest[idx-1] < dest[idx]) { // 0 -> 1 transition
445 if ((idx-last_transition)<(fclow-2)){ //0-5 = garbage noise
446 //do nothing with extra garbage
447 } else if ((idx-last_transition) < (fchigh-1)) { //6-8 = 8 waves
448 dest[numBits++]=1;
449 } else if ((idx-last_transition) > (fchigh+1) && !numBits) { //12 + and first bit = garbage
450 //do nothing with beginning garbage
451 } else { //9+ = 10 waves
452 dest[numBits++]=0;
453 }
454 last_transition = idx;
455 }
456 }
457 return numBits; //Actually, it returns the number of bytes, but each byte represents a bit: 1 or 0
458 }
459
460 //translate 11111100000 to 10
461 size_t aggregate_bits(uint8_t *dest, size_t size, uint8_t rfLen,
462 uint8_t invert, uint8_t fchigh, uint8_t fclow)
463 {
464 uint8_t lastval=dest[0];
465 size_t idx=0;
466 size_t numBits=0;
467 uint32_t n=1;
468 for( idx=1; idx < size; idx++) {
469 n++;
470 if (dest[idx]==lastval) continue;
471
472 //if lastval was 1, we have a 1->0 crossing
473 if (dest[idx-1]==1) {
474 if (!numBits && n < rfLen/fclow) {
475 n=0;
476 lastval = dest[idx];
477 continue;
478 }
479 n = (n * fclow + rfLen/2) / rfLen;
480 } else {// 0->1 crossing
481 //test first bitsample too small
482 if (!numBits && n < rfLen/fchigh) {
483 n=0;
484 lastval = dest[idx];
485 continue;
486 }
487 n = (n * fchigh + rfLen/2) / rfLen;
488 }
489 if (n == 0) n = 1;
490
491 memset(dest+numBits, dest[idx-1]^invert , n);
492 numBits += n;
493 n=0;
494 lastval=dest[idx];
495 }//end for
496 // if valid extra bits at the end were all the same frequency - add them in
497 if (n > rfLen/fchigh) {
498 if (dest[idx-2]==1) {
499 n = (n * fclow + rfLen/2) / rfLen;
500 } else {
501 n = (n * fchigh + rfLen/2) / rfLen;
502 }
503 memset(dest+numBits, dest[idx-1]^invert , n);
504 numBits += n;
505 }
506 return numBits;
507 }
508 //by marshmellow (from holiman's base)
509 // full fsk demod from GraphBuffer wave to decoded 1s and 0s (no mandemod)
510 int fskdemod(uint8_t *dest, size_t size, uint8_t rfLen, uint8_t invert, uint8_t fchigh, uint8_t fclow)
511 {
512 // FSK demodulator
513 size = fsk_wave_demod(dest, size, fchigh, fclow);
514 size = aggregate_bits(dest, size, rfLen, invert, fchigh, fclow);
515 return size;
516 }
517
518 // loop to get raw HID waveform then FSK demodulate the TAG ID from it
519 int HIDdemodFSK(uint8_t *dest, size_t *size, uint32_t *hi2, uint32_t *hi, uint32_t *lo)
520 {
521 if (justNoise(dest, *size)) return -1;
522
523 size_t numStart=0, size2=*size, startIdx=0;
524 // FSK demodulator
525 *size = fskdemod(dest, size2,50,1,10,8); //fsk2a
526 if (*size < 96*2) return -2;
527 // 00011101 bit pattern represent start of frame, 01 pattern represents a 0 and 10 represents a 1
528 uint8_t preamble[] = {0,0,0,1,1,1,0,1};
529 // find bitstring in array
530 uint8_t errChk = preambleSearch(dest, preamble, sizeof(preamble), size, &startIdx);
531 if (errChk == 0) return -3; //preamble not found
532
533 numStart = startIdx + sizeof(preamble);
534 // final loop, go over previously decoded FSK data and manchester decode into usable tag ID
535 for (size_t idx = numStart; (idx-numStart) < *size - sizeof(preamble); idx+=2){
536 if (dest[idx] == dest[idx+1]){
537 return -4; //not manchester data
538 }
539 *hi2 = (*hi2<<1)|(*hi>>31);
540 *hi = (*hi<<1)|(*lo>>31);
541 //Then, shift in a 0 or one into low
542 if (dest[idx] && !dest[idx+1]) // 1 0
543 *lo=(*lo<<1)|1;
544 else // 0 1
545 *lo=(*lo<<1)|0;
546 }
547 return (int)startIdx;
548 }
549
550 // loop to get raw paradox waveform then FSK demodulate the TAG ID from it
551 int ParadoxdemodFSK(uint8_t *dest, size_t *size, uint32_t *hi2, uint32_t *hi, uint32_t *lo)
552 {
553 if (justNoise(dest, *size)) return -1;
554
555 size_t numStart=0, size2=*size, startIdx=0;
556 // FSK demodulator
557 *size = fskdemod(dest, size2,50,1,10,8); //fsk2a
558 if (*size < 96) return -2;
559
560 // 00001111 bit pattern represent start of frame, 01 pattern represents a 0 and 10 represents a 1
561 uint8_t preamble[] = {0,0,0,0,1,1,1,1};
562
563 uint8_t errChk = preambleSearch(dest, preamble, sizeof(preamble), size, &startIdx);
564 if (errChk == 0) return -3; //preamble not found
565
566 numStart = startIdx + sizeof(preamble);
567 // final loop, go over previously decoded FSK data and manchester decode into usable tag ID
568 for (size_t idx = numStart; (idx-numStart) < *size - sizeof(preamble); idx+=2){
569 if (dest[idx] == dest[idx+1])
570 return -4; //not manchester data
571 *hi2 = (*hi2<<1)|(*hi>>31);
572 *hi = (*hi<<1)|(*lo>>31);
573 //Then, shift in a 0 or one into low
574 if (dest[idx] && !dest[idx+1]) // 1 0
575 *lo=(*lo<<1)|1;
576 else // 0 1
577 *lo=(*lo<<1)|0;
578 }
579 return (int)startIdx;
580 }
581
582 uint32_t bytebits_to_byte(uint8_t* src, size_t numbits)
583 {
584 uint32_t num = 0;
585 for(int i = 0 ; i < numbits ; i++)
586 {
587 num = (num << 1) | (*src);
588 src++;
589 }
590 return num;
591 }
592
593 int IOdemodFSK(uint8_t *dest, size_t size)
594 {
595 if (justNoise(dest, size)) return -1;
596 //make sure buffer has data
597 if (size < 66*64) return -2;
598 // FSK demodulator
599 size = fskdemod(dest, size, 64, 1, 10, 8); // FSK2a RF/64
600 if (size < 65) return -3; //did we get a good demod?
601 //Index map
602 //0 10 20 30 40 50 60
603 //| | | | | | |
604 //01234567 8 90123456 7 89012345 6 78901234 5 67890123 4 56789012 3 45678901 23
605 //-----------------------------------------------------------------------------
606 //00000000 0 11110000 1 facility 1 version* 1 code*one 1 code*two 1 ???????? 11
607 //
608 //XSF(version)facility:codeone+codetwo
609 //Handle the data
610 size_t startIdx = 0;
611 uint8_t preamble[] = {0,0,0,0,0,0,0,0,0,1};
612 uint8_t errChk = preambleSearch(dest, preamble, sizeof(preamble), &size, &startIdx);
613 if (errChk == 0) return -4; //preamble not found
614
615 if (!dest[startIdx+8] && dest[startIdx+17]==1 && dest[startIdx+26]==1 && dest[startIdx+35]==1 && dest[startIdx+44]==1 && dest[startIdx+53]==1){
616 //confirmed proper separator bits found
617 //return start position
618 return (int) startIdx;
619 }
620 return -5;
621 }
622
623 // by marshmellow
624 // takes a array of binary values, start position, length of bits per parity (includes parity bit),
625 // Parity Type (1 for odd 0 for even), and binary Length (length to run)
626 size_t removeParity(uint8_t *BitStream, size_t startIdx, uint8_t pLen, uint8_t pType, size_t bLen)
627 {
628 uint32_t parityWd = 0;
629 size_t j = 0, bitCnt = 0;
630 for (int word = 0; word < (bLen); word+=pLen){
631 for (int bit=0; bit < pLen; bit++){
632 parityWd = (parityWd << 1) | BitStream[startIdx+word+bit];
633 BitStream[j++] = (BitStream[startIdx+word+bit]);
634 }
635 j--;
636 // if parity fails then return 0
637 if (parityTest(parityWd, pLen, pType) == 0) return -1;
638 bitCnt+=(pLen-1);
639 parityWd = 0;
640 }
641 // if we got here then all the parities passed
642 //return ID start index and size
643 return bitCnt;
644 }
645
646 // by marshmellow
647 // FSK Demod then try to locate an AWID ID
648 int AWIDdemodFSK(uint8_t *dest, size_t *size)
649 {
650 //make sure buffer has enough data
651 if (*size < 96*50) return -1;
652
653 if (justNoise(dest, *size)) return -2;
654
655 // FSK demodulator
656 *size = fskdemod(dest, *size, 50, 1, 10, 8); // fsk2a RF/50
657 if (*size < 96) return -3; //did we get a good demod?
658
659 uint8_t preamble[] = {0,0,0,0,0,0,0,1};
660 size_t startIdx = 0;
661 uint8_t errChk = preambleSearch(dest, preamble, sizeof(preamble), size, &startIdx);
662 if (errChk == 0) return -4; //preamble not found
663 if (*size != 96) return -5;
664 return (int)startIdx;
665 }
666
667 // by marshmellow
668 // FSK Demod then try to locate an Farpointe Data (pyramid) ID
669 int PyramiddemodFSK(uint8_t *dest, size_t *size)
670 {
671 //make sure buffer has data
672 if (*size < 128*50) return -5;
673
674 //test samples are not just noise
675 if (justNoise(dest, *size)) return -1;
676
677 // FSK demodulator
678 *size = fskdemod(dest, *size, 50, 1, 10, 8); // fsk2a RF/50
679 if (*size < 128) return -2; //did we get a good demod?
680
681 uint8_t preamble[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
682 size_t startIdx = 0;
683 uint8_t errChk = preambleSearch(dest, preamble, sizeof(preamble), size, &startIdx);
684 if (errChk == 0) return -4; //preamble not found
685 if (*size != 128) return -3;
686 return (int)startIdx;
687 }
688
689
690 uint8_t DetectCleanAskWave(uint8_t dest[], size_t size, int high, int low)
691 {
692 uint16_t allPeaks=1;
693 uint16_t cntPeaks=0;
694 size_t loopEnd = 572;
695 if (loopEnd > size) loopEnd = size;
696 for (size_t i=60; i<loopEnd; i++){
697 if (dest[i]>low && dest[i]<high)
698 allPeaks=0;
699 else
700 cntPeaks++;
701 }
702 if (allPeaks == 0){
703 if (cntPeaks > 300) return 1;
704 }
705 return allPeaks;
706 }
707
708 // by marshmellow
709 // to help detect clocks on heavily clipped samples
710 // based on counts between zero crossings
711 int DetectStrongAskClock(uint8_t dest[], size_t size)
712 {
713 int clk[]={0,8,16,32,40,50,64,100,128};
714 size_t idx = 40;
715 uint8_t high=0;
716 size_t cnt = 0;
717 size_t highCnt = 0;
718 size_t highCnt2 = 0;
719 for (;idx < size; idx++){
720 if (dest[idx]>128) {
721 if (!high){
722 high=1;
723 if (cnt > highCnt){
724 if (highCnt != 0) highCnt2 = highCnt;
725 highCnt = cnt;
726 } else if (cnt > highCnt2) {
727 highCnt2 = cnt;
728 }
729 cnt=1;
730 } else {
731 cnt++;
732 }
733 } else if (dest[idx] <= 128){
734 if (high) {
735 high=0;
736 if (cnt > highCnt) {
737 if (highCnt != 0) highCnt2 = highCnt;
738 highCnt = cnt;
739 } else if (cnt > highCnt2) {
740 highCnt2 = cnt;
741 }
742 cnt=1;
743 } else {
744 cnt++;
745 }
746 }
747 }
748 uint8_t tol;
749 for (idx=8; idx>0; idx--){
750 tol = clk[idx]/8;
751 if (clk[idx] >= highCnt - tol && clk[idx] <= highCnt + tol)
752 return clk[idx];
753 if (clk[idx] >= highCnt2 - tol && clk[idx] <= highCnt2 + tol)
754 return clk[idx];
755 }
756 return -1;
757 }
758
759 // by marshmellow
760 // not perfect especially with lower clocks or VERY good antennas (heavy wave clipping)
761 // maybe somehow adjust peak trimming value based on samples to fix?
762 // return start index of best starting position for that clock and return clock (by reference)
763 int DetectASKClock(uint8_t dest[], size_t size, int *clock, int maxErr)
764 {
765 size_t i=1;
766 uint8_t clk[]={255,8,16,32,40,50,64,100,128,255};
767 uint8_t loopCnt = 255; //don't need to loop through entire array...
768 if (size==0) return -1;
769 if (size <= loopCnt) loopCnt = size-1; //not enough samples
770
771 //if we already have a valid clock
772 uint8_t clockFnd=0;
773 for (;i<9;++i)
774 if (clk[i] == *clock) clockFnd=i;
775 //clock found but continue to find best startpos
776
777 //get high and low peak
778 int peak, low;
779 if (getHiLo(dest, loopCnt, &peak, &low, 75, 75) < 1) return -1;
780
781 //test for large clean peaks
782 if (DetectCleanAskWave(dest, size, peak, low)==1){
783 int ans = DetectStrongAskClock(dest, size);
784 for (i=8; i>1; i--){
785 if (clk[i] == ans) {
786 *clock = ans;
787 //clockFnd = i;
788 return 0; // for strong waves i don't use the 'best start position' yet...
789 //break; //clock found but continue to find best startpos [not yet]
790 }
791 }
792 }
793 uint8_t ii;
794 uint8_t clkCnt, tol = 0;
795 uint16_t bestErr[]={1000,1000,1000,1000,1000,1000,1000,1000,1000};
796 uint8_t bestStart[]={0,0,0,0,0,0,0,0,0};
797 size_t errCnt = 0;
798 size_t arrLoc, loopEnd;
799 //test each valid clock from smallest to greatest to see which lines up
800 uint8_t clkEnd=9;
801 if (clockFnd>0) clkEnd=clockFnd+1;
802 else clockFnd=1;
803
804 for(clkCnt=clockFnd; clkCnt < clkEnd; clkCnt++){
805 if (clk[clkCnt] == 32){
806 tol=1;
807 }else{
808 tol=0;
809 }
810 //if no errors allowed - keep start within the first clock
811 if (!maxErr && size > clk[clkCnt]*3 + tol) loopCnt=clk[clkCnt]*2;
812 bestErr[clkCnt]=1000;
813 //try lining up the peaks by moving starting point (try first few clocks)
814 for (ii=0; ii < loopCnt-clk[clkCnt]; ii++){
815 if (dest[ii] < peak && dest[ii] > low) continue;
816
817 errCnt=0;
818 // now that we have the first one lined up test rest of wave array
819 loopEnd = ((size-ii-tol) / clk[clkCnt]) - 1;
820 for (i=0; i < loopEnd; ++i){
821 arrLoc = ii + (i * clk[clkCnt]);
822 if (dest[arrLoc] >= peak || dest[arrLoc] <= low){
823 }else if (dest[arrLoc-tol] >= peak || dest[arrLoc-tol] <= low){
824 }else if (dest[arrLoc+tol] >= peak || dest[arrLoc+tol] <= low){
825 }else{ //error no peak detected
826 errCnt++;
827 }
828 }
829 //if we found no errors then we can stop here
830 // this is correct one - return this clock
831 //PrintAndLog("DEBUG: clk %d, err %d, ii %d, i %d",clk[clkCnt],errCnt,ii,i);
832 if(errCnt==0 && clkCnt<6) {
833 *clock = clk[clkCnt];
834 return ii;
835 }
836 //if we found errors see if it is lowest so far and save it as best run
837 if(errCnt<bestErr[clkCnt]){
838 bestErr[clkCnt]=errCnt;
839 bestStart[clkCnt]=ii;
840 }
841 }
842 }
843 uint8_t iii=0;
844 uint8_t best=0;
845 for (iii=0; iii<8; ++iii){
846 if (bestErr[iii] < bestErr[best]){
847 if (bestErr[iii] == 0) bestErr[iii]=1;
848 // current best bit to error ratio vs new bit to error ratio
849 if ( (size/clk[best])/bestErr[best] < (size/clk[iii])/bestErr[iii] ){
850 best = iii;
851 }
852 }
853 }
854 //if (bestErr[best] > maxErr) return -1;
855 *clock = clk[best];
856 return bestStart[best];
857 }
858
859 //by marshmellow
860 //detect psk clock by reading each phase shift
861 // a phase shift is determined by measuring the sample length of each wave
862 int DetectPSKClock(uint8_t dest[], size_t size, int clock)
863 {
864 uint8_t clk[]={255,16,32,40,50,64,100,128,255}; //255 is not a valid clock
865 uint16_t loopCnt = 4096; //don't need to loop through entire array...
866 if (size == 0) return 0;
867 if (size<loopCnt) loopCnt = size;
868
869 //if we already have a valid clock quit
870 size_t i=1;
871 for (; i < 8; ++i)
872 if (clk[i] == clock) return clock;
873
874 size_t waveStart=0, waveEnd=0, firstFullWave=0, lastClkBit=0;
875 uint8_t clkCnt, fc=0, fullWaveLen=0, tol=1;
876 uint16_t peakcnt=0, errCnt=0, waveLenCnt=0;
877 uint16_t bestErr[]={1000,1000,1000,1000,1000,1000,1000,1000,1000};
878 uint16_t peaksdet[]={0,0,0,0,0,0,0,0,0};
879 fc = countFC(dest, size, 0);
880 if (fc!=2 && fc!=4 && fc!=8) return -1;
881 //PrintAndLog("DEBUG: FC: %d",fc);
882
883 //find first full wave
884 for (i=0; i<loopCnt; i++){
885 if (dest[i] < dest[i+1] && dest[i+1] >= dest[i+2]){
886 if (waveStart == 0) {
887 waveStart = i+1;
888 //PrintAndLog("DEBUG: waveStart: %d",waveStart);
889 } else {
890 waveEnd = i+1;
891 //PrintAndLog("DEBUG: waveEnd: %d",waveEnd);
892 waveLenCnt = waveEnd-waveStart;
893 if (waveLenCnt > fc){
894 firstFullWave = waveStart;
895 fullWaveLen=waveLenCnt;
896 break;
897 }
898 waveStart=0;
899 }
900 }
901 }
902 //PrintAndLog("DEBUG: firstFullWave: %d, waveLen: %d",firstFullWave,fullWaveLen);
903
904 //test each valid clock from greatest to smallest to see which lines up
905 for(clkCnt=7; clkCnt >= 1 ; clkCnt--){
906 lastClkBit = firstFullWave; //set end of wave as clock align
907 waveStart = 0;
908 errCnt=0;
909 peakcnt=0;
910 //PrintAndLog("DEBUG: clk: %d, lastClkBit: %d",clk[clkCnt],lastClkBit);
911
912 for (i = firstFullWave+fullWaveLen-1; i < loopCnt-2; i++){
913 //top edge of wave = start of new wave
914 if (dest[i] < dest[i+1] && dest[i+1] >= dest[i+2]){
915 if (waveStart == 0) {
916 waveStart = i+1;
917 waveLenCnt=0;
918 } else { //waveEnd
919 waveEnd = i+1;
920 waveLenCnt = waveEnd-waveStart;
921 if (waveLenCnt > fc){
922 //if this wave is a phase shift
923 //PrintAndLog("DEBUG: phase shift at: %d, len: %d, nextClk: %d, ii: %d, fc: %d",waveStart,waveLenCnt,lastClkBit+clk[clkCnt]-tol,ii+1,fc);
924 if (i+1 >= lastClkBit + clk[clkCnt] - tol){ //should be a clock bit
925 peakcnt++;
926 lastClkBit+=clk[clkCnt];
927 } else if (i<lastClkBit+8){
928 //noise after a phase shift - ignore
929 } else { //phase shift before supposed to based on clock
930 errCnt++;
931 }
932 } else if (i+1 > lastClkBit + clk[clkCnt] + tol + fc){
933 lastClkBit+=clk[clkCnt]; //no phase shift but clock bit
934 }
935 waveStart=i+1;
936 }
937 }
938 }
939 if (errCnt == 0){
940 return clk[clkCnt];
941 }
942 if (errCnt <= bestErr[clkCnt]) bestErr[clkCnt]=errCnt;
943 if (peakcnt > peaksdet[clkCnt]) peaksdet[clkCnt]=peakcnt;
944 }
945 //all tested with errors
946 //return the highest clk with the most peaks found
947 uint8_t best=7;
948 for (i=7; i>=1; i--){
949 if (peaksdet[i] > peaksdet[best]) {
950 best = i;
951 }
952 //PrintAndLog("DEBUG: Clk: %d, peaks: %d, errs: %d, bestClk: %d",clk[iii],peaksdet[iii],bestErr[iii],clk[best]);
953 }
954 return clk[best];
955 }
956
957 //by marshmellow
958 //detect nrz clock by reading #peaks vs no peaks(or errors)
959 int DetectNRZClock(uint8_t dest[], size_t size, int clock)
960 {
961 size_t i=0;
962 uint8_t clk[]={8,16,32,40,50,64,100,128,255};
963 size_t loopCnt = 4096; //don't need to loop through entire array...
964 if (size == 0) return 0;
965 if (size<loopCnt) loopCnt = size;
966
967 //if we already have a valid clock quit
968 for (; i < 8; ++i)
969 if (clk[i] == clock) return clock;
970
971 //get high and low peak
972 int peak, low;
973 if (getHiLo(dest, loopCnt, &peak, &low, 75, 75) < 1) return 0;
974
975 //PrintAndLog("DEBUG: peak: %d, low: %d",peak,low);
976 size_t ii;
977 uint8_t clkCnt;
978 uint8_t tol = 0;
979 uint16_t peakcnt=0;
980 uint16_t peaksdet[]={0,0,0,0,0,0,0,0};
981 uint16_t maxPeak=0;
982 //test for large clipped waves
983 for (i=0; i<loopCnt; i++){
984 if (dest[i] >= peak || dest[i] <= low){
985 peakcnt++;
986 } else {
987 if (peakcnt>0 && maxPeak < peakcnt){
988 maxPeak = peakcnt;
989 }
990 peakcnt=0;
991 }
992 }
993 peakcnt=0;
994 //test each valid clock from smallest to greatest to see which lines up
995 for(clkCnt=0; clkCnt < 8; ++clkCnt){
996 //ignore clocks smaller than largest peak
997 if (clk[clkCnt]<maxPeak) continue;
998
999 //try lining up the peaks by moving starting point (try first 256)
1000 for (ii=0; ii< loopCnt; ++ii){
1001 if ((dest[ii] >= peak) || (dest[ii] <= low)){
1002 peakcnt=0;
1003 // now that we have the first one lined up test rest of wave array
1004 for (i=0; i < ((int)((size-ii-tol)/clk[clkCnt])-1); ++i){
1005 if (dest[ii+(i*clk[clkCnt])]>=peak || dest[ii+(i*clk[clkCnt])]<=low){
1006 peakcnt++;
1007 }
1008 }
1009 if(peakcnt>peaksdet[clkCnt]) {
1010 peaksdet[clkCnt]=peakcnt;
1011 }
1012 }
1013 }
1014 }
1015 int iii=7;
1016 uint8_t best=0;
1017 for (iii=7; iii > 0; iii--){
1018 if (peaksdet[iii] > peaksdet[best]){
1019 best = iii;
1020 }
1021 //PrintAndLog("DEBUG: Clk: %d, peaks: %d, errs: %d, bestClk: %d",clk[iii],peaksdet[iii],bestErr[iii],clk[best]);
1022 }
1023 return clk[best];
1024 }
1025
1026 // by marshmellow
1027 // convert psk1 demod to psk2 demod
1028 // only transition waves are 1s
1029 void psk1TOpsk2(uint8_t *BitStream, size_t size)
1030 {
1031 size_t i=1;
1032 uint8_t lastBit=BitStream[0];
1033 for (; i<size; i++){
1034 if (BitStream[i]==7){
1035 //ignore errors
1036 } else if (lastBit!=BitStream[i]){
1037 lastBit=BitStream[i];
1038 BitStream[i]=1;
1039 } else {
1040 BitStream[i]=0;
1041 }
1042 }
1043 return;
1044 }
1045
1046 // by marshmellow
1047 // convert psk2 demod to psk1 demod
1048 // from only transition waves are 1s to phase shifts change bit
1049 void psk2TOpsk1(uint8_t *BitStream, size_t size)
1050 {
1051 uint8_t phase=0;
1052 for (size_t i=0; i<size; i++){
1053 if (BitStream[i]==1){
1054 phase ^=1;
1055 }
1056 BitStream[i]=phase;
1057 }
1058 return;
1059 }
1060
1061 // redesigned by marshmellow adjusted from existing decode functions
1062 // indala id decoding - only tested on 26 bit tags, but attempted to make it work for more
1063 int indala26decode(uint8_t *bitStream, size_t *size, uint8_t *invert)
1064 {
1065 //26 bit 40134 format (don't know other formats)
1066 int i;
1067 int long_wait=29;//29 leading zeros in format
1068 int start;
1069 int first = 0;
1070 int first2 = 0;
1071 int bitCnt = 0;
1072 int ii;
1073 // Finding the start of a UID
1074 for (start = 0; start <= *size - 250; start++) {
1075 first = bitStream[start];
1076 for (i = start; i < start + long_wait; i++) {
1077 if (bitStream[i] != first) {
1078 break;
1079 }
1080 }
1081 if (i == (start + long_wait)) {
1082 break;
1083 }
1084 }
1085 if (start == *size - 250 + 1) {
1086 // did not find start sequence
1087 return -1;
1088 }
1089 // Inverting signal if needed
1090 if (first == 1) {
1091 for (i = start; i < *size; i++) {
1092 bitStream[i] = !bitStream[i];
1093 }
1094 *invert = 1;
1095 }else *invert=0;
1096
1097 int iii;
1098 //found start once now test length by finding next one
1099 for (ii=start+29; ii <= *size - 250; ii++) {
1100 first2 = bitStream[ii];
1101 for (iii = ii; iii < ii + long_wait; iii++) {
1102 if (bitStream[iii] != first2) {
1103 break;
1104 }
1105 }
1106 if (iii == (ii + long_wait)) {
1107 break;
1108 }
1109 }
1110 if (ii== *size - 250 + 1){
1111 // did not find second start sequence
1112 return -2;
1113 }
1114 bitCnt=ii-start;
1115
1116 // Dumping UID
1117 i = start;
1118 for (ii = 0; ii < bitCnt; ii++) {
1119 bitStream[ii] = bitStream[i++];
1120 }
1121 *size=bitCnt;
1122 return 1;
1123 }
1124
1125 // by marshmellow - demodulate NRZ wave (both similar enough)
1126 // peaks invert bit (high=1 low=0) each clock cycle = 1 bit determined by last peak
1127 // there probably is a much simpler way to do this....
1128 int nrzRawDemod(uint8_t *dest, size_t *size, int *clk, int *invert, int maxErr)
1129 {
1130 if (justNoise(dest, *size)) return -1;
1131 *clk = DetectNRZClock(dest, *size, *clk);
1132 if (*clk==0) return -2;
1133 size_t i, gLen = 4096;
1134 if (gLen>*size) gLen = *size;
1135 int high, low;
1136 if (getHiLo(dest, gLen, &high, &low, 75, 75) < 1) return -3; //25% fuzz on high 25% fuzz on low
1137 int lastBit = 0; //set first clock check
1138 size_t iii = 0, bitnum = 0; //bitnum counter
1139 uint16_t errCnt = 0, MaxBits = 1000;
1140 size_t bestErrCnt = maxErr+1;
1141 size_t bestPeakCnt = 0, bestPeakStart = 0;
1142 uint8_t bestFirstPeakHigh=0, firstPeakHigh=0, curBit=0, bitHigh=0, errBitHigh=0;
1143 uint8_t tol = 1; //clock tolerance adjust - waves will be accepted as within the clock if they fall + or - this value + clock from last valid wave
1144 uint16_t peakCnt=0;
1145 uint8_t ignoreWindow=4;
1146 uint8_t ignoreCnt=ignoreWindow; //in case of noise near peak
1147 //loop to find first wave that works - align to clock
1148 for (iii=0; iii < gLen; ++iii){
1149 if ((dest[iii]>=high) || (dest[iii]<=low)){
1150 if (dest[iii]>=high) firstPeakHigh=1;
1151 else firstPeakHigh=0;
1152 lastBit=iii-*clk;
1153 peakCnt=0;
1154 errCnt=0;
1155 //loop through to see if this start location works
1156 for (i = iii; i < *size; ++i) {
1157 // if we are at a clock bit
1158 if ((i >= lastBit + *clk - tol) && (i <= lastBit + *clk + tol)) {
1159 //test high/low
1160 if (dest[i] >= high || dest[i] <= low) {
1161 bitHigh = 1;
1162 peakCnt++;
1163 errBitHigh = 0;
1164 ignoreCnt = ignoreWindow;
1165 lastBit += *clk;
1166 } else if (i == lastBit + *clk + tol) {
1167 lastBit += *clk;
1168 }
1169 //else if no bars found
1170 } else if (dest[i] < high && dest[i] > low){
1171 if (ignoreCnt==0){
1172 bitHigh=0;
1173 if (errBitHigh==1) errCnt++;
1174 errBitHigh=0;
1175 } else {
1176 ignoreCnt--;
1177 }
1178 } else if ((dest[i]>=high || dest[i]<=low) && (bitHigh==0)) {
1179 //error bar found no clock...
1180 errBitHigh=1;
1181 }
1182 if (((i-iii) / *clk)>=MaxBits) break;
1183 }
1184 //we got more than 64 good bits and not all errors
1185 if (((i-iii) / *clk) > 64 && (errCnt <= (maxErr))) {
1186 //possible good read
1187 if (!errCnt || peakCnt > bestPeakCnt){
1188 bestFirstPeakHigh=firstPeakHigh;
1189 bestErrCnt = errCnt;
1190 bestPeakCnt = peakCnt;
1191 bestPeakStart = iii;
1192 if (!errCnt) break; //great read - finish
1193 }
1194 }
1195 }
1196 }
1197 //PrintAndLog("DEBUG: bestErrCnt: %d, maxErr: %d, bestStart: %d, bestPeakCnt: %d, bestPeakStart: %d",bestErrCnt,maxErr,bestStart,bestPeakCnt,bestPeakStart);
1198 if (bestErrCnt > maxErr) return bestErrCnt;
1199
1200 //best run is good enough set to best run and set overwrite BinStream
1201 lastBit = bestPeakStart - *clk;
1202 memset(dest, bestFirstPeakHigh^1, bestPeakStart / *clk);
1203 bitnum += (bestPeakStart / *clk);
1204 for (i = bestPeakStart; i < *size; ++i) {
1205 // if expecting a clock bit
1206 if ((i >= lastBit + *clk - tol) && (i <= lastBit + *clk + tol)) {
1207 // test high/low
1208 if (dest[i] >= high || dest[i] <= low) {
1209 peakCnt++;
1210 bitHigh = 1;
1211 errBitHigh = 0;
1212 ignoreCnt = ignoreWindow;
1213 curBit = *invert;
1214 if (dest[i] >= high) curBit ^= 1;
1215 dest[bitnum++] = curBit;
1216 lastBit += *clk;
1217 //else no bars found in clock area
1218 } else if (i == lastBit + *clk + tol) {
1219 dest[bitnum++] = curBit;
1220 lastBit += *clk;
1221 }
1222 //else if no bars found
1223 } else if (dest[i] < high && dest[i] > low){
1224 if (ignoreCnt == 0){
1225 bitHigh = 0;
1226 if (errBitHigh == 1){
1227 dest[bitnum++] = 7;
1228 errCnt++;
1229 }
1230 errBitHigh=0;
1231 } else {
1232 ignoreCnt--;
1233 }
1234 } else if ((dest[i] >= high || dest[i] <= low) && (bitHigh == 0)) {
1235 //error bar found no clock...
1236 errBitHigh=1;
1237 }
1238 if (bitnum >= MaxBits) break;
1239 }
1240 *size = bitnum;
1241 return bestErrCnt;
1242 }
1243
1244 //by marshmellow
1245 //detects the bit clock for FSK given the high and low Field Clocks
1246 uint8_t detectFSKClk(uint8_t *BitStream, size_t size, uint8_t fcHigh, uint8_t fcLow)
1247 {
1248 uint8_t clk[] = {8,16,32,40,50,64,100,128,0};
1249 uint16_t rfLens[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
1250 uint8_t rfCnts[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
1251 uint8_t rfLensFnd = 0;
1252 uint8_t lastFCcnt = 0;
1253 uint16_t fcCounter = 0;
1254 uint16_t rfCounter = 0;
1255 uint8_t firstBitFnd = 0;
1256 size_t i;
1257 if (size == 0) return 0;
1258
1259 uint8_t fcTol = (uint8_t)(0.5+(float)(fcHigh-fcLow)/2);
1260 rfLensFnd=0;
1261 fcCounter=0;
1262 rfCounter=0;
1263 firstBitFnd=0;
1264 //PrintAndLog("DEBUG: fcTol: %d",fcTol);
1265 // prime i to first up transition
1266 for (i = 1; i < size-1; i++)
1267 if (BitStream[i] > BitStream[i-1] && BitStream[i]>=BitStream[i+1])
1268 break;
1269
1270 for (; i < size-1; i++){
1271 fcCounter++;
1272 rfCounter++;
1273
1274 if (BitStream[i] <= BitStream[i-1] || BitStream[i] < BitStream[i+1])
1275 continue;
1276 // else new peak
1277 // if we got less than the small fc + tolerance then set it to the small fc
1278 if (fcCounter < fcLow+fcTol)
1279 fcCounter = fcLow;
1280 else //set it to the large fc
1281 fcCounter = fcHigh;
1282
1283 //look for bit clock (rf/xx)
1284 if ((fcCounter < lastFCcnt || fcCounter > lastFCcnt)){
1285 //not the same size as the last wave - start of new bit sequence
1286 if (firstBitFnd > 1){ //skip first wave change - probably not a complete bit
1287 for (int ii=0; ii<15; ii++){
1288 if (rfLens[ii] == rfCounter){
1289 rfCnts[ii]++;
1290 rfCounter = 0;
1291 break;
1292 }
1293 }
1294 if (rfCounter > 0 && rfLensFnd < 15){
1295 //PrintAndLog("DEBUG: rfCntr %d, fcCntr %d",rfCounter,fcCounter);
1296 rfCnts[rfLensFnd]++;
1297 rfLens[rfLensFnd++] = rfCounter;
1298 }
1299 } else {
1300 firstBitFnd++;
1301 }
1302 rfCounter=0;
1303 lastFCcnt=fcCounter;
1304 }
1305 fcCounter=0;
1306 }
1307 uint8_t rfHighest=15, rfHighest2=15, rfHighest3=15;
1308
1309 for (i=0; i<15; i++){
1310 //PrintAndLog("DEBUG: RF %d, cnts %d",rfLens[i], rfCnts[i]);
1311 //get highest 2 RF values (might need to get more values to compare or compare all?)
1312 if (rfCnts[i]>rfCnts[rfHighest]){
1313 rfHighest3=rfHighest2;
1314 rfHighest2=rfHighest;
1315 rfHighest=i;
1316 } else if(rfCnts[i]>rfCnts[rfHighest2]){
1317 rfHighest3=rfHighest2;
1318 rfHighest2=i;
1319 } else if(rfCnts[i]>rfCnts[rfHighest3]){
1320 rfHighest3=i;
1321 }
1322 }
1323 // set allowed clock remainder tolerance to be 1 large field clock length+1
1324 // we could have mistakenly made a 9 a 10 instead of an 8 or visa versa so rfLens could be 1 FC off
1325 uint8_t tol1 = fcHigh+1;
1326
1327 //PrintAndLog("DEBUG: hightest: 1 %d, 2 %d, 3 %d",rfLens[rfHighest],rfLens[rfHighest2],rfLens[rfHighest3]);
1328
1329 // loop to find the highest clock that has a remainder less than the tolerance
1330 // compare samples counted divided by
1331 int ii=7;
1332 for (; ii>=0; ii--){
1333 if (rfLens[rfHighest] % clk[ii] < tol1 || rfLens[rfHighest] % clk[ii] > clk[ii]-tol1){
1334 if (rfLens[rfHighest2] % clk[ii] < tol1 || rfLens[rfHighest2] % clk[ii] > clk[ii]-tol1){
1335 if (rfLens[rfHighest3] % clk[ii] < tol1 || rfLens[rfHighest3] % clk[ii] > clk[ii]-tol1){
1336 break;
1337 }
1338 }
1339 }
1340 }
1341
1342 if (ii<0) return 0; // oops we went too far
1343
1344 return clk[ii];
1345 }
1346
1347 //by marshmellow
1348 //countFC is to detect the field clock lengths.
1349 //counts and returns the 2 most common wave lengths
1350 //mainly used for FSK field clock detection
1351 uint16_t countFC(uint8_t *BitStream, size_t size, uint8_t fskAdj)
1352 {
1353 uint8_t fcLens[] = {0,0,0,0,0,0,0,0,0,0};
1354 uint16_t fcCnts[] = {0,0,0,0,0,0,0,0,0,0};
1355 uint8_t fcLensFnd = 0;
1356 uint8_t lastFCcnt=0;
1357 uint8_t fcCounter = 0;
1358 size_t i;
1359 if (size == 0) return 0;
1360
1361 // prime i to first up transition
1362 for (i = 1; i < size-1; i++)
1363 if (BitStream[i] > BitStream[i-1] && BitStream[i] >= BitStream[i+1])
1364 break;
1365
1366 for (; i < size-1; i++){
1367 if (BitStream[i] > BitStream[i-1] && BitStream[i] >= BitStream[i+1]){
1368 // new up transition
1369 fcCounter++;
1370 if (fskAdj){
1371 //if we had 5 and now have 9 then go back to 8 (for when we get a fc 9 instead of an 8)
1372 if (lastFCcnt==5 && fcCounter==9) fcCounter--;
1373 //if fc=9 or 4 add one (for when we get a fc 9 instead of 10 or a 4 instead of a 5)
1374 if ((fcCounter==9) || fcCounter==4) fcCounter++;
1375 // save last field clock count (fc/xx)
1376 lastFCcnt = fcCounter;
1377 }
1378 // find which fcLens to save it to:
1379 for (int ii=0; ii<10; ii++){
1380 if (fcLens[ii]==fcCounter){
1381 fcCnts[ii]++;
1382 fcCounter=0;
1383 break;
1384 }
1385 }
1386 if (fcCounter>0 && fcLensFnd<10){
1387 //add new fc length
1388 fcCnts[fcLensFnd]++;
1389 fcLens[fcLensFnd++]=fcCounter;
1390 }
1391 fcCounter=0;
1392 } else {
1393 // count sample
1394 fcCounter++;
1395 }
1396 }
1397
1398 uint8_t best1=9, best2=9, best3=9;
1399 uint16_t maxCnt1=0;
1400 // go through fclens and find which ones are bigest 2
1401 for (i=0; i<10; i++){
1402 // PrintAndLog("DEBUG: FC %d, Cnt %d, Errs %d",fcLens[i],fcCnts[i],errCnt);
1403 // get the 3 best FC values
1404 if (fcCnts[i]>maxCnt1) {
1405 best3=best2;
1406 best2=best1;
1407 maxCnt1=fcCnts[i];
1408 best1=i;
1409 } else if(fcCnts[i]>fcCnts[best2]){
1410 best3=best2;
1411 best2=i;
1412 } else if(fcCnts[i]>fcCnts[best3]){
1413 best3=i;
1414 }
1415 }
1416 uint8_t fcH=0, fcL=0;
1417 if (fcLens[best1]>fcLens[best2]){
1418 fcH=fcLens[best1];
1419 fcL=fcLens[best2];
1420 } else{
1421 fcH=fcLens[best2];
1422 fcL=fcLens[best1];
1423 }
1424
1425 // TODO: take top 3 answers and compare to known Field clocks to get top 2
1426
1427 uint16_t fcs = (((uint16_t)fcH)<<8) | fcL;
1428 // PrintAndLog("DEBUG: Best %d best2 %d best3 %d",fcLens[best1],fcLens[best2],fcLens[best3]);
1429 if (fskAdj) return fcs;
1430 return fcLens[best1];
1431 }
1432
1433 //by marshmellow - demodulate PSK1 wave
1434 //uses wave lengths (# Samples)
1435 int pskRawDemod(uint8_t dest[], size_t *size, int *clock, int *invert)
1436 {
1437 if (size == 0) return -1;
1438 uint16_t loopCnt = 4096; //don't need to loop through entire array...
1439 if (*size<loopCnt) loopCnt = *size;
1440
1441 uint8_t curPhase = *invert;
1442 size_t i, waveStart=1, waveEnd=0, firstFullWave=0, lastClkBit=0;
1443 uint8_t fc=0, fullWaveLen=0, tol=1;
1444 uint16_t errCnt=0, waveLenCnt=0;
1445 fc = countFC(dest, *size, 0);
1446 if (fc!=2 && fc!=4 && fc!=8) return -1;
1447 //PrintAndLog("DEBUG: FC: %d",fc);
1448 *clock = DetectPSKClock(dest, *size, *clock);
1449 if (*clock == 0) return -1;
1450 int avgWaveVal=0, lastAvgWaveVal=0;
1451 //find first phase shift
1452 for (i=0; i<loopCnt; i++){
1453 if (dest[i]+fc < dest[i+1] && dest[i+1] >= dest[i+2]){
1454 waveEnd = i+1;
1455 //PrintAndLog("DEBUG: waveEnd: %d",waveEnd);
1456 waveLenCnt = waveEnd-waveStart;
1457 if (waveLenCnt > fc && waveStart > fc){ //not first peak and is a large wave
1458 lastAvgWaveVal = avgWaveVal/(waveLenCnt);
1459 firstFullWave = waveStart;
1460 fullWaveLen=waveLenCnt;
1461 //if average wave value is > graph 0 then it is an up wave or a 1
1462 if (lastAvgWaveVal > 123) curPhase ^= 1; //fudge graph 0 a little 123 vs 128
1463 break;
1464 }
1465 waveStart = i+1;
1466 avgWaveVal = 0;
1467 }
1468 avgWaveVal += dest[i+2];
1469 }
1470 //PrintAndLog("DEBUG: firstFullWave: %d, waveLen: %d",firstFullWave,fullWaveLen);
1471 lastClkBit = firstFullWave; //set start of wave as clock align
1472 //PrintAndLog("DEBUG: clk: %d, lastClkBit: %d", *clock, lastClkBit);
1473 waveStart = 0;
1474 size_t numBits=0;
1475 //set skipped bits
1476 memset(dest, curPhase^1, firstFullWave / *clock);
1477 numBits += (firstFullWave / *clock);
1478 dest[numBits++] = curPhase; //set first read bit
1479 for (i = firstFullWave + fullWaveLen - 1; i < *size-3; i++){
1480 //top edge of wave = start of new wave
1481 if (dest[i]+fc < dest[i+1] && dest[i+1] >= dest[i+2]){
1482 if (waveStart == 0) {
1483 waveStart = i+1;
1484 waveLenCnt = 0;
1485 avgWaveVal = dest[i+1];
1486 } else { //waveEnd
1487 waveEnd = i+1;
1488 waveLenCnt = waveEnd-waveStart;
1489 lastAvgWaveVal = avgWaveVal/waveLenCnt;
1490 if (waveLenCnt > fc){
1491 //PrintAndLog("DEBUG: avgWaveVal: %d, waveSum: %d",lastAvgWaveVal,avgWaveVal);
1492 //this wave is a phase shift
1493 //PrintAndLog("DEBUG: phase shift at: %d, len: %d, nextClk: %d, i: %d, fc: %d",waveStart,waveLenCnt,lastClkBit+*clock-tol,i+1,fc);
1494 if (i+1 >= lastClkBit + *clock - tol){ //should be a clock bit
1495 curPhase ^= 1;
1496 dest[numBits++] = curPhase;
1497 lastClkBit += *clock;
1498 } else if (i < lastClkBit+10+fc){
1499 //noise after a phase shift - ignore
1500 } else { //phase shift before supposed to based on clock
1501 errCnt++;
1502 dest[numBits++] = 7;
1503 }
1504 } else if (i+1 > lastClkBit + *clock + tol + fc){
1505 lastClkBit += *clock; //no phase shift but clock bit
1506 dest[numBits++] = curPhase;
1507 }
1508 avgWaveVal = 0;
1509 waveStart = i+1;
1510 }
1511 }
1512 avgWaveVal += dest[i+1];
1513 }
1514 *size = numBits;
1515 return errCnt;
1516 }
Impressum, Datenschutz