]>
git.zerfleddert.de Git - proxmark3-svn/blob - common/lfdemod.c
5a1007fb160e29cac7541a22ca5c2a413cc969fe
1 //-----------------------------------------------------------------------------
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
7 //-----------------------------------------------------------------------------
8 // Low frequency demod/decode commands - by marshmellow, holiman, iceman and
9 // many others who came before
12 // LF Demod functions are placed here to allow the flexability to use client or
13 // device side. Most BUT NOT ALL of these functions are currenlty safe for
14 // device side use currently. (DetectST for example...)
16 // There are likely many improvements to the code that could be made, please
17 // make suggestions...
19 // we tried to include author comments so any questions could be directed to
22 // There are 4 main sections of code below:
24 // for general utilities used by multiple other functions
25 // Clock / Bitrate Detection Section:
26 // for clock detection functions for each modulation
27 // Modulation Demods &/or Decoding Section:
28 // for main general modulation demodulating and encoding decoding code.
29 // Tag format detection section:
30 // for detection of specific tag formats within demodulated data
33 //-----------------------------------------------------------------------------
35 #include <string.h> // for memset, memcmp and size_t
36 #include <stdint.h> // for uint_32+
37 #include <stdbool.h> // for bool
39 //**********************************************************************************************
40 //---------------------------------Utilities Section--------------------------------------------
41 //**********************************************************************************************
42 #define LOWEST_DEFAULT_CLOCK 32
43 #define FSK_PSK_THRESHOLD 123
45 //to allow debug print calls when used not on device
46 void dummy ( char * fmt
, ...){}
49 #include "cmdparser.h"
51 #define prnt PrintAndLog
53 uint8_t g_debugMode
= 0 ;
57 uint8_t justNoise ( uint8_t * BitStream
, size_t size
) {
58 //test samples are not just noise
59 uint8_t justNoise1
= 1 ;
60 for ( size_t idx
= 0 ; idx
< size
&& justNoise1
; idx
++){
61 justNoise1
= BitStream
[ idx
] < FSK_PSK_THRESHOLD
;
67 //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
68 int getHiLo ( uint8_t * BitStream
, size_t size
, int * high
, int * low
, uint8_t fuzzHi
, uint8_t fuzzLo
) {
71 // get high and low thresholds
72 for ( size_t i
= 0 ; i
< size
; i
++){
73 if ( BitStream
[ i
] > * high
) * high
= BitStream
[ i
];
74 if ( BitStream
[ i
] < * low
) * low
= BitStream
[ i
];
76 if (* high
< FSK_PSK_THRESHOLD
) return - 1 ; // just noise
77 * high
= ((* high
- 128 )* fuzzHi
+ 12800 )/ 100 ;
78 * low
= ((* low
- 128 )* fuzzLo
+ 12800 )/ 100 ;
83 // pass bits to be tested in bits, length bits passed in bitLen, and parity type (even=0 | odd=1) in pType
84 // returns 1 if passed
85 uint8_t parityTest ( uint32_t bits
, uint8_t bitLen
, uint8_t pType
) {
87 for ( uint8_t i
= 0 ; i
< bitLen
; i
++){
88 ans
^= (( bits
>> i
) & 1 );
90 if ( g_debugMode
) prnt ( "DEBUG: ans: %d, ptype: %d, bits: %08X" , ans
, pType
, bits
);
91 return ( ans
== pType
);
95 // takes a array of binary values, start position, length of bits per parity (includes parity bit),
96 // Parity Type (1 for odd; 0 for even; 2 for Always 1's; 3 for Always 0's), and binary Length (length to run)
97 size_t removeParity ( uint8_t * BitStream
, size_t startIdx
, uint8_t pLen
, uint8_t pType
, size_t bLen
) {
98 uint32_t parityWd
= 0 ;
99 size_t j
= 0 , bitCnt
= 0 ;
100 for ( int word
= 0 ; word
< ( bLen
); word
+= pLen
) {
101 for ( int bit
= 0 ; bit
< pLen
; bit
++) {
102 parityWd
= ( parityWd
<< 1 ) | BitStream
[ startIdx
+ word
+ bit
];
103 BitStream
[ j
++] = ( BitStream
[ startIdx
+ word
+ bit
]);
105 if ( word
+ pLen
> bLen
) break ;
107 j
--; // overwrite parity with next data
108 // if parity fails then return 0
110 case 3 : if ( BitStream
[ j
]== 1 ) { return 0 ;} break ; //should be 0 spacer bit
111 case 2 : if ( BitStream
[ j
]== 0 ) { return 0 ;} break ; //should be 1 spacer bit
112 default : if ( parityTest ( parityWd
, pLen
, pType
) == 0 ) { return 0 ;} break ; //test parity
117 // if we got here then all the parities passed
118 //return ID start index and size
123 // takes a array of binary values, length of bits per parity (includes parity bit),
124 // Parity Type (1 for odd; 0 for even; 2 Always 1's; 3 Always 0's), and binary Length (length to run)
125 // Make sure *dest is long enough to store original sourceLen + #_of_parities_to_be_added
126 size_t addParity ( uint8_t * BitSource
, uint8_t * dest
, uint8_t sourceLen
, uint8_t pLen
, uint8_t pType
) {
127 uint32_t parityWd
= 0 ;
128 size_t j
= 0 , bitCnt
= 0 ;
129 for ( int word
= 0 ; word
< sourceLen
; word
+= pLen
- 1 ) {
130 for ( int bit
= 0 ; bit
< pLen
- 1 ; bit
++){
131 parityWd
= ( parityWd
<< 1 ) | BitSource
[ word
+ bit
];
132 dest
[ j
++] = ( BitSource
[ word
+ bit
]);
134 // if parity fails then return 0
136 case 3 : dest
[ j
++]= 0 ; break ; // marker bit which should be a 0
137 case 2 : dest
[ j
++]= 1 ; break ; // marker bit which should be a 1
139 dest
[ j
++] = parityTest ( parityWd
, pLen
- 1 , pType
) ^ 1 ;
145 // if we got here then all the parities passed
146 //return ID start index and size
150 uint32_t bytebits_to_byte ( uint8_t * src
, size_t numbits
) {
152 for ( int i
= 0 ; i
< numbits
; i
++)
154 num
= ( num
<< 1 ) | (* src
);
160 //least significant bit first
161 uint32_t bytebits_to_byteLSBF ( uint8_t * src
, size_t numbits
) {
163 for ( int i
= 0 ; i
< numbits
; i
++)
165 num
= ( num
<< 1 ) | *( src
+ ( numbits
-( i
+ 1 )));
170 // search for given preamble in given BitStream and return success=1 or fail=0 and startIndex (where it was found) and length if not fineone
171 // fineone does not look for a repeating preamble for em4x05/4x69 sends preamble once, so look for it once in the first pLen bits
172 bool preambleSearchEx ( uint8_t * BitStream
, uint8_t * preamble
, size_t pLen
, size_t * size
, size_t * startIdx
, bool findone
) {
173 // Sanity check. If preamble length is bigger than bitstream length.
174 if ( * size
<= pLen
) return false ;
176 uint8_t foundCnt
= 0 ;
177 for ( size_t idx
= 0 ; idx
< * size
- pLen
; idx
++) {
178 if ( memcmp ( BitStream
+ idx
, preamble
, pLen
) == 0 ) {
182 if ( g_debugMode
) prnt ( "DEBUG: preamble found at %u" , idx
);
184 if ( findone
) return true ;
185 } else if ( foundCnt
== 2 ) {
186 * size
= idx
- * startIdx
;
195 //search for given preamble in given BitStream and return success=1 or fail=0 and startIndex and length
196 uint8_t preambleSearch ( uint8_t * BitStream
, uint8_t * preamble
, size_t pLen
, size_t * size
, size_t * startIdx
) {
197 return ( preambleSearchEx ( BitStream
, preamble
, pLen
, size
, startIdx
, false )) ? 1 : 0 ;
200 // find start of modulating data (for fsk and psk) in case of beginning noise or slow chip startup.
201 size_t findModStart ( uint8_t dest
[], size_t size
, uint8_t expWaveSize
) {
203 size_t waveSizeCnt
= 0 ;
204 uint8_t thresholdCnt
= 0 ;
205 bool isAboveThreshold
= dest
[ i
++] >= FSK_PSK_THRESHOLD
;
206 for (; i
< size
- 20 ; i
++ ) {
207 if ( dest
[ i
] < FSK_PSK_THRESHOLD
&& isAboveThreshold
) {
209 if ( thresholdCnt
> 2 && waveSizeCnt
< expWaveSize
+ 1 ) break ;
210 isAboveThreshold
= false ;
212 } else if ( dest
[ i
] >= FSK_PSK_THRESHOLD
&& ! isAboveThreshold
) {
214 if ( thresholdCnt
> 2 && waveSizeCnt
< expWaveSize
+ 1 ) break ;
215 isAboveThreshold
= true ;
220 if ( thresholdCnt
> 10 ) break ;
222 if ( g_debugMode
== 2 ) prnt ( "DEBUG: threshold Count reached at %u, count: %u" , i
, thresholdCnt
);
226 int getClosestClock ( int testclk
) {
227 uint8_t fndClk
[] = { 8 , 16 , 32 , 40 , 50 , 64 , 128 };
229 for ( uint8_t clkCnt
= 0 ; clkCnt
< 7 ; clkCnt
++)
230 if ( testclk
>= fndClk
[ clkCnt
]-( fndClk
[ clkCnt
]/ 8 ) && testclk
<= fndClk
[ clkCnt
]+ 1 )
231 return fndClk
[ clkCnt
];
236 void getNextLow ( uint8_t samples
[], size_t size
, int low
, size_t * i
) {
237 while (( samples
[* i
] > low
) && (* i
< size
))
241 void getNextHigh ( uint8_t samples
[], size_t size
, int high
, size_t * i
) {
242 while (( samples
[* i
] < high
) && (* i
< size
))
246 // load wave counters
247 bool loadWaveCounters ( uint8_t samples
[], size_t size
, int lowToLowWaveLen
[], int highToLowWaveLen
[], int * waveCnt
, int * skip
, int * minClk
, int * high
, int * low
) {
248 size_t i
= 0 , firstLow
, firstHigh
;
249 size_t testsize
= ( size
< 512 ) ? size
: 512 ;
251 if ( getHiLo ( samples
, testsize
, high
, low
, 80 , 80 ) == - 1 ) {
252 if ( g_debugMode
== 2 ) prnt ( "DEBUG STT: just noise detected - quitting" );
253 return false ; //just noise
256 // get to first full low to prime loop and skip incomplete first pulse
257 getNextHigh ( samples
, size
, * high
, & i
);
258 getNextLow ( samples
, size
, * low
, & i
);
261 // populate tmpbuff buffer with pulse lengths
263 // measure from low to low
265 //find first high point for this wave
266 getNextHigh ( samples
, size
, * high
, & i
);
269 getNextLow ( samples
, size
, * low
, & i
);
271 if (* waveCnt
>= ( size
/ LOWEST_DEFAULT_CLOCK
))
274 highToLowWaveLen
[* waveCnt
] = i
- firstHigh
; //first high to first low
275 lowToLowWaveLen
[* waveCnt
] = i
- firstLow
;
277 if ( i
- firstLow
< * minClk
&& i
< size
) {
278 * minClk
= i
- firstLow
;
285 //amplify based on ask edge detection - not accurate enough to use all the time
286 void askAmp ( uint8_t * BitStream
, size_t size
) {
288 for ( size_t i
= 1 ; i
< size
; i
++){
289 if ( BitStream
[ i
]- BitStream
[ i
- 1 ]>= 30 ) //large jump up
291 else if ( BitStream
[ i
- 1 ]- BitStream
[ i
]>= 20 ) //large jump down
294 BitStream
[ i
- 1 ] = Last
;
299 uint32_t manchesterEncode2Bytes ( uint16_t datain
) {
302 for ( uint8_t i
= 0 ; i
< 16 ; i
++) {
303 curBit
= ( datain
>> ( 15 - i
) & 1 );
304 output
|= ( 1 <<((( 15 - i
)* 2 )+ curBit
));
310 //encode binary data into binary manchester
311 //NOTE: BitStream must have double the size available in memory to do the swap
312 int ManchesterEncode ( uint8_t * BitStream
, size_t size
) {
313 size_t modIdx
= size
, i
= 0 ;
314 if ( size
> modIdx
) return - 1 ;
315 for ( size_t idx
= 0 ; idx
< size
; idx
++){
316 BitStream
[ idx
+ modIdx
++] = BitStream
[ idx
];
317 BitStream
[ idx
+ modIdx
++] = BitStream
[ idx
]^ 1 ;
319 for (; i
<( size
* 2 ); i
++){
320 BitStream
[ i
] = BitStream
[ i
+ size
];
326 // to detect a wave that has heavily clipped (clean) samples
327 uint8_t DetectCleanAskWave ( uint8_t dest
[], size_t size
, uint8_t high
, uint8_t low
) {
328 bool allArePeaks
= true ;
330 size_t loopEnd
= 512 + 160 ;
331 if ( loopEnd
> size
) loopEnd
= size
;
332 for ( size_t i
= 160 ; i
< loopEnd
; i
++){
333 if ( dest
[ i
]> low
&& dest
[ i
]< high
)
339 if ( cntPeaks
> 300 ) return true ;
344 //**********************************************************************************************
345 //-------------------Clock / Bitrate Detection Section------------------------------------------
346 //**********************************************************************************************
349 // to help detect clocks on heavily clipped samples
350 // based on count of low to low
351 int DetectStrongAskClock ( uint8_t dest
[], size_t size
, int high
, int low
, int * clock
) {
355 int shortestWaveIdx
= 0 ;
356 // get to first full low to prime loop and skip incomplete first pulse
357 getNextHigh ( dest
, size
, high
, & i
);
358 getNextLow ( dest
, size
, low
, & i
);
360 // loop through all samples
362 // measure from low to low
365 getNextHigh ( dest
, size
, high
, & i
);
366 getNextLow ( dest
, size
, low
, & i
);
367 //get minimum measured distance
368 if ( i
- startwave
< minClk
&& i
< size
) {
369 minClk
= i
- startwave
;
370 shortestWaveIdx
= startwave
;
374 if ( g_debugMode
== 2 ) prnt ( "DEBUG ASK: DetectStrongAskClock smallest wave: %d" , minClk
);
375 * clock
= getClosestClock ( minClk
);
379 return shortestWaveIdx
;
383 // not perfect especially with lower clocks or VERY good antennas (heavy wave clipping)
384 // maybe somehow adjust peak trimming value based on samples to fix?
385 // return start index of best starting position for that clock and return clock (by reference)
386 int DetectASKClock ( uint8_t dest
[], size_t size
, int * clock
, int maxErr
) {
388 uint8_t clk
[] = { 255 , 8 , 16 , 32 , 40 , 50 , 64 , 100 , 128 , 255 };
390 uint8_t loopCnt
= 255 ; //don't need to loop through entire array...
391 if ( size
<= loopCnt
+ 60 ) return - 1 ; //not enough samples
392 size
-= 60 ; //sometimes there is a strange end wave - filter out this....
393 //if we already have a valid clock
396 if ( clk
[ i
] == * clock
) clockFnd
= i
;
397 //clock found but continue to find best startpos
399 //get high and low peak
401 if ( getHiLo ( dest
, loopCnt
, & peak
, & low
, 75 , 75 ) < 1 ) return - 1 ;
403 //test for large clean peaks
405 if ( DetectCleanAskWave ( dest
, size
, peak
, low
)== 1 ){
406 int ans
= DetectStrongAskClock ( dest
, size
, peak
, low
, clock
);
407 if ( g_debugMode
== 2 ) prnt ( "DEBUG ASK: detectaskclk Clean Ask Wave Detected: clk %i, ShortestWave: %i" , clock
, ans
);
409 return ans
; //return shortest wave start position
414 uint8_t clkCnt
, tol
= 0 ;
415 uint16_t bestErr
[]={ 1000 , 1000 , 1000 , 1000 , 1000 , 1000 , 1000 , 1000 , 1000 };
416 uint8_t bestStart
[]={ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 };
418 size_t arrLoc
, loopEnd
;
426 //test each valid clock from smallest to greatest to see which lines up
427 for (; clkCnt
< clkEnd
; clkCnt
++){
428 if ( clk
[ clkCnt
] <= 32 ){
433 //if no errors allowed - keep start within the first clock
434 if (! maxErr
&& size
> clk
[ clkCnt
]* 2 + tol
&& clk
[ clkCnt
]< 128 ) loopCnt
= clk
[ clkCnt
]* 2 ;
435 bestErr
[ clkCnt
]= 1000 ;
436 //try lining up the peaks by moving starting point (try first few clocks)
437 for ( ii
= 0 ; ii
< loopCnt
; ii
++){
438 if ( dest
[ ii
] < peak
&& dest
[ ii
] > low
) continue ;
441 // now that we have the first one lined up test rest of wave array
442 loopEnd
= (( size
- ii
- tol
) / clk
[ clkCnt
]) - 1 ;
443 for ( i
= 0 ; i
< loopEnd
; ++ i
){
444 arrLoc
= ii
+ ( i
* clk
[ clkCnt
]);
445 if ( dest
[ arrLoc
] >= peak
|| dest
[ arrLoc
] <= low
){
446 } else if ( dest
[ arrLoc
- tol
] >= peak
|| dest
[ arrLoc
- tol
] <= low
){
447 } else if ( dest
[ arrLoc
+ tol
] >= peak
|| dest
[ arrLoc
+ tol
] <= low
){
448 } else { //error no peak detected
452 //if we found no errors then we can stop here and a low clock (common clocks)
453 // this is correct one - return this clock
454 if ( g_debugMode
== 2 ) prnt ( "DEBUG ASK: clk %d, err %d, startpos %d, endpos %d" , clk
[ clkCnt
], errCnt
, ii
, i
);
455 if ( errCnt
== 0 && clkCnt
< 7 ) {
456 if (! clockFnd
) * clock
= clk
[ clkCnt
];
459 //if we found errors see if it is lowest so far and save it as best run
460 if ( errCnt
< bestErr
[ clkCnt
]){
461 bestErr
[ clkCnt
]= errCnt
;
462 bestStart
[ clkCnt
]= ii
;
468 for ( iii
= 1 ; iii
< clkEnd
; ++ iii
){
469 if ( bestErr
[ iii
] < bestErr
[ best
]){
470 if ( bestErr
[ iii
] == 0 ) bestErr
[ iii
]= 1 ;
471 // current best bit to error ratio vs new bit to error ratio
472 if ( ( size
/ clk
[ best
])/ bestErr
[ best
] < ( size
/ clk
[ iii
])/ bestErr
[ iii
] ){
476 if ( g_debugMode
== 2 ) prnt ( "DEBUG ASK: clk %d, # Errors %d, Current Best Clk %d, bestStart %d" , clk
[ iii
], bestErr
[ iii
], clk
[ best
], bestStart
[ best
]);
478 if (! clockFnd
) * clock
= clk
[ best
];
479 return bestStart
[ best
];
482 int DetectStrongNRZClk ( uint8_t * dest
, size_t size
, int peak
, int low
){
483 //find shortest transition from high to low
485 size_t transition1
= 0 ;
486 int lowestTransition
= 255 ;
487 bool lastWasHigh
= false ;
489 //find first valid beginning of a high or low wave
490 while (( dest
[ i
] >= peak
|| dest
[ i
] <= low
) && ( i
< size
))
492 while (( dest
[ i
] < peak
&& dest
[ i
] > low
) && ( i
< size
))
494 lastWasHigh
= ( dest
[ i
] >= peak
);
496 if ( i
== size
) return 0 ;
499 for (; i
< size
; i
++) {
500 if (( dest
[ i
] >= peak
&& ! lastWasHigh
) || ( dest
[ i
] <= low
&& lastWasHigh
)) {
501 lastWasHigh
= ( dest
[ i
] >= peak
);
502 if ( i
- transition1
< lowestTransition
) lowestTransition
= i
- transition1
;
506 if ( lowestTransition
== 255 ) lowestTransition
= 0 ;
507 if ( g_debugMode
== 2 ) prnt ( "DEBUG NRZ: detectstrongNRZclk smallest wave: %d" , lowestTransition
);
508 return lowestTransition
;
512 //detect nrz clock by reading #peaks vs no peaks(or errors)
513 int DetectNRZClock ( uint8_t dest
[], size_t size
, int clock
, size_t * clockStartIdx
) {
515 uint8_t clk
[]={ 8 , 16 , 32 , 40 , 50 , 64 , 100 , 128 , 255 };
516 size_t loopCnt
= 4096 ; //don't need to loop through entire array...
517 if ( size
== 0 ) return 0 ;
518 if ( size
< loopCnt
) loopCnt
= size
- 20 ;
519 //if we already have a valid clock quit
521 if ( clk
[ i
] == clock
) return clock
;
523 //get high and low peak
525 if ( getHiLo ( dest
, loopCnt
, & peak
, & low
, 75 , 75 ) < 1 ) return 0 ;
527 int lowestTransition
= DetectStrongNRZClk ( dest
, size
- 20 , peak
, low
);
531 uint16_t smplCnt
= 0 ;
533 int16_t peaksdet
[] = { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 };
534 uint16_t maxPeak
= 255 ;
535 bool firstpeak
= false ;
536 //test for large clipped waves
537 for ( i
= 0 ; i
< loopCnt
; i
++){
538 if ( dest
[ i
] >= peak
|| dest
[ i
] <= low
){
539 if (! firstpeak
) continue ;
544 if ( maxPeak
> smplCnt
){
546 //prnt("maxPk: %d",maxPeak);
549 //prnt("maxPk: %d, smplCnt: %d, peakcnt: %d",maxPeak,smplCnt,peakcnt);
556 uint8_t ignoreCnt
= 0 ;
557 uint8_t ignoreWindow
= 4 ;
558 bool lastPeakHigh
= 0 ;
560 size_t bestStart
[]={ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 };
562 //test each valid clock from smallest to greatest to see which lines up
563 for ( clkCnt
= 0 ; clkCnt
< 8 ; ++ clkCnt
){
564 //ignore clocks smaller than smallest peak
565 if ( clk
[ clkCnt
] < maxPeak
- ( clk
[ clkCnt
]/ 4 )) continue ;
566 //try lining up the peaks by moving starting point (try first 256)
567 for ( ii
= 20 ; ii
< loopCnt
; ++ ii
){
568 if (( dest
[ ii
] >= peak
) || ( dest
[ ii
] <= low
)){
572 lastBit
= ii
- clk
[ clkCnt
];
573 //loop through to see if this start location works
574 for ( i
= ii
; i
< size
- 20 ; ++ i
) {
575 //if we are at a clock bit
576 if (( i
>= lastBit
+ clk
[ clkCnt
] - tol
) && ( i
<= lastBit
+ clk
[ clkCnt
] + tol
)) {
578 if ( dest
[ i
] >= peak
|| dest
[ i
] <= low
) {
579 //if same peak don't count it
580 if (( dest
[ i
] >= peak
&& ! lastPeakHigh
) || ( dest
[ i
] <= low
&& lastPeakHigh
)) {
583 lastPeakHigh
= ( dest
[ i
] >= peak
);
586 ignoreCnt
= ignoreWindow
;
587 lastBit
+= clk
[ clkCnt
];
588 } else if ( i
== lastBit
+ clk
[ clkCnt
] + tol
) {
589 lastBit
+= clk
[ clkCnt
];
591 //else if not a clock bit and no peaks
592 } else if ( dest
[ i
] < peak
&& dest
[ i
] > low
){
595 if ( errBitHigh
== true ) peakcnt
--;
600 // else if not a clock bit but we have a peak
601 } else if (( dest
[ i
]>= peak
|| dest
[ i
]<= low
) && (! bitHigh
)) {
602 //error bar found no clock...
606 if ( peakcnt
> peaksdet
[ clkCnt
]) {
607 bestStart
[ clkCnt
]= ii
;
608 peaksdet
[ clkCnt
]= peakcnt
;
615 for ( iii
= 7 ; iii
> 0 ; iii
--){
616 if (( peaksdet
[ iii
] >= ( peaksdet
[ best
]- 1 )) && ( peaksdet
[ iii
] <= peaksdet
[ best
]+ 1 ) && lowestTransition
) {
617 if ( clk
[ iii
] > ( lowestTransition
- ( clk
[ iii
]/ 8 )) && clk
[ iii
] < ( lowestTransition
+ ( clk
[ iii
]/ 8 ))) {
620 } else if ( peaksdet
[ iii
] > peaksdet
[ best
]){
623 if ( g_debugMode
== 2 ) prnt ( "DEBUG NRZ: Clk: %d, peaks: %d, maxPeak: %d, bestClk: %d, lowestTrs: %d" , clk
[ iii
], peaksdet
[ iii
], maxPeak
, clk
[ best
], lowestTransition
);
625 * clockStartIdx
= bestStart
[ best
];
630 //countFC is to detect the field clock lengths.
631 //counts and returns the 2 most common wave lengths
632 //mainly used for FSK field clock detection
633 uint16_t countFC ( uint8_t * BitStream
, size_t size
, uint8_t fskAdj
) {
634 uint8_t fcLens
[] = { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 };
635 uint16_t fcCnts
[] = { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 };
636 uint8_t fcLensFnd
= 0 ;
637 uint8_t lastFCcnt
= 0 ;
638 uint8_t fcCounter
= 0 ;
640 if ( size
< 180 ) return 0 ;
642 // prime i to first up transition
643 for ( i
= 160 ; i
< size
- 20 ; i
++)
644 if ( BitStream
[ i
] > BitStream
[ i
- 1 ] && BitStream
[ i
] >= BitStream
[ i
+ 1 ])
647 for (; i
< size
- 20 ; i
++){
648 if ( BitStream
[ i
] > BitStream
[ i
- 1 ] && BitStream
[ i
] >= BitStream
[ i
+ 1 ]){
652 //if we had 5 and now have 9 then go back to 8 (for when we get a fc 9 instead of an 8)
653 if ( lastFCcnt
== 5 && fcCounter
== 9 ) fcCounter
--;
654 //if fc=9 or 4 add one (for when we get a fc 9 instead of 10 or a 4 instead of a 5)
655 if (( fcCounter
== 9 ) || fcCounter
== 4 ) fcCounter
++;
656 // save last field clock count (fc/xx)
657 lastFCcnt
= fcCounter
;
659 // find which fcLens to save it to:
660 for ( int ii
= 0 ; ii
< 15 ; ii
++){
661 if ( fcLens
[ ii
]== fcCounter
){
667 if ( fcCounter
> 0 && fcLensFnd
< 15 ){
670 fcLens
[ fcLensFnd
++]= fcCounter
;
679 uint8_t best1
= 14 , best2
= 14 , best3
= 14 ;
681 // go through fclens and find which ones are bigest 2
682 for ( i
= 0 ; i
< 15 ; i
++){
683 // get the 3 best FC values
684 if ( fcCnts
[ i
]> maxCnt1
) {
689 } else if ( fcCnts
[ i
]> fcCnts
[ best2
]){
692 } else if ( fcCnts
[ i
]> fcCnts
[ best3
]){
695 if ( g_debugMode
== 2 ) prnt ( "DEBUG countfc: FC %u, Cnt %u, best fc: %u, best2 fc: %u" , fcLens
[ i
], fcCnts
[ i
], fcLens
[ best1
], fcLens
[ best2
]);
697 if ( fcLens
[ best1
]== 0 ) return 0 ;
698 uint8_t fcH
= 0 , fcL
= 0 ;
699 if ( fcLens
[ best1
]> fcLens
[ best2
]){
706 if (( size
- 180 )/ fcH
/ 3 > fcCnts
[ best1
]+ fcCnts
[ best2
]) {
707 if ( g_debugMode
== 2 ) prnt ( "DEBUG countfc: fc is too large: %u > %u. Not psk or fsk" ,( size
- 180 )/ fcH
/ 3 , fcCnts
[ best1
]+ fcCnts
[ best2
]);
708 return 0 ; //lots of waves not psk or fsk
710 // TODO: take top 3 answers and compare to known Field clocks to get top 2
712 uint16_t fcs
= ((( uint16_t ) fcH
)<< 8 ) | fcL
;
713 if ( fskAdj
) return fcs
;
714 return fcLens
[ best1
];
718 //detect psk clock by reading each phase shift
719 // a phase shift is determined by measuring the sample length of each wave
720 int DetectPSKClock_ext ( uint8_t dest
[], size_t size
, int clock
, int * firstPhaseShift
) {
721 uint8_t clk
[]={ 255 , 16 , 32 , 40 , 50 , 64 , 100 , 128 , 255 }; //255 is not a valid clock
722 uint16_t loopCnt
= 4096 ; //don't need to loop through entire array...
723 if ( size
== 0 ) return 0 ;
724 if ( size
< loopCnt
) loopCnt
= size
- 20 ;
726 //if we already have a valid clock quit
729 if ( clk
[ i
] == clock
) return clock
;
731 size_t waveStart
= 0 , waveEnd
= 0 , firstFullWave
= 0 , lastClkBit
= 0 ;
732 uint8_t clkCnt
, fc
= 0 , fullWaveLen
= 0 , tol
= 1 ;
733 uint16_t peakcnt
= 0 , errCnt
= 0 , waveLenCnt
= 0 ;
734 uint16_t bestErr
[]={ 1000 , 1000 , 1000 , 1000 , 1000 , 1000 , 1000 , 1000 , 1000 };
735 uint16_t peaksdet
[]={ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 };
736 fc
= countFC ( dest
, size
, 0 );
737 if ( fc
!= 2 && fc
!= 4 && fc
!= 8 ) return - 1 ;
738 if ( g_debugMode
== 2 ) prnt ( "DEBUG PSK: FC: %d" , fc
);
740 //find first full wave
741 for ( i
= 160 ; i
< loopCnt
; i
++){
742 if ( dest
[ i
] < dest
[ i
+ 1 ] && dest
[ i
+ 1 ] >= dest
[ i
+ 2 ]){
743 if ( waveStart
== 0 ) {
745 //prnt("DEBUG: waveStart: %d",waveStart);
748 //prnt("DEBUG: waveEnd: %d",waveEnd);
749 waveLenCnt
= waveEnd
- waveStart
;
750 if ( waveLenCnt
> fc
){
751 firstFullWave
= waveStart
;
752 fullWaveLen
= waveLenCnt
;
759 * firstPhaseShift
= firstFullWave
;
760 if ( g_debugMode
== 2 ) prnt ( "DEBUG PSK: firstFullWave: %d, waveLen: %d" , firstFullWave
, fullWaveLen
);
761 //test each valid clock from greatest to smallest to see which lines up
762 for ( clkCnt
= 7 ; clkCnt
>= 1 ; clkCnt
--){
763 lastClkBit
= firstFullWave
; //set end of wave as clock align
767 if ( g_debugMode
== 2 ) prnt ( "DEBUG PSK: clk: %d, lastClkBit: %d" , clk
[ clkCnt
], lastClkBit
);
769 for ( i
= firstFullWave
+ fullWaveLen
- 1 ; i
< loopCnt
- 2 ; i
++){
770 //top edge of wave = start of new wave
771 if ( dest
[ i
] < dest
[ i
+ 1 ] && dest
[ i
+ 1 ] >= dest
[ i
+ 2 ]){
772 if ( waveStart
== 0 ) {
777 waveLenCnt
= waveEnd
- waveStart
;
778 if ( waveLenCnt
> fc
){
779 //if this wave is a phase shift
780 if ( g_debugMode
== 2 ) prnt ( "DEBUG PSK: phase shift at: %d, len: %d, nextClk: %d, i: %d, fc: %d" , waveStart
, waveLenCnt
, lastClkBit
+ clk
[ clkCnt
]- tol
, i
+ 1 , fc
);
781 if ( i
+ 1 >= lastClkBit
+ clk
[ clkCnt
] - tol
){ //should be a clock bit
783 lastClkBit
+= clk
[ clkCnt
];
784 } else if ( i
< lastClkBit
+ 8 ){
785 //noise after a phase shift - ignore
786 } else { //phase shift before supposed to based on clock
789 } else if ( i
+ 1 > lastClkBit
+ clk
[ clkCnt
] + tol
+ fc
){
790 lastClkBit
+= clk
[ clkCnt
]; //no phase shift but clock bit
799 if ( errCnt
<= bestErr
[ clkCnt
]) bestErr
[ clkCnt
]= errCnt
;
800 if ( peakcnt
> peaksdet
[ clkCnt
]) peaksdet
[ clkCnt
]= peakcnt
;
802 //all tested with errors
803 //return the highest clk with the most peaks found
805 for ( i
= 7 ; i
>= 1 ; i
--){
806 if ( peaksdet
[ i
] > peaksdet
[ best
]) {
809 if ( g_debugMode
== 2 ) prnt ( "DEBUG PSK: Clk: %d, peaks: %d, errs: %d, bestClk: %d" , clk
[ i
], peaksdet
[ i
], bestErr
[ i
], clk
[ best
]);
814 int DetectPSKClock ( uint8_t dest
[], size_t size
, int clock
) {
815 int firstPhaseShift
= 0 ;
816 return DetectPSKClock_ext ( dest
, size
, clock
, & firstPhaseShift
);
820 //detects the bit clock for FSK given the high and low Field Clocks
821 uint8_t detectFSKClk_ext ( uint8_t * BitStream
, size_t size
, uint8_t fcHigh
, uint8_t fcLow
, int * firstClockEdge
) {
822 uint8_t clk
[] = { 8 , 16 , 32 , 40 , 50 , 64 , 100 , 128 , 0 };
823 uint16_t rfLens
[] = { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 };
824 uint8_t rfCnts
[] = { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 };
825 uint8_t rfLensFnd
= 0 ;
826 uint8_t lastFCcnt
= 0 ;
827 uint16_t fcCounter
= 0 ;
828 uint16_t rfCounter
= 0 ;
829 uint8_t firstBitFnd
= 0 ;
831 if ( size
== 0 ) return 0 ;
833 uint8_t fcTol
= (( fcHigh
* 100 - fcLow
* 100 )/ 2 + 50 )/ 100 ; //(uint8_t)(0.5+(float)(fcHigh-fcLow)/2);
838 //PrintAndLog("DEBUG: fcTol: %d",fcTol);
839 // prime i to first peak / up transition
840 for ( i
= 160 ; i
< size
- 20 ; i
++)
841 if ( BitStream
[ i
] > BitStream
[ i
- 1 ] && BitStream
[ i
]>= BitStream
[ i
+ 1 ])
844 for (; i
< size
- 20 ; i
++){
848 if ( BitStream
[ i
] <= BitStream
[ i
- 1 ] || BitStream
[ i
] < BitStream
[ i
+ 1 ])
851 // if we got less than the small fc + tolerance then set it to the small fc
852 // if it is inbetween set it to the last counter
853 if ( fcCounter
< fcHigh
&& fcCounter
> fcLow
)
854 fcCounter
= lastFCcnt
;
855 else if ( fcCounter
< fcLow
+ fcTol
)
857 else //set it to the large fc
860 //look for bit clock (rf/xx)
861 if (( fcCounter
< lastFCcnt
|| fcCounter
> lastFCcnt
)){
862 //not the same size as the last wave - start of new bit sequence
863 if ( firstBitFnd
> 1 ){ //skip first wave change - probably not a complete bit
864 for ( int ii
= 0 ; ii
< 15 ; ii
++){
865 if ( rfLens
[ ii
] >= ( rfCounter
- 4 ) && rfLens
[ ii
] <= ( rfCounter
+ 4 )){
871 if ( rfCounter
> 0 && rfLensFnd
< 15 ){
872 //PrintAndLog("DEBUG: rfCntr %d, fcCntr %d",rfCounter,fcCounter);
874 rfLens
[ rfLensFnd
++] = rfCounter
;
885 uint8_t rfHighest
= 15 , rfHighest2
= 15 , rfHighest3
= 15 ;
887 for ( i
= 0 ; i
< 15 ; i
++){
888 //get highest 2 RF values (might need to get more values to compare or compare all?)
889 if ( rfCnts
[ i
]> rfCnts
[ rfHighest
]){
890 rfHighest3
= rfHighest2
;
891 rfHighest2
= rfHighest
;
893 } else if ( rfCnts
[ i
]> rfCnts
[ rfHighest2
]){
894 rfHighest3
= rfHighest2
;
896 } else if ( rfCnts
[ i
]> rfCnts
[ rfHighest3
]){
899 if ( g_debugMode
== 2 ) prnt ( "DEBUG FSK: RF %d, cnts %d" , rfLens
[ i
], rfCnts
[ i
]);
901 // set allowed clock remainder tolerance to be 1 large field clock length+1
902 // we could have mistakenly made a 9 a 10 instead of an 8 or visa versa so rfLens could be 1 FC off
903 uint8_t tol1
= fcHigh
+ 1 ;
905 if ( g_debugMode
== 2 ) prnt ( "DEBUG FSK: most counted rf values: 1 %d, 2 %d, 3 %d" , rfLens
[ rfHighest
], rfLens
[ rfHighest2
], rfLens
[ rfHighest3
]);
907 // loop to find the highest clock that has a remainder less than the tolerance
908 // compare samples counted divided by
909 // test 128 down to 32 (shouldn't be possible to have fc/10 & fc/8 and rf/16 or less)
912 if ( rfLens
[ rfHighest
] % clk
[ ii
] < tol1
|| rfLens
[ rfHighest
] % clk
[ ii
] > clk
[ ii
]- tol1
){
913 if ( rfLens
[ rfHighest2
] % clk
[ ii
] < tol1
|| rfLens
[ rfHighest2
] % clk
[ ii
] > clk
[ ii
]- tol1
){
914 if ( rfLens
[ rfHighest3
] % clk
[ ii
] < tol1
|| rfLens
[ rfHighest3
] % clk
[ ii
] > clk
[ ii
]- tol1
){
915 if ( g_debugMode
== 2 ) prnt ( "DEBUG FSK: clk %d divides into the 3 most rf values within tolerance" , clk
[ ii
]);
922 if ( ii
< 2 ) return 0 ; // oops we went too far
927 uint8_t detectFSKClk ( uint8_t * BitStream
, size_t size
, uint8_t fcHigh
, uint8_t fcLow
) {
928 int firstClockEdge
= 0 ;
929 return detectFSKClk_ext ( BitStream
, size
, fcHigh
, fcLow
, & firstClockEdge
);
932 //**********************************************************************************************
933 //--------------------Modulation Demods &/or Decoding Section-----------------------------------
934 //**********************************************************************************************
936 // look for Sequence Terminator - should be pulses of clk*(1 or 2), clk*2, clk*(1.5 or 2), by idx we mean graph position index...
937 bool findST ( int * stStopLoc
, int * stStartIdx
, int lowToLowWaveLen
[], int highToLowWaveLen
[], int clk
, int tol
, int buffSize
, size_t * i
) {
938 for (; * i
< buffSize
- 4 ; * i
+= 1 ) {
939 * stStartIdx
+= lowToLowWaveLen
[* i
]; //caution part of this wave may be data and part may be ST.... to be accounted for in main function for now...
940 if ( lowToLowWaveLen
[* i
] >= clk
* 1 - tol
&& lowToLowWaveLen
[* i
] <= ( clk
* 2 )+ tol
&& highToLowWaveLen
[* i
] < clk
+ tol
) { //1 to 2 clocks depending on 2 bits prior
941 if ( lowToLowWaveLen
[* i
+ 1 ] >= clk
* 2 - tol
&& lowToLowWaveLen
[* i
+ 1 ] <= clk
* 2 + tol
&& highToLowWaveLen
[* i
+ 1 ] > clk
* 3 / 2 - tol
) { //2 clocks and wave size is 1 1/2
942 if ( lowToLowWaveLen
[* i
+ 2 ] >= ( clk
* 3 )/ 2 - tol
&& lowToLowWaveLen
[* i
+ 2 ] <= clk
* 2 + tol
&& highToLowWaveLen
[* i
+ 2 ] > clk
- tol
) { //1 1/2 to 2 clocks and at least one full clock wave
943 if ( lowToLowWaveLen
[* i
+ 3 ] >= clk
* 1 - tol
&& lowToLowWaveLen
[* i
+ 3 ] <= clk
* 2 + tol
) { //1 to 2 clocks for end of ST + first bit
954 //attempt to identify a Sequence Terminator in ASK modulated raw wave
955 bool DetectST_ext ( uint8_t buffer
[], size_t * size
, int * foundclock
, size_t * ststart
, size_t * stend
) {
956 size_t bufsize
= * size
;
957 //need to loop through all samples and identify our clock, look for the ST pattern
960 int j
, high
, low
, skip
, start
, end
, minClk
= 255 ;
962 //probably should malloc... || test if memory is available ... handle device side? memory danger!!! [marshmellow]
963 int tmpbuff
[ bufsize
/ LOWEST_DEFAULT_CLOCK
]; // low to low wave count //guess rf/32 clock, if click is smaller we will only have room for a fraction of the samples captured
964 int waveLen
[ bufsize
/ LOWEST_DEFAULT_CLOCK
]; // high to low wave count //if clock is larger then we waste memory in array size that is not needed...
965 //size_t testsize = (bufsize < 512) ? bufsize : 512;
968 memset ( tmpbuff
, 0 , sizeof ( tmpbuff
));
969 memset ( waveLen
, 0 , sizeof ( waveLen
));
971 if (! loadWaveCounters ( buffer
, bufsize
, tmpbuff
, waveLen
, & j
, & skip
, & minClk
, & high
, & low
)) return false ;
972 // set clock - might be able to get this externally and remove this work...
973 clk
= getClosestClock ( minClk
);
974 // clock not found - ERROR
976 if ( g_debugMode
== 2 ) prnt ( "DEBUG STT: clock not found - quitting" );
982 if (! findST (& start
, & skip
, tmpbuff
, waveLen
, clk
, tol
, j
, & i
)) {
983 // first ST not found - ERROR
984 if ( g_debugMode
== 2 ) prnt ( "DEBUG STT: first STT not found - quitting" );
987 if ( g_debugMode
== 2 ) prnt ( "DEBUG STT: first STT found at wave: %i, skip: %i, j=%i" , start
, skip
, j
);
989 if ( waveLen
[ i
+ 2 ] > clk
* 1 + tol
)
994 // skip over the remainder of ST
995 skip
+= clk
* 7 / 2 ; //3.5 clocks from tmpbuff[i] = end of st - also aligns for ending point
997 // now do it again to find the end
1001 if (! findST (& dummy1
, & end
, tmpbuff
, waveLen
, clk
, tol
, j
, & i
)) {
1002 //didn't find second ST - ERROR
1003 if ( g_debugMode
== 2 ) prnt ( "DEBUG STT: second STT not found - quitting" );
1007 if ( g_debugMode
== 2 ) prnt ( "DEBUG STT: start of data: %d end of data: %d, datalen: %d, clk: %d, bits: %d, phaseoff: %d" , skip
, end
, end
- skip
, clk
, ( end
- skip
)/ clk
, phaseoff
);
1008 //now begin to trim out ST so we can use normal demod cmds
1010 size_t datalen
= end
- start
;
1011 // check validity of datalen (should be even clock increments) - use a tolerance of up to 1/8th a clock
1012 if ( clk
- ( datalen
% clk
) <= clk
/ 8 ) {
1013 // padd the amount off - could be problematic... but shouldn't happen often
1014 datalen
+= clk
- ( datalen
% clk
);
1015 } else if ( ( datalen
% clk
) <= clk
/ 8 ) {
1016 // padd the amount off - could be problematic... but shouldn't happen often
1017 datalen
-= datalen
% clk
;
1019 if ( g_debugMode
== 2 ) prnt ( "DEBUG STT: datalen not divisible by clk: %u %% %d = %d - quitting" , datalen
, clk
, datalen
% clk
);
1022 // if datalen is less than one t55xx block - ERROR
1023 if ( datalen
/ clk
< 8 * 4 ) {
1024 if ( g_debugMode
== 2 ) prnt ( "DEBUG STT: datalen is less than 1 full t55xx block - quitting" );
1027 size_t dataloc
= start
;
1028 if ( buffer
[ dataloc
-( clk
* 4 )-( clk
/ 8 )] <= low
&& buffer
[ dataloc
] <= low
&& buffer
[ dataloc
-( clk
* 4 )] >= high
) {
1029 //we have low drift (and a low just before the ST and a low just after the ST) - compensate by backing up the start
1030 for ( i
= 0 ; i
<= ( clk
/ 8 ); ++ i
) {
1031 if ( buffer
[ dataloc
- ( clk
* 4 ) - i
] <= low
) {
1040 if ( g_debugMode
== 2 ) prnt ( "DEBUG STT: Starting STT trim - start: %d, datalen: %d " , dataloc
, datalen
);
1041 bool firstrun
= true ;
1042 // warning - overwriting buffer given with raw wave data with ST removed...
1043 while ( dataloc
< bufsize
-( clk
/ 2 ) ) {
1044 //compensate for long high at end of ST not being high due to signal loss... (and we cut out the start of wave high part)
1045 if ( buffer
[ dataloc
]< high
&& buffer
[ dataloc
]> low
&& buffer
[ dataloc
+ 3 ]< high
&& buffer
[ dataloc
+ 3 ]> low
) {
1046 for ( i
= 0 ; i
< clk
/ 2 - tol
; ++ i
) {
1047 buffer
[ dataloc
+ i
] = high
+ 5 ;
1049 } //test for single sample outlier (high between two lows) in the case of very strong waves
1050 if ( buffer
[ dataloc
] >= high
&& buffer
[ dataloc
+ 2 ] <= low
) {
1051 buffer
[ dataloc
] = buffer
[ dataloc
+ 2 ];
1052 buffer
[ dataloc
+ 1 ] = buffer
[ dataloc
+ 2 ];
1056 * ststart
= dataloc
-( clk
* 4 );
1059 for ( i
= 0 ; i
< datalen
; ++ i
) {
1060 if ( i
+ newloc
< bufsize
) {
1061 if ( i
+ newloc
< dataloc
)
1062 buffer
[ i
+ newloc
] = buffer
[ dataloc
];
1068 //skip next ST - we just assume it will be there from now on...
1069 if ( g_debugMode
== 2 ) prnt ( "DEBUG STT: skipping STT at %d to %d" , dataloc
, dataloc
+( clk
* 4 ));
1075 bool DetectST ( uint8_t buffer
[], size_t * size
, int * foundclock
) {
1076 size_t ststart
= 0 , stend
= 0 ;
1077 return DetectST_ext ( buffer
, size
, foundclock
, & ststart
, & stend
);
1081 //take 11 10 01 11 00 and make 01100 ... miller decoding
1082 //check for phase errors - should never have half a 1 or 0 by itself and should never exceed 1111 or 0000 in a row
1083 //decodes miller encoded binary
1084 //NOTE askrawdemod will NOT demod miller encoded ask unless the clock is manually set to 1/2 what it is detected as!
1085 int millerRawDecode ( uint8_t * BitStream
, size_t * size
, int invert
) {
1086 if (* size
< 16 ) return - 1 ;
1087 uint16_t MaxBits
= 512 , errCnt
= 0 ;
1089 uint8_t alignCnt
= 0 , curBit
= BitStream
[ 0 ], alignedIdx
= 0 ;
1090 uint8_t halfClkErr
= 0 ;
1091 //find alignment, needs 4 1s or 0s to properly align
1092 for ( i
= 1 ; i
< * size
- 1 ; i
++) {
1093 alignCnt
= ( BitStream
[ i
] == curBit
) ? alignCnt
+ 1 : 0 ;
1094 curBit
= BitStream
[ i
];
1095 if ( alignCnt
== 4 ) break ;
1097 // for now error if alignment not found. later add option to run it with multiple offsets...
1098 if ( alignCnt
!= 4 ) {
1099 if ( g_debugMode
) prnt ( "ERROR MillerDecode: alignment not found so either your bitstream is not miller or your data does not have a 101 in it" );
1102 alignedIdx
= ( i
- 1 ) % 2 ;
1103 for ( i
= alignedIdx
; i
< * size
- 3 ; i
+= 2 ) {
1104 halfClkErr
= ( uint8_t )(( halfClkErr
<< 1 | BitStream
[ i
]) & 0xFF );
1105 if ( ( halfClkErr
& 0x7 ) == 5 || ( halfClkErr
& 0x7 ) == 2 || ( i
> 2 && ( halfClkErr
& 0x7 ) == 0 ) || ( halfClkErr
& 0x1F ) == 0x1F ) {
1107 BitStream
[ bitCnt
++] = 7 ;
1110 BitStream
[ bitCnt
++] = BitStream
[ i
] ^ BitStream
[ i
+ 1 ] ^ invert
;
1112 if ( bitCnt
> MaxBits
) break ;
1119 //take 01 or 10 = 1 and 11 or 00 = 0
1120 //check for phase errors - should never have 111 or 000 should be 01001011 or 10110100 for 1010
1121 //decodes biphase or if inverted it is AKA conditional dephase encoding AKA differential manchester encoding
1122 int BiphaseRawDecode ( uint8_t * BitStream
, size_t * size
, int offset
, int invert
) {
1123 uint16_t bitnum
= 0 ;
1124 uint16_t errCnt
= 0 ;
1126 uint16_t MaxBits
= 512 ;
1127 //if not enough samples - error
1128 if (* size
< 51 ) return - 1 ;
1129 //check for phase change faults - skip one sample if faulty
1130 uint8_t offsetA
= 1 , offsetB
= 1 ;
1132 if ( BitStream
[ i
+ 1 ]== BitStream
[ i
+ 2 ]) offsetA
= 0 ;
1133 if ( BitStream
[ i
+ 2 ]== BitStream
[ i
+ 3 ]) offsetB
= 0 ;
1135 if (! offsetA
&& offsetB
) offset
++;
1136 for ( i
= offset
; i
<* size
- 3 ; i
+= 2 ){
1137 //check for phase error
1138 if ( BitStream
[ i
+ 1 ]== BitStream
[ i
+ 2 ]) {
1139 BitStream
[ bitnum
++]= 7 ;
1142 if (( BitStream
[ i
]== 1 && BitStream
[ i
+ 1 ]== 0 ) || ( BitStream
[ i
]== 0 && BitStream
[ i
+ 1 ]== 1 )){
1143 BitStream
[ bitnum
++]= 1 ^ invert
;
1144 } else if (( BitStream
[ i
]== 0 && BitStream
[ i
+ 1 ]== 0 ) || ( BitStream
[ i
]== 1 && BitStream
[ i
+ 1 ]== 1 )){
1145 BitStream
[ bitnum
++]= invert
;
1147 BitStream
[ bitnum
++]= 7 ;
1150 if ( bitnum
> MaxBits
) break ;
1157 //take 10 and 01 and manchester decode
1158 //run through 2 times and take least errCnt
1159 int manrawdecode ( uint8_t * BitStream
, size_t * size
, uint8_t invert
, uint8_t * alignPos
) {
1160 uint16_t bitnum
= 0 , MaxBits
= 512 , errCnt
= 0 ;
1162 uint16_t bestErr
= 1000 , bestRun
= 0 ;
1163 if (* size
< 16 ) return - 1 ;
1164 //find correct start position [alignment]
1165 for ( ii
= 0 ; ii
< 2 ;++ ii
){
1166 for ( i
= ii
; i
<* size
- 3 ; i
+= 2 )
1167 if ( BitStream
[ i
]== BitStream
[ i
+ 1 ])
1170 if ( bestErr
> errCnt
){
1178 for ( i
= bestRun
; i
< * size
- 3 ; i
+= 2 ){
1179 if ( BitStream
[ i
] == 1 && ( BitStream
[ i
+ 1 ] == 0 )){
1180 BitStream
[ bitnum
++]= invert
;
1181 } else if (( BitStream
[ i
] == 0 ) && BitStream
[ i
+ 1 ] == 1 ){
1182 BitStream
[ bitnum
++]= invert
^ 1 ;
1184 BitStream
[ bitnum
++]= 7 ;
1186 if ( bitnum
> MaxBits
) break ;
1193 //demodulates strong heavily clipped samples
1194 int cleanAskRawDemod ( uint8_t * BinStream
, size_t * size
, int clk
, int invert
, int high
, int low
, int * startIdx
)
1197 size_t bitCnt
= 0 , smplCnt
= 1 , errCnt
= 0 ;
1198 bool waveHigh
= ( BinStream
[ 0 ] >= high
);
1199 for ( size_t i
= 1 ; i
< * size
; i
++){
1200 if ( BinStream
[ i
] >= high
&& waveHigh
){
1202 } else if ( BinStream
[ i
] <= low
&& ! waveHigh
){
1204 } else { //transition
1205 if (( BinStream
[ i
] >= high
&& ! waveHigh
) || ( BinStream
[ i
] <= low
&& waveHigh
)){
1206 if ( smplCnt
> clk
-( clk
/ 4 )- 1 ) { //full clock
1207 if ( smplCnt
> clk
+ ( clk
/ 4 )+ 1 ) { //too many samples
1209 if ( g_debugMode
== 2 ) prnt ( "DEBUG ASK: Modulation Error at: %u" , i
);
1210 BinStream
[ bitCnt
++] = 7 ;
1211 } else if ( waveHigh
) {
1212 BinStream
[ bitCnt
++] = invert
;
1213 BinStream
[ bitCnt
++] = invert
;
1214 } else if (! waveHigh
) {
1215 BinStream
[ bitCnt
++] = invert
^ 1 ;
1216 BinStream
[ bitCnt
++] = invert
^ 1 ;
1218 if (* startIdx
== 0 ) * startIdx
= i
- clk
;
1219 waveHigh
= ! waveHigh
;
1221 } else if ( smplCnt
> ( clk
/ 2 ) - ( clk
/ 4 )- 1 ) { //half clock
1223 BinStream
[ bitCnt
++] = invert
;
1224 } else if (! waveHigh
) {
1225 BinStream
[ bitCnt
++] = invert
^ 1 ;
1227 if (* startIdx
== 0 ) * startIdx
= i
-( clk
/ 2 );
1228 waveHigh
= ! waveHigh
;
1232 //transition bit oops
1234 } else { //haven't hit new high or new low yet
1244 //attempts to demodulate ask modulations, askType == 0 for ask/raw, askType==1 for ask/manchester
1245 int askdemod_ext ( uint8_t * BinStream
, size_t * size
, int * clk
, int * invert
, int maxErr
, uint8_t amp
, uint8_t askType
, int * startIdx
) {
1246 if (* size
== 0 ) return - 1 ;
1247 int start
= DetectASKClock ( BinStream
, * size
, clk
, maxErr
); //clock default
1248 if (* clk
== 0 || start
< 0 ) return - 3 ;
1249 if (* invert
!= 1 ) * invert
= 0 ;
1250 if ( amp
== 1 ) askAmp ( BinStream
, * size
);
1251 if ( g_debugMode
== 2 ) prnt ( "DEBUG ASK: clk %d, beststart %d, amp %d" , * clk
, start
, amp
);
1253 //start pos from detect ask clock is 1/2 clock offset
1254 // NOTE: can be negative (demod assumes rest of wave was there)
1255 * startIdx
= start
- (* clk
/ 2 );
1256 uint8_t initLoopMax
= 255 ;
1257 if ( initLoopMax
> * size
) initLoopMax
= * size
;
1258 // Detect high and lows
1259 //25% clip in case highs and lows aren't clipped [marshmellow]
1261 if ( getHiLo ( BinStream
, initLoopMax
, & high
, & low
, 75 , 75 ) < 1 )
1262 return - 2 ; //just noise
1265 // if clean clipped waves detected run alternate demod
1266 if ( DetectCleanAskWave ( BinStream
, * size
, high
, low
)) {
1267 if ( g_debugMode
== 2 ) prnt ( "DEBUG ASK: Clean Wave Detected - using clean wave demod" );
1268 errCnt
= cleanAskRawDemod ( BinStream
, size
, * clk
, * invert
, high
, low
, startIdx
);
1269 if ( askType
) { //askman
1270 uint8_t alignPos
= 0 ;
1271 errCnt
= manrawdecode ( BinStream
, size
, 0 , & alignPos
);
1272 * startIdx
+= * clk
/ 2 * alignPos
;
1273 if ( g_debugMode
) prnt ( "DEBUG ASK CLEAN: startIdx %i, alignPos %u" , * startIdx
, alignPos
);
1279 if ( g_debugMode
) prnt ( "DEBUG ASK WEAK: startIdx %i" , * startIdx
);
1280 if ( g_debugMode
== 2 ) prnt ( "DEBUG ASK: Weak Wave Detected - using weak wave demod" );
1282 int lastBit
; //set first clock check - can go negative
1283 size_t i
, bitnum
= 0 ; //output counter
1285 uint8_t tol
= 0 ; //clock tolerance adjust - waves will be accepted as within the clock if they fall + or - this value + clock from last valid wave
1286 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
1287 size_t MaxBits
= 3072 ; //max bits to collect
1288 lastBit
= start
- * clk
;
1290 for ( i
= start
; i
< * size
; ++ i
) {
1291 if ( i
- lastBit
>= * clk
- tol
){
1292 if ( BinStream
[ i
] >= high
) {
1293 BinStream
[ bitnum
++] = * invert
;
1294 } else if ( BinStream
[ i
] <= low
) {
1295 BinStream
[ bitnum
++] = * invert
^ 1 ;
1296 } else if ( i
- lastBit
>= * clk
+ tol
) {
1298 if ( g_debugMode
== 2 ) prnt ( "DEBUG ASK: Modulation Error at: %u" , i
);
1299 BinStream
[ bitnum
++]= 7 ;
1302 } else { //in tolerance - looking for peak
1307 } else if ( i
- lastBit
>= (* clk
/ 2 - tol
) && ! midBit
&& ! askType
){
1308 if ( BinStream
[ i
] >= high
) {
1309 BinStream
[ bitnum
++] = * invert
;
1310 } else if ( BinStream
[ i
] <= low
) {
1311 BinStream
[ bitnum
++] = * invert
^ 1 ;
1312 } else if ( i
- lastBit
>= * clk
/ 2 + tol
) {
1313 BinStream
[ bitnum
] = BinStream
[ bitnum
- 1 ];
1315 } else { //in tolerance - looking for peak
1320 if ( bitnum
>= MaxBits
) break ;
1326 int askdemod ( uint8_t * BinStream
, size_t * size
, int * clk
, int * invert
, int maxErr
, uint8_t amp
, uint8_t askType
) {
1328 return askdemod_ext ( BinStream
, size
, clk
, invert
, maxErr
, amp
, askType
, & start
);
1331 // by marshmellow - demodulate NRZ wave - requires a read with strong signal
1332 // peaks invert bit (high=1 low=0) each clock cycle = 1 bit determined by last peak
1333 int nrzRawDemod ( uint8_t * dest
, size_t * size
, int * clk
, int * invert
, int * startIdx
) {
1334 if ( justNoise ( dest
, * size
)) return - 1 ;
1335 size_t clkStartIdx
= 0 ;
1336 * clk
= DetectNRZClock ( dest
, * size
, * clk
, & clkStartIdx
);
1337 if (* clk
== 0 ) return - 2 ;
1338 size_t i
, gLen
= 4096 ;
1339 if ( gLen
>* size
) gLen
= * size
- 20 ;
1341 if ( getHiLo ( dest
, gLen
, & high
, & low
, 75 , 75 ) < 1 ) return - 3 ; //25% fuzz on high 25% fuzz on low
1344 //convert wave samples to 1's and 0's
1345 for ( i
= 20 ; i
< * size
- 20 ; i
++){
1346 if ( dest
[ i
] >= high
) bit
= 1 ;
1347 if ( dest
[ i
] <= low
) bit
= 0 ;
1350 //now demod based on clock (rf/32 = 32 1's for one 1 bit, 32 0's for one 0 bit)
1353 for ( i
= 21 ; i
< * size
- 20 ; i
++) {
1354 //if transition detected or large number of same bits - store the passed bits
1355 if ( dest
[ i
] != dest
[ i
- 1 ] || ( i
- lastBit
) == ( 10 * * clk
)) {
1356 memset ( dest
+ numBits
, dest
[ i
- 1 ] ^ * invert
, ( i
- lastBit
+ (* clk
/ 4 )) / * clk
);
1357 numBits
+= ( i
- lastBit
+ (* clk
/ 4 )) / * clk
;
1359 * startIdx
= i
- ( numBits
* * clk
);
1360 if ( g_debugMode
== 2 ) prnt ( "DEBUG NRZ: startIdx %i" , * startIdx
);
1369 //translate wave to 11111100000 (1 for each short wave [higher freq] 0 for each long wave [lower freq])
1370 size_t fsk_wave_demod ( uint8_t * dest
, size_t size
, uint8_t fchigh
, uint8_t fclow
, int * startIdx
) {
1371 size_t last_transition
= 0 ;
1373 if ( fchigh
== 0 ) fchigh
= 10 ;
1374 if ( fclow
== 0 ) fclow
= 8 ;
1375 //set the threshold close to 0 (graph) or 128 std to avoid static
1376 size_t preLastSample
= 0 ;
1377 size_t LastSample
= 0 ;
1378 size_t currSample
= 0 ;
1379 if ( size
< 1024 ) return 0 ; // not enough samples
1381 //find start of modulating data in trace
1382 idx
= findModStart ( dest
, size
, fchigh
);
1383 // Need to threshold first sample
1384 if ( dest
[ idx
] < FSK_PSK_THRESHOLD
) dest
[ 0 ] = 0 ;
1387 last_transition
= idx
;
1390 // count cycles between consecutive lo-hi transitions, there should be either 8 (fc/8)
1391 // or 10 (fc/10) cycles but in practice due to noise etc we may end up with anywhere
1392 // between 7 to 11 cycles so fuzz it by treat anything <9 as 8 and anything else as 10
1393 // (could also be fc/5 && fc/7 for fsk1 = 4-9)
1394 for (; idx
< size
; idx
++) {
1395 // threshold current value
1396 if ( dest
[ idx
] < FSK_PSK_THRESHOLD
) dest
[ idx
] = 0 ;
1399 // Check for 0->1 transition
1400 if ( dest
[ idx
- 1 ] < dest
[ idx
]) {
1401 preLastSample
= LastSample
;
1402 LastSample
= currSample
;
1403 currSample
= idx
- last_transition
;
1404 if ( currSample
< ( fclow
- 2 )) { //0-5 = garbage noise (or 0-3)
1405 //do nothing with extra garbage
1406 } else if ( currSample
< ( fchigh
- 1 )) { //6-8 = 8 sample waves (or 3-6 = 5)
1407 //correct previous 9 wave surrounded by 8 waves (or 6 surrounded by 5)
1408 if ( numBits
> 1 && LastSample
> ( fchigh
- 2 ) && ( preLastSample
< ( fchigh
- 1 ))){
1412 if ( numBits
> 0 && * startIdx
== 0 ) * startIdx
= idx
- fclow
;
1413 } else if ( currSample
> ( fchigh
+ 1 ) && numBits
< 3 ) { //12 + and first two bit = unusable garbage
1414 //do nothing with beginning garbage and reset.. should be rare..
1416 } else if ( currSample
== ( fclow
+ 1 ) && LastSample
== ( fclow
- 1 )) { // had a 7 then a 9 should be two 8's (or 4 then a 6 should be two 5's)
1418 if ( numBits
> 0 && * startIdx
== 0 ) * startIdx
= idx
- fclow
;
1419 } else { //9+ = 10 sample waves (or 6+ = 7)
1421 if ( numBits
> 0 && * startIdx
== 0 ) * startIdx
= idx
- fchigh
;
1423 last_transition
= idx
;
1426 return numBits
; //Actually, it returns the number of bytes, but each byte represents a bit: 1 or 0
1429 //translate 11111100000 to 10
1430 //rfLen = clock, fchigh = larger field clock, fclow = smaller field clock
1431 size_t aggregate_bits ( uint8_t * dest
, size_t size
, uint8_t rfLen
, uint8_t invert
, uint8_t fchigh
, uint8_t fclow
, int * startIdx
) {
1432 uint8_t lastval
= dest
[ 0 ];
1436 for ( idx
= 1 ; idx
< size
; idx
++) {
1438 if ( dest
[ idx
]== lastval
) continue ; //skip until we hit a transition
1440 //find out how many bits (n) we collected (use 1/2 clk tolerance)
1441 //if lastval was 1, we have a 1->0 crossing
1442 if ( dest
[ idx
- 1 ]== 1 ) {
1443 n
= ( n
* fclow
+ rfLen
/ 2 ) / rfLen
;
1444 } else { // 0->1 crossing
1445 n
= ( n
* fchigh
+ rfLen
/ 2 ) / rfLen
;
1449 //first transition - save startidx
1451 if ( lastval
== 1 ) { //high to low
1452 * startIdx
+= ( fclow
* idx
) - ( n
* rfLen
);
1453 if ( g_debugMode
== 2 ) prnt ( "DEBUG FSK: startIdx %i, fclow*idx %i, n*rflen %u" , * startIdx
, fclow
*( idx
), n
* rfLen
);
1455 * startIdx
+= ( fchigh
* idx
) - ( n
* rfLen
);
1456 if ( g_debugMode
== 2 ) prnt ( "DEBUG FSK: startIdx %i, fchigh*idx %i, n*rflen %u" , * startIdx
, fchigh
*( idx
), n
* rfLen
);
1460 //add to our destination the bits we collected
1461 memset ( dest
+ numBits
, dest
[ idx
- 1 ]^ invert
, n
);
1466 // if valid extra bits at the end were all the same frequency - add them in
1467 if ( n
> rfLen
/ fchigh
) {
1468 if ( dest
[ idx
- 2 ]== 1 ) {
1469 n
= ( n
* fclow
+ rfLen
/ 2 ) / rfLen
;
1471 n
= ( n
* fchigh
+ rfLen
/ 2 ) / rfLen
;
1473 memset ( dest
+ numBits
, dest
[ idx
- 1 ]^ invert
, n
);
1479 //by marshmellow (from holiman's base)
1480 // full fsk demod from GraphBuffer wave to decoded 1s and 0s (no mandemod)
1481 int fskdemod_ext ( uint8_t * dest
, size_t size
, uint8_t rfLen
, uint8_t invert
, uint8_t fchigh
, uint8_t fclow
, int * startIdx
) {
1483 size
= fsk_wave_demod ( dest
, size
, fchigh
, fclow
, startIdx
);
1484 size
= aggregate_bits ( dest
, size
, rfLen
, invert
, fchigh
, fclow
, startIdx
);
1488 int fskdemod ( uint8_t * dest
, size_t size
, uint8_t rfLen
, uint8_t invert
, uint8_t fchigh
, uint8_t fclow
) {
1490 return fskdemod_ext ( dest
, size
, rfLen
, invert
, fchigh
, fclow
, & startIdx
);
1494 // convert psk1 demod to psk2 demod
1495 // only transition waves are 1s
1496 void psk1TOpsk2 ( uint8_t * BitStream
, size_t size
) {
1498 uint8_t lastBit
= BitStream
[ 0 ];
1499 for (; i
< size
; i
++){
1500 if ( BitStream
[ i
]== 7 ){
1502 } else if ( lastBit
!= BitStream
[ i
]){
1503 lastBit
= BitStream
[ i
];
1513 // convert psk2 demod to psk1 demod
1514 // from only transition waves are 1s to phase shifts change bit
1515 void psk2TOpsk1 ( uint8_t * BitStream
, size_t size
) {
1517 for ( size_t i
= 0 ; i
< size
; i
++){
1518 if ( BitStream
[ i
]== 1 ){
1526 size_t pskFindFirstPhaseShift ( uint8_t samples
[], size_t size
, uint8_t * curPhase
, size_t waveStart
, uint16_t fc
, uint16_t * fullWaveLen
) {
1527 uint16_t loopCnt
= ( size
+ 3 < 4096 ) ? size
: 4096 ; //don't need to loop through entire array...
1529 uint16_t avgWaveVal
= 0 , lastAvgWaveVal
= 0 ;
1530 size_t i
= waveStart
, waveEnd
, waveLenCnt
, firstFullWave
;
1531 for (; i
< loopCnt
; i
++) {
1533 if ( samples
[ i
]+ fc
< samples
[ i
+ 1 ] && samples
[ i
+ 1 ] >= samples
[ i
+ 2 ]){
1535 if ( g_debugMode
== 2 ) prnt ( "DEBUG PSK: waveEnd: %u, waveStart: %u" , waveEnd
, waveStart
);
1536 waveLenCnt
= waveEnd
- waveStart
;
1537 if ( waveLenCnt
> fc
&& waveStart
> fc
&& !( waveLenCnt
> fc
+ 8 )){ //not first peak and is a large wave but not out of whack
1538 lastAvgWaveVal
= avgWaveVal
/( waveLenCnt
);
1539 firstFullWave
= waveStart
;
1540 * fullWaveLen
= waveLenCnt
;
1541 //if average wave value is > graph 0 then it is an up wave or a 1 (could cause inverting)
1542 if ( lastAvgWaveVal
> FSK_PSK_THRESHOLD
) * curPhase
^= 1 ;
1543 return firstFullWave
;
1548 avgWaveVal
+= samples
[ i
+ 2 ];
1553 //by marshmellow - demodulate PSK1 wave
1554 //uses wave lengths (# Samples)
1555 int pskRawDemod_ext ( uint8_t dest
[], size_t * size
, int * clock
, int * invert
, int * startIdx
) {
1556 if (* size
< 170 ) return - 1 ;
1558 uint8_t curPhase
= * invert
;
1559 size_t i
= 0 , numBits
= 0 , waveStart
= 1 , waveEnd
= 0 , firstFullWave
= 0 , lastClkBit
= 0 ;
1560 uint16_t fc
= 0 , fullWaveLen
= 0 , waveLenCnt
= 0 , avgWaveVal
, tol
= 1 ;
1561 uint16_t errCnt
= 0 , errCnt2
= 0 ;
1563 fc
= countFC ( dest
, * size
, 1 );
1564 if (( fc
>> 8 ) == 10 ) return - 1 ; //fsk found - quit
1566 if ( fc
!= 2 && fc
!= 4 && fc
!= 8 ) return - 1 ;
1567 * clock
= DetectPSKClock ( dest
, * size
, * clock
);
1568 if (* clock
== 0 ) return - 1 ;
1570 //find start of modulating data in trace
1571 i
= findModStart ( dest
, * size
, fc
);
1573 //find first phase shift
1574 firstFullWave
= pskFindFirstPhaseShift ( dest
, * size
, & curPhase
, i
, fc
, & fullWaveLen
);
1575 if ( firstFullWave
== 0 ) {
1576 // no phase shift detected - could be all 1's or 0's - doesn't matter where we start
1577 // so skip a little to ensure we are past any Start Signal
1578 firstFullWave
= 160 ;
1579 memset ( dest
, curPhase
, firstFullWave
/ * clock
);
1581 memset ( dest
, curPhase
^ 1 , firstFullWave
/ * clock
);
1584 numBits
+= ( firstFullWave
/ * clock
);
1585 * startIdx
= firstFullWave
- (* clock
* numBits
)+ 2 ;
1586 //set start of wave as clock align
1587 lastClkBit
= firstFullWave
;
1588 if ( g_debugMode
== 2 ) prnt ( "DEBUG PSK: firstFullWave: %u, waveLen: %u, startIdx %i" , firstFullWave
, fullWaveLen
, * startIdx
);
1589 if ( g_debugMode
== 2 ) prnt ( "DEBUG PSK: clk: %d, lastClkBit: %u, fc: %u" , * clock
, lastClkBit
,( unsigned int ) fc
);
1591 dest
[ numBits
++] = curPhase
; //set first read bit
1592 for ( i
= firstFullWave
+ fullWaveLen
- 1 ; i
< * size
- 3 ; i
++){
1593 //top edge of wave = start of new wave
1594 if ( dest
[ i
]+ fc
< dest
[ i
+ 1 ] && dest
[ i
+ 1 ] >= dest
[ i
+ 2 ]){
1595 if ( waveStart
== 0 ) {
1598 avgWaveVal
= dest
[ i
+ 1 ];
1601 waveLenCnt
= waveEnd
- waveStart
;
1602 if ( waveLenCnt
> fc
){
1603 //this wave is a phase shift
1604 //PrintAndLog("DEBUG: phase shift at: %d, len: %d, nextClk: %d, i: %d, fc: %d",waveStart,waveLenCnt,lastClkBit+*clock-tol,i+1,fc);
1605 if ( i
+ 1 >= lastClkBit
+ * clock
- tol
){ //should be a clock bit
1607 dest
[ numBits
++] = curPhase
;
1608 lastClkBit
+= * clock
;
1609 } else if ( i
< lastClkBit
+ 10 + fc
){
1610 //noise after a phase shift - ignore
1611 } else { //phase shift before supposed to based on clock
1613 dest
[ numBits
++] = 7 ;
1615 } else if ( i
+ 1 > lastClkBit
+ * clock
+ tol
+ fc
){
1616 lastClkBit
+= * clock
; //no phase shift but clock bit
1617 dest
[ numBits
++] = curPhase
;
1618 } else if ( waveLenCnt
< fc
- 1 ) { //wave is smaller than field clock (shouldn't happen often)
1620 if ( errCnt2
> 101 ) return errCnt2
;
1626 avgWaveVal
+= dest
[ i
+ 1 ];
1632 int pskRawDemod ( uint8_t dest
[], size_t * size
, int * clock
, int * invert
) {
1634 return pskRawDemod_ext ( dest
, size
, clock
, invert
, & startIdx
);
1637 //**********************************************************************************************
1638 //-----------------Tag format detection section-------------------------------------------------
1639 //**********************************************************************************************
1642 // FSK Demod then try to locate an AWID ID
1643 int AWIDdemodFSK ( uint8_t * dest
, size_t * size
) {
1644 //make sure buffer has enough data
1645 if (* size
< 96 * 50 ) return - 1 ;
1647 if ( justNoise ( dest
, * size
)) return - 2 ;
1650 * size
= fskdemod ( dest
, * size
, 50 , 1 , 10 , 8 ); // fsk2a RF/50
1651 if (* size
< 96 ) return - 3 ; //did we get a good demod?
1653 uint8_t preamble
[] = { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 };
1654 size_t startIdx
= 0 ;
1655 uint8_t errChk
= preambleSearch ( dest
, preamble
, sizeof ( preamble
), size
, & startIdx
);
1656 if ( errChk
== 0 ) return - 4 ; //preamble not found
1657 if (* size
!= 96 ) return - 5 ;
1658 return ( int ) startIdx
;
1662 //takes 1s and 0s and searches for EM410x format - output EM ID
1663 uint8_t Em410xDecode ( uint8_t * BitStream
, size_t * size
, size_t * startIdx
, uint32_t * hi
, uint64_t * lo
)
1666 if (* size
< 64 ) return 0 ;
1667 if ( BitStream
[ 1 ]> 1 ) return 0 ; //allow only 1s and 0s
1669 // 111111111 bit pattern represent start of frame
1670 // include 0 in front to help get start pos
1671 uint8_t preamble
[] = { 0 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 };
1673 uint8_t FmtLen
= 10 ; // sets of 4 bits = end data
1675 errChk
= preambleSearch ( BitStream
, preamble
, sizeof ( preamble
), size
, startIdx
);
1676 if ( errChk
== 0 || (* size
!= 64 && * size
!= 128 ) ) return 0 ;
1677 if (* size
== 128 ) FmtLen
= 22 ; // 22 sets of 4 bits
1679 //skip last 4bit parity row for simplicity
1680 * size
= removeParity ( BitStream
, * startIdx
+ sizeof ( preamble
), 5 , 0 , FmtLen
* 5 );
1681 if (* size
== 40 ) { // std em410x format
1683 * lo
= (( uint64_t )( bytebits_to_byte ( BitStream
, 8 )) << 32 ) | ( bytebits_to_byte ( BitStream
+ 8 , 32 ));
1684 } else if (* size
== 88 ) { // long em format
1685 * hi
= ( bytebits_to_byte ( BitStream
, 24 ));
1686 * lo
= (( uint64_t )( bytebits_to_byte ( BitStream
+ 24 , 32 )) << 32 ) | ( bytebits_to_byte ( BitStream
+ 24 + 32 , 32 ));
1693 // Ask/Biphase Demod then try to locate an ISO 11784/85 ID
1694 // BitStream must contain previously askrawdemod and biphasedemoded data
1695 int FDXBdemodBI ( uint8_t * dest
, size_t * size
) {
1696 //make sure buffer has enough data
1697 if (* size
< 128 ) return - 1 ;
1699 size_t startIdx
= 0 ;
1700 uint8_t preamble
[] = { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 };
1702 uint8_t errChk
= preambleSearch ( dest
, preamble
, sizeof ( preamble
), size
, & startIdx
);
1703 if ( errChk
== 0 ) return - 2 ; //preamble not found
1704 return ( int ) startIdx
;
1708 // demod gProxIIDemod
1709 // error returns as -x
1710 // success returns start position in BitStream
1711 // BitStream must contain previously askrawdemod and biphasedemoded data
1712 int gProxII_Demod ( uint8_t BitStream
[], size_t * size
) {
1714 uint8_t preamble
[] = { 1 , 1 , 1 , 1 , 1 , 0 };
1716 uint8_t errChk
= preambleSearch ( BitStream
, preamble
, sizeof ( preamble
), size
, & startIdx
);
1717 if ( errChk
== 0 ) return - 3 ; //preamble not found
1718 if (* size
!= 96 ) return - 2 ; //should have found 96 bits
1719 //check first 6 spacer bits to verify format
1720 if (! BitStream
[ startIdx
+ 5 ] && ! BitStream
[ startIdx
+ 10 ] && ! BitStream
[ startIdx
+ 15 ] && ! BitStream
[ startIdx
+ 20 ] && ! BitStream
[ startIdx
+ 25 ] && ! BitStream
[ startIdx
+ 30 ]){
1721 //confirmed proper separator bits found
1722 //return start position
1723 return ( int ) startIdx
;
1725 return - 5 ; //spacer bits not found - not a valid gproxII
1728 // loop to get raw HID waveform then FSK demodulate the TAG ID from it
1729 int HIDdemodFSK ( uint8_t * dest
, size_t * size
, uint32_t * hi2
, uint32_t * hi
, uint32_t * lo
) {
1730 if ( justNoise ( dest
, * size
)) return - 1 ;
1732 size_t numStart
= 0 , size2
=* size
, startIdx
= 0 ;
1734 * size
= fskdemod ( dest
, size2
, 50 , 1 , 10 , 8 ); //fsk2a
1735 if (* size
< 96 * 2 ) return - 2 ;
1736 // 00011101 bit pattern represent start of frame, 01 pattern represents a 0 and 10 represents a 1
1737 uint8_t preamble
[] = { 0 , 0 , 0 , 1 , 1 , 1 , 0 , 1 };
1738 // find bitstring in array
1739 uint8_t errChk
= preambleSearch ( dest
, preamble
, sizeof ( preamble
), size
, & startIdx
);
1740 if ( errChk
== 0 ) return - 3 ; //preamble not found
1742 numStart
= startIdx
+ sizeof ( preamble
);
1743 // final loop, go over previously decoded FSK data and manchester decode into usable tag ID
1744 for ( size_t idx
= numStart
; ( idx
- numStart
) < * size
- sizeof ( preamble
); idx
+= 2 ){
1745 if ( dest
[ idx
] == dest
[ idx
+ 1 ]){
1746 return - 4 ; //not manchester data
1748 * hi2
= (* hi2
<< 1 )|(* hi
>> 31 );
1749 * hi
= (* hi
<< 1 )|(* lo
>> 31 );
1750 //Then, shift in a 0 or one into low
1751 if ( dest
[ idx
] && ! dest
[ idx
+ 1 ]) // 1 0
1756 return ( int ) startIdx
;
1759 int IOdemodFSK ( uint8_t * dest
, size_t size
) {
1760 if ( justNoise ( dest
, size
)) return - 1 ;
1761 //make sure buffer has data
1762 if ( size
< 66 * 64 ) return - 2 ;
1764 size
= fskdemod ( dest
, size
, 64 , 1 , 10 , 8 ); // FSK2a RF/64
1765 if ( size
< 65 ) return - 3 ; //did we get a good demod?
1767 //0 10 20 30 40 50 60
1769 //01234567 8 90123456 7 89012345 6 78901234 5 67890123 4 56789012 3 45678901 23
1770 //-----------------------------------------------------------------------------
1771 //00000000 0 11110000 1 facility 1 version* 1 code*one 1 code*two 1 ???????? 11
1773 //XSF(version)facility:codeone+codetwo
1775 size_t startIdx
= 0 ;
1776 uint8_t preamble
[] = { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 };
1777 uint8_t errChk
= preambleSearch ( dest
, preamble
, sizeof ( preamble
), & size
, & startIdx
);
1778 if ( errChk
== 0 ) return - 4 ; //preamble not found
1780 if (! dest
[ startIdx
+ 8 ] && dest
[ startIdx
+ 17 ]== 1 && dest
[ startIdx
+ 26 ]== 1 && dest
[ startIdx
+ 35 ]== 1 && dest
[ startIdx
+ 44 ]== 1 && dest
[ startIdx
+ 53 ]== 1 ){
1781 //confirmed proper separator bits found
1782 //return start position
1783 return ( int ) startIdx
;
1788 // redesigned by marshmellow adjusted from existing decode functions
1789 // indala id decoding - only tested on 26 bit tags, but attempted to make it work for more
1790 int indala26decode ( uint8_t * bitStream
, size_t * size
, uint8_t * invert
) {
1791 //26 bit 40134 format (don't know other formats)
1792 uint8_t preamble
[] = { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 };
1793 uint8_t preamble_i
[] = { 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 0 };
1794 size_t startidx
= 0 ;
1795 if (! preambleSearch ( bitStream
, preamble
, sizeof ( preamble
), size
, & startidx
)){
1796 // if didn't find preamble try again inverting
1797 if (! preambleSearch ( bitStream
, preamble_i
, sizeof ( preamble_i
), size
, & startidx
)) return - 1 ;
1800 if (* size
!= 64 && * size
!= 224 ) return - 2 ;
1802 for ( size_t i
= startidx
; i
< * size
; i
++)
1805 return ( int ) startidx
;
1808 // loop to get raw paradox waveform then FSK demodulate the TAG ID from it
1809 int ParadoxdemodFSK ( uint8_t * dest
, size_t * size
, uint32_t * hi2
, uint32_t * hi
, uint32_t * lo
) {
1810 if ( justNoise ( dest
, * size
)) return - 1 ;
1812 size_t numStart
= 0 , size2
=* size
, startIdx
= 0 ;
1814 * size
= fskdemod ( dest
, size2
, 50 , 1 , 10 , 8 ); //fsk2a
1815 if (* size
< 96 ) return - 2 ;
1817 // 00001111 bit pattern represent start of frame, 01 pattern represents a 0 and 10 represents a 1
1818 uint8_t preamble
[] = { 0 , 0 , 0 , 0 , 1 , 1 , 1 , 1 };
1820 uint8_t errChk
= preambleSearch ( dest
, preamble
, sizeof ( preamble
), size
, & startIdx
);
1821 if ( errChk
== 0 ) return - 3 ; //preamble not found
1823 numStart
= startIdx
+ sizeof ( preamble
);
1824 // final loop, go over previously decoded FSK data and manchester decode into usable tag ID
1825 for ( size_t idx
= numStart
; ( idx
- numStart
) < * size
- sizeof ( preamble
); idx
+= 2 ){
1826 if ( dest
[ idx
] == dest
[ idx
+ 1 ])
1827 return - 4 ; //not manchester data
1828 * hi2
= (* hi2
<< 1 )|(* hi
>> 31 );
1829 * hi
= (* hi
<< 1 )|(* lo
>> 31 );
1830 //Then, shift in a 0 or one into low
1831 if ( dest
[ idx
] && ! dest
[ idx
+ 1 ]) // 1 0
1836 return ( int ) startIdx
;
1839 // find presco preamble 0x10D in already demoded data
1840 int PrescoDemod ( uint8_t * dest
, size_t * size
) {
1841 //make sure buffer has data
1842 if (* size
< 64 * 2 ) return - 2 ;
1844 size_t startIdx
= 0 ;
1845 uint8_t preamble
[] = { 1 , 0 , 0 , 0 , 0 , 1 , 1 , 0 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 };
1846 uint8_t errChk
= preambleSearch ( dest
, preamble
, sizeof ( preamble
), size
, & startIdx
);
1847 if ( errChk
== 0 ) return - 4 ; //preamble not found
1848 //return start position
1849 return ( int ) startIdx
;
1853 // FSK Demod then try to locate a Farpointe Data (pyramid) ID
1854 int PyramiddemodFSK ( uint8_t * dest
, size_t * size
) {
1855 //make sure buffer has data
1856 if (* size
< 128 * 50 ) return - 5 ;
1858 //test samples are not just noise
1859 if ( justNoise ( dest
, * size
)) return - 1 ;
1862 * size
= fskdemod ( dest
, * size
, 50 , 1 , 10 , 8 ); // fsk2a RF/50
1863 if (* size
< 128 ) return - 2 ; //did we get a good demod?
1865 uint8_t preamble
[] = { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 };
1866 size_t startIdx
= 0 ;
1867 uint8_t errChk
= preambleSearch ( dest
, preamble
, sizeof ( preamble
), size
, & startIdx
);
1868 if ( errChk
== 0 ) return - 4 ; //preamble not found
1869 if (* size
!= 128 ) return - 3 ;
1870 return ( int ) startIdx
;
1874 // find viking preamble 0xF200 in already demoded data
1875 int VikingDemod_AM ( uint8_t * dest
, size_t * size
) {
1876 //make sure buffer has data
1877 if (* size
< 64 * 2 ) return - 2 ;
1879 size_t startIdx
= 0 ;
1880 uint8_t preamble
[] = { 1 , 1 , 1 , 1 , 0 , 0 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 };
1881 uint8_t errChk
= preambleSearch ( dest
, preamble
, sizeof ( preamble
), size
, & startIdx
);
1882 if ( errChk
== 0 ) return - 4 ; //preamble not found
1883 uint32_t checkCalc
= bytebits_to_byte ( dest
+ startIdx
, 8 ) ^ bytebits_to_byte ( dest
+ startIdx
+ 8 , 8 ) ^ bytebits_to_byte ( dest
+ startIdx
+ 16 , 8 )
1884 ^ bytebits_to_byte ( dest
+ startIdx
+ 24 , 8 ) ^ bytebits_to_byte ( dest
+ startIdx
+ 32 , 8 ) ^ bytebits_to_byte ( dest
+ startIdx
+ 40 , 8 )
1885 ^ bytebits_to_byte ( dest
+ startIdx
+ 48 , 8 ) ^ bytebits_to_byte ( dest
+ startIdx
+ 56 , 8 );
1886 if ( checkCalc
!= 0xA8 ) return - 5 ;
1887 if (* size
!= 64 ) return - 6 ;
1888 //return start position
1889 return ( int ) startIdx
;
1893 // find Visa2000 preamble in already demoded data
1894 int Visa2kDemod_AM ( uint8_t * dest
, size_t * size
) {
1895 if (* size
< 96 ) return - 1 ; //make sure buffer has data
1896 size_t startIdx
= 0 ;
1897 uint8_t preamble
[] = { 0 , 1 , 0 , 1 , 0 , 1 , 1 , 0 , 0 , 1 , 0 , 0 , 1 , 0 , 0 , 1 , 0 , 1 , 0 , 1 , 0 , 0 , 1 , 1 , 0 , 0 , 1 , 1 , 0 , 0 , 1 , 0 };
1898 if ( preambleSearch ( dest
, preamble
, sizeof ( preamble
), size
, & startIdx
) == 0 )
1899 return - 2 ; //preamble not found
1900 if (* size
!= 96 ) return - 3 ; //wrong demoded size
1901 //return start position
1902 return ( int ) startIdx
;