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