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