]> cvs.zerfleddert.de Git - proxmark3-svn/blob - client/cmddata.c
be6e35d58f49b0afdc4408835df6ebc22afe3c05
[proxmark3-svn] / client / cmddata.c
1 //-----------------------------------------------------------------------------
2 // Copyright (C) 2010 iZsh <izsh at fail0verflow.com>
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 // Data and Graph commands
9 //-----------------------------------------------------------------------------
10
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <string.h>
14 #include <inttypes.h>
15
16 #include <limits.h>
17 #include "proxmark3.h"
18 #include "data.h"
19 #include "ui.h"
20 #include "graph.h"
21 #include "cmdparser.h"
22 #include "util.h"
23 #include "cmdmain.h"
24 #include "cmddata.h"
25
26 static int CmdHelp(const char *Cmd);
27
28 int CmdAmp(const char *Cmd)
29 {
30 int i, rising, falling;
31 int max = INT_MIN, min = INT_MAX;
32
33 for (i = 10; i < GraphTraceLen; ++i) {
34 if (GraphBuffer[i] > max)
35 max = GraphBuffer[i];
36 if (GraphBuffer[i] < min)
37 min = GraphBuffer[i];
38 }
39
40 if (max != min) {
41 rising = falling= 0;
42 for (i = 0; i < GraphTraceLen; ++i) {
43 if (GraphBuffer[i + 1] < GraphBuffer[i]) {
44 if (rising) {
45 GraphBuffer[i] = max;
46 rising = 0;
47 }
48 falling = 1;
49 }
50 if (GraphBuffer[i + 1] > GraphBuffer[i]) {
51 if (falling) {
52 GraphBuffer[i] = min;
53 falling = 0;
54 }
55 rising= 1;
56 }
57 }
58 }
59 RepaintGraphWindow();
60 return 0;
61 }
62
63 /*
64 * Generic command to demodulate ASK.
65 *
66 * Argument is convention: positive or negative (High mod means zero
67 * or high mod means one)
68 *
69 * Updates the Graph trace with 0/1 values
70 *
71 * Arguments:
72 * c : 0 or 1
73 */
74 //this method is dependant on all highs and lows to be the same(or clipped) this creates issues[marshmellow] it also ignores the clock
75 int Cmdaskdemod(const char *Cmd)
76 {
77 int i;
78 int c, high = 0, low = 0;
79
80 // TODO: complain if we do not give 2 arguments here !
81 // (AL - this doesn't make sense! we're only using one argument!!!)
82 sscanf(Cmd, "%i", &c);
83
84 /* Detect high and lows and clock */
85 // (AL - clock???)
86 for (i = 0; i < GraphTraceLen; ++i)
87 {
88 if (GraphBuffer[i] > high)
89 high = GraphBuffer[i];
90 else if (GraphBuffer[i] < low)
91 low = GraphBuffer[i];
92 }
93 if (c != 0 && c != 1) {
94 PrintAndLog("Invalid argument: %s", Cmd);
95 return 0;
96 }
97 //prime loop
98 if (GraphBuffer[0] > 0) {
99 GraphBuffer[0] = 1-c;
100 } else {
101 GraphBuffer[0] = c;
102 }
103 for (i = 1; i < GraphTraceLen; ++i) {
104 /* Transitions are detected at each peak
105 * Transitions are either:
106 * - we're low: transition if we hit a high
107 * - we're high: transition if we hit a low
108 * (we need to do it this way because some tags keep high or
109 * low for long periods, others just reach the peak and go
110 * down)
111 */
112 //[marhsmellow] change == to >= for high and <= for low for fuzz
113 if ((GraphBuffer[i] == high) && (GraphBuffer[i - 1] == c)) {
114 GraphBuffer[i] = 1 - c;
115 } else if ((GraphBuffer[i] == low) && (GraphBuffer[i - 1] == (1 - c))){
116 GraphBuffer[i] = c;
117 } else {
118 /* No transition */
119 GraphBuffer[i] = GraphBuffer[i - 1];
120 }
121 }
122 RepaintGraphWindow();
123 return 0;
124 }
125
126 void printBitStream(int BitStream[], uint32_t bitLen){
127 uint32_t i = 0;
128 if (bitLen<16) return;
129 if (bitLen>512) bitLen=512;
130 for (i = 0; i < (bitLen-16); i+=16) {
131 PrintAndLog("%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i",
132 BitStream[i],
133 BitStream[i+1],
134 BitStream[i+2],
135 BitStream[i+3],
136 BitStream[i+4],
137 BitStream[i+5],
138 BitStream[i+6],
139 BitStream[i+7],
140 BitStream[i+8],
141 BitStream[i+9],
142 BitStream[i+10],
143 BitStream[i+11],
144 BitStream[i+12],
145 BitStream[i+13],
146 BitStream[i+14],
147 BitStream[i+15]);
148 }
149 return;
150 }
151 void printBitStream2(uint8_t BitStream[], uint32_t bitLen){
152 uint32_t i = 0;
153 if (bitLen<16) {
154 PrintAndLog("Too few bits found: %d",bitLen);
155 return;
156 }
157 if (bitLen>512) bitLen=512;
158 for (i = 0; i < (bitLen-16); i+=16) {
159 PrintAndLog("%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i",
160 BitStream[i],
161 BitStream[i+1],
162 BitStream[i+2],
163 BitStream[i+3],
164 BitStream[i+4],
165 BitStream[i+5],
166 BitStream[i+6],
167 BitStream[i+7],
168 BitStream[i+8],
169 BitStream[i+9],
170 BitStream[i+10],
171 BitStream[i+11],
172 BitStream[i+12],
173 BitStream[i+13],
174 BitStream[i+14],
175 BitStream[i+15]);
176 }
177 return;
178 }
179
180 //by marshmellow
181 //takes 1s and 0s and searches for EM410x format - output EM ID
182 int Em410xDecode(const char *Cmd)
183 {
184 //no arguments needed - built this way in case we want this to be a direct call from "data " cmds in the future
185 // otherwise could be a void with no arguments
186 //set defaults
187 int high=0, low=0;
188 uint64_t lo=0; //hi=0,
189
190 uint32_t i = 0;
191 uint32_t initLoopMax = 1000;
192 if (initLoopMax>GraphTraceLen) initLoopMax=GraphTraceLen;
193
194 for (;i < initLoopMax; ++i) //1000 samples should be plenty to find high and low values
195 {
196 if (GraphBuffer[i] > high)
197 high = GraphBuffer[i];
198 else if (GraphBuffer[i] < low)
199 low = GraphBuffer[i];
200 }
201 if (((high !=1)||(low !=0))){ //allow only 1s and 0s
202 PrintAndLog("no data found");
203 return 0;
204 }
205 uint8_t parityTest=0;
206 // 111111111 bit pattern represent start of frame
207 int frame_marker_mask[] = {1,1,1,1,1,1,1,1,1};
208 uint32_t idx = 0;
209 uint32_t ii=0;
210 uint8_t resetCnt = 0;
211 while( (idx + 64) < GraphTraceLen) {
212 restart:
213 // search for a start of frame marker
214 if ( memcmp(GraphBuffer+idx, frame_marker_mask, sizeof(frame_marker_mask)) == 0)
215 { // frame marker found
216 idx+=9;//sizeof(frame_marker_mask);
217 for (i=0; i<10;i++){
218 for(ii=0; ii<5; ++ii){
219 parityTest += GraphBuffer[(i*5)+ii+idx];
220 }
221 if (parityTest== ((parityTest>>1)<<1)){
222 parityTest=0;
223 for (ii=0; ii<4;++ii){
224 //hi = (hi<<1)|(lo>>31);
225 lo=(lo<<1LL)|(GraphBuffer[(i*5)+ii+idx]);
226 }
227 //PrintAndLog("DEBUG: EM parity passed parity val: %d, i:%d, ii:%d,idx:%d, Buffer: %d%d%d%d%d,lo: %d",parityTest,i,ii,idx,GraphBuffer[idx+ii+(i*5)-5],GraphBuffer[idx+ii+(i*5)-4],GraphBuffer[idx+ii+(i*5)-3],GraphBuffer[idx+ii+(i*5)-2],GraphBuffer[idx+ii+(i*5)-1],lo);
228 }else {//parity failed
229 //PrintAndLog("DEBUG: EM parity failed parity val: %d, i:%d, ii:%d,idx:%d, Buffer: %d%d%d%d%d",parityTest,i,ii,idx,GraphBuffer[idx+ii+(i*5)-5],GraphBuffer[idx+ii+(i*5)-4],GraphBuffer[idx+ii+(i*5)-3],GraphBuffer[idx+ii+(i*5)-2],GraphBuffer[idx+ii+(i*5)-1]);
230 parityTest=0;
231 idx-=8;
232 if (resetCnt>5)return 0;
233 resetCnt++;
234 goto restart;//continue;
235 }
236 }
237 //skip last 5 bit parity test for simplicity.
238
239 //get Unique ID
240 uint64_t iii=1;
241 uint64_t id2lo=0; //id2hi=0,
242 //for (i=0;i<8;i++){ //for uint32 instead of uint64
243 // id2hi=(id2hi<<1)|((hi & (iii<<(i)))>>i);
244 //}
245 for (ii=5; ii>0;ii--){
246 for (i=0;i<8;i++){
247 id2lo=(id2lo<<1LL)|((lo & (iii<<(i+((ii-1)*8))))>>(i+((ii-1)*8)));
248 }
249 }
250 //output em id
251 PrintAndLog("EM TAG ID : %010llx", lo);
252 PrintAndLog("Unique TAG ID: %010llx", id2lo); //id2hi,
253 PrintAndLog("DEZ 8 : %08lld",lo & 0xFFFFFF);
254 PrintAndLog("DEZ 10 : %010lld",lo & 0xFFFFFF);
255 PrintAndLog("DEZ 5.5 : %05lld.%05lld",(lo>>16LL) & 0xFFFF,(lo & 0xFFFF));
256 PrintAndLog("DEZ 3.5A : %03lld.%05lld",(lo>>32ll),(lo & 0xFFFF));
257 PrintAndLog("DEZ 14/IK2 : %014lld",lo);
258 PrintAndLog("DEZ 15/IK3 : %015lld",id2lo);
259 PrintAndLog("Other : %05lld_%03lld_%08lld",(lo&0xFFFF),((lo>>16LL) & 0xFF),(lo & 0xFFFFFF));
260 return 0;
261 }else{
262 idx++;
263 }
264 }
265 return 0;
266 }
267
268
269 //by marshmellow
270 //takes 2 arguments - clock and invert both as integers
271 //prints binary found and saves in graphbuffer for further commands
272 int Cmdaskmandemod(const char *Cmd)
273 {
274 uint32_t i;
275 int invert=0; //invert default
276 int high = 0, low = 0;
277 int clk=DetectClock(0); //clock default
278 uint8_t BitStream[MAX_GRAPH_TRACE_LEN] = {0};
279
280 sscanf(Cmd, "%i %i", &clk, &invert);
281 if (clk<8) clk =64;
282 if (clk<32) clk=32;
283 if (invert != 0 && invert != 1) {
284 PrintAndLog("Invalid argument: %s", Cmd);
285 return 0;
286 }
287 uint32_t initLoopMax = 1000;
288 if (initLoopMax>GraphTraceLen) initLoopMax=GraphTraceLen;
289 // Detect high and lows
290 PrintAndLog("Using Clock: %d and invert=%d",clk,invert);
291 for (i = 0; i < initLoopMax; ++i) //1000 samples should be plenty to find high and low values
292 {
293 if (GraphBuffer[i] > high)
294 high = GraphBuffer[i];
295 else if (GraphBuffer[i] < low)
296 low = GraphBuffer[i];
297 }
298 if ((high < 30) && ((high !=1)||(low !=-1))){ //throw away static - allow 1 and -1 (in case of threshold command first)
299 PrintAndLog("no data found");
300 return 0;
301 }
302 //13% fuzz in case highs and lows aren't clipped [marshmellow]
303 high=(int)(0.75*high);
304 low=(int)(0.75*low);
305
306 //PrintAndLog("DEBUG - valid high: %d - valid low: %d",high,low);
307 int lastBit = 0; //set first clock check
308 uint32_t bitnum = 0; //output counter
309 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
310 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
311 uint32_t iii = 0;
312 uint32_t gLen = GraphTraceLen;
313 if (gLen > 500) gLen=500;
314 uint8_t errCnt =0;
315 uint32_t bestStart = GraphTraceLen;
316 uint32_t bestErrCnt = (GraphTraceLen/1000);
317 //PrintAndLog("DEBUG - lastbit - %d",lastBit);
318 //loop to find first wave that works
319 for (iii=0; iii < gLen; ++iii){
320 if ((GraphBuffer[iii]>=high)||(GraphBuffer[iii]<=low)){
321 lastBit=iii-clk;
322 //loop through to see if this start location works
323 for (i = iii; i < GraphTraceLen; ++i) {
324 if ((GraphBuffer[i] >= high) && ((i-lastBit)>(clk-tol))){
325 lastBit+=clk;
326 BitStream[bitnum] = invert;
327 bitnum++;
328 } else if ((GraphBuffer[i] <= low) && ((i-lastBit)>(clk-tol))){
329 //low found and we are expecting a bar
330 lastBit+=clk;
331 BitStream[bitnum] = 1-invert;
332 bitnum++;
333 } else {
334 //mid value found or no bar supposed to be here
335 if ((i-lastBit)>(clk+tol)){
336 //should have hit a high or low based on clock!!
337
338
339 //debug
340 //PrintAndLog("DEBUG - no wave in expected area - location: %d, expected: %d-%d, lastBit: %d - resetting search",i,(lastBit+(clk-((int)(tol)))),(lastBit+(clk+((int)(tol)))),lastBit);
341 if (bitnum > 0){
342 BitStream[bitnum]=77;
343 bitnum++;
344 }
345
346
347 errCnt++;
348 lastBit+=clk;//skip over until hit too many errors
349 if (errCnt>((GraphTraceLen/1000))){ //allow 1 error for every 1000 samples else start over
350 errCnt=0;
351 bitnum=0;//start over
352 break;
353 }
354 }
355 }
356 }
357 //we got more than 64 good bits and not all errors
358 if ((bitnum > (64+errCnt)) && (errCnt<(GraphTraceLen/1000))) {
359 //possible good read
360 if (errCnt==0) break; //great read - finish
361 if (bestStart == iii) break; //if current run == bestErrCnt run (after exhausted testing) then finish
362 if (errCnt<bestErrCnt){ //set this as new best run
363 bestErrCnt=errCnt;
364 bestStart = iii;
365 }
366 }
367 }
368 if (iii>=gLen){ //exhausted test
369 //if there was a ok test go back to that one and re-run the best run (then dump after that run)
370 if (bestErrCnt < (GraphTraceLen/1000)) iii=bestStart;
371 }
372 }
373 if (bitnum>16){
374
375 PrintAndLog("Data start pos:%d, lastBit:%d, stop pos:%d, numBits:%d",iii,lastBit,i,bitnum);
376 //move BitStream back to GraphBuffer
377 ClearGraph(0);
378 for (i=0; i < bitnum; ++i){
379 GraphBuffer[i]=BitStream[i];
380 }
381 GraphTraceLen=bitnum;
382 RepaintGraphWindow();
383 //output
384 if (errCnt>0){
385 PrintAndLog("# Errors during Demoding (shown as 77 in bit stream): %d",errCnt);
386 }
387 PrintAndLog("ASK decoded bitstream:");
388 // Now output the bitstream to the scrollback by line of 16 bits
389 printBitStream2(BitStream,bitnum);
390 Em410xDecode(Cmd);
391 }
392 return 0;
393 }
394
395 int CmdAutoCorr(const char *Cmd)
396 {
397 static int CorrelBuffer[MAX_GRAPH_TRACE_LEN];
398
399 int window = atoi(Cmd);
400
401 if (window == 0) {
402 PrintAndLog("needs a window");
403 return 0;
404 }
405 if (window >= GraphTraceLen) {
406 PrintAndLog("window must be smaller than trace (%d samples)",
407 GraphTraceLen);
408 return 0;
409 }
410
411 PrintAndLog("performing %d correlations", GraphTraceLen - window);
412
413 for (int i = 0; i < GraphTraceLen - window; ++i) {
414 int sum = 0;
415 for (int j = 0; j < window; ++j) {
416 sum += (GraphBuffer[j]*GraphBuffer[i + j]) / 256;
417 }
418 CorrelBuffer[i] = sum;
419 }
420 GraphTraceLen = GraphTraceLen - window;
421 memcpy(GraphBuffer, CorrelBuffer, GraphTraceLen * sizeof (int));
422
423 RepaintGraphWindow();
424 return 0;
425 }
426
427 int CmdBitsamples(const char *Cmd)
428 {
429 int cnt = 0;
430 uint8_t got[12288];
431
432 GetFromBigBuf(got,sizeof(got),0);
433 WaitForResponse(CMD_ACK,NULL);
434
435 for (int j = 0; j < sizeof(got); j++) {
436 for (int k = 0; k < 8; k++) {
437 if(got[j] & (1 << (7 - k))) {
438 GraphBuffer[cnt++] = 1;
439 } else {
440 GraphBuffer[cnt++] = 0;
441 }
442 }
443 }
444 GraphTraceLen = cnt;
445 RepaintGraphWindow();
446 return 0;
447 }
448
449 /*
450 * Convert to a bitstream
451 */
452 int CmdBitstream(const char *Cmd)
453 {
454 int i, j;
455 int bit;
456 int gtl;
457 int clock;
458 int low = 0;
459 int high = 0;
460 int hithigh, hitlow, first;
461
462 /* Detect high and lows and clock */
463 for (i = 0; i < GraphTraceLen; ++i)
464 {
465 if (GraphBuffer[i] > high)
466 high = GraphBuffer[i];
467 else if (GraphBuffer[i] < low)
468 low = GraphBuffer[i];
469 }
470
471 /* Get our clock */
472 clock = GetClock(Cmd, high, 1);
473 gtl = ClearGraph(0);
474
475 bit = 0;
476 for (i = 0; i < (int)(gtl / clock); ++i)
477 {
478 hithigh = 0;
479 hitlow = 0;
480 first = 1;
481 /* Find out if we hit both high and low peaks */
482 for (j = 0; j < clock; ++j)
483 {
484 if (GraphBuffer[(i * clock) + j] == high)
485 hithigh = 1;
486 else if (GraphBuffer[(i * clock) + j] == low)
487 hitlow = 1;
488 /* it doesn't count if it's the first part of our read
489 because it's really just trailing from the last sequence */
490 if (first && (hithigh || hitlow))
491 hithigh = hitlow = 0;
492 else
493 first = 0;
494
495 if (hithigh && hitlow)
496 break;
497 }
498
499 /* If we didn't hit both high and low peaks, we had a bit transition */
500 if (!hithigh || !hitlow)
501 bit ^= 1;
502
503 AppendGraph(0, clock, bit);
504 // for (j = 0; j < (int)(clock/2); j++)
505 // GraphBuffer[(i * clock) + j] = bit ^ 1;
506 // for (j = (int)(clock/2); j < clock; j++)
507 // GraphBuffer[(i * clock) + j] = bit;
508 }
509
510 RepaintGraphWindow();
511 return 0;
512 }
513
514 int CmdBuffClear(const char *Cmd)
515 {
516 UsbCommand c = {CMD_BUFF_CLEAR};
517 SendCommand(&c);
518 ClearGraph(true);
519 return 0;
520 }
521
522 int CmdDec(const char *Cmd)
523 {
524 for (int i = 0; i < (GraphTraceLen / 2); ++i)
525 GraphBuffer[i] = GraphBuffer[i * 2];
526 GraphTraceLen /= 2;
527 PrintAndLog("decimated by 2");
528 RepaintGraphWindow();
529 return 0;
530 }
531
532 /* Print our clock rate */
533 int CmdDetectClockRate(const char *Cmd)
534 {
535 int clock = DetectClock(0);
536 PrintAndLog("Auto-detected clock rate: %d", clock);
537 return 0;
538 }
539
540 //by marshmellow
541 //demod GraphBuffer wave to 0s and 1s for each wave - 0s for short waves 1s for long waves
542 size_t fsk_wave_demod(int size)
543 {
544 uint32_t last_transition = 0;
545 uint32_t idx = 1;
546 uint32_t maxVal = 0;
547 // we don't care about actual value, only if it's more or less than a
548 // threshold essentially we capture zero crossings for later analysis
549 for(idx=1; idx<size; idx++){
550 if(maxVal<GraphBuffer[idx]) maxVal = GraphBuffer[idx];
551 }
552 // set close to the top of the wave threshold with 13% margin for error
553 // less likely to get a false transition up there.
554 // (but have to be careful not to go too high and miss some short waves)
555 uint32_t threshold_value = (uint32_t)(maxVal*.87);
556 idx=1;
557 // int threshold_value = 100;
558
559 // sync to first lo-hi transition, and threshold
560 // PrintAndLog("FSK init complete size: %d",size);//debug
561 // Need to threshold first sample
562 if(GraphBuffer[0] < threshold_value) GraphBuffer[0] = 0;
563 else GraphBuffer[0] = 1;
564 size_t numBits = 0;
565 // count cycles between consecutive lo-hi transitions, there should be either 8 (fc/8)
566 // or 10 (fc/10) cycles but in practice due to noise etc we may end up with with anywhere
567 // between 7 to 11 cycles so fuzz it by treat anything <9 as 8 and anything else as 10
568 for(idx = 1; idx < size; idx++) {
569 // threshold current value
570 if (GraphBuffer[idx] < threshold_value) GraphBuffer[idx] = 0;
571 else GraphBuffer[idx] = 1;
572 // Check for 0->1 transition
573 if (GraphBuffer[idx-1] < GraphBuffer[idx]) { // 0 -> 1 transition
574 if (idx-last_transition<6){
575 // do nothing with extra garbage (shouldn't be any) noise tolerance?
576 } else if(idx-last_transition < 9) {
577 GraphBuffer[numBits]=1;
578 // Other fsk demods reverse this making the short waves 1 and long waves 0
579 // this is really backwards... smaller waves will typically be 0 and larger 1 [marshmellow]
580 // but will leave as is and invert when needed later
581 } else{
582 GraphBuffer[numBits]=0;
583 }
584 last_transition = idx;
585 numBits++;
586 // PrintAndLog("numbits %d",numBits);
587 }
588 }
589 return numBits; //Actually, it returns the number of bytes, but each byte represents a bit: 1 or 0
590 }
591 uint32_t myround(float f)
592 {
593 if (f >= UINT_MAX) return UINT_MAX;
594 return (uint32_t) (f + (float)0.5);
595 }
596
597 //by marshmellow (from holiman's base)
598 //translate 11111100000 to 10
599 size_t aggregate_bits(int size, uint8_t rfLen, uint8_t maxConsequtiveBits, uint8_t invert) //,uint8_t l2h_crossing_value
600 {
601 int lastval=GraphBuffer[0];
602 uint32_t idx=0;
603 size_t numBits=0;
604 uint32_t n=1;
605 uint32_t n2=0;
606 for( idx=1; idx < size; idx++) {
607
608 if (GraphBuffer[idx]==lastval) {
609 n++;
610 continue;
611 }
612 // if lastval was 1, we have a 1->0 crossing
613 if ( GraphBuffer[idx-1]==1 ) {
614 n=myround((float)(n+1)/((float)(rfLen)/(float)8)); //-2 noise tolerance
615
616 // n=(n+1) / h2l_crossing_value;
617 //truncating could get us into trouble
618 //now we will try with actual clock (RF/64 or RF/50) variable instead
619 //then devide with float casting then truncate after more acurate division
620 //and round to nearest int
621 //like n = (((float)n)/(float)rfLen/(float)10);
622 } else {// 0->1 crossing
623 n=myround((float)(n+1)/((float)(rfLen-2)/(float)10)); // as int 120/6 = 20 as float 120/(64/10) = 18 (18.75)
624 //n=(n+1) / l2h_crossing_value;
625 }
626 if (n == 0) n = 1; //this should never happen... should we error if it does?
627
628 if (n < maxConsequtiveBits) // Consecutive //when the consecutive bits are low - the noise tolerance can be high
629 //if it is high then we must be careful how much noise tolerance we allow
630 {
631 if (invert==0){ // do not invert bits
632 for (n2=0; n2<n; n2++){
633 GraphBuffer[numBits+n2]=GraphBuffer[idx-1];
634 }
635 //memset(GraphBuffer+numBits, GraphBuffer[idx-1] , n);
636 }else{ // invert bits
637 for (n2=0; n2<n; n2++){
638 GraphBuffer[numBits+n2]=GraphBuffer[idx-1]^1;
639 }
640 //memset(GraphBuffer+numBits, GraphBuffer[idx-1]^1 , n);
641 }
642 numBits += n;
643 }
644 n=0;
645 lastval=GraphBuffer[idx];
646 }//end for
647 return numBits;
648 }
649
650 //by marshmellow (from holiman's base)
651 // full fsk demod from GraphBuffer wave to decoded 1s and 0s (no mandemod)
652 size_t fskdemod(uint8_t rfLen, uint8_t invert)
653 {
654 //uint8_t h2l_crossing_value = 6;
655 //uint8_t l2h_crossing_value = 5;
656
657 // if (rfLen==64) //currently only know settings for RF/64 change from default if option entered
658 // {
659 // h2l_crossing_value=8; //or 8 as 64/8 = 8
660 // l2h_crossing_value=6; //or 6.4 as 64/10 = 6.4
661 // }
662 size_t size = GraphTraceLen;
663 // FSK demodulator
664 size = fsk_wave_demod(size);
665 size = aggregate_bits(size,rfLen,192,invert);
666 // size = aggregate_bits(size, h2l_crossing_value, l2h_crossing_value,192, invert); //192=no limit to same values
667 //done messing with GraphBuffer - repaint
668 RepaintGraphWindow();
669 return size;
670 }
671 uint32_t bytebits_to_byte(int* src, int numbits)
672 {
673 uint32_t num = 0;
674 for(int i = 0 ; i < numbits ; i++)
675 {
676 num = (num << 1) | (*src);
677 src++;
678 }
679 return num;
680 }
681
682 //by marshmellow
683 //fsk demod and print binary
684 int CmdFSKrawdemod(const char *Cmd)
685 {
686 //raw fsk demod no manchester decoding no start bit finding just get binary from wave
687 //set defaults
688 uint8_t rfLen = 50;
689 uint8_t invert=0;
690 //set options from parameters entered with the command
691 if (strlen(Cmd)>0 && strlen(Cmd)<=2) {
692 rfLen=param_get8(Cmd, 0); //if rfLen option only is used
693 if (rfLen==1){
694 invert=1; //if invert option only is used
695 rfLen = 50;
696 } else if(rfLen==0) rfLen=50;
697 }
698 if (strlen(Cmd)>2) {
699 rfLen=param_get8(Cmd, 0); //if both options are used
700 invert=param_get8(Cmd,1);
701 }
702 PrintAndLog("Args invert: %d \nClock:%d",invert,rfLen);
703
704 size_t size = fskdemod(rfLen,invert);
705
706 PrintAndLog("FSK decoded bitstream:");
707 // Now output the bitstream to the scrollback by line of 16 bits
708 if(size > (7*32)+2) size = (7*32)+2; //only output a max of 7 blocks of 32 bits most tags will have full bit stream inside that sample size
709 printBitStream(GraphBuffer,size);
710
711 ClearGraph(1);
712 return 0;
713 }
714
715 //by marshmellow
716 int CmdFSKdemodHID(const char *Cmd)
717 {
718 //raw fsk demod no manchester decoding no start bit finding just get binary from wave
719 //set defaults
720 uint8_t rfLen = 50;
721 uint8_t invert=0;//param_get8(Cmd, 0);
722 size_t idx=0;
723 uint32_t hi2=0, hi=0, lo=0;
724
725 //get binary from fsk wave
726 size_t size = fskdemod(rfLen,invert);
727
728 // final loop, go over previously decoded fsk data and now manchester decode into usable tag ID
729 // 111000 bit pattern represent start of frame, 01 pattern represents a 1 and 10 represents a 0
730 int frame_marker_mask[] = {1,1,1,0,0,0};
731 int numshifts = 0;
732 idx = 0;
733 while( idx + 6 < size) {
734 // search for a start of frame marker
735
736 if ( memcmp(GraphBuffer+idx, frame_marker_mask, sizeof(frame_marker_mask)) == 0)
737 { // frame marker found
738 idx+=6;//sizeof(frame_marker_mask); //size of int is >6
739 while(GraphBuffer[idx] != GraphBuffer[idx+1] && idx < size-2)
740 {
741 // Keep going until next frame marker (or error)
742 // Shift in a bit. Start by shifting high registers
743 hi2 = (hi2<<1)|(hi>>31);
744 hi = (hi<<1)|(lo>>31);
745 //Then, shift in a 0 or one into low
746 if (GraphBuffer[idx] && !GraphBuffer[idx+1]) // 1 0
747 lo=(lo<<1)|0;
748 else // 0 1
749 lo=(lo<<1)|1;
750 numshifts++;
751 idx += 2;
752 }
753
754 //PrintAndLog("Num shifts: %d ", numshifts);
755 // Hopefully, we read a tag and hit upon the next frame marker
756 if(idx + 6 < size)
757 {
758 if ( memcmp(GraphBuffer+(idx), frame_marker_mask, sizeof(frame_marker_mask)) == 0)
759 {
760 if (hi2 != 0){ //extra large HID tags
761 PrintAndLog("TAG ID: %x%08x%08x (%d)",
762 (unsigned int) hi2, (unsigned int) hi, (unsigned int) lo, (unsigned int) (lo>>1) & 0xFFFF);
763 }
764 else { //standard HID tags <38 bits
765 //Dbprintf("TAG ID: %x%08x (%d)",(unsigned int) hi, (unsigned int) lo, (unsigned int) (lo>>1) & 0xFFFF); //old print cmd
766 uint8_t bitlen = 0;
767 uint32_t fc = 0;
768 uint32_t cardnum = 0;
769 if (((hi>>5)&1)==1){//if bit 38 is set then < 37 bit format is used
770 uint32_t lo2=0;
771 lo2=(((hi & 15) << 12) | (lo>>20)); //get bits 21-37 to check for format len bit
772 uint8_t idx3 = 1;
773 while(lo2>1){ //find last bit set to 1 (format len bit)
774 lo2=lo2>>1;
775 idx3++;
776 }
777 bitlen =idx3+19;
778 fc =0;
779 cardnum=0;
780 if(bitlen==26){
781 cardnum = (lo>>1)&0xFFFF;
782 fc = (lo>>17)&0xFF;
783 }
784 if(bitlen==37){
785 cardnum = (lo>>1)&0x7FFFF;
786 fc = ((hi&0xF)<<12)|(lo>>20);
787 }
788 if(bitlen==34){
789 cardnum = (lo>>1)&0xFFFF;
790 fc= ((hi&1)<<15)|(lo>>17);
791 }
792 if(bitlen==35){
793 cardnum = (lo>>1)&0xFFFFF;
794 fc = ((hi&1)<<11)|(lo>>21);
795 }
796 }
797 else { //if bit 38 is not set then 37 bit format is used
798 bitlen= 37;
799 fc =0;
800 cardnum=0;
801 if(bitlen==37){
802 cardnum = (lo>>1)&0x7FFFF;
803 fc = ((hi&0xF)<<12)|(lo>>20);
804 }
805 }
806
807 PrintAndLog("TAG ID: %x%08x (%d) - Format Len: %dbit - FC: %d - Card: %d",
808 (unsigned int) hi, (unsigned int) lo, (unsigned int) (lo>>1) & 0xFFFF,
809 (unsigned int) bitlen, (unsigned int) fc, (unsigned int) cardnum);
810 ClearGraph(1);
811 return 0;
812 }
813 }
814 }
815 // reset
816 hi2 = hi = lo = 0;
817 numshifts = 0;
818 }else
819 {
820 idx++;
821 }
822 }
823 if (idx + sizeof(frame_marker_mask) >= size){
824 PrintAndLog("start bits for hid not found");
825 PrintAndLog("FSK decoded bitstream:");
826 // Now output the bitstream to the scrollback by line of 16 bits
827 printBitStream(GraphBuffer,size);
828
829 }
830 ClearGraph(1);
831 return 0;
832 }
833
834 //by marshmellow
835 int CmdFSKdemodIO(const char *Cmd)
836 {
837 //raw fsk demod no manchester decoding no start bit finding just get binary from wave
838 //set defaults
839 uint8_t rfLen = 64;
840 uint8_t invert=1;
841 size_t idx=0;
842 uint8_t testMax=0;
843 //test samples are not just noise
844 if (GraphTraceLen < 64) return 0;
845 for(idx=0;idx<64;idx++){
846 if (testMax<GraphBuffer[idx]) testMax=GraphBuffer[idx];
847 }
848 idx=0;
849 //get full binary from fsk wave
850 size_t size = fskdemod(rfLen,invert);
851
852 //if not just noise
853 //PrintAndLog("testMax %d",testMax);
854 if (testMax>40){
855 //Index map
856 //0 10 20 30 40 50 60
857 //| | | | | | |
858 //01234567 8 90123456 7 89012345 6 78901234 5 67890123 4 56789012 3 45678901 23
859 //-----------------------------------------------------------------------------
860 //00000000 0 11110000 1 facility 1 version* 1 code*one 1 code*two 1 ???????? 11
861 //
862 //XSF(version)facility:codeone+codetwo (raw)
863 //Handle the data
864 int mask[] = {0,0,0,0,0,0,0,0,0,1};
865 for( idx=0; idx < (size - 74); idx++) {
866 if ( memcmp(GraphBuffer + idx, mask, sizeof(mask))==0) {
867 //frame marker found
868 if (GraphBuffer[idx+17]==1 && GraphBuffer[idx+26]==1 && GraphBuffer[idx+35]==1 && GraphBuffer[idx+44]==1 && GraphBuffer[idx+53]==1){
869 //confirmed proper separator bits found
870
871 PrintAndLog("%d%d%d%d%d%d%d%d %d",GraphBuffer[idx], GraphBuffer[idx+1], GraphBuffer[idx+2], GraphBuffer[idx+3], GraphBuffer[idx+4], GraphBuffer[idx+5], GraphBuffer[idx+6], GraphBuffer[idx+7], GraphBuffer[idx+8]);
872 PrintAndLog("%d%d%d%d%d%d%d%d %d",GraphBuffer[idx+9], GraphBuffer[idx+10], GraphBuffer[idx+11],GraphBuffer[idx+12],GraphBuffer[idx+13],GraphBuffer[idx+14],GraphBuffer[idx+15],GraphBuffer[idx+16],GraphBuffer[idx+17]);
873 PrintAndLog("%d%d%d%d%d%d%d%d %d",GraphBuffer[idx+18], GraphBuffer[idx+19], GraphBuffer[idx+20],GraphBuffer[idx+21],GraphBuffer[idx+22],GraphBuffer[idx+23],GraphBuffer[idx+24],GraphBuffer[idx+25],GraphBuffer[idx+26]);
874 PrintAndLog("%d%d%d%d%d%d%d%d %d",GraphBuffer[idx+27], GraphBuffer[idx+28], GraphBuffer[idx+29],GraphBuffer[idx+30],GraphBuffer[idx+31],GraphBuffer[idx+32],GraphBuffer[idx+33],GraphBuffer[idx+34],GraphBuffer[idx+35]);
875 PrintAndLog("%d%d%d%d%d%d%d%d %d",GraphBuffer[idx+36], GraphBuffer[idx+37], GraphBuffer[idx+38],GraphBuffer[idx+39],GraphBuffer[idx+40],GraphBuffer[idx+41],GraphBuffer[idx+42],GraphBuffer[idx+43],GraphBuffer[idx+44]);
876 PrintAndLog("%d%d%d%d%d%d%d%d %d",GraphBuffer[idx+45], GraphBuffer[idx+46], GraphBuffer[idx+47],GraphBuffer[idx+48],GraphBuffer[idx+49],GraphBuffer[idx+50],GraphBuffer[idx+51],GraphBuffer[idx+52],GraphBuffer[idx+53]);
877 PrintAndLog("%d%d%d%d%d%d%d%d %d%d",GraphBuffer[idx+54],GraphBuffer[idx+55],GraphBuffer[idx+56],GraphBuffer[idx+57],GraphBuffer[idx+58],GraphBuffer[idx+59],GraphBuffer[idx+60],GraphBuffer[idx+61],GraphBuffer[idx+62],GraphBuffer[idx+63]);
878
879 uint32_t code = bytebits_to_byte(GraphBuffer+idx,32);
880 uint32_t code2 = bytebits_to_byte(GraphBuffer+idx+32,32);
881 short version = bytebits_to_byte(GraphBuffer+idx+27,8); //14,4
882 uint8_t facilitycode = bytebits_to_byte(GraphBuffer+idx+19,8) ;
883 uint16_t number = (bytebits_to_byte(GraphBuffer+idx+36,8)<<8)|(bytebits_to_byte(GraphBuffer+idx+45,8)); //36,9
884
885 PrintAndLog("XSF(%02d)%02x:%d (%08x%08x)",version,facilitycode,number,code,code2);
886 ClearGraph(1);
887 return 0;
888 } else {
889 PrintAndLog("thought we had a valid tag but did not match format");
890 }
891 }
892 }
893 if (idx >= (size-74)){
894 PrintAndLog("start bits for io prox not found");
895 PrintAndLog("FSK decoded bitstream:");
896 // Now output the bitstream to the scrollback by line of 16 bits
897 printBitStream(GraphBuffer,size);
898 }
899 }
900 ClearGraph(1);
901 return 0;
902 }
903 int CmdFSKdemod(const char *Cmd) //old CmdFSKdemod needs updating
904 {
905 static const int LowTone[] = {
906 1, 1, 1, 1, 1, -1, -1, -1, -1, -1,
907 1, 1, 1, 1, 1, -1, -1, -1, -1, -1,
908 1, 1, 1, 1, 1, -1, -1, -1, -1, -1,
909 1, 1, 1, 1, 1, -1, -1, -1, -1, -1,
910 1, 1, 1, 1, 1, -1, -1, -1, -1, -1
911 };
912 static const int HighTone[] = {
913 1, 1, 1, 1, 1, -1, -1, -1, -1,
914 1, 1, 1, 1, -1, -1, -1, -1,
915 1, 1, 1, 1, -1, -1, -1, -1,
916 1, 1, 1, 1, -1, -1, -1, -1,
917 1, 1, 1, 1, -1, -1, -1, -1,
918 1, 1, 1, 1, -1, -1, -1, -1, -1,
919 };
920
921 int lowLen = sizeof (LowTone) / sizeof (int);
922 int highLen = sizeof (HighTone) / sizeof (int);
923 int convLen = (highLen > lowLen) ? highLen : lowLen; //if highlen > lowLen then highlen else lowlen
924 uint32_t hi = 0, lo = 0;
925
926 int i, j;
927 int minMark = 0, maxMark = 0;
928
929 for (i = 0; i < GraphTraceLen - convLen; ++i) {
930 int lowSum = 0, highSum = 0;
931
932 for (j = 0; j < lowLen; ++j) {
933 lowSum += LowTone[j]*GraphBuffer[i+j];
934 }
935 for (j = 0; j < highLen; ++j) {
936 highSum += HighTone[j] * GraphBuffer[i + j];
937 }
938 lowSum = abs(100 * lowSum / lowLen);
939 highSum = abs(100 * highSum / highLen);
940 GraphBuffer[i] = (highSum << 16) | lowSum;
941 }
942
943 for(i = 0; i < GraphTraceLen - convLen - 16; ++i) {
944 int lowTot = 0, highTot = 0;
945 // 10 and 8 are f_s divided by f_l and f_h, rounded
946 for (j = 0; j < 10; ++j) {
947 lowTot += (GraphBuffer[i+j] & 0xffff);
948 }
949 for (j = 0; j < 8; j++) {
950 highTot += (GraphBuffer[i + j] >> 16);
951 }
952 GraphBuffer[i] = lowTot - highTot;
953 if (GraphBuffer[i] > maxMark) maxMark = GraphBuffer[i];
954 if (GraphBuffer[i] < minMark) minMark = GraphBuffer[i];
955 }
956
957 GraphTraceLen -= (convLen + 16);
958 RepaintGraphWindow();
959
960 // Find bit-sync (3 lo followed by 3 high) (HID ONLY)
961 int max = 0, maxPos = 0;
962 for (i = 0; i < 6000; ++i) {
963 int dec = 0;
964 for (j = 0; j < 3 * lowLen; ++j) {
965 dec -= GraphBuffer[i + j];
966 }
967 for (; j < 3 * (lowLen + highLen ); ++j) {
968 dec += GraphBuffer[i + j];
969 }
970 if (dec > max) {
971 max = dec;
972 maxPos = i;
973 }
974 }
975
976 // place start of bit sync marker in graph
977 GraphBuffer[maxPos] = maxMark;
978 GraphBuffer[maxPos + 1] = minMark;
979
980 maxPos += j;
981
982 // place end of bit sync marker in graph
983 GraphBuffer[maxPos] = maxMark;
984 GraphBuffer[maxPos+1] = minMark;
985
986 PrintAndLog("actual data bits start at sample %d", maxPos);
987 PrintAndLog("length %d/%d", highLen, lowLen);
988
989 uint8_t bits[46];
990 bits[sizeof(bits)-1] = '\0';
991
992 // find bit pairs and manchester decode them
993 for (i = 0; i < arraylen(bits) - 1; ++i) {
994 int dec = 0;
995 for (j = 0; j < lowLen; ++j) {
996 dec -= GraphBuffer[maxPos + j];
997 }
998 for (; j < lowLen + highLen; ++j) {
999 dec += GraphBuffer[maxPos + j];
1000 }
1001 maxPos += j;
1002 // place inter bit marker in graph
1003 GraphBuffer[maxPos] = maxMark;
1004 GraphBuffer[maxPos + 1] = minMark;
1005
1006 // hi and lo form a 64 bit pair
1007 hi = (hi << 1) | (lo >> 31);
1008 lo = (lo << 1);
1009 // store decoded bit as binary (in hi/lo) and text (in bits[])
1010 if(dec < 0) {
1011 bits[i] = '1';
1012 lo |= 1;
1013 } else {
1014 bits[i] = '0';
1015 }
1016 }
1017 PrintAndLog("bits: '%s'", bits);
1018 PrintAndLog("hex: %08x %08x", hi, lo);
1019 return 0;
1020 }
1021
1022 int CmdGrid(const char *Cmd)
1023 {
1024 sscanf(Cmd, "%i %i", &PlotGridX, &PlotGridY);
1025 PlotGridXdefault= PlotGridX;
1026 PlotGridYdefault= PlotGridY;
1027 RepaintGraphWindow();
1028 return 0;
1029 }
1030
1031 int CmdHexsamples(const char *Cmd)
1032 {
1033 int i, j;
1034 int requested = 0;
1035 int offset = 0;
1036 char string_buf[25];
1037 char* string_ptr = string_buf;
1038 uint8_t got[40000];
1039
1040 sscanf(Cmd, "%i %i", &requested, &offset);
1041
1042 /* if no args send something */
1043 if (requested == 0) {
1044 requested = 8;
1045 }
1046 if (offset + requested > sizeof(got)) {
1047 PrintAndLog("Tried to read past end of buffer, <bytes> + <offset> > 40000");
1048 return 0;
1049 }
1050
1051 GetFromBigBuf(got,requested,offset);
1052 WaitForResponse(CMD_ACK,NULL);
1053
1054 i = 0;
1055 for (j = 0; j < requested; j++) {
1056 i++;
1057 string_ptr += sprintf(string_ptr, "%02x ", got[j]);
1058 if (i == 8) {
1059 *(string_ptr - 1) = '\0'; // remove the trailing space
1060 PrintAndLog("%s", string_buf);
1061 string_buf[0] = '\0';
1062 string_ptr = string_buf;
1063 i = 0;
1064 }
1065 if (j == requested - 1 && string_buf[0] != '\0') { // print any remaining bytes
1066 *(string_ptr - 1) = '\0';
1067 PrintAndLog("%s", string_buf);
1068 string_buf[0] = '\0';
1069 }
1070 }
1071 return 0;
1072 }
1073
1074 int CmdHide(const char *Cmd)
1075 {
1076 HideGraphWindow();
1077 return 0;
1078 }
1079
1080 int CmdHpf(const char *Cmd)
1081 {
1082 int i;
1083 int accum = 0;
1084
1085 for (i = 10; i < GraphTraceLen; ++i)
1086 accum += GraphBuffer[i];
1087 accum /= (GraphTraceLen - 10);
1088 for (i = 0; i < GraphTraceLen; ++i)
1089 GraphBuffer[i] -= accum;
1090
1091 RepaintGraphWindow();
1092 return 0;
1093 }
1094
1095 int CmdSamples(const char *Cmd)
1096 {
1097 int cnt = 0;
1098 int n;
1099 uint8_t got[40000];
1100
1101 n = strtol(Cmd, NULL, 0);
1102 if (n == 0) n = 6000;
1103 if (n > sizeof(got)) n = sizeof(got);
1104
1105 PrintAndLog("Reading %d samples\n", n);
1106 GetFromBigBuf(got,n,0);
1107 WaitForResponse(CMD_ACK,NULL);
1108 for (int j = 0; j < n; j++) {
1109 GraphBuffer[cnt++] = ((int)got[j]) - 128;
1110 }
1111
1112 PrintAndLog("Done!\n");
1113 GraphTraceLen = n;
1114 RepaintGraphWindow();
1115 return 0;
1116 }
1117
1118 int CmdTuneSamples(const char *Cmd)
1119 {
1120 int cnt = 0;
1121 int n = 255;
1122 uint8_t got[255];
1123
1124 PrintAndLog("Reading %d samples\n", n);
1125 GetFromBigBuf(got,n,7256); // armsrc/apps.h: #define FREE_BUFFER_OFFSET 7256
1126 WaitForResponse(CMD_ACK,NULL);
1127 for (int j = 0; j < n; j++) {
1128 GraphBuffer[cnt++] = ((int)got[j]) - 128;
1129 }
1130
1131 PrintAndLog("Done! Divisor 89 is 134khz, 95 is 125khz.\n");
1132 PrintAndLog("\n");
1133 GraphTraceLen = n;
1134 RepaintGraphWindow();
1135 return 0;
1136 }
1137
1138 int CmdLoad(const char *Cmd)
1139 {
1140 FILE *f = fopen(Cmd, "r");
1141 if (!f) {
1142 PrintAndLog("couldn't open '%s'", Cmd);
1143 return 0;
1144 }
1145
1146 GraphTraceLen = 0;
1147 char line[80];
1148 while (fgets(line, sizeof (line), f)) {
1149 GraphBuffer[GraphTraceLen] = atoi(line);
1150 GraphTraceLen++;
1151 }
1152 fclose(f);
1153 PrintAndLog("loaded %d samples", GraphTraceLen);
1154 RepaintGraphWindow();
1155 return 0;
1156 }
1157
1158 int CmdLtrim(const char *Cmd)
1159 {
1160 int ds = atoi(Cmd);
1161
1162 for (int i = ds; i < GraphTraceLen; ++i)
1163 GraphBuffer[i-ds] = GraphBuffer[i];
1164 GraphTraceLen -= ds;
1165
1166 RepaintGraphWindow();
1167 return 0;
1168 }
1169
1170 /*
1171 * Manchester demodulate a bitstream. The bitstream needs to be already in
1172 * the GraphBuffer as 0 and 1 values
1173 *
1174 * Give the clock rate as argument in order to help the sync - the algorithm
1175 * resyncs at each pulse anyway.
1176 *
1177 * Not optimized by any means, this is the 1st time I'm writing this type of
1178 * routine, feel free to improve...
1179 *
1180 * 1st argument: clock rate (as number of samples per clock rate)
1181 * Typical values can be 64, 32, 128...
1182 */
1183 int CmdManchesterDemod(const char *Cmd)
1184 {
1185 int i, j, invert= 0;
1186 int bit;
1187 int clock;
1188 int lastval = 0;
1189 int low = 0;
1190 int high = 0;
1191 int hithigh, hitlow, first;
1192 int lc = 0;
1193 int bitidx = 0;
1194 int bit2idx = 0;
1195 int warnings = 0;
1196
1197 /* check if we're inverting output */
1198 if (*Cmd == 'i')
1199 {
1200 PrintAndLog("Inverting output");
1201 invert = 1;
1202 ++Cmd;
1203 do
1204 ++Cmd;
1205 while(*Cmd == ' '); // in case a 2nd argument was given
1206 }
1207
1208 /* Holds the decoded bitstream: each clock period contains 2 bits */
1209 /* later simplified to 1 bit after manchester decoding. */
1210 /* Add 10 bits to allow for noisy / uncertain traces without aborting */
1211 /* int BitStream[GraphTraceLen*2/clock+10]; */
1212
1213 /* But it does not work if compiling on WIndows: therefore we just allocate a */
1214 /* large array */
1215 uint8_t BitStream[MAX_GRAPH_TRACE_LEN] = {0};
1216
1217 /* Detect high and lows */
1218 for (i = 0; i < GraphTraceLen; i++)
1219 {
1220 if (GraphBuffer[i] > high)
1221 high = GraphBuffer[i];
1222 else if (GraphBuffer[i] < low)
1223 low = GraphBuffer[i];
1224 }
1225
1226 /* Get our clock */
1227 clock = GetClock(Cmd, high, 1);
1228
1229 int tolerance = clock/4;
1230
1231 /* Detect first transition */
1232 /* Lo-Hi (arbitrary) */
1233 /* skip to the first high */
1234 for (i= 0; i < GraphTraceLen; i++)
1235 if (GraphBuffer[i] == high)
1236 break;
1237 /* now look for the first low */
1238 for (; i < GraphTraceLen; i++)
1239 {
1240 if (GraphBuffer[i] == low)
1241 {
1242 lastval = i;
1243 break;
1244 }
1245 }
1246
1247 /* If we're not working with 1/0s, demod based off clock */
1248 if (high != 1)
1249 {
1250 bit = 0; /* We assume the 1st bit is zero, it may not be
1251 * the case: this routine (I think) has an init problem.
1252 * Ed.
1253 */
1254 for (; i < (int)(GraphTraceLen / clock); i++)
1255 {
1256 hithigh = 0;
1257 hitlow = 0;
1258 first = 1;
1259
1260 /* Find out if we hit both high and low peaks */
1261 for (j = 0; j < clock; j++)
1262 {
1263 if (GraphBuffer[(i * clock) + j] == high)
1264 hithigh = 1;
1265 else if (GraphBuffer[(i * clock) + j] == low)
1266 hitlow = 1;
1267
1268 /* it doesn't count if it's the first part of our read
1269 because it's really just trailing from the last sequence */
1270 if (first && (hithigh || hitlow))
1271 hithigh = hitlow = 0;
1272 else
1273 first = 0;
1274
1275 if (hithigh && hitlow)
1276 break;
1277 }
1278
1279 /* If we didn't hit both high and low peaks, we had a bit transition */
1280 if (!hithigh || !hitlow)
1281 bit ^= 1;
1282
1283 BitStream[bit2idx++] = bit ^ invert;
1284 }
1285 }
1286
1287 /* standard 1/0 bitstream */
1288 else
1289 {
1290
1291 /* Then detect duration between 2 successive transitions */
1292 for (bitidx = 1; i < GraphTraceLen; i++)
1293 {
1294 if (GraphBuffer[i-1] != GraphBuffer[i])
1295 {
1296 lc = i-lastval;
1297 lastval = i;
1298
1299 // Error check: if bitidx becomes too large, we do not
1300 // have a Manchester encoded bitstream or the clock is really
1301 // wrong!
1302 if (bitidx > (GraphTraceLen*2/clock+8) ) {
1303 PrintAndLog("Error: the clock you gave is probably wrong, aborting.");
1304 return 0;
1305 }
1306 // Then switch depending on lc length:
1307 // Tolerance is 1/4 of clock rate (arbitrary)
1308 if (abs(lc-clock/2) < tolerance) {
1309 // Short pulse : either "1" or "0"
1310 BitStream[bitidx++]=GraphBuffer[i-1];
1311 } else if (abs(lc-clock) < tolerance) {
1312 // Long pulse: either "11" or "00"
1313 BitStream[bitidx++]=GraphBuffer[i-1];
1314 BitStream[bitidx++]=GraphBuffer[i-1];
1315 } else {
1316 // Error
1317 warnings++;
1318 PrintAndLog("Warning: Manchester decode error for pulse width detection.");
1319 PrintAndLog("(too many of those messages mean either the stream is not Manchester encoded, or clock is wrong)");
1320
1321 if (warnings > 10)
1322 {
1323 PrintAndLog("Error: too many detection errors, aborting.");
1324 return 0;
1325 }
1326 }
1327 }
1328 }
1329
1330 // At this stage, we now have a bitstream of "01" ("1") or "10" ("0"), parse it into final decoded bitstream
1331 // Actually, we overwrite BitStream with the new decoded bitstream, we just need to be careful
1332 // to stop output at the final bitidx2 value, not bitidx
1333 for (i = 0; i < bitidx; i += 2) {
1334 if ((BitStream[i] == 0) && (BitStream[i+1] == 1)) {
1335 BitStream[bit2idx++] = 1 ^ invert;
1336 } else if ((BitStream[i] == 1) && (BitStream[i+1] == 0)) {
1337 BitStream[bit2idx++] = 0 ^ invert;
1338 } else {
1339 // We cannot end up in this state, this means we are unsynchronized,
1340 // move up 1 bit:
1341 i++;
1342 warnings++;
1343 PrintAndLog("Unsynchronized, resync...");
1344 PrintAndLog("(too many of those messages mean the stream is not Manchester encoded)");
1345
1346 if (warnings > 10)
1347 {
1348 PrintAndLog("Error: too many decode errors, aborting.");
1349 return 0;
1350 }
1351 }
1352 }
1353 }
1354
1355 PrintAndLog("Manchester decoded bitstream");
1356 // Now output the bitstream to the scrollback by line of 16 bits
1357 for (i = 0; i < (bit2idx-16); i+=16) {
1358 PrintAndLog("%i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i",
1359 BitStream[i],
1360 BitStream[i+1],
1361 BitStream[i+2],
1362 BitStream[i+3],
1363 BitStream[i+4],
1364 BitStream[i+5],
1365 BitStream[i+6],
1366 BitStream[i+7],
1367 BitStream[i+8],
1368 BitStream[i+9],
1369 BitStream[i+10],
1370 BitStream[i+11],
1371 BitStream[i+12],
1372 BitStream[i+13],
1373 BitStream[i+14],
1374 BitStream[i+15]);
1375 }
1376 return 0;
1377 }
1378
1379 /* Modulate our data into manchester */
1380 int CmdManchesterMod(const char *Cmd)
1381 {
1382 int i, j;
1383 int clock;
1384 int bit, lastbit, wave;
1385
1386 /* Get our clock */
1387 clock = GetClock(Cmd, 0, 1);
1388
1389 wave = 0;
1390 lastbit = 1;
1391 for (i = 0; i < (int)(GraphTraceLen / clock); i++)
1392 {
1393 bit = GraphBuffer[i * clock] ^ 1;
1394
1395 for (j = 0; j < (int)(clock/2); j++)
1396 GraphBuffer[(i * clock) + j] = bit ^ lastbit ^ wave;
1397 for (j = (int)(clock/2); j < clock; j++)
1398 GraphBuffer[(i * clock) + j] = bit ^ lastbit ^ wave ^ 1;
1399
1400 /* Keep track of how we start our wave and if we changed or not this time */
1401 wave ^= bit ^ lastbit;
1402 lastbit = bit;
1403 }
1404
1405 RepaintGraphWindow();
1406 return 0;
1407 }
1408
1409 int CmdNorm(const char *Cmd)
1410 {
1411 int i;
1412 int max = INT_MIN, min = INT_MAX;
1413
1414 for (i = 10; i < GraphTraceLen; ++i) {
1415 if (GraphBuffer[i] > max)
1416 max = GraphBuffer[i];
1417 if (GraphBuffer[i] < min)
1418 min = GraphBuffer[i];
1419 }
1420
1421 if (max != min) {
1422 for (i = 0; i < GraphTraceLen; ++i) {
1423 GraphBuffer[i] = (GraphBuffer[i] - ((max + min) / 2)) * 1000 /
1424 (max - min);
1425 }
1426 }
1427 RepaintGraphWindow();
1428 return 0;
1429 }
1430
1431 int CmdPlot(const char *Cmd)
1432 {
1433 ShowGraphWindow();
1434 return 0;
1435 }
1436
1437 int CmdSave(const char *Cmd)
1438 {
1439 FILE *f = fopen(Cmd, "w");
1440 if(!f) {
1441 PrintAndLog("couldn't open '%s'", Cmd);
1442 return 0;
1443 }
1444 int i;
1445 for (i = 0; i < GraphTraceLen; i++) {
1446 fprintf(f, "%d\n", GraphBuffer[i]);
1447 }
1448 fclose(f);
1449 PrintAndLog("saved to '%s'", Cmd);
1450 return 0;
1451 }
1452
1453 int CmdScale(const char *Cmd)
1454 {
1455 CursorScaleFactor = atoi(Cmd);
1456 if (CursorScaleFactor == 0) {
1457 PrintAndLog("bad, can't have zero scale");
1458 CursorScaleFactor = 1;
1459 }
1460 RepaintGraphWindow();
1461 return 0;
1462 }
1463
1464 int CmdThreshold(const char *Cmd)
1465 {
1466 int threshold = atoi(Cmd);
1467
1468 for (int i = 0; i < GraphTraceLen; ++i) {
1469 if (GraphBuffer[i] >= threshold)
1470 GraphBuffer[i] = 1;
1471 else
1472 GraphBuffer[i] = -1;
1473 }
1474 RepaintGraphWindow();
1475 return 0;
1476 }
1477
1478 int CmdDirectionalThreshold(const char *Cmd)
1479 {
1480 int8_t upThres = param_get8(Cmd, 0);
1481 int8_t downThres = param_get8(Cmd, 1);
1482
1483 printf("Applying Up Threshold: %d, Down Threshold: %d\n", upThres, downThres);
1484
1485 int lastValue = GraphBuffer[0];
1486 GraphBuffer[0] = 0; // Will be changed at the end, but init 0 as we adjust to last samples value if no threshold kicks in.
1487
1488 for (int i = 1; i < GraphTraceLen; ++i) {
1489 // Apply first threshold to samples heading up
1490 if (GraphBuffer[i] >= upThres && GraphBuffer[i] > lastValue)
1491 {
1492 lastValue = GraphBuffer[i]; // Buffer last value as we overwrite it.
1493 GraphBuffer[i] = 1;
1494 }
1495 // Apply second threshold to samples heading down
1496 else if (GraphBuffer[i] <= downThres && GraphBuffer[i] < lastValue)
1497 {
1498 lastValue = GraphBuffer[i]; // Buffer last value as we overwrite it.
1499 GraphBuffer[i] = -1;
1500 }
1501 else
1502 {
1503 lastValue = GraphBuffer[i]; // Buffer last value as we overwrite it.
1504 GraphBuffer[i] = GraphBuffer[i-1];
1505
1506 }
1507 }
1508 GraphBuffer[0] = GraphBuffer[1]; // Aline with first edited sample.
1509 RepaintGraphWindow();
1510 return 0;
1511 }
1512
1513 int CmdZerocrossings(const char *Cmd)
1514 {
1515 // Zero-crossings aren't meaningful unless the signal is zero-mean.
1516 CmdHpf("");
1517
1518 int sign = 1;
1519 int zc = 0;
1520 int lastZc = 0;
1521
1522 for (int i = 0; i < GraphTraceLen; ++i) {
1523 if (GraphBuffer[i] * sign >= 0) {
1524 // No change in sign, reproduce the previous sample count.
1525 zc++;
1526 GraphBuffer[i] = lastZc;
1527 } else {
1528 // Change in sign, reset the sample count.
1529 sign = -sign;
1530 GraphBuffer[i] = lastZc;
1531 if (sign > 0) {
1532 lastZc = zc;
1533 zc = 0;
1534 }
1535 }
1536 }
1537
1538 RepaintGraphWindow();
1539 return 0;
1540 }
1541
1542 static command_t CommandTable[] =
1543 {
1544 {"help", CmdHelp, 1, "This help"},
1545 {"amp", CmdAmp, 1, "Amplify peaks"},
1546 {"askdemod", Cmdaskdemod, 1, "<0 or 1> -- Attempt to demodulate simple ASK tags"},
1547 {"askmandemod", Cmdaskmandemod, 1, "[clock] [invert<0 or 1>] -- Attempt to demodulate ASK/Manchester tags and output binary (args optional[clock will try Auto-detect])"},
1548 {"autocorr", CmdAutoCorr, 1, "<window length> -- Autocorrelation over window"},
1549 {"bitsamples", CmdBitsamples, 0, "Get raw samples as bitstring"},
1550 {"bitstream", CmdBitstream, 1, "[clock rate] -- Convert waveform into a bitstream"},
1551 {"buffclear", CmdBuffClear, 1, "Clear sample buffer and graph window"},
1552 {"dec", CmdDec, 1, "Decimate samples"},
1553 {"detectclock", CmdDetectClockRate, 1, "Detect clock rate"},
1554 {"fskdemod", CmdFSKdemod, 1, "Demodulate graph window as a HID FSK"},
1555 {"fskhiddemod", CmdFSKdemodHID, 1, "Demodulate graph window as a HID FSK using raw"},
1556 {"fskiodemod", CmdFSKdemodIO, 1, "Demodulate graph window as an IO Prox FSK using raw"},
1557 {"fskrawdemod", CmdFSKrawdemod, 1, "[clock rate] [invert] Demodulate graph window from FSK to binary (clock = 64 or 50)(invert = 1 or 0)"},
1558 {"grid", CmdGrid, 1, "<x> <y> -- overlay grid on graph window, use zero value to turn off either"},
1559 {"hexsamples", CmdHexsamples, 0, "<bytes> [<offset>] -- Dump big buffer as hex bytes"},
1560 {"hide", CmdHide, 1, "Hide graph window"},
1561 {"hpf", CmdHpf, 1, "Remove DC offset from trace"},
1562 {"load", CmdLoad, 1, "<filename> -- Load trace (to graph window"},
1563 {"ltrim", CmdLtrim, 1, "<samples> -- Trim samples from left of trace"},
1564 {"mandemod", CmdManchesterDemod, 1, "[i] [clock rate] -- Manchester demodulate binary stream (option 'i' to invert output)"},
1565 {"manmod", CmdManchesterMod, 1, "[clock rate] -- Manchester modulate a binary stream"},
1566 {"norm", CmdNorm, 1, "Normalize max/min to +/-500"},
1567 {"plot", CmdPlot, 1, "Show graph window (hit 'h' in window for keystroke help)"},
1568 {"samples", CmdSamples, 0, "[512 - 40000] -- Get raw samples for graph window"},
1569 {"tune", CmdTuneSamples, 0, "Get hw tune samples for graph window"},
1570 {"save", CmdSave, 1, "<filename> -- Save trace (from graph window)"},
1571 {"scale", CmdScale, 1, "<int> -- Set cursor display scale"},
1572 {"threshold", CmdThreshold, 1, "<threshold> -- Maximize/minimize every value in the graph window depending on threshold"},
1573 {"zerocrossings", CmdZerocrossings, 1, "Count time between zero-crossings"},
1574 {"dirthreshold", CmdDirectionalThreshold, 1, "<thres up> <thres down> -- Max rising higher up-thres/ Min falling lower down-thres, keep rest as prev."},
1575 {NULL, NULL, 0, NULL}
1576 };
1577
1578 int CmdData(const char *Cmd)
1579 {
1580 CmdsParse(CommandTable, Cmd);
1581 return 0;
1582 }
1583
1584 int CmdHelp(const char *Cmd)
1585 {
1586 CmdsHelp(CommandTable);
1587 return 0;
1588 }
Impressum, Datenschutz