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