]>
git.zerfleddert.de Git - proxmark3-svn/blob - common/lfdemod.c
a6e215c90a2321316dbc71675a24f1f319cf9c16
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
11 // LF Demod functions are placed here to allow the flexability to use client or
12 // device side. Most BUT NOT ALL of these functions are currenlty safe for
13 // device side use currently. (DetectST for example...)
15 // There are likely many improvements to the code that could be made, please
16 // make suggestions...
18 // There are 4 main sections of code below:
20 // for general utilities used by multiple other functions
21 // Modulation Demods &/or Decoding Section:
22 // for main general modulation demodulating and encoding decoding code.
23 // Clock / Bitrate Detection Section:
24 // for clock detection functions for each modulation
25 // Tag format detection section:
26 // for detection of specific tag formats within demodulated data
29 //-----------------------------------------------------------------------------
35 //to allow debug print calls when used not on device
36 void dummy ( char * fmt
, ...){}
40 #include "cmdparser.h"
42 #define prnt PrintAndLog
44 uint8_t g_debugMode
= 0 ;
48 //---------------------------------Utilities Section--------------------------------------------------
50 uint8_t justNoise ( uint8_t * BitStream
, size_t size
)
52 static const uint8_t THRESHOLD
= 123 ;
53 //test samples are not just noise
54 uint8_t justNoise1
= 1 ;
55 for ( size_t idx
= 0 ; idx
< size
&& justNoise1
; idx
++){
56 justNoise1
= BitStream
[ idx
] < THRESHOLD
;
62 //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
63 int getHiLo ( uint8_t * BitStream
, size_t size
, int * high
, int * low
, uint8_t fuzzHi
, uint8_t fuzzLo
)
67 // get high and low thresholds
68 for ( size_t i
= 0 ; i
< size
; i
++){
69 if ( BitStream
[ i
] > * high
) * high
= BitStream
[ i
];
70 if ( BitStream
[ i
] < * low
) * low
= BitStream
[ i
];
72 if (* high
< 123 ) return - 1 ; // just noise
73 * high
= ((* high
- 128 )* fuzzHi
+ 12800 )/ 100 ;
74 * low
= ((* low
- 128 )* fuzzLo
+ 12800 )/ 100 ;
79 // pass bits to be tested in bits, length bits passed in bitLen, and parity type (even=0 | odd=1) in pType
80 // returns 1 if passed
81 uint8_t parityTest ( uint32_t bits
, uint8_t bitLen
, uint8_t pType
)
84 for ( uint8_t i
= 0 ; i
< bitLen
; i
++){
85 ans
^= (( bits
>> i
) & 1 );
87 if ( g_debugMode
) prnt ( "DEBUG: ans: %d, ptype: %d, bits: %08X" , ans
, pType
, bits
);
88 return ( ans
== pType
);
92 // takes a array of binary values, start position, length of bits per parity (includes parity bit),
93 // Parity Type (1 for odd; 0 for even; 2 for Always 1's; 3 for Always 0's), and binary Length (length to run)
94 size_t removeParity ( uint8_t * BitStream
, size_t startIdx
, uint8_t pLen
, uint8_t pType
, size_t bLen
)
96 uint32_t parityWd
= 0 ;
97 size_t j
= 0 , bitCnt
= 0 ;
98 for ( int word
= 0 ; word
< ( bLen
); word
+= pLen
) {
99 for ( int bit
= 0 ; bit
< pLen
; bit
++) {
100 parityWd
= ( parityWd
<< 1 ) | BitStream
[ startIdx
+ word
+ bit
];
101 BitStream
[ j
++] = ( BitStream
[ startIdx
+ word
+ bit
]);
103 if ( word
+ pLen
> bLen
) break ;
105 j
--; // overwrite parity with next data
106 // if parity fails then return 0
108 case 3 : if ( BitStream
[ j
]== 1 ) { return 0 ;} break ; //should be 0 spacer bit
109 case 2 : if ( BitStream
[ j
]== 0 ) { return 0 ;} break ; //should be 1 spacer bit
110 default : if ( parityTest ( parityWd
, pLen
, pType
) == 0 ) { return 0 ;} break ; //test parity
115 // if we got here then all the parities passed
116 //return ID start index and size
121 // takes a array of binary values, length of bits per parity (includes parity bit),
122 // Parity Type (1 for odd; 0 for even; 2 Always 1's; 3 Always 0's), and binary Length (length to run)
123 // Make sure *dest is long enough to store original sourceLen + #_of_parities_to_be_added
124 size_t addParity ( uint8_t * BitSource
, uint8_t * dest
, uint8_t sourceLen
, uint8_t pLen
, uint8_t pType
)
126 uint32_t parityWd
= 0 ;
127 size_t j
= 0 , bitCnt
= 0 ;
128 for ( int word
= 0 ; word
< sourceLen
; word
+= pLen
- 1 ) {
129 for ( int bit
= 0 ; bit
< pLen
- 1 ; bit
++){
130 parityWd
= ( parityWd
<< 1 ) | BitSource
[ word
+ bit
];
131 dest
[ j
++] = ( BitSource
[ word
+ bit
]);
133 // if parity fails then return 0
135 case 3 : dest
[ j
++]= 0 ; break ; // marker bit which should be a 0
136 case 2 : dest
[ j
++]= 1 ; break ; // marker bit which should be a 1
138 dest
[ j
++] = parityTest ( parityWd
, pLen
- 1 , pType
) ^ 1 ;
144 // if we got here then all the parities passed
145 //return ID start index and size
149 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
)
164 for ( int i
= 0 ; i
< numbits
; i
++)
166 num
= ( num
<< 1 ) | *( src
+ ( numbits
-( i
+ 1 )));
172 //search for given preamble in given BitStream and return success=1 or fail=0 and startIndex and length
173 uint8_t preambleSearch ( uint8_t * BitStream
, uint8_t * preamble
, size_t pLen
, size_t * size
, size_t * startIdx
)
175 return ( preambleSearchEx ( BitStream
, preamble
, pLen
, size
, startIdx
, false )) ? 1 : 0 ;
178 // 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
179 // fineone does not look for a repeating preamble for em4x05/4x69 sends preamble once, so look for it once in the first pLen bits
180 bool preambleSearchEx ( uint8_t * BitStream
, uint8_t * preamble
, size_t pLen
, size_t * size
, size_t * startIdx
, bool findone
) {
181 // Sanity check. If preamble length is bigger than bitstream length.
182 if ( * size
<= pLen
) return false ;
184 uint8_t foundCnt
= 0 ;
185 for ( size_t idx
= 0 ; idx
< * size
- pLen
; idx
++) {
186 if ( memcmp ( BitStream
+ idx
, preamble
, pLen
) == 0 ) {
190 if ( g_debugMode
) prnt ( "DEBUG: preamble found at %u" , idx
);
192 if ( findone
) return true ;
193 } else if ( foundCnt
== 2 ) {
194 * size
= idx
- * startIdx
;
202 // find start of modulating data (for fsk and psk) in case of beginning noise or slow chip startup.
203 size_t findModStart ( uint8_t dest
[], size_t size
, uint8_t threshold_value
, uint8_t expWaveSize
) {
205 size_t waveSizeCnt
= 0 ;
206 uint8_t thresholdCnt
= 0 ;
207 bool isAboveThreshold
= dest
[ i
++] >= threshold_value
;
208 for (; i
< size
- 20 ; i
++ ) {
209 if ( dest
[ i
] < threshold_value
&& isAboveThreshold
) {
211 if ( thresholdCnt
> 2 && waveSizeCnt
< expWaveSize
+ 1 ) break ;
212 isAboveThreshold
= false ;
214 } else if ( dest
[ i
] >= threshold_value
&& ! isAboveThreshold
) {
216 if ( thresholdCnt
> 2 && waveSizeCnt
< expWaveSize
+ 1 ) break ;
217 isAboveThreshold
= true ;
222 if ( thresholdCnt
> 10 ) break ;
224 if ( g_debugMode
== 2 ) prnt ( "DEBUG: threshold Count reached at %u, count: %u" , i
, thresholdCnt
);
229 //amplify based on ask edge detection - not accurate enough to use all the time
230 void askAmp ( uint8_t * BitStream
, size_t size
) {
232 for ( size_t i
= 1 ; i
< size
; i
++){
233 if ( BitStream
[ i
]- BitStream
[ i
- 1 ]>= 30 ) //large jump up
235 else if ( BitStream
[ i
- 1 ]- BitStream
[ i
]>= 20 ) //large jump down
238 BitStream
[ i
- 1 ] = Last
;
243 uint32_t manchesterEncode2Bytes ( uint16_t datain
) {
246 for ( uint8_t i
= 0 ; i
< 16 ; i
++) {
247 curBit
= ( datain
>> ( 15 - i
) & 1 );
248 output
|= ( 1 <<((( 15 - i
)* 2 )+ curBit
));
254 //encode binary data into binary manchester
255 //NOTE: BitStream must have double the size available in memory to do the swap
256 int ManchesterEncode ( uint8_t * BitStream
, size_t size
) {
257 size_t modIdx
= size
, i
= 0 ;
258 if ( size
> modIdx
) return - 1 ;
259 for ( size_t idx
= 0 ; idx
< size
; idx
++){
260 BitStream
[ idx
+ modIdx
++] = BitStream
[ idx
];
261 BitStream
[ idx
+ modIdx
++] = BitStream
[ idx
]^ 1 ;
263 for (; i
<( size
* 2 ); i
++){
264 BitStream
[ i
] = BitStream
[ i
+ size
];
269 //------------------------------Modulation Demods &/or Decoding Section------------------------------------------------------
272 //attempt to identify a Sequence Terminator in ASK modulated raw wave
273 bool DetectST_ext ( uint8_t buffer
[], size_t * size
, int * foundclock
, size_t * ststart
, size_t * stend
) {
274 size_t bufsize
= * size
;
275 //need to loop through all samples and identify our clock, look for the ST pattern
276 uint8_t fndClk
[] = { 8 , 16 , 32 , 40 , 50 , 64 , 128 };
279 int i
, j
, skip
, start
, end
, low
, high
, minClk
, waveStart
;
280 bool complete
= false ;
281 int tmpbuff
[ bufsize
/ 32 ]; //guess rf/32 clock, if click is smaller we will only have room for a fraction of the samples captured
282 int waveLen
[ bufsize
/ 32 ]; // if clock is larger then we waste memory in array size that is not needed...
283 size_t testsize
= ( bufsize
< 512 ) ? bufsize
: 512 ;
286 memset ( tmpbuff
, 0 , sizeof ( tmpbuff
));
288 if ( getHiLo ( buffer
, testsize
, & high
, & low
, 80 , 80 ) == - 1 ) {
289 if ( g_debugMode
== 2 ) prnt ( "DEBUG STT: just noise detected - quitting" );
290 return false ; //just noise
295 // get to first full low to prime loop and skip incomplete first pulse
296 while (( buffer
[ i
] < high
) && ( i
< bufsize
))
298 while (( buffer
[ i
] > low
) && ( i
< bufsize
))
302 // populate tmpbuff buffer with pulse lengths
303 while ( i
< bufsize
) {
304 // measure from low to low
305 while (( buffer
[ i
] > low
) && ( i
< bufsize
))
308 while (( buffer
[ i
] < high
) && ( i
< bufsize
))
310 //first high point for this wave
312 while (( buffer
[ i
] > low
) && ( i
< bufsize
))
314 if ( j
>= ( bufsize
/ 32 )) {
317 waveLen
[ j
] = i
- waveStart
; //first high to first low
318 tmpbuff
[ j
++] = i
- start
;
319 if ( i
- start
< minClk
&& i
< bufsize
) {
323 // set clock - might be able to get this externally and remove this work...
325 for ( uint8_t clkCnt
= 0 ; clkCnt
< 7 ; clkCnt
++) {
326 tol
= fndClk
[ clkCnt
]/ 8 ;
327 if ( minClk
>= fndClk
[ clkCnt
]- tol
&& minClk
<= fndClk
[ clkCnt
]+ 1 ) {
332 // clock not found - ERROR
334 if ( g_debugMode
== 2 ) prnt ( "DEBUG STT: clock not found - quitting" );
341 // look for Sequence Terminator - should be pulses of clk*(1 or 1.5), clk*2, clk*(1.5 or 2)
343 for ( i
= 0 ; i
< j
- 4 ; ++ i
) {
345 if ( tmpbuff
[ i
] >= clk
* 1 - tol
&& tmpbuff
[ i
] <= ( clk
* 2 )+ tol
&& waveLen
[ i
] < clk
+ tol
) { //1 to 2 clocks depending on 2 bits prior
346 if ( tmpbuff
[ i
+ 1 ] >= clk
* 2 - tol
&& tmpbuff
[ i
+ 1 ] <= clk
* 2 + tol
&& waveLen
[ i
+ 1 ] > clk
* 3 / 2 - tol
) { //2 clocks and wave size is 1 1/2
347 if ( tmpbuff
[ i
+ 2 ] >= ( clk
* 3 )/ 2 - tol
&& tmpbuff
[ i
+ 2 ] <= clk
* 2 + tol
&& waveLen
[ i
+ 2 ] > clk
- tol
) { //1 1/2 to 2 clocks and at least one full clock wave
348 if ( tmpbuff
[ i
+ 3 ] >= clk
* 1 - tol
&& tmpbuff
[ i
+ 3 ] <= clk
* 2 + tol
) { //1 to 2 clocks for end of ST + first bit
356 // first ST not found - ERROR
358 if ( g_debugMode
== 2 ) prnt ( "DEBUG STT: first STT not found - quitting" );
361 if ( g_debugMode
== 2 ) prnt ( "DEBUG STT: first STT found at: %d, j=%d" , start
, j
);
363 if ( waveLen
[ i
+ 2 ] > clk
* 1 + tol
)
368 // skip over the remainder of ST
369 skip
+= clk
* 7 / 2 ; //3.5 clocks from tmpbuff[i] = end of st - also aligns for ending point
371 // now do it again to find the end
373 for ( i
+= 3 ; i
< j
- 4 ; ++ i
) {
375 if ( tmpbuff
[ i
] >= clk
* 1 - tol
&& tmpbuff
[ i
] <= ( clk
* 2 )+ tol
&& waveLen
[ i
] < clk
+ tol
) { //1 to 2 clocks depending on 2 bits prior
376 if ( tmpbuff
[ i
+ 1 ] >= clk
* 2 - tol
&& tmpbuff
[ i
+ 1 ] <= clk
* 2 + tol
&& waveLen
[ i
+ 1 ] > clk
* 3 / 2 - tol
) { //2 clocks and wave size is 1 1/2
377 if ( tmpbuff
[ i
+ 2 ] >= ( clk
* 3 )/ 2 - tol
&& tmpbuff
[ i
+ 2 ] <= clk
* 2 + tol
&& waveLen
[ i
+ 2 ] > clk
- tol
) { //1 1/2 to 2 clocks and at least one full clock wave
378 if ( tmpbuff
[ i
+ 3 ] >= clk
* 1 - tol
&& tmpbuff
[ i
+ 3 ] <= clk
* 2 + tol
) { //1 to 2 clocks for end of ST + first bit
387 //didn't find second ST - ERROR
389 if ( g_debugMode
== 2 ) prnt ( "DEBUG STT: second STT not found - quitting" );
392 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
);
393 //now begin to trim out ST so we can use normal demod cmds
395 size_t datalen
= end
- start
;
396 // check validity of datalen (should be even clock increments) - use a tolerance of up to 1/8th a clock
397 if ( clk
- ( datalen
% clk
) <= clk
/ 8 ) {
398 // padd the amount off - could be problematic... but shouldn't happen often
399 datalen
+= clk
- ( datalen
% clk
);
400 } else if ( ( datalen
% clk
) <= clk
/ 8 ) {
401 // padd the amount off - could be problematic... but shouldn't happen often
402 datalen
-= datalen
% clk
;
404 if ( g_debugMode
== 2 ) prnt ( "DEBUG STT: datalen not divisible by clk: %u %% %d = %d - quitting" , datalen
, clk
, datalen
% clk
);
407 // if datalen is less than one t55xx block - ERROR
408 if ( datalen
/ clk
< 8 * 4 ) {
409 if ( g_debugMode
== 2 ) prnt ( "DEBUG STT: datalen is less than 1 full t55xx block - quitting" );
412 size_t dataloc
= start
;
413 if ( buffer
[ dataloc
-( clk
* 4 )-( clk
/ 8 )] <= low
&& buffer
[ dataloc
] <= low
&& buffer
[ dataloc
-( clk
* 4 )] >= high
) {
414 //we have low drift (and a low just before the ST and a low just after the ST) - compensate by backing up the start
415 for ( i
= 0 ; i
<= ( clk
/ 8 ); ++ i
) {
416 if ( buffer
[ dataloc
- ( clk
* 4 ) - i
] <= low
) {
425 if ( g_debugMode
== 2 ) prnt ( "DEBUG STT: Starting STT trim - start: %d, datalen: %d " , dataloc
, datalen
);
426 bool firstrun
= true ;
427 // warning - overwriting buffer given with raw wave data with ST removed...
428 while ( dataloc
< bufsize
-( clk
/ 2 ) ) {
429 //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)
430 if ( buffer
[ dataloc
]< high
&& buffer
[ dataloc
]> low
&& buffer
[ dataloc
+ 3 ]< high
&& buffer
[ dataloc
+ 3 ]> low
) {
431 for ( i
= 0 ; i
< clk
/ 2 - tol
; ++ i
) {
432 buffer
[ dataloc
+ i
] = high
+ 5 ;
434 } //test for single sample outlier (high between two lows) in the case of very strong waves
435 if ( buffer
[ dataloc
] >= high
&& buffer
[ dataloc
+ 2 ] <= low
) {
436 buffer
[ dataloc
] = buffer
[ dataloc
+ 2 ];
437 buffer
[ dataloc
+ 1 ] = buffer
[ dataloc
+ 2 ];
441 * ststart
= dataloc
-( clk
* 4 );
444 for ( i
= 0 ; i
< datalen
; ++ i
) {
445 if ( i
+ newloc
< bufsize
) {
446 if ( i
+ newloc
< dataloc
)
447 buffer
[ i
+ newloc
] = buffer
[ dataloc
];
453 //skip next ST - we just assume it will be there from now on...
454 if ( g_debugMode
== 2 ) prnt ( "DEBUG STT: skipping STT at %d to %d" , dataloc
, dataloc
+( clk
* 4 ));
460 bool DetectST ( uint8_t buffer
[], size_t * size
, int * foundclock
) {
461 size_t ststart
= 0 , stend
= 0 ;
462 return DetectST_ext ( buffer
, size
, foundclock
, & ststart
, & stend
);
466 //take 01 or 10 = 1 and 11 or 00 = 0
467 //check for phase errors - should never have 111 or 000 should be 01001011 or 10110100 for 1010
468 //decodes biphase or if inverted it is AKA conditional dephase encoding AKA differential manchester encoding
469 int BiphaseRawDecode ( uint8_t * BitStream
, size_t * size
, int offset
, int invert
) {
473 uint16_t MaxBits
= 512 ;
474 //if not enough samples - error
475 if (* size
< 51 ) return - 1 ;
476 //check for phase change faults - skip one sample if faulty
477 uint8_t offsetA
= 1 , offsetB
= 1 ;
479 if ( BitStream
[ i
+ 1 ]== BitStream
[ i
+ 2 ]) offsetA
= 0 ;
480 if ( BitStream
[ i
+ 2 ]== BitStream
[ i
+ 3 ]) offsetB
= 0 ;
482 if (! offsetA
&& offsetB
) offset
++;
483 for ( i
= offset
; i
<* size
- 3 ; i
+= 2 ){
484 //check for phase error
485 if ( BitStream
[ i
+ 1 ]== BitStream
[ i
+ 2 ]) {
486 BitStream
[ bitnum
++]= 7 ;
489 if (( BitStream
[ i
]== 1 && BitStream
[ i
+ 1 ]== 0 ) || ( BitStream
[ i
]== 0 && BitStream
[ i
+ 1 ]== 1 )){
490 BitStream
[ bitnum
++]= 1 ^ invert
;
491 } else if (( BitStream
[ i
]== 0 && BitStream
[ i
+ 1 ]== 0 ) || ( BitStream
[ i
]== 1 && BitStream
[ i
+ 1 ]== 1 )){
492 BitStream
[ bitnum
++]= invert
;
494 BitStream
[ bitnum
++]= 7 ;
497 if ( bitnum
> MaxBits
) break ;
504 //take 10 and 01 and manchester decode
505 //run through 2 times and take least errCnt
506 int manrawdecode ( uint8_t * BitStream
, size_t * size
, uint8_t invert
, uint8_t * alignPos
) {
507 uint16_t bitnum
= 0 , MaxBits
= 512 , errCnt
= 0 ;
509 uint16_t bestErr
= 1000 , bestRun
= 0 ;
510 if (* size
< 16 ) return - 1 ;
511 //find correct start position [alignment]
512 for ( ii
= 0 ; ii
< 2 ;++ ii
){
513 for ( i
= ii
; i
<* size
- 3 ; i
+= 2 )
514 if ( BitStream
[ i
]== BitStream
[ i
+ 1 ])
525 for ( i
= bestRun
; i
< * size
- 3 ; i
+= 2 ){
526 if ( BitStream
[ i
] == 1 && ( BitStream
[ i
+ 1 ] == 0 )){
527 BitStream
[ bitnum
++]= invert
;
528 } else if (( BitStream
[ i
] == 0 ) && BitStream
[ i
+ 1 ] == 1 ){
529 BitStream
[ bitnum
++]= invert
^ 1 ;
531 BitStream
[ bitnum
++]= 7 ;
533 if ( bitnum
> MaxBits
) break ;
540 // to detect a wave that has heavily clipped (clean) samples
541 uint8_t DetectCleanAskWave ( uint8_t dest
[], size_t size
, uint8_t high
, uint8_t low
) {
542 bool allArePeaks
= true ;
544 size_t loopEnd
= 512 + 160 ;
545 if ( loopEnd
> size
) loopEnd
= size
;
546 for ( size_t i
= 160 ; i
< loopEnd
; i
++){
547 if ( dest
[ i
]> low
&& dest
[ i
]< high
)
553 if ( cntPeaks
> 300 ) return true ;
559 //demodulates strong heavily clipped samples
560 int cleanAskRawDemod ( uint8_t * BinStream
, size_t * size
, int clk
, int invert
, int high
, int low
, int * startIdx
)
563 size_t bitCnt
= 0 , smplCnt
= 1 , errCnt
= 0 ;
564 bool waveHigh
= ( BinStream
[ 0 ] >= high
);
565 for ( size_t i
= 1 ; i
< * size
; i
++){
566 if ( BinStream
[ i
] >= high
&& waveHigh
){
568 } else if ( BinStream
[ i
] <= low
&& ! waveHigh
){
570 } else { //transition
571 if (( BinStream
[ i
] >= high
&& ! waveHigh
) || ( BinStream
[ i
] <= low
&& waveHigh
)){
572 if ( smplCnt
> clk
-( clk
/ 4 )- 1 ) { //full clock
573 if ( smplCnt
> clk
+ ( clk
/ 4 )+ 1 ) { //too many samples
575 if ( g_debugMode
== 2 ) prnt ( "DEBUG ASK: Modulation Error at: %u" , i
);
576 BinStream
[ bitCnt
++] = 7 ;
577 } else if ( waveHigh
) {
578 BinStream
[ bitCnt
++] = invert
;
579 BinStream
[ bitCnt
++] = invert
;
580 } else if (! waveHigh
) {
581 BinStream
[ bitCnt
++] = invert
^ 1 ;
582 BinStream
[ bitCnt
++] = invert
^ 1 ;
584 if (* startIdx
== 0 ) * startIdx
= i
- clk
;
585 waveHigh
= ! waveHigh
;
587 } else if ( smplCnt
> ( clk
/ 2 ) - ( clk
/ 4 )- 1 ) { //half clock
589 BinStream
[ bitCnt
++] = invert
;
590 } else if (! waveHigh
) {
591 BinStream
[ bitCnt
++] = invert
^ 1 ;
593 if (* startIdx
== 0 ) * startIdx
= i
-( clk
/ 2 );
594 waveHigh
= ! waveHigh
;
598 //transition bit oops
600 } else { //haven't hit new high or new low yet
610 //attempts to demodulate ask modulations, askType == 0 for ask/raw, askType==1 for ask/manchester
611 int askdemod_ext ( uint8_t * BinStream
, size_t * size
, int * clk
, int * invert
, int maxErr
, uint8_t amp
, uint8_t askType
, int * startIdx
) {
612 if (* size
== 0 ) return - 1 ;
613 int start
= DetectASKClock ( BinStream
, * size
, clk
, maxErr
); //clock default
614 if (* clk
== 0 || start
< 0 ) return - 3 ;
615 if (* invert
!= 1 ) * invert
= 0 ;
616 if ( amp
== 1 ) askAmp ( BinStream
, * size
);
617 if ( g_debugMode
== 2 ) prnt ( "DEBUG ASK: clk %d, beststart %d, amp %d" , * clk
, start
, amp
);
619 //start pos from detect ask clock is 1/2 clock offset
620 // NOTE: can be negative (demod assumes rest of wave was there)
621 * startIdx
= start
- (* clk
/ 2 );
622 uint8_t initLoopMax
= 255 ;
623 if ( initLoopMax
> * size
) initLoopMax
= * size
;
624 // Detect high and lows
625 //25% clip in case highs and lows aren't clipped [marshmellow]
627 if ( getHiLo ( BinStream
, initLoopMax
, & high
, & low
, 75 , 75 ) < 1 )
628 return - 2 ; //just noise
631 // if clean clipped waves detected run alternate demod
632 if ( DetectCleanAskWave ( BinStream
, * size
, high
, low
)) {
633 if ( g_debugMode
== 2 ) prnt ( "DEBUG ASK: Clean Wave Detected - using clean wave demod" );
634 errCnt
= cleanAskRawDemod ( BinStream
, size
, * clk
, * invert
, high
, low
, startIdx
);
635 if ( askType
) { //askman
636 uint8_t alignPos
= 0 ;
637 errCnt
= manrawdecode ( BinStream
, size
, 0 , & alignPos
);
638 * startIdx
+= * clk
/ 2 * alignPos
;
639 if ( g_debugMode
) prnt ( "DEBUG ASK CLEAN: startIdx %i, alignPos %u" , * startIdx
, alignPos
);
645 if ( g_debugMode
) prnt ( "DEBUG ASK WEAK: startIdx %i" , * startIdx
);
646 if ( g_debugMode
== 2 ) prnt ( "DEBUG ASK: Weak Wave Detected - using weak wave demod" );
648 int lastBit
; //set first clock check - can go negative
649 size_t i
, bitnum
= 0 ; //output counter
651 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
652 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
653 size_t MaxBits
= 3072 ; //max bits to collect
654 lastBit
= start
- * clk
;
656 for ( i
= start
; i
< * size
; ++ i
) {
657 if ( i
- lastBit
>= * clk
- tol
){
658 if ( BinStream
[ i
] >= high
) {
659 BinStream
[ bitnum
++] = * invert
;
660 } else if ( BinStream
[ i
] <= low
) {
661 BinStream
[ bitnum
++] = * invert
^ 1 ;
662 } else if ( i
- lastBit
>= * clk
+ tol
) {
664 if ( g_debugMode
== 2 ) prnt ( "DEBUG ASK: Modulation Error at: %u" , i
);
665 BinStream
[ bitnum
++]= 7 ;
668 } else { //in tolerance - looking for peak
673 } else if ( i
- lastBit
>= (* clk
/ 2 - tol
) && ! midBit
&& ! askType
){
674 if ( BinStream
[ i
] >= high
) {
675 BinStream
[ bitnum
++] = * invert
;
676 } else if ( BinStream
[ i
] <= low
) {
677 BinStream
[ bitnum
++] = * invert
^ 1 ;
678 } else if ( i
- lastBit
>= * clk
/ 2 + tol
) {
679 BinStream
[ bitnum
] = BinStream
[ bitnum
- 1 ];
681 } else { //in tolerance - looking for peak
686 if ( bitnum
>= MaxBits
) break ;
692 int askdemod ( uint8_t * BinStream
, size_t * size
, int * clk
, int * invert
, int maxErr
, uint8_t amp
, uint8_t askType
) {
694 return askdemod_ext ( BinStream
, size
, clk
, invert
, maxErr
, amp
, askType
, & start
);
697 // by marshmellow - demodulate NRZ wave - requires a read with strong signal
698 // peaks invert bit (high=1 low=0) each clock cycle = 1 bit determined by last peak
699 int nrzRawDemod_ext ( uint8_t * dest
, size_t * size
, int * clk
, int * invert
, int * startIdx
) {
700 if ( justNoise ( dest
, * size
)) return - 1 ;
701 * clk
= DetectNRZClock ( dest
, * size
, * clk
);
702 if (* clk
== 0 ) return - 2 ;
703 size_t i
, gLen
= 4096 ;
704 if ( gLen
>* size
) gLen
= * size
- 20 ;
706 if ( getHiLo ( dest
, gLen
, & high
, & low
, 75 , 75 ) < 1 ) return - 3 ; //25% fuzz on high 25% fuzz on low
709 //convert wave samples to 1's and 0's
710 for ( i
= 20 ; i
< * size
- 20 ; i
++){
711 if ( dest
[ i
] >= high
) bit
= 1 ;
712 if ( dest
[ i
] <= low
) bit
= 0 ;
715 //now demod based on clock (rf/32 = 32 1's for one 1 bit, 32 0's for one 0 bit)
718 for ( i
= 21 ; i
< * size
- 20 ; i
++) {
719 //if transition detected or large number of same bits - store the passed bits
720 if ( dest
[ i
] != dest
[ i
- 1 ] || ( i
- lastBit
) == ( 10 * * clk
)) {
721 memset ( dest
+ numBits
, dest
[ i
- 1 ] ^ * invert
, ( i
- lastBit
+ (* clk
/ 4 )) / * clk
);
722 numBits
+= ( i
- lastBit
+ (* clk
/ 4 )) / * clk
;
724 * startIdx
= i
- ( numBits
* * clk
);
725 if ( g_debugMode
== 2 ) prnt ( "DEBUG NRZ: startIdx %i" , * startIdx
);
733 int nrzRawDemod ( uint8_t * dest
, size_t * size
, int * clk
, int * invert
) {
735 return nrzRawDemod_ext ( dest
, size
, clk
, invert
, & startIdx
);
738 //translate wave to 11111100000 (1 for each short wave [higher freq] 0 for each long wave [lower freq])
739 size_t fsk_wave_demod ( uint8_t * dest
, size_t size
, uint8_t fchigh
, uint8_t fclow
, int * startIdx
) {
740 size_t last_transition
= 0 ;
742 if ( fchigh
== 0 ) fchigh
= 10 ;
743 if ( fclow
== 0 ) fclow
= 8 ;
744 //set the threshold close to 0 (graph) or 128 std to avoid static
745 uint8_t threshold_value
= 123 ;
746 size_t preLastSample
= 0 ;
747 size_t LastSample
= 0 ;
748 size_t currSample
= 0 ;
749 if ( size
< 1024 ) return 0 ; // not enough samples
751 //find start of modulating data in trace
752 idx
= findModStart ( dest
, size
, threshold_value
, fchigh
);
753 // Need to threshold first sample
754 if ( dest
[ idx
] < threshold_value
) dest
[ 0 ] = 0 ;
757 last_transition
= idx
;
760 // count cycles between consecutive lo-hi transitions, there should be either 8 (fc/8)
761 // or 10 (fc/10) cycles but in practice due to noise etc we may end up with anywhere
762 // between 7 to 11 cycles so fuzz it by treat anything <9 as 8 and anything else as 10
763 // (could also be fc/5 && fc/7 for fsk1 = 4-9)
764 for (; idx
< size
; idx
++) {
765 // threshold current value
766 if ( dest
[ idx
] < threshold_value
) dest
[ idx
] = 0 ;
769 // Check for 0->1 transition
770 if ( dest
[ idx
- 1 ] < dest
[ idx
]) {
771 preLastSample
= LastSample
;
772 LastSample
= currSample
;
773 currSample
= idx
- last_transition
;
774 if ( currSample
< ( fclow
- 2 )) { //0-5 = garbage noise (or 0-3)
775 //do nothing with extra garbage
776 } else if ( currSample
< ( fchigh
- 1 )) { //6-8 = 8 sample waves (or 3-6 = 5)
777 //correct previous 9 wave surrounded by 8 waves (or 6 surrounded by 5)
778 if ( numBits
> 1 && LastSample
> ( fchigh
- 2 ) && ( preLastSample
< ( fchigh
- 1 ))){
782 if ( numBits
> 0 && * startIdx
== 0 ) * startIdx
= idx
- fclow
;
783 } else if ( currSample
> ( fchigh
+ 1 ) && numBits
< 3 ) { //12 + and first two bit = unusable garbage
784 //do nothing with beginning garbage and reset.. should be rare..
786 } 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)
788 if ( numBits
> 0 && * startIdx
== 0 ) * startIdx
= idx
- fclow
;
789 } else { //9+ = 10 sample waves (or 6+ = 7)
791 if ( numBits
> 0 && * startIdx
== 0 ) * startIdx
= idx
- fchigh
;
793 last_transition
= idx
;
796 return numBits
; //Actually, it returns the number of bytes, but each byte represents a bit: 1 or 0
799 //translate 11111100000 to 10
800 //rfLen = clock, fchigh = larger field clock, fclow = smaller field clock
801 size_t aggregate_bits ( uint8_t * dest
, size_t size
, uint8_t rfLen
, uint8_t invert
, uint8_t fchigh
, uint8_t fclow
, int * startIdx
) {
802 uint8_t lastval
= dest
[ 0 ];
806 for ( idx
= 1 ; idx
< size
; idx
++) {
808 if ( dest
[ idx
]== lastval
) continue ; //skip until we hit a transition
810 //find out how many bits (n) we collected (use 1/2 clk tolerance)
811 //if lastval was 1, we have a 1->0 crossing
812 if ( dest
[ idx
- 1 ]== 1 ) {
813 n
= ( n
* fclow
+ rfLen
/ 2 ) / rfLen
;
814 } else { // 0->1 crossing
815 n
= ( n
* fchigh
+ rfLen
/ 2 ) / rfLen
;
819 //first transition - save startidx
821 if ( lastval
== 1 ) { //high to low
822 * startIdx
+= ( fclow
* idx
) - ( n
* rfLen
);
823 if ( g_debugMode
== 2 ) prnt ( "DEBUG FSK: startIdx %i, fclow*idx %i, n*rflen %u" , * startIdx
, fclow
*( idx
), n
* rfLen
);
825 * startIdx
+= ( fchigh
* idx
) - ( n
* rfLen
);
826 if ( g_debugMode
== 2 ) prnt ( "DEBUG FSK: startIdx %i, fchigh*idx %i, n*rflen %u" , * startIdx
, fchigh
*( idx
), n
* rfLen
);
830 //add to our destination the bits we collected
831 memset ( dest
+ numBits
, dest
[ idx
- 1 ]^ invert
, n
);
836 // if valid extra bits at the end were all the same frequency - add them in
837 if ( n
> rfLen
/ fchigh
) {
838 if ( dest
[ idx
- 2 ]== 1 ) {
839 n
= ( n
* fclow
+ rfLen
/ 2 ) / rfLen
;
841 n
= ( n
* fchigh
+ rfLen
/ 2 ) / rfLen
;
843 memset ( dest
+ numBits
, dest
[ idx
- 1 ]^ invert
, n
);
849 //by marshmellow (from holiman's base)
850 // full fsk demod from GraphBuffer wave to decoded 1s and 0s (no mandemod)
851 int fskdemod_ext ( uint8_t * dest
, size_t size
, uint8_t rfLen
, uint8_t invert
, uint8_t fchigh
, uint8_t fclow
, int * startIdx
) {
853 size
= fsk_wave_demod ( dest
, size
, fchigh
, fclow
, startIdx
);
854 size
= aggregate_bits ( dest
, size
, rfLen
, invert
, fchigh
, fclow
, startIdx
);
858 int fskdemod ( uint8_t * dest
, size_t size
, uint8_t rfLen
, uint8_t invert
, uint8_t fchigh
, uint8_t fclow
) {
860 return fskdemod_ext ( dest
, size
, rfLen
, invert
, fchigh
, fclow
, & startIdx
);
864 // convert psk1 demod to psk2 demod
865 // only transition waves are 1s
866 void psk1TOpsk2 ( uint8_t * BitStream
, size_t size
) {
868 uint8_t lastBit
= BitStream
[ 0 ];
870 if ( BitStream
[ i
]== 7 ){
872 } else if ( lastBit
!= BitStream
[ i
]){
873 lastBit
= BitStream
[ i
];
883 // convert psk2 demod to psk1 demod
884 // from only transition waves are 1s to phase shifts change bit
885 void psk2TOpsk1 ( uint8_t * BitStream
, size_t size
) {
887 for ( size_t i
= 0 ; i
< size
; i
++){
888 if ( BitStream
[ i
]== 1 ){
896 //by marshmellow - demodulate PSK1 wave
897 //uses wave lengths (# Samples)
898 int pskRawDemod_ext ( uint8_t dest
[], size_t * size
, int * clock
, int * invert
, int * startIdx
) {
899 if ( size
== 0 ) return - 1 ;
900 uint16_t loopCnt
= 4096 ; //don't need to loop through entire array...
901 if (* size
< loopCnt
) loopCnt
= * size
;
904 uint8_t curPhase
= * invert
;
905 size_t i
= 0 , waveStart
= 1 , waveEnd
= 0 , firstFullWave
= 0 , lastClkBit
= 0 ;
906 uint16_t fc
= 0 , fullWaveLen
= 0 , tol
= 1 ;
907 uint16_t errCnt
= 0 , waveLenCnt
= 0 , errCnt2
= 0 ;
908 fc
= countFC ( dest
, * size
, 1 );
909 uint8_t fc2
= fc
>> 8 ;
910 if ( fc2
== 10 ) return - 1 ; //fsk found - quit
912 if ( fc
!= 2 && fc
!= 4 && fc
!= 8 ) return - 1 ;
913 //PrintAndLog("DEBUG: FC: %d",fc);
914 * clock
= DetectPSKClock ( dest
, * size
, * clock
);
915 if (* clock
== 0 ) return - 1 ;
917 //find start of modulating data in trace
918 uint8_t threshold_value
= 123 ; //-5
919 i
= findModStart ( dest
, * size
, threshold_value
, fc
);
921 //find first phase shift
922 int avgWaveVal
= 0 , lastAvgWaveVal
= 0 ;
924 for (; i
< loopCnt
; i
++) {
926 if ( dest
[ i
]+ fc
< dest
[ i
+ 1 ] && dest
[ i
+ 1 ] >= dest
[ i
+ 2 ]){
928 if ( g_debugMode
== 2 ) prnt ( "DEBUG PSK: waveEnd: %u, waveStart: %u" , waveEnd
, waveStart
);
929 waveLenCnt
= waveEnd
- waveStart
;
930 if ( waveLenCnt
> fc
&& waveStart
> fc
&& !( waveLenCnt
> fc
+ 3 )){ //not first peak and is a large wave but not out of whack
931 lastAvgWaveVal
= avgWaveVal
/( waveLenCnt
);
932 firstFullWave
= waveStart
;
933 fullWaveLen
= waveLenCnt
;
934 //if average wave value is > graph 0 then it is an up wave or a 1 (could cause inverting)
935 if ( lastAvgWaveVal
> threshold_value
) curPhase
^= 1 ;
942 avgWaveVal
+= dest
[ i
+ 2 ];
944 if ( firstFullWave
== 0 ) {
945 // no phase shift detected - could be all 1's or 0's - doesn't matter where we start
946 // so skip a little to ensure we are past any Start Signal
948 memset ( dest
, curPhase
, firstFullWave
/ * clock
);
950 memset ( dest
, curPhase
^ 1 , firstFullWave
/ * clock
);
953 numBits
+= ( firstFullWave
/ * clock
);
954 * startIdx
= firstFullWave
- (* clock
* numBits
)+ 2 ;
955 //set start of wave as clock align
956 lastClkBit
= firstFullWave
;
957 if ( g_debugMode
== 2 ) prnt ( "DEBUG PSK: firstFullWave: %u, waveLen: %u, startIdx %i" , firstFullWave
, fullWaveLen
, * startIdx
);
958 if ( g_debugMode
== 2 ) prnt ( "DEBUG PSK: clk: %d, lastClkBit: %u, fc: %u" , * clock
, lastClkBit
,( unsigned int ) fc
);
960 dest
[ numBits
++] = curPhase
; //set first read bit
961 for ( i
= firstFullWave
+ fullWaveLen
- 1 ; i
< * size
- 3 ; i
++){
962 //top edge of wave = start of new wave
963 if ( dest
[ i
]+ fc
< dest
[ i
+ 1 ] && dest
[ i
+ 1 ] >= dest
[ i
+ 2 ]){
964 if ( waveStart
== 0 ) {
967 avgWaveVal
= dest
[ i
+ 1 ];
970 waveLenCnt
= waveEnd
- waveStart
;
971 lastAvgWaveVal
= avgWaveVal
/ waveLenCnt
;
972 if ( waveLenCnt
> fc
){
973 //PrintAndLog("DEBUG: avgWaveVal: %d, waveSum: %d",lastAvgWaveVal,avgWaveVal);
974 //this wave is a phase shift
975 //PrintAndLog("DEBUG: phase shift at: %d, len: %d, nextClk: %d, i: %d, fc: %d",waveStart,waveLenCnt,lastClkBit+*clock-tol,i+1,fc);
976 if ( i
+ 1 >= lastClkBit
+ * clock
- tol
){ //should be a clock bit
978 dest
[ numBits
++] = curPhase
;
979 lastClkBit
+= * clock
;
980 } else if ( i
< lastClkBit
+ 10 + fc
){
981 //noise after a phase shift - ignore
982 } else { //phase shift before supposed to based on clock
986 } else if ( i
+ 1 > lastClkBit
+ * clock
+ tol
+ fc
){
987 lastClkBit
+= * clock
; //no phase shift but clock bit
988 dest
[ numBits
++] = curPhase
;
989 } else if ( waveLenCnt
< fc
- 1 ) { //wave is smaller than field clock (shouldn't happen often)
991 if ( errCnt2
> 101 ) return errCnt2
;
997 avgWaveVal
+= dest
[ i
+ 1 ];
1003 int pskRawDemod ( uint8_t dest
[], size_t * size
, int * clock
, int * invert
) {
1005 return pskRawDemod_ext ( dest
, size
, clock
, invert
, & startIdx
);
1008 //-------------------Clock / Bitrate Detection Section------------------------------------------------------------------------------------
1011 // to help detect clocks on heavily clipped samples
1012 // based on count of low to low
1013 int DetectStrongAskClock ( uint8_t dest
[], size_t size
, uint8_t high
, uint8_t low
, int * clock
) {
1014 uint8_t fndClk
[] = { 8 , 16 , 32 , 40 , 50 , 64 , 128 };
1017 size_t minClk
= 255 ;
1018 int shortestWaveIdx
= 0 ;
1019 // get to first full low to prime loop and skip incomplete first pulse
1020 while (( dest
[ i
] < high
) && ( i
< size
))
1022 while (( dest
[ i
] > low
) && ( i
< size
))
1025 // loop through all samples
1027 // measure from low to low
1028 while (( dest
[ i
] > low
) && ( i
< size
))
1031 while (( dest
[ i
] < high
) && ( i
< size
))
1033 while (( dest
[ i
] > low
) && ( i
< size
))
1035 //get minimum measured distance
1036 if ( i
- startwave
< minClk
&& i
< size
) {
1037 minClk
= i
- startwave
;
1038 shortestWaveIdx
= startwave
;
1042 if ( g_debugMode
== 2 ) prnt ( "DEBUG ASK: detectstrongASKclk smallest wave: %d" , minClk
);
1043 for ( uint8_t clkCnt
= 0 ; clkCnt
< 7 ; clkCnt
++) {
1044 if ( minClk
>= fndClk
[ clkCnt
]-( fndClk
[ clkCnt
]/ 8 ) && minClk
<= fndClk
[ clkCnt
]+ 1 ) {
1045 * clock
= fndClk
[ clkCnt
];
1046 return shortestWaveIdx
;
1053 // not perfect especially with lower clocks or VERY good antennas (heavy wave clipping)
1054 // maybe somehow adjust peak trimming value based on samples to fix?
1055 // return start index of best starting position for that clock and return clock (by reference)
1056 int DetectASKClock ( uint8_t dest
[], size_t size
, int * clock
, int maxErr
) {
1058 uint8_t clk
[] = { 255 , 8 , 16 , 32 , 40 , 50 , 64 , 100 , 128 , 255 };
1060 uint8_t loopCnt
= 255 ; //don't need to loop through entire array...
1061 if ( size
<= loopCnt
+ 60 ) return - 1 ; //not enough samples
1062 size
-= 60 ; //sometimes there is a strange end wave - filter out this....
1063 //if we already have a valid clock
1066 if ( clk
[ i
] == * clock
) clockFnd
= i
;
1067 //clock found but continue to find best startpos
1069 //get high and low peak
1071 if ( getHiLo ( dest
, loopCnt
, & peak
, & low
, 75 , 75 ) < 1 ) return - 1 ;
1073 //test for large clean peaks
1075 if ( DetectCleanAskWave ( dest
, size
, peak
, low
)== 1 ){
1076 int ans
= DetectStrongAskClock ( dest
, size
, peak
, low
, clock
);
1077 if ( g_debugMode
== 2 ) prnt ( "DEBUG ASK: detectaskclk Clean Ask Wave Detected: clk %i, ShortestWave: %i" , clock
, ans
);
1079 return ans
; //return shortest wave start position
1084 uint8_t clkCnt
, tol
= 0 ;
1085 uint16_t bestErr
[]={ 1000 , 1000 , 1000 , 1000 , 1000 , 1000 , 1000 , 1000 , 1000 };
1086 uint8_t bestStart
[]={ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 };
1088 size_t arrLoc
, loopEnd
;
1092 clkEnd
= clockFnd
+ 1 ;
1096 //test each valid clock from smallest to greatest to see which lines up
1097 for (; clkCnt
< clkEnd
; clkCnt
++){
1098 if ( clk
[ clkCnt
] <= 32 ){
1103 //if no errors allowed - keep start within the first clock
1104 if (! maxErr
&& size
> clk
[ clkCnt
]* 2 + tol
&& clk
[ clkCnt
]< 128 ) loopCnt
= clk
[ clkCnt
]* 2 ;
1105 bestErr
[ clkCnt
]= 1000 ;
1106 //try lining up the peaks by moving starting point (try first few clocks)
1107 for ( ii
= 0 ; ii
< loopCnt
; ii
++){
1108 if ( dest
[ ii
] < peak
&& dest
[ ii
] > low
) continue ;
1111 // now that we have the first one lined up test rest of wave array
1112 loopEnd
= (( size
- ii
- tol
) / clk
[ clkCnt
]) - 1 ;
1113 for ( i
= 0 ; i
< loopEnd
; ++ i
){
1114 arrLoc
= ii
+ ( i
* clk
[ clkCnt
]);
1115 if ( dest
[ arrLoc
] >= peak
|| dest
[ arrLoc
] <= low
){
1116 } else if ( dest
[ arrLoc
- tol
] >= peak
|| dest
[ arrLoc
- tol
] <= low
){
1117 } else if ( dest
[ arrLoc
+ tol
] >= peak
|| dest
[ arrLoc
+ tol
] <= low
){
1118 } else { //error no peak detected
1122 //if we found no errors then we can stop here and a low clock (common clocks)
1123 // this is correct one - return this clock
1124 if ( g_debugMode
== 2 ) prnt ( "DEBUG ASK: clk %d, err %d, startpos %d, endpos %d" , clk
[ clkCnt
], errCnt
, ii
, i
);
1125 if ( errCnt
== 0 && clkCnt
< 7 ) {
1126 if (! clockFnd
) * clock
= clk
[ clkCnt
];
1129 //if we found errors see if it is lowest so far and save it as best run
1130 if ( errCnt
< bestErr
[ clkCnt
]){
1131 bestErr
[ clkCnt
]= errCnt
;
1132 bestStart
[ clkCnt
]= ii
;
1138 for ( iii
= 1 ; iii
< clkEnd
; ++ iii
){
1139 if ( bestErr
[ iii
] < bestErr
[ best
]){
1140 if ( bestErr
[ iii
] == 0 ) bestErr
[ iii
]= 1 ;
1141 // current best bit to error ratio vs new bit to error ratio
1142 if ( ( size
/ clk
[ best
])/ bestErr
[ best
] < ( size
/ clk
[ iii
])/ bestErr
[ iii
] ){
1146 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
]);
1148 if (! clockFnd
) * clock
= clk
[ best
];
1149 return bestStart
[ best
];
1152 int DetectStrongNRZClk ( uint8_t * dest
, size_t size
, int peak
, int low
){
1153 //find shortest transition from high to low
1155 size_t transition1
= 0 ;
1156 int lowestTransition
= 255 ;
1157 bool lastWasHigh
= false ;
1159 //find first valid beginning of a high or low wave
1160 while (( dest
[ i
] >= peak
|| dest
[ i
] <= low
) && ( i
< size
))
1162 while (( dest
[ i
] < peak
&& dest
[ i
] > low
) && ( i
< size
))
1164 lastWasHigh
= ( dest
[ i
] >= peak
);
1166 if ( i
== size
) return 0 ;
1169 for (; i
< size
; i
++) {
1170 if (( dest
[ i
] >= peak
&& ! lastWasHigh
) || ( dest
[ i
] <= low
&& lastWasHigh
)) {
1171 lastWasHigh
= ( dest
[ i
] >= peak
);
1172 if ( i
- transition1
< lowestTransition
) lowestTransition
= i
- transition1
;
1176 if ( lowestTransition
== 255 ) lowestTransition
= 0 ;
1177 if ( g_debugMode
== 2 ) prnt ( "DEBUG NRZ: detectstrongNRZclk smallest wave: %d" , lowestTransition
);
1178 return lowestTransition
;
1182 //detect nrz clock by reading #peaks vs no peaks(or errors)
1183 int DetectNRZClock_ext ( uint8_t dest
[], size_t size
, int clock
, size_t * clockStartIdx
) {
1185 uint8_t clk
[]={ 8 , 16 , 32 , 40 , 50 , 64 , 100 , 128 , 255 };
1186 size_t loopCnt
= 4096 ; //don't need to loop through entire array...
1187 if ( size
== 0 ) return 0 ;
1188 if ( size
< loopCnt
) loopCnt
= size
- 20 ;
1189 //if we already have a valid clock quit
1191 if ( clk
[ i
] == clock
) return clock
;
1193 //get high and low peak
1195 if ( getHiLo ( dest
, loopCnt
, & peak
, & low
, 75 , 75 ) < 1 ) return 0 ;
1197 int lowestTransition
= DetectStrongNRZClk ( dest
, size
- 20 , peak
, low
);
1201 uint16_t smplCnt
= 0 ;
1202 int16_t peakcnt
= 0 ;
1203 int16_t peaksdet
[] = { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 };
1204 uint16_t maxPeak
= 255 ;
1205 bool firstpeak
= false ;
1206 //test for large clipped waves
1207 for ( i
= 0 ; i
< loopCnt
; i
++){
1208 if ( dest
[ i
] >= peak
|| dest
[ i
] <= low
){
1209 if (! firstpeak
) continue ;
1214 if ( maxPeak
> smplCnt
){
1216 //prnt("maxPk: %d",maxPeak);
1219 //prnt("maxPk: %d, smplCnt: %d, peakcnt: %d",maxPeak,smplCnt,peakcnt);
1224 bool errBitHigh
= 0 ;
1226 uint8_t ignoreCnt
= 0 ;
1227 uint8_t ignoreWindow
= 4 ;
1228 bool lastPeakHigh
= 0 ;
1230 size_t bestStart
[]={ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 };
1232 //test each valid clock from smallest to greatest to see which lines up
1233 for ( clkCnt
= 0 ; clkCnt
< 8 ; ++ clkCnt
){
1234 //ignore clocks smaller than smallest peak
1235 if ( clk
[ clkCnt
] < maxPeak
- ( clk
[ clkCnt
]/ 4 )) continue ;
1236 //try lining up the peaks by moving starting point (try first 256)
1237 for ( ii
= 20 ; ii
< loopCnt
; ++ ii
){
1238 if (( dest
[ ii
] >= peak
) || ( dest
[ ii
] <= low
)){
1242 lastBit
= ii
- clk
[ clkCnt
];
1243 //loop through to see if this start location works
1244 for ( i
= ii
; i
< size
- 20 ; ++ i
) {
1245 //if we are at a clock bit
1246 if (( i
>= lastBit
+ clk
[ clkCnt
] - tol
) && ( i
<= lastBit
+ clk
[ clkCnt
] + tol
)) {
1248 if ( dest
[ i
] >= peak
|| dest
[ i
] <= low
) {
1249 //if same peak don't count it
1250 if (( dest
[ i
] >= peak
&& ! lastPeakHigh
) || ( dest
[ i
] <= low
&& lastPeakHigh
)) {
1253 lastPeakHigh
= ( dest
[ i
] >= peak
);
1256 ignoreCnt
= ignoreWindow
;
1257 lastBit
+= clk
[ clkCnt
];
1258 } else if ( i
== lastBit
+ clk
[ clkCnt
] + tol
) {
1259 lastBit
+= clk
[ clkCnt
];
1261 //else if not a clock bit and no peaks
1262 } else if ( dest
[ i
] < peak
&& dest
[ i
] > low
){
1265 if ( errBitHigh
== true ) peakcnt
--;
1270 // else if not a clock bit but we have a peak
1271 } else if (( dest
[ i
]>= peak
|| dest
[ i
]<= low
) && (! bitHigh
)) {
1272 //error bar found no clock...
1276 if ( peakcnt
> peaksdet
[ clkCnt
]) {
1277 bestStart
[ clkCnt
]= ii
;
1278 peaksdet
[ clkCnt
]= peakcnt
;
1285 for ( iii
= 7 ; iii
> 0 ; iii
--){
1286 if (( peaksdet
[ iii
] >= ( peaksdet
[ best
]- 1 )) && ( peaksdet
[ iii
] <= peaksdet
[ best
]+ 1 ) && lowestTransition
) {
1287 if ( clk
[ iii
] > ( lowestTransition
- ( clk
[ iii
]/ 8 )) && clk
[ iii
] < ( lowestTransition
+ ( clk
[ iii
]/ 8 ))) {
1290 } else if ( peaksdet
[ iii
] > peaksdet
[ best
]){
1293 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
);
1295 * clockStartIdx
= bestStart
[ best
];
1299 int DetectNRZClock ( uint8_t dest
[], size_t size
, int clock
) {
1301 return DetectNRZClock_ext ( dest
, size
, clock
, & bestStart
);
1305 //countFC is to detect the field clock lengths.
1306 //counts and returns the 2 most common wave lengths
1307 //mainly used for FSK field clock detection
1308 uint16_t countFC ( uint8_t * BitStream
, size_t size
, uint8_t fskAdj
) {
1309 uint8_t fcLens
[] = { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 };
1310 uint16_t fcCnts
[] = { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 };
1311 uint8_t fcLensFnd
= 0 ;
1312 uint8_t lastFCcnt
= 0 ;
1313 uint8_t fcCounter
= 0 ;
1315 if ( size
< 180 ) return 0 ;
1317 // prime i to first up transition
1318 for ( i
= 160 ; i
< size
- 20 ; i
++)
1319 if ( BitStream
[ i
] > BitStream
[ i
- 1 ] && BitStream
[ i
] >= BitStream
[ i
+ 1 ])
1322 for (; i
< size
- 20 ; i
++){
1323 if ( BitStream
[ i
] > BitStream
[ i
- 1 ] && BitStream
[ i
] >= BitStream
[ i
+ 1 ]){
1324 // new up transition
1327 //if we had 5 and now have 9 then go back to 8 (for when we get a fc 9 instead of an 8)
1328 if ( lastFCcnt
== 5 && fcCounter
== 9 ) fcCounter
--;
1329 //if fc=9 or 4 add one (for when we get a fc 9 instead of 10 or a 4 instead of a 5)
1330 if (( fcCounter
== 9 ) || fcCounter
== 4 ) fcCounter
++;
1331 // save last field clock count (fc/xx)
1332 lastFCcnt
= fcCounter
;
1334 // find which fcLens to save it to:
1335 for ( int ii
= 0 ; ii
< 15 ; ii
++){
1336 if ( fcLens
[ ii
]== fcCounter
){
1342 if ( fcCounter
> 0 && fcLensFnd
< 15 ){
1344 fcCnts
[ fcLensFnd
]++;
1345 fcLens
[ fcLensFnd
++]= fcCounter
;
1354 uint8_t best1
= 14 , best2
= 14 , best3
= 14 ;
1356 // go through fclens and find which ones are bigest 2
1357 for ( i
= 0 ; i
< 15 ; i
++){
1358 // get the 3 best FC values
1359 if ( fcCnts
[ i
]> maxCnt1
) {
1364 } else if ( fcCnts
[ i
]> fcCnts
[ best2
]){
1367 } else if ( fcCnts
[ i
]> fcCnts
[ best3
]){
1370 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
]);
1372 if ( fcLens
[ best1
]== 0 ) return 0 ;
1373 uint8_t fcH
= 0 , fcL
= 0 ;
1374 if ( fcLens
[ best1
]> fcLens
[ best2
]){
1381 if (( size
- 180 )/ fcH
/ 3 > fcCnts
[ best1
]+ fcCnts
[ best2
]) {
1382 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
]);
1383 return 0 ; //lots of waves not psk or fsk
1385 // TODO: take top 3 answers and compare to known Field clocks to get top 2
1387 uint16_t fcs
= ((( uint16_t ) fcH
)<< 8 ) | fcL
;
1388 if ( fskAdj
) return fcs
;
1389 return fcLens
[ best1
];
1393 //detect psk clock by reading each phase shift
1394 // a phase shift is determined by measuring the sample length of each wave
1395 int DetectPSKClock_ext ( uint8_t dest
[], size_t size
, int clock
, int * firstPhaseShift
) {
1396 uint8_t clk
[]={ 255 , 16 , 32 , 40 , 50 , 64 , 100 , 128 , 255 }; //255 is not a valid clock
1397 uint16_t loopCnt
= 4096 ; //don't need to loop through entire array...
1398 if ( size
== 0 ) return 0 ;
1399 if ( size
< loopCnt
) loopCnt
= size
- 20 ;
1401 //if we already have a valid clock quit
1404 if ( clk
[ i
] == clock
) return clock
;
1406 size_t waveStart
= 0 , waveEnd
= 0 , firstFullWave
= 0 , lastClkBit
= 0 ;
1407 uint8_t clkCnt
, fc
= 0 , fullWaveLen
= 0 , tol
= 1 ;
1408 uint16_t peakcnt
= 0 , errCnt
= 0 , waveLenCnt
= 0 ;
1409 uint16_t bestErr
[]={ 1000 , 1000 , 1000 , 1000 , 1000 , 1000 , 1000 , 1000 , 1000 };
1410 uint16_t peaksdet
[]={ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 };
1411 fc
= countFC ( dest
, size
, 0 );
1412 if ( fc
!= 2 && fc
!= 4 && fc
!= 8 ) return - 1 ;
1413 if ( g_debugMode
== 2 ) prnt ( "DEBUG PSK: FC: %d" , fc
);
1415 //find first full wave
1416 for ( i
= 160 ; i
< loopCnt
; i
++){
1417 if ( dest
[ i
] < dest
[ i
+ 1 ] && dest
[ i
+ 1 ] >= dest
[ i
+ 2 ]){
1418 if ( waveStart
== 0 ) {
1420 //prnt("DEBUG: waveStart: %d",waveStart);
1423 //prnt("DEBUG: waveEnd: %d",waveEnd);
1424 waveLenCnt
= waveEnd
- waveStart
;
1425 if ( waveLenCnt
> fc
){
1426 firstFullWave
= waveStart
;
1427 fullWaveLen
= waveLenCnt
;
1434 * firstPhaseShift
= firstFullWave
;
1435 if ( g_debugMode
== 2 ) prnt ( "DEBUG PSK: firstFullWave: %d, waveLen: %d" , firstFullWave
, fullWaveLen
);
1436 //test each valid clock from greatest to smallest to see which lines up
1437 for ( clkCnt
= 7 ; clkCnt
>= 1 ; clkCnt
--){
1438 lastClkBit
= firstFullWave
; //set end of wave as clock align
1442 if ( g_debugMode
== 2 ) prnt ( "DEBUG PSK: clk: %d, lastClkBit: %d" , clk
[ clkCnt
], lastClkBit
);
1444 for ( i
= firstFullWave
+ fullWaveLen
- 1 ; i
< loopCnt
- 2 ; i
++){
1445 //top edge of wave = start of new wave
1446 if ( dest
[ i
] < dest
[ i
+ 1 ] && dest
[ i
+ 1 ] >= dest
[ i
+ 2 ]){
1447 if ( waveStart
== 0 ) {
1452 waveLenCnt
= waveEnd
- waveStart
;
1453 if ( waveLenCnt
> fc
){
1454 //if this wave is a phase shift
1455 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
);
1456 if ( i
+ 1 >= lastClkBit
+ clk
[ clkCnt
] - tol
){ //should be a clock bit
1458 lastClkBit
+= clk
[ clkCnt
];
1459 } else if ( i
< lastClkBit
+ 8 ){
1460 //noise after a phase shift - ignore
1461 } else { //phase shift before supposed to based on clock
1464 } else if ( i
+ 1 > lastClkBit
+ clk
[ clkCnt
] + tol
+ fc
){
1465 lastClkBit
+= clk
[ clkCnt
]; //no phase shift but clock bit
1474 if ( errCnt
<= bestErr
[ clkCnt
]) bestErr
[ clkCnt
]= errCnt
;
1475 if ( peakcnt
> peaksdet
[ clkCnt
]) peaksdet
[ clkCnt
]= peakcnt
;
1477 //all tested with errors
1478 //return the highest clk with the most peaks found
1480 for ( i
= 7 ; i
>= 1 ; i
--){
1481 if ( peaksdet
[ i
] > peaksdet
[ best
]) {
1484 if ( g_debugMode
== 2 ) prnt ( "DEBUG PSK: Clk: %d, peaks: %d, errs: %d, bestClk: %d" , clk
[ i
], peaksdet
[ i
], bestErr
[ i
], clk
[ best
]);
1489 int DetectPSKClock ( uint8_t dest
[], size_t size
, int clock
) {
1490 int firstPhaseShift
= 0 ;
1491 return DetectPSKClock_ext ( dest
, size
, clock
, & firstPhaseShift
);
1495 //detects the bit clock for FSK given the high and low Field Clocks
1496 uint8_t detectFSKClk_ext ( uint8_t * BitStream
, size_t size
, uint8_t fcHigh
, uint8_t fcLow
, int * firstClockEdge
) {
1497 uint8_t clk
[] = { 8 , 16 , 32 , 40 , 50 , 64 , 100 , 128 , 0 };
1498 uint16_t rfLens
[] = { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 };
1499 uint8_t rfCnts
[] = { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 };
1500 uint8_t rfLensFnd
= 0 ;
1501 uint8_t lastFCcnt
= 0 ;
1502 uint16_t fcCounter
= 0 ;
1503 uint16_t rfCounter
= 0 ;
1504 uint8_t firstBitFnd
= 0 ;
1506 if ( size
== 0 ) return 0 ;
1508 uint8_t fcTol
= (( fcHigh
* 100 - fcLow
* 100 )/ 2 + 50 )/ 100 ; //(uint8_t)(0.5+(float)(fcHigh-fcLow)/2);
1513 //PrintAndLog("DEBUG: fcTol: %d",fcTol);
1514 // prime i to first peak / up transition
1515 for ( i
= 160 ; i
< size
- 20 ; i
++)
1516 if ( BitStream
[ i
] > BitStream
[ i
- 1 ] && BitStream
[ i
]>= BitStream
[ i
+ 1 ])
1519 for (; i
< size
- 20 ; i
++){
1523 if ( BitStream
[ i
] <= BitStream
[ i
- 1 ] || BitStream
[ i
] < BitStream
[ i
+ 1 ])
1526 // if we got less than the small fc + tolerance then set it to the small fc
1527 // if it is inbetween set it to the last counter
1528 if ( fcCounter
< fcHigh
&& fcCounter
> fcLow
)
1529 fcCounter
= lastFCcnt
;
1530 else if ( fcCounter
< fcLow
+ fcTol
)
1532 else //set it to the large fc
1535 //look for bit clock (rf/xx)
1536 if (( fcCounter
< lastFCcnt
|| fcCounter
> lastFCcnt
)){
1537 //not the same size as the last wave - start of new bit sequence
1538 if ( firstBitFnd
> 1 ){ //skip first wave change - probably not a complete bit
1539 for ( int ii
= 0 ; ii
< 15 ; ii
++){
1540 if ( rfLens
[ ii
] >= ( rfCounter
- 4 ) && rfLens
[ ii
] <= ( rfCounter
+ 4 )){
1546 if ( rfCounter
> 0 && rfLensFnd
< 15 ){
1547 //PrintAndLog("DEBUG: rfCntr %d, fcCntr %d",rfCounter,fcCounter);
1548 rfCnts
[ rfLensFnd
]++;
1549 rfLens
[ rfLensFnd
++] = rfCounter
;
1552 * firstClockEdge
= i
;
1556 lastFCcnt
= fcCounter
;
1560 uint8_t rfHighest
= 15 , rfHighest2
= 15 , rfHighest3
= 15 ;
1562 for ( i
= 0 ; i
< 15 ; i
++){
1563 //get highest 2 RF values (might need to get more values to compare or compare all?)
1564 if ( rfCnts
[ i
]> rfCnts
[ rfHighest
]){
1565 rfHighest3
= rfHighest2
;
1566 rfHighest2
= rfHighest
;
1568 } else if ( rfCnts
[ i
]> rfCnts
[ rfHighest2
]){
1569 rfHighest3
= rfHighest2
;
1571 } else if ( rfCnts
[ i
]> rfCnts
[ rfHighest3
]){
1574 if ( g_debugMode
== 2 ) prnt ( "DEBUG FSK: RF %d, cnts %d" , rfLens
[ i
], rfCnts
[ i
]);
1576 // set allowed clock remainder tolerance to be 1 large field clock length+1
1577 // we could have mistakenly made a 9 a 10 instead of an 8 or visa versa so rfLens could be 1 FC off
1578 uint8_t tol1
= fcHigh
+ 1 ;
1580 if ( g_debugMode
== 2 ) prnt ( "DEBUG FSK: most counted rf values: 1 %d, 2 %d, 3 %d" , rfLens
[ rfHighest
], rfLens
[ rfHighest2
], rfLens
[ rfHighest3
]);
1582 // loop to find the highest clock that has a remainder less than the tolerance
1583 // compare samples counted divided by
1584 // test 128 down to 32 (shouldn't be possible to have fc/10 & fc/8 and rf/16 or less)
1586 for (; ii
>= 2 ; ii
--){
1587 if ( rfLens
[ rfHighest
] % clk
[ ii
] < tol1
|| rfLens
[ rfHighest
] % clk
[ ii
] > clk
[ ii
]- tol1
){
1588 if ( rfLens
[ rfHighest2
] % clk
[ ii
] < tol1
|| rfLens
[ rfHighest2
] % clk
[ ii
] > clk
[ ii
]- tol1
){
1589 if ( rfLens
[ rfHighest3
] % clk
[ ii
] < tol1
|| rfLens
[ rfHighest3
] % clk
[ ii
] > clk
[ ii
]- tol1
){
1590 if ( g_debugMode
== 2 ) prnt ( "DEBUG FSK: clk %d divides into the 3 most rf values within tolerance" , clk
[ ii
]);
1597 if ( ii
< 2 ) return 0 ; // oops we went too far
1602 uint8_t detectFSKClk ( uint8_t * BitStream
, size_t size
, uint8_t fcHigh
, uint8_t fcLow
) {
1603 int firstClockEdge
= 0 ;
1604 return detectFSKClk_ext ( BitStream
, size
, fcHigh
, fcLow
, & firstClockEdge
);
1607 //-----------------Tag format detection section--------------------------------------------------------------
1610 // FSK Demod then try to locate an AWID ID
1611 int AWIDdemodFSK ( uint8_t * dest
, size_t * size
) {
1612 //make sure buffer has enough data
1613 if (* size
< 96 * 50 ) return - 1 ;
1615 if ( justNoise ( dest
, * size
)) return - 2 ;
1618 * size
= fskdemod ( dest
, * size
, 50 , 1 , 10 , 8 ); // fsk2a RF/50
1619 if (* size
< 96 ) return - 3 ; //did we get a good demod?
1621 uint8_t preamble
[] = { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 };
1622 size_t startIdx
= 0 ;
1623 uint8_t errChk
= preambleSearch ( dest
, preamble
, sizeof ( preamble
), size
, & startIdx
);
1624 if ( errChk
== 0 ) return - 4 ; //preamble not found
1625 if (* size
!= 96 ) return - 5 ;
1626 return ( int ) startIdx
;
1630 //takes 1s and 0s and searches for EM410x format - output EM ID
1631 uint8_t Em410xDecode ( uint8_t * BitStream
, size_t * size
, size_t * startIdx
, uint32_t * hi
, uint64_t * lo
)
1634 if (* size
< 64 ) return 0 ;
1635 if ( BitStream
[ 1 ]> 1 ) return 0 ; //allow only 1s and 0s
1637 // 111111111 bit pattern represent start of frame
1638 // include 0 in front to help get start pos
1639 uint8_t preamble
[] = { 0 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 };
1641 uint8_t FmtLen
= 10 ; // sets of 4 bits = end data
1643 errChk
= preambleSearch ( BitStream
, preamble
, sizeof ( preamble
), size
, startIdx
);
1644 if ( errChk
== 0 || (* size
!= 64 && * size
!= 128 ) ) return 0 ;
1645 if (* size
== 128 ) FmtLen
= 22 ; // 22 sets of 4 bits
1647 //skip last 4bit parity row for simplicity
1648 * size
= removeParity ( BitStream
, * startIdx
+ sizeof ( preamble
), 5 , 0 , FmtLen
* 5 );
1649 if (* size
== 40 ) { // std em410x format
1651 * lo
= (( uint64_t )( bytebits_to_byte ( BitStream
, 8 )) << 32 ) | ( bytebits_to_byte ( BitStream
+ 8 , 32 ));
1652 } else if (* size
== 88 ) { // long em format
1653 * hi
= ( bytebits_to_byte ( BitStream
, 24 ));
1654 * lo
= (( uint64_t )( bytebits_to_byte ( BitStream
+ 24 , 32 )) << 32 ) | ( bytebits_to_byte ( BitStream
+ 24 + 32 , 32 ));
1661 // Ask/Biphase Demod then try to locate an ISO 11784/85 ID
1662 // BitStream must contain previously askrawdemod and biphasedemoded data
1663 int FDXBdemodBI ( uint8_t * dest
, size_t * size
) {
1664 //make sure buffer has enough data
1665 if (* size
< 128 ) return - 1 ;
1667 size_t startIdx
= 0 ;
1668 uint8_t preamble
[] = { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 };
1670 uint8_t errChk
= preambleSearch ( dest
, preamble
, sizeof ( preamble
), size
, & startIdx
);
1671 if ( errChk
== 0 ) return - 2 ; //preamble not found
1672 return ( int ) startIdx
;
1676 // demod gProxIIDemod
1677 // error returns as -x
1678 // success returns start position in BitStream
1679 // BitStream must contain previously askrawdemod and biphasedemoded data
1680 int gProxII_Demod ( uint8_t BitStream
[], size_t * size
) {
1682 uint8_t preamble
[] = { 1 , 1 , 1 , 1 , 1 , 0 };
1684 uint8_t errChk
= preambleSearch ( BitStream
, preamble
, sizeof ( preamble
), size
, & startIdx
);
1685 if ( errChk
== 0 ) return - 3 ; //preamble not found
1686 if (* size
!= 96 ) return - 2 ; //should have found 96 bits
1687 //check first 6 spacer bits to verify format
1688 if (! BitStream
[ startIdx
+ 5 ] && ! BitStream
[ startIdx
+ 10 ] && ! BitStream
[ startIdx
+ 15 ] && ! BitStream
[ startIdx
+ 20 ] && ! BitStream
[ startIdx
+ 25 ] && ! BitStream
[ startIdx
+ 30 ]){
1689 //confirmed proper separator bits found
1690 //return start position
1691 return ( int ) startIdx
;
1693 return - 5 ; //spacer bits not found - not a valid gproxII
1696 // loop to get raw HID waveform then FSK demodulate the TAG ID from it
1697 int HIDdemodFSK ( uint8_t * dest
, size_t * size
, uint32_t * hi2
, uint32_t * hi
, uint32_t * lo
) {
1698 if ( justNoise ( dest
, * size
)) return - 1 ;
1700 size_t numStart
= 0 , size2
=* size
, startIdx
= 0 ;
1702 * size
= fskdemod ( dest
, size2
, 50 , 1 , 10 , 8 ); //fsk2a
1703 if (* size
< 96 * 2 ) return - 2 ;
1704 // 00011101 bit pattern represent start of frame, 01 pattern represents a 0 and 10 represents a 1
1705 uint8_t preamble
[] = { 0 , 0 , 0 , 1 , 1 , 1 , 0 , 1 };
1706 // find bitstring in array
1707 uint8_t errChk
= preambleSearch ( dest
, preamble
, sizeof ( preamble
), size
, & startIdx
);
1708 if ( errChk
== 0 ) return - 3 ; //preamble not found
1710 numStart
= startIdx
+ sizeof ( preamble
);
1711 // final loop, go over previously decoded FSK data and manchester decode into usable tag ID
1712 for ( size_t idx
= numStart
; ( idx
- numStart
) < * size
- sizeof ( preamble
); idx
+= 2 ){
1713 if ( dest
[ idx
] == dest
[ idx
+ 1 ]){
1714 return - 4 ; //not manchester data
1716 * hi2
= (* hi2
<< 1 )|(* hi
>> 31 );
1717 * hi
= (* hi
<< 1 )|(* lo
>> 31 );
1718 //Then, shift in a 0 or one into low
1719 if ( dest
[ idx
] && ! dest
[ idx
+ 1 ]) // 1 0
1724 return ( int ) startIdx
;
1727 int IOdemodFSK ( uint8_t * dest
, size_t size
) {
1728 if ( justNoise ( dest
, size
)) return - 1 ;
1729 //make sure buffer has data
1730 if ( size
< 66 * 64 ) return - 2 ;
1732 size
= fskdemod ( dest
, size
, 64 , 1 , 10 , 8 ); // FSK2a RF/64
1733 if ( size
< 65 ) return - 3 ; //did we get a good demod?
1735 //0 10 20 30 40 50 60
1737 //01234567 8 90123456 7 89012345 6 78901234 5 67890123 4 56789012 3 45678901 23
1738 //-----------------------------------------------------------------------------
1739 //00000000 0 11110000 1 facility 1 version* 1 code*one 1 code*two 1 ???????? 11
1741 //XSF(version)facility:codeone+codetwo
1743 size_t startIdx
= 0 ;
1744 uint8_t preamble
[] = { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 };
1745 uint8_t errChk
= preambleSearch ( dest
, preamble
, sizeof ( preamble
), & size
, & startIdx
);
1746 if ( errChk
== 0 ) return - 4 ; //preamble not found
1748 if (! dest
[ startIdx
+ 8 ] && dest
[ startIdx
+ 17 ]== 1 && dest
[ startIdx
+ 26 ]== 1 && dest
[ startIdx
+ 35 ]== 1 && dest
[ startIdx
+ 44 ]== 1 && dest
[ startIdx
+ 53 ]== 1 ){
1749 //confirmed proper separator bits found
1750 //return start position
1751 return ( int ) startIdx
;
1756 // redesigned by marshmellow adjusted from existing decode functions
1757 // indala id decoding - only tested on 26 bit tags, but attempted to make it work for more
1758 int indala26decode ( uint8_t * bitStream
, size_t * size
, uint8_t * invert
) {
1759 //26 bit 40134 format (don't know other formats)
1760 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 };
1761 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 };
1762 size_t startidx
= 0 ;
1763 if (! preambleSearch ( bitStream
, preamble
, sizeof ( preamble
), size
, & startidx
)){
1764 // if didn't find preamble try again inverting
1765 if (! preambleSearch ( bitStream
, preamble_i
, sizeof ( preamble_i
), size
, & startidx
)) return - 1 ;
1768 if (* size
!= 64 && * size
!= 224 ) return - 2 ;
1770 for ( size_t i
= startidx
; i
< * size
; i
++)
1773 return ( int ) startidx
;
1776 // loop to get raw paradox waveform then FSK demodulate the TAG ID from it
1777 int ParadoxdemodFSK ( uint8_t * dest
, size_t * size
, uint32_t * hi2
, uint32_t * hi
, uint32_t * lo
) {
1778 if ( justNoise ( dest
, * size
)) return - 1 ;
1780 size_t numStart
= 0 , size2
=* size
, startIdx
= 0 ;
1782 * size
= fskdemod ( dest
, size2
, 50 , 1 , 10 , 8 ); //fsk2a
1783 if (* size
< 96 ) return - 2 ;
1785 // 00001111 bit pattern represent start of frame, 01 pattern represents a 0 and 10 represents a 1
1786 uint8_t preamble
[] = { 0 , 0 , 0 , 0 , 1 , 1 , 1 , 1 };
1788 uint8_t errChk
= preambleSearch ( dest
, preamble
, sizeof ( preamble
), size
, & startIdx
);
1789 if ( errChk
== 0 ) return - 3 ; //preamble not found
1791 numStart
= startIdx
+ sizeof ( preamble
);
1792 // final loop, go over previously decoded FSK data and manchester decode into usable tag ID
1793 for ( size_t idx
= numStart
; ( idx
- numStart
) < * size
- sizeof ( preamble
); idx
+= 2 ){
1794 if ( dest
[ idx
] == dest
[ idx
+ 1 ])
1795 return - 4 ; //not manchester data
1796 * hi2
= (* hi2
<< 1 )|(* hi
>> 31 );
1797 * hi
= (* hi
<< 1 )|(* lo
>> 31 );
1798 //Then, shift in a 0 or one into low
1799 if ( dest
[ idx
] && ! dest
[ idx
+ 1 ]) // 1 0
1804 return ( int ) startIdx
;
1807 // find presco preamble 0x10D in already demoded data
1808 int PrescoDemod ( uint8_t * dest
, size_t * size
) {
1809 //make sure buffer has data
1810 if (* size
< 64 * 2 ) return - 2 ;
1812 size_t startIdx
= 0 ;
1813 uint8_t preamble
[] = { 1 , 0 , 0 , 0 , 0 , 1 , 1 , 0 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 };
1814 uint8_t errChk
= preambleSearch ( dest
, preamble
, sizeof ( preamble
), size
, & startIdx
);
1815 if ( errChk
== 0 ) return - 4 ; //preamble not found
1816 //return start position
1817 return ( int ) startIdx
;
1821 // FSK Demod then try to locate a Farpointe Data (pyramid) ID
1822 int PyramiddemodFSK ( uint8_t * dest
, size_t * size
) {
1823 //make sure buffer has data
1824 if (* size
< 128 * 50 ) return - 5 ;
1826 //test samples are not just noise
1827 if ( justNoise ( dest
, * size
)) return - 1 ;
1830 * size
= fskdemod ( dest
, * size
, 50 , 1 , 10 , 8 ); // fsk2a RF/50
1831 if (* size
< 128 ) return - 2 ; //did we get a good demod?
1833 uint8_t preamble
[] = { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 };
1834 size_t startIdx
= 0 ;
1835 uint8_t errChk
= preambleSearch ( dest
, preamble
, sizeof ( preamble
), size
, & startIdx
);
1836 if ( errChk
== 0 ) return - 4 ; //preamble not found
1837 if (* size
!= 128 ) return - 3 ;
1838 return ( int ) startIdx
;
1842 // find viking preamble 0xF200 in already demoded data
1843 int VikingDemod_AM ( uint8_t * dest
, size_t * size
) {
1844 //make sure buffer has data
1845 if (* size
< 64 * 2 ) return - 2 ;
1847 size_t startIdx
= 0 ;
1848 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 };
1849 uint8_t errChk
= preambleSearch ( dest
, preamble
, sizeof ( preamble
), size
, & startIdx
);
1850 if ( errChk
== 0 ) return - 4 ; //preamble not found
1851 uint32_t checkCalc
= bytebits_to_byte ( dest
+ startIdx
, 8 ) ^ bytebits_to_byte ( dest
+ startIdx
+ 8 , 8 ) ^ bytebits_to_byte ( dest
+ startIdx
+ 16 , 8 )
1852 ^ bytebits_to_byte ( dest
+ startIdx
+ 24 , 8 ) ^ bytebits_to_byte ( dest
+ startIdx
+ 32 , 8 ) ^ bytebits_to_byte ( dest
+ startIdx
+ 40 , 8 )
1853 ^ bytebits_to_byte ( dest
+ startIdx
+ 48 , 8 ) ^ bytebits_to_byte ( dest
+ startIdx
+ 56 , 8 );
1854 if ( checkCalc
!= 0xA8 ) return - 5 ;
1855 if (* size
!= 64 ) return - 6 ;
1856 //return start position
1857 return ( int ) startIdx
;
1862 // find Visa2000 preamble in already demoded data
1863 int Visa2kDemod_AM ( uint8_t * dest
, size_t * size
) {
1864 if (* size
< 96 ) return - 1 ; //make sure buffer has data
1865 size_t startIdx
= 0 ;
1866 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 };
1867 if ( preambleSearch ( dest
, preamble
, sizeof ( preamble
), size
, & startIdx
) == 0 )
1868 return - 2 ; //preamble not found
1869 if (* size
!= 96 ) return - 3 ; //wrong demoded size
1870 //return start position
1871 return ( int ) startIdx
;