1 //-----------------------------------------------------------------------------
2 // Copyright (C) 2010 iZsh <izsh at fail0verflow.com>
4 // This code is licensed to you under the terms of the GNU GPL, version 2 or,
5 // at your option, any later version. See the LICENSE.txt file for the text of
7 //-----------------------------------------------------------------------------
8 // Data and Graph commands
9 //-----------------------------------------------------------------------------
11 #include <stdio.h> // also included in util.h
12 #include <string.h> // also included in util.h
14 #include <limits.h> // for CmdNorm INT_MIN && INT_MAX
15 #include "data.h" // also included in util.h
19 #include "proxmark3.h"
20 #include "ui.h" // for show graph controls
21 #include "graph.h" // for graph data
22 #include "cmdparser.h"// already included in cmdmain.h
23 #include "usb_cmd.h" // already included in cmdmain.h and proxmark3.h
24 #include "lfdemod.h" // for demod code
25 #include "loclass/cipherutils.h" // for decimating samples in getsamples
26 #include "cmdlfem4x.h"// for em410x demod
28 uint8_t DemodBuffer
[MAX_DEMOD_BUF_LEN
];
29 uint8_t g_debugMode
=0;
30 size_t DemodBufferLen
=0;
32 static int CmdHelp(const char *Cmd
);
34 //set the demod buffer with given array of binary (one bit per byte)
36 void setDemodBuf(uint8_t *buff
, size_t size
, size_t startIdx
)
41 if ( size
> MAX_DEMOD_BUF_LEN
- startIdx
)
42 size
= MAX_DEMOD_BUF_LEN
- startIdx
;
45 for (; i
< size
; i
++){
46 DemodBuffer
[i
]=buff
[startIdx
++];
52 bool getDemodBuf(uint8_t *buff
, size_t *size
) {
53 if (buff
== NULL
) return false;
54 if (size
== NULL
) return false;
55 if (*size
== 0) return false;
57 *size
= (*size
> DemodBufferLen
) ? DemodBufferLen
: *size
;
59 memcpy(buff
, DemodBuffer
, *size
);
63 // option '1' to save DemodBuffer any other to restore
64 void save_restoreDB(uint8_t saveOpt
)
66 static uint8_t SavedDB
[MAX_DEMOD_BUF_LEN
];
67 static size_t SavedDBlen
;
68 static bool DB_Saved
= false;
70 if (saveOpt
==1) { //save
72 memcpy(SavedDB
, DemodBuffer
, sizeof(DemodBuffer
));
73 SavedDBlen
= DemodBufferLen
;
75 } else if (DB_Saved
) { //restore
76 memcpy(DemodBuffer
, SavedDB
, sizeof(DemodBuffer
));
77 DemodBufferLen
= SavedDBlen
;
82 int CmdSetDebugMode(const char *Cmd
)
85 sscanf(Cmd
, "%i", &demod
);
86 g_debugMode
=(uint8_t)demod
;
90 int usage_data_printdemodbuf(){
91 PrintAndLog("Usage: data printdemodbuffer x o <offset> l <length>");
92 PrintAndLog("Options: ");
93 PrintAndLog(" h This help");
94 PrintAndLog(" x output in hex (omit for binary output)");
95 PrintAndLog(" o <offset> enter offset in # of bits");
96 PrintAndLog(" l <length> enter length to print in # of bits or hex characters respectively");
101 void printDemodBuff(void)
103 int bitLen
= DemodBufferLen
;
105 PrintAndLog("no bits found in demod buffer");
108 if (bitLen
>512) bitLen
=512; //max output to 512 bits if we have more - should be plenty
110 char *bin
= sprint_bin_break(DemodBuffer
,bitLen
,16);
111 PrintAndLog("%s",bin
);
116 int CmdPrintDemodBuff(const char *Cmd
)
118 char hex
[512]={0x00};
119 bool hexMode
= false;
121 uint32_t offset
= 0; //could be size_t but no param_get16...
122 uint32_t length
= 512;
124 while(param_getchar(Cmd
, cmdp
) != 0x00)
126 switch(param_getchar(Cmd
, cmdp
))
130 return usage_data_printdemodbuf();
138 offset
= param_get32ex(Cmd
, cmdp
+1, 0, 10);
139 if (!offset
) errors
= true;
144 length
= param_get32ex(Cmd
, cmdp
+1, 512, 10);
145 if (!length
) errors
= true;
149 PrintAndLog("Unknown parameter '%c'", param_getchar(Cmd
, cmdp
));
156 if(errors
) return usage_data_printdemodbuf();
157 length
= (length
> (DemodBufferLen
-offset
)) ? DemodBufferLen
-offset
: length
;
158 int numBits
= (length
) & 0x00FFC; //make sure we don't exceed our string
161 char *buf
= (char *) (DemodBuffer
+ offset
);
162 numBits
= (numBits
> sizeof(hex
)) ? sizeof(hex
) : numBits
;
163 numBits
= binarraytohex(hex
, buf
, numBits
);
164 if (numBits
==0) return 0;
165 PrintAndLog("DemodBuffer: %s",hex
);
167 PrintAndLog("DemodBuffer:\n%s", sprint_bin_break(DemodBuffer
+offset
,numBits
,16));
173 //this function strictly converts >1 to 1 and <1 to 0 for each sample in the graphbuffer
174 int CmdGetBitStream(const char *Cmd
)
178 for (i
= 0; i
< GraphTraceLen
; i
++) {
179 if (GraphBuffer
[i
] >= 1) {
185 RepaintGraphWindow();
190 //Cmd Args: Clock, invert, maxErr, maxLen as integers and amplify as char == 'a'
191 // (amp may not be needed anymore)
192 //verbose will print results and demoding messages
193 //emSearch will auto search for EM410x format in bitstream
194 //askType switches decode: ask/raw = 0, ask/manchester = 1
195 int ASKDemod_ext(const char *Cmd
, bool verbose
, bool emSearch
, uint8_t askType
, bool *stCheck
) {
201 char amp
= param_getchar(Cmd
, 0);
202 uint8_t BitStream
[MAX_GRAPH_TRACE_LEN
]={0};
203 sscanf(Cmd
, "%i %i %i %i %c", &clk
, &invert
, &maxErr
, &maxLen
, &
);
204 if (!maxLen
) maxLen
= BIGBUF_SIZE
;
205 if (invert
!= 0 && invert
!= 1) {
206 PrintAndLog("Invalid argument: %s", Cmd
);
213 size_t BitLen
= getFromGraphBuf(BitStream
);
214 if (g_debugMode
) PrintAndLog("DEBUG: Bitlen from grphbuff: %d",BitLen
);
215 if (BitLen
< 255) return 0;
216 if (maxLen
< BitLen
&& maxLen
!= 0) BitLen
= maxLen
;
218 //amp before ST check
219 if (amp
== 'a' || amp
== 'A') {
220 askAmp(BitStream
, BitLen
);
223 size_t ststart
= 0, stend
= 0;
224 if (*stCheck
) st
= DetectST(BitStream
, &BitLen
, &foundclk
, &ststart
, &stend
);
227 clk
= (clk
== 0) ? foundclk
: clk
;
228 CursorCPos
= ststart
;
230 if (verbose
|| g_debugMode
) PrintAndLog("\nFound Sequence Terminator - First one is shown by orange and blue graph markers");
231 //Graph ST trim (for testing)
232 //for (int i = 0; i < BitLen; i++) {
233 // GraphBuffer[i] = BitStream[i]-128;
235 //RepaintGraphWindow();
238 int errCnt
= askdemod_ext(BitStream
, &BitLen
, &clk
, &invert
, maxErr
, askamp
, askType
, &startIdx
);
239 if (errCnt
<0 || BitLen
<16){ //if fatal error (or -1)
240 if (g_debugMode
) PrintAndLog("DEBUG: no data found %d, errors:%d, bitlen:%d, clock:%d",errCnt
,invert
,BitLen
,clk
);
243 if (errCnt
> maxErr
){
244 if (g_debugMode
) PrintAndLog("DEBUG: Too many errors found, errors:%d, bits:%d, clock:%d",errCnt
, BitLen
, clk
);
247 if (verbose
|| g_debugMode
) PrintAndLog("\nUsing Clock:%d, Invert:%d, Bits Found:%d",clk
,invert
,BitLen
);
250 setDemodBuf(BitStream
,BitLen
,0);
251 setClockGrid(clk
, startIdx
);
253 if (verbose
|| g_debugMode
){
254 if (errCnt
>0) PrintAndLog("# Errors during Demoding (shown as 7 in bit stream): %d",errCnt
);
255 if (askType
) PrintAndLog("ASK/Manchester - Clock: %d - Decoded bitstream:",clk
);
256 else PrintAndLog("ASK/Raw - Clock: %d - Decoded bitstream:",clk
);
257 // Now output the bitstream to the scrollback by line of 16 bits
264 AskEm410xDecode(true, &hi
, &lo
);
268 int ASKDemod(const char *Cmd
, bool verbose
, bool emSearch
, uint8_t askType
) {
270 return ASKDemod_ext(Cmd
, verbose
, emSearch
, askType
, &st
);
274 //takes 5 arguments - clock, invert, maxErr, maxLen as integers and amplify as char == 'a'
275 //attempts to demodulate ask while decoding manchester
276 //prints binary found and saves in graphbuffer for further commands
277 int Cmdaskmandemod(const char *Cmd
)
279 char cmdp
= param_getchar(Cmd
, 0);
280 if (strlen(Cmd
) > 45 || cmdp
== 'h' || cmdp
== 'H') {
281 PrintAndLog("Usage: data rawdemod am <s> [clock] <invert> [maxError] [maxLen] [amplify]");
282 PrintAndLog(" ['s'] optional, check for Sequence Terminator");
283 PrintAndLog(" [set clock as integer] optional, if not set, autodetect");
284 PrintAndLog(" <invert>, 1 to invert output");
285 PrintAndLog(" [set maximum allowed errors], default = 100");
286 PrintAndLog(" [set maximum Samples to read], default = 32768 (512 bits at rf/64)");
287 PrintAndLog(" <amplify>, 'a' to attempt demod with ask amplification, default = no amp");
289 PrintAndLog(" sample: data rawdemod am = demod an ask/manchester tag from GraphBuffer");
290 PrintAndLog(" : data rawdemod am 32 = demod an ask/manchester tag from GraphBuffer using a clock of RF/32");
291 PrintAndLog(" : data rawdemod am 32 1 = demod an ask/manchester tag from GraphBuffer using a clock of RF/32 and inverting data");
292 PrintAndLog(" : data rawdemod am 1 = demod an ask/manchester tag from GraphBuffer while inverting data");
293 PrintAndLog(" : data rawdemod am 64 1 0 = demod an ask/manchester tag from GraphBuffer using a clock of RF/64, inverting data and allowing 0 demod errors");
298 return ASKDemod_ext(Cmd
++, true, true, 1, &st
);
299 else if (Cmd
[1] == 's')
300 return ASKDemod_ext(Cmd
+=2, true, true, 1, &st
);
302 return ASKDemod(Cmd
, true, true, 1);
307 //stricktly take 10 and 01 and convert to 0 and 1
308 int Cmdmandecoderaw(const char *Cmd
)
315 char cmdp
= param_getchar(Cmd
, 0);
316 if (strlen(Cmd
) > 5 || cmdp
== 'h' || cmdp
== 'H') {
317 PrintAndLog("Usage: data manrawdecode [invert] [maxErr]");
318 PrintAndLog(" Takes 10 and 01 and converts to 0 and 1 respectively");
319 PrintAndLog(" --must have binary sequence in demodbuffer (run data askrawdemod first)");
320 PrintAndLog(" [invert] invert output");
321 PrintAndLog(" [maxErr] set number of errors allowed (default = 20)");
323 PrintAndLog(" sample: data manrawdecode = decode manchester bitstream from the demodbuffer");
326 if (DemodBufferLen
==0) return 0;
327 uint8_t BitStream
[MAX_DEMOD_BUF_LEN
]={0};
329 for (;i
<DemodBufferLen
;++i
){
330 if (DemodBuffer
[i
]>high
) high
=DemodBuffer
[i
];
331 else if(DemodBuffer
[i
]<low
) low
=DemodBuffer
[i
];
332 BitStream
[i
]=DemodBuffer
[i
];
334 if (high
>7 || low
<0 ){
335 PrintAndLog("Error: please raw demod the wave first then manchester raw decode");
339 sscanf(Cmd
, "%i %i", &invert
, &maxErr
);
341 uint8_t alignPos
= 0;
342 errCnt
=manrawdecode(BitStream
, &size
, invert
, &alignPos
);
344 PrintAndLog("Too many errors: %d",errCnt
);
347 PrintAndLog("Manchester Decoded - # errors:%d - data:",errCnt
);
348 PrintAndLog("%s", sprint_bin_break(BitStream
, size
, 16));
353 if (Em410xDecode(BitStream
, &size
, &idx
, &hi
, &id
)){
354 //need to adjust to set bitstream back to manchester encoded data
355 //setDemodBuf(BitStream, size, idx);
365 //take 01 or 10 = 0 and 11 or 00 = 1
366 //takes 2 arguments "offset" default = 0 if 1 it will shift the decode by one bit
367 // and "invert" default = 0 if 1 it will invert output
368 // the argument offset allows us to manually shift if the output is incorrect - [EDIT: now auto detects]
369 int CmdBiphaseDecodeRaw(const char *Cmd
)
372 int offset
=0, invert
=0, maxErr
=20, errCnt
=0;
373 char cmdp
= param_getchar(Cmd
, 0);
374 if (strlen(Cmd
) > 3 || cmdp
== 'h' || cmdp
== 'H') {
375 PrintAndLog("Usage: data biphaserawdecode [offset] [invert] [maxErr]");
376 PrintAndLog(" Converts 10 or 01 to 1 and 11 or 00 to 0");
377 PrintAndLog(" --must have binary sequence in demodbuffer (run data askrawdemod first)");
378 PrintAndLog(" --invert for Conditional Dephase Encoding (CDP) AKA Differential Manchester");
380 PrintAndLog(" [offset <0|1>], set to 0 not to adjust start position or to 1 to adjust decode start position");
381 PrintAndLog(" [invert <0|1>], set to 1 to invert output");
382 PrintAndLog(" [maxErr int], set max errors tolerated - default=20");
384 PrintAndLog(" sample: data biphaserawdecode = decode biphase bitstream from the demodbuffer");
385 PrintAndLog(" sample: data biphaserawdecode 1 1 = decode biphase bitstream from the demodbuffer, set offset, and invert output");
388 sscanf(Cmd
, "%i %i %i", &offset
, &invert
, &maxErr
);
389 if (DemodBufferLen
==0) {
390 PrintAndLog("DemodBuffer Empty - run 'data rawdemod ar' first");
393 uint8_t BitStream
[MAX_DEMOD_BUF_LEN
]={0};
394 size
= sizeof(BitStream
);
395 if ( !getDemodBuf(BitStream
, &size
) ) return 0;
396 errCnt
=BiphaseRawDecode(BitStream
, &size
, offset
, invert
);
398 PrintAndLog("Error during decode:%d", errCnt
);
402 PrintAndLog("Too many errors attempting to decode: %d",errCnt
);
407 PrintAndLog("# Errors found during Demod (shown as 7 in bit stream): %d",errCnt
);
409 PrintAndLog("Biphase Decoded using offset: %d - # invert:%d - data:",offset
,invert
);
410 PrintAndLog("%s", sprint_bin_break(BitStream
, size
, 16));
412 if (offset
) setDemodBuf(DemodBuffer
,DemodBufferLen
-offset
, offset
); //remove first bit from raw demod
417 // - ASK Demod then Biphase decode GraphBuffer samples
418 int ASKbiphaseDemod(const char *Cmd
, bool verbose
)
420 //ask raw demod GraphBuffer first
421 int offset
=0, clk
=0, invert
=0, maxErr
=0;
422 sscanf(Cmd
, "%i %i %i %i", &offset
, &clk
, &invert
, &maxErr
);
424 uint8_t BitStream
[MAX_GRAPH_TRACE_LEN
];
425 size_t size
= getFromGraphBuf(BitStream
);
426 //invert here inverts the ask raw demoded bits which has no effect on the demod, but we need the pointer
427 int errCnt
= askdemod(BitStream
, &size
, &clk
, &invert
, maxErr
, 0, 0);
428 if ( errCnt
< 0 || errCnt
> maxErr
) {
429 if (g_debugMode
) PrintAndLog("DEBUG: no data or error found %d, clock: %d", errCnt
, clk
);
433 //attempt to Biphase decode BitStream
434 errCnt
= BiphaseRawDecode(BitStream
, &size
, offset
, invert
);
436 if (g_debugMode
|| verbose
) PrintAndLog("Error BiphaseRawDecode: %d", errCnt
);
439 if (errCnt
> maxErr
) {
440 if (g_debugMode
|| verbose
) PrintAndLog("Error BiphaseRawDecode too many errors: %d", errCnt
);
443 //success set DemodBuffer and return
444 setDemodBuf(BitStream
, size
, 0);
445 if (g_debugMode
|| verbose
){
446 PrintAndLog("Biphase Decoded using offset: %d - clock: %d - # errors:%d - data:",offset
,clk
,errCnt
);
451 //by marshmellow - see ASKbiphaseDemod
452 int Cmdaskbiphdemod(const char *Cmd
)
454 char cmdp
= param_getchar(Cmd
, 0);
455 if (strlen(Cmd
) > 25 || cmdp
== 'h' || cmdp
== 'H') {
456 PrintAndLog("Usage: data rawdemod ab [offset] [clock] <invert> [maxError] [maxLen] <amplify>");
457 PrintAndLog(" [offset], offset to begin biphase, default=0");
458 PrintAndLog(" [set clock as integer] optional, if not set, autodetect");
459 PrintAndLog(" <invert>, 1 to invert output");
460 PrintAndLog(" [set maximum allowed errors], default = 100");
461 PrintAndLog(" [set maximum Samples to read], default = 32768 (512 bits at rf/64)");
462 PrintAndLog(" <amplify>, 'a' to attempt demod with ask amplification, default = no amp");
463 PrintAndLog(" NOTE: <invert> can be entered as second or third argument");
464 PrintAndLog(" NOTE: <amplify> can be entered as first, second or last argument");
465 PrintAndLog(" NOTE: any other arg must have previous args set to work");
467 PrintAndLog(" NOTE: --invert for Conditional Dephase Encoding (CDP) AKA Differential Manchester");
469 PrintAndLog(" sample: data rawdemod ab = demod an ask/biph tag from GraphBuffer");
470 PrintAndLog(" : data rawdemod ab 0 a = demod an ask/biph tag from GraphBuffer, amplified");
471 PrintAndLog(" : data rawdemod ab 1 32 = demod an ask/biph tag from GraphBuffer using an offset of 1 and a clock of RF/32");
472 PrintAndLog(" : data rawdemod ab 0 32 1 = demod an ask/biph tag from GraphBuffer using a clock of RF/32 and inverting data");
473 PrintAndLog(" : data rawdemod ab 0 1 = demod an ask/biph tag from GraphBuffer while inverting data");
474 PrintAndLog(" : data rawdemod ab 0 64 1 0 = demod an ask/biph tag from GraphBuffer using a clock of RF/64, inverting data and allowing 0 demod errors");
475 PrintAndLog(" : data rawdemod ab 0 64 1 0 0 a = demod an ask/biph tag from GraphBuffer using a clock of RF/64, inverting data and allowing 0 demod errors, and amp");
478 return ASKbiphaseDemod(Cmd
, true);
481 //by marshmellow - see ASKDemod
482 int Cmdaskrawdemod(const char *Cmd
)
484 char cmdp
= param_getchar(Cmd
, 0);
485 if (strlen(Cmd
) > 35 || cmdp
== 'h' || cmdp
== 'H') {
486 PrintAndLog("Usage: data rawdemod ar [clock] <invert> [maxError] [maxLen] [amplify]");
487 PrintAndLog(" [set clock as integer] optional, if not set, autodetect");
488 PrintAndLog(" <invert>, 1 to invert output");
489 PrintAndLog(" [set maximum allowed errors], default = 100");
490 PrintAndLog(" [set maximum Samples to read], default = 32768 (1024 bits at rf/64)");
491 PrintAndLog(" <amplify>, 'a' to attempt demod with ask amplification, default = no amp");
493 PrintAndLog(" sample: data rawdemod ar = demod an ask tag from GraphBuffer");
494 PrintAndLog(" : data rawdemod ar a = demod an ask tag from GraphBuffer, amplified");
495 PrintAndLog(" : data rawdemod ar 32 = demod an ask tag from GraphBuffer using a clock of RF/32");
496 PrintAndLog(" : data rawdemod ar 32 1 = demod an ask tag from GraphBuffer using a clock of RF/32 and inverting data");
497 PrintAndLog(" : data rawdemod ar 1 = demod an ask tag from GraphBuffer while inverting data");
498 PrintAndLog(" : data rawdemod ar 64 1 0 = demod an ask tag from GraphBuffer using a clock of RF/64, inverting data and allowing 0 demod errors");
499 PrintAndLog(" : data rawdemod ar 64 1 0 0 a = demod an ask tag from GraphBuffer using a clock of RF/64, inverting data and allowing 0 demod errors, and amp");
502 return ASKDemod(Cmd
, true, false, 0);
505 int AutoCorrelate(int window
, bool SaveGrph
, bool verbose
)
507 static int CorrelBuffer
[MAX_GRAPH_TRACE_LEN
];
508 size_t Correlation
= 0;
511 if (verbose
) PrintAndLog("performing %d correlations", GraphTraceLen
- window
);
512 for (int i
= 0; i
< GraphTraceLen
- window
; ++i
) {
514 for (int j
= 0; j
< window
; ++j
) {
515 sum
+= (GraphBuffer
[j
]*GraphBuffer
[i
+ j
]) / 256;
517 CorrelBuffer
[i
] = sum
;
518 if (sum
>= maxSum
-100 && sum
<= maxSum
+100){
520 Correlation
= i
-lastMax
;
522 if (sum
> maxSum
) maxSum
= sum
;
523 } else if (sum
> maxSum
){
529 //try again with wider margin
530 for (int i
= 0; i
< GraphTraceLen
- window
; i
++){
531 if (CorrelBuffer
[i
] >= maxSum
-(maxSum
*0.05) && CorrelBuffer
[i
] <= maxSum
+(maxSum
*0.05)){
533 Correlation
= i
-lastMax
;
535 //if (CorrelBuffer[i] > maxSum) maxSum = sum;
539 if (verbose
&& Correlation
> 0) PrintAndLog("Possible Correlation: %d samples",Correlation
);
542 GraphTraceLen
= GraphTraceLen
- window
;
543 memcpy(GraphBuffer
, CorrelBuffer
, GraphTraceLen
* sizeof (int));
544 RepaintGraphWindow();
549 int usage_data_autocorr(void)
552 PrintAndLog("Usage: data autocorr [window] [g]");
553 PrintAndLog("Options: ");
554 PrintAndLog(" h This help");
555 PrintAndLog(" [window] window length for correlation - default = 4000");
556 PrintAndLog(" g save back to GraphBuffer (overwrite)");
560 int CmdAutoCorr(const char *Cmd
)
562 char cmdp
= param_getchar(Cmd
, 0);
563 if (cmdp
== 'h' || cmdp
== 'H')
564 return usage_data_autocorr();
565 int window
= 4000; //set default
567 bool updateGrph
= false;
568 sscanf(Cmd
, "%i %c", &window
, &grph
);
570 if (window
>= GraphTraceLen
) {
571 PrintAndLog("window must be smaller than trace (%d samples)",
575 if (grph
== 'g') updateGrph
=true;
576 return AutoCorrelate(window
, updateGrph
, true);
579 int CmdBitsamples(const char *Cmd
)
584 GetFromBigBuf(got
,sizeof(got
),0);
585 WaitForResponse(CMD_ACK
,NULL
);
587 for (int j
= 0; j
< sizeof(got
); j
++) {
588 for (int k
= 0; k
< 8; k
++) {
589 if(got
[j
] & (1 << (7 - k
))) {
590 GraphBuffer
[cnt
++] = 1;
592 GraphBuffer
[cnt
++] = 0;
597 RepaintGraphWindow();
601 int CmdBuffClear(const char *Cmd
)
603 UsbCommand c
= {CMD_BUFF_CLEAR
};
609 int CmdDec(const char *Cmd
)
611 for (int i
= 0; i
< (GraphTraceLen
/ 2); ++i
)
612 GraphBuffer
[i
] = GraphBuffer
[i
* 2];
614 PrintAndLog("decimated by 2");
615 RepaintGraphWindow();
619 * Undecimate - I'd call it 'interpolate', but we'll save that
620 * name until someone does an actual interpolation command, not just
621 * blindly repeating samples
625 int CmdUndec(const char *Cmd
)
627 if(param_getchar(Cmd
, 0) == 'h')
629 PrintAndLog("Usage: data undec [factor]");
630 PrintAndLog("This function performs un-decimation, by repeating each sample N times");
631 PrintAndLog("Options: ");
632 PrintAndLog(" h This help");
633 PrintAndLog(" factor The number of times to repeat each sample.[default:2]");
634 PrintAndLog("Example: 'data undec 3'");
638 uint8_t factor
= param_get8ex(Cmd
, 0,2, 10);
639 //We have memory, don't we?
640 int swap
[MAX_GRAPH_TRACE_LEN
] = { 0 };
641 uint32_t g_index
= 0, s_index
= 0;
642 while(g_index
< GraphTraceLen
&& s_index
+ factor
< MAX_GRAPH_TRACE_LEN
)
645 for(count
= 0; count
< factor
&& s_index
+ count
< MAX_GRAPH_TRACE_LEN
; count
++)
646 swap
[s_index
+count
] = GraphBuffer
[g_index
];
652 memcpy(GraphBuffer
, swap
, s_index
* sizeof(int));
653 GraphTraceLen
= s_index
;
654 RepaintGraphWindow();
659 //shift graph zero up or down based on input + or -
660 int CmdGraphShiftZero(const char *Cmd
)
664 //set options from parameters entered with the command
665 sscanf(Cmd
, "%i", &shift
);
667 for(int i
= 0; i
<GraphTraceLen
; i
++){
668 shiftedVal
=GraphBuffer
[i
]+shift
;
671 else if (shiftedVal
<-127)
673 GraphBuffer
[i
]= shiftedVal
;
680 //use large jumps in read samples to identify edges of waves and then amplify that wave to max
681 //similar to dirtheshold, threshold commands
682 //takes a threshold length which is the measured length between two samples then determines an edge
683 int CmdAskEdgeDetect(const char *Cmd
)
687 sscanf(Cmd
, "%i", &thresLen
);
689 for(int i
= 1; i
<GraphTraceLen
; i
++){
690 if (GraphBuffer
[i
]-GraphBuffer
[i
-1]>=thresLen
) //large jump up
692 else if(GraphBuffer
[i
]-GraphBuffer
[i
-1]<=-1*thresLen
) //large jump down
694 GraphBuffer
[i
-1] = Last
;
696 RepaintGraphWindow();
700 /* Print our clock rate */
701 // uses data from graphbuffer
702 // adjusted to take char parameter for type of modulation to find the clock - by marshmellow.
703 int CmdDetectClockRate(const char *Cmd
)
705 char cmdp
= param_getchar(Cmd
, 0);
706 if (strlen(Cmd
) > 6 || strlen(Cmd
) == 0 || cmdp
== 'h' || cmdp
== 'H') {
707 PrintAndLog("Usage: data detectclock [modulation] <clock>");
708 PrintAndLog(" [modulation as char], specify the modulation type you want to detect the clock of");
709 PrintAndLog(" <clock> , specify the clock (optional - to get best start position only)");
710 PrintAndLog(" 'a' = ask, 'f' = fsk, 'n' = nrz/direct, 'p' = psk");
712 PrintAndLog(" sample: data detectclock a = detect the clock of an ask modulated wave in the GraphBuffer");
713 PrintAndLog(" data detectclock f = detect the clock of an fsk modulated wave in the GraphBuffer");
714 PrintAndLog(" data detectclock p = detect the clock of an psk modulated wave in the GraphBuffer");
715 PrintAndLog(" data detectclock n = detect the clock of an nrz/direct modulated wave in the GraphBuffer");
719 ans
= GetAskClock(Cmd
+1, true, false);
720 } else if (cmdp
== 'f'){
721 ans
= GetFskClock("", true, false);
722 } else if (cmdp
== 'n'){
723 ans
= GetNrzClock("", true, false);
724 } else if (cmdp
== 'p'){
725 ans
= GetPskClock("", true, false);
727 PrintAndLog ("Please specify a valid modulation to detect the clock of - see option h for help");
732 char *GetFSKType(uint8_t fchigh
, uint8_t fclow
, uint8_t invert
)
734 static char fType
[8];
735 memset(fType
, 0x00, 8);
736 char *fskType
= fType
;
737 if (fchigh
==10 && fclow
==8){
739 memcpy(fskType
, "FSK2a", 5);
741 memcpy(fskType
, "FSK2", 4);
742 } else if (fchigh
== 8 && fclow
== 5) {
744 memcpy(fskType
, "FSK1", 4);
746 memcpy(fskType
, "FSK1a", 5);
748 memcpy(fskType
, "FSK??", 5);
754 //fsk raw demod and print binary
755 //takes 4 arguments - Clock, invert, fchigh, fclow
756 //defaults: clock = 50, invert=1, fchigh=10, fclow=8 (RF/10 RF/8 (fsk2a))
757 int FSKrawDemod(const char *Cmd
, bool verbose
)
759 //raw fsk demod no manchester decoding no start bit finding just get binary from wave
760 uint8_t rfLen
, invert
, fchigh
, fclow
;
762 //set options from parameters entered with the command
763 rfLen
= param_get8(Cmd
, 0);
764 invert
= param_get8(Cmd
, 1);
765 fchigh
= param_get8(Cmd
, 2);
766 fclow
= param_get8(Cmd
, 3);
768 if (strlen(Cmd
)>0 && strlen(Cmd
)<=2) {
770 invert
= 1; //if invert option only is used
774 uint8_t BitStream
[MAX_GRAPH_TRACE_LEN
]={0};
775 size_t BitLen
= getFromGraphBuf(BitStream
);
776 if (BitLen
==0) return 0;
777 //get field clock lengths
779 if (!fchigh
|| !fclow
) {
780 fcs
= countFC(BitStream
, BitLen
, 1);
785 fchigh
= (fcs
>> 8) & 0x00FF;
786 fclow
= fcs
& 0x00FF;
789 //get bit clock length
791 int firstClockEdge
= 0; //todo - align grid on graph with this...
792 rfLen
= detectFSKClk(BitStream
, BitLen
, fchigh
, fclow
, &firstClockEdge
);
793 if (!rfLen
) rfLen
= 50;
796 int size
= fskdemod_ext(BitStream
, BitLen
, rfLen
, invert
, fchigh
, fclow
, &startIdx
);
798 setDemodBuf(BitStream
,size
,0);
799 setClockGrid(rfLen
, startIdx
);
801 // Now output the bitstream to the scrollback by line of 16 bits
802 if (verbose
|| g_debugMode
) {
803 PrintAndLog("\nUsing Clock:%u, invert:%u, fchigh:%u, fclow:%u", (unsigned int)rfLen
, (unsigned int)invert
, (unsigned int)fchigh
, (unsigned int)fclow
);
804 PrintAndLog("%s decoded bitstream:",GetFSKType(fchigh
,fclow
,invert
));
810 if (g_debugMode
) PrintAndLog("no FSK data found");
816 //fsk raw demod and print binary
817 //takes 4 arguments - Clock, invert, fchigh, fclow
818 //defaults: clock = 50, invert=1, fchigh=10, fclow=8 (RF/10 RF/8 (fsk2a))
819 int CmdFSKrawdemod(const char *Cmd
)
821 char cmdp
= param_getchar(Cmd
, 0);
822 if (strlen(Cmd
) > 20 || cmdp
== 'h' || cmdp
== 'H') {
823 PrintAndLog("Usage: data rawdemod fs [clock] <invert> [fchigh] [fclow]");
824 PrintAndLog(" [set clock as integer] optional, omit for autodetect.");
825 PrintAndLog(" <invert>, 1 for invert output, can be used even if the clock is omitted");
826 PrintAndLog(" [fchigh], larger field clock length, omit for autodetect");
827 PrintAndLog(" [fclow], small field clock length, omit for autodetect");
829 PrintAndLog(" sample: data rawdemod fs = demod an fsk tag from GraphBuffer using autodetect");
830 PrintAndLog(" : data rawdemod fs 32 = demod an fsk tag from GraphBuffer using a clock of RF/32, autodetect fc");
831 PrintAndLog(" : data rawdemod fs 1 = demod an fsk tag from GraphBuffer using autodetect, invert output");
832 PrintAndLog(" : data rawdemod fs 32 1 = demod an fsk tag from GraphBuffer using a clock of RF/32, invert output, autodetect fc");
833 PrintAndLog(" : data rawdemod fs 64 0 8 5 = demod an fsk1 RF/64 tag from GraphBuffer");
834 PrintAndLog(" : data rawdemod fs 50 0 10 8 = demod an fsk2 RF/50 tag from GraphBuffer");
835 PrintAndLog(" : data rawdemod fs 50 1 10 8 = demod an fsk2a RF/50 tag from GraphBuffer");
838 return FSKrawDemod(Cmd
, true);
842 //attempt to psk1 demod graph buffer
843 int PSKDemod(const char *Cmd
, bool verbose
)
848 sscanf(Cmd
, "%i %i %i", &clk
, &invert
, &maxErr
);
853 if (invert
!= 0 && invert
!= 1) {
854 if (g_debugMode
|| verbose
) PrintAndLog("Invalid argument: %s", Cmd
);
857 uint8_t BitStream
[MAX_GRAPH_TRACE_LEN
]={0};
858 size_t BitLen
= getFromGraphBuf(BitStream
);
859 if (BitLen
==0) return 0;
862 errCnt
= pskRawDemod_ext(BitStream
, &BitLen
, &clk
, &invert
, &startIdx
);
863 if (errCnt
> maxErr
){
864 if (g_debugMode
|| verbose
) PrintAndLog("Too many errors found, clk: %d, invert: %d, numbits: %d, errCnt: %d",clk
,invert
,BitLen
,errCnt
);
867 if (errCnt
<0|| BitLen
<16){ //throw away static - allow 1 and -1 (in case of threshold command first)
868 if (g_debugMode
|| verbose
) PrintAndLog("no data found, clk: %d, invert: %d, numbits: %d, errCnt: %d",clk
,invert
,BitLen
,errCnt
);
871 if (verbose
|| g_debugMode
){
872 PrintAndLog("\nUsing Clock:%d, invert:%d, Bits Found:%d",clk
,invert
,BitLen
);
874 PrintAndLog("# Errors during Demoding (shown as 7 in bit stream): %d",errCnt
);
877 //prime demod buffer for output
878 setDemodBuf(BitStream
,BitLen
,0);
879 setClockGrid(clk
, startIdx
);
885 // takes 3 arguments - clock, invert, maxErr as integers
886 // attempts to demodulate nrz only
887 // prints binary found and saves in demodbuffer for further commands
888 int NRZrawDemod(const char *Cmd
, bool verbose
)
893 sscanf(Cmd
, "%i %i %i", &clk
, &invert
, &maxErr
);
898 if (invert
!= 0 && invert
!= 1) {
899 PrintAndLog("Invalid argument: %s", Cmd
);
902 uint8_t BitStream
[MAX_GRAPH_TRACE_LEN
]={0};
903 size_t BitLen
= getFromGraphBuf(BitStream
);
904 if (BitLen
==0) return 0;
907 errCnt
= nrzRawDemod(BitStream
, &BitLen
, &clk
, &invert
, &clkStartIdx
);
908 if (errCnt
> maxErr
){
909 if (g_debugMode
) PrintAndLog("Too many errors found, clk: %d, invert: %d, numbits: %d, errCnt: %d",clk
,invert
,BitLen
,errCnt
);
912 if (errCnt
<0 || BitLen
<16){ //throw away static - allow 1 and -1 (in case of threshold command first)
913 if (g_debugMode
) PrintAndLog("no data found, clk: %d, invert: %d, numbits: %d, errCnt: %d",clk
,invert
,BitLen
,errCnt
);
916 if (verbose
|| g_debugMode
) PrintAndLog("Tried NRZ Demod using Clock: %d - invert: %d - Bits Found: %d",clk
,invert
,BitLen
);
917 //prime demod buffer for output
918 setDemodBuf(BitStream
,BitLen
,0);
919 setClockGrid(clk
, clkStartIdx
);
922 if (errCnt
>0 && (verbose
|| g_debugMode
)) PrintAndLog("# Errors during Demoding (shown as 7 in bit stream): %d",errCnt
);
923 if (verbose
|| g_debugMode
) {
924 PrintAndLog("NRZ demoded bitstream:");
925 // Now output the bitstream to the scrollback by line of 16 bits
931 int CmdNRZrawDemod(const char *Cmd
)
933 char cmdp
= param_getchar(Cmd
, 0);
934 if (strlen(Cmd
) > 16 || cmdp
== 'h' || cmdp
== 'H') {
935 PrintAndLog("Usage: data rawdemod nr [clock] <0|1> [maxError]");
936 PrintAndLog(" [set clock as integer] optional, if not set, autodetect.");
937 PrintAndLog(" <invert>, 1 for invert output");
938 PrintAndLog(" [set maximum allowed errors], default = 100.");
940 PrintAndLog(" sample: data rawdemod nr = demod a nrz/direct tag from GraphBuffer");
941 PrintAndLog(" : data rawdemod nr 32 = demod a nrz/direct tag from GraphBuffer using a clock of RF/32");
942 PrintAndLog(" : data rawdemod nr 32 1 = demod a nrz/direct tag from GraphBuffer using a clock of RF/32 and inverting data");
943 PrintAndLog(" : data rawdemod nr 1 = demod a nrz/direct tag from GraphBuffer while inverting data");
944 PrintAndLog(" : data rawdemod nr 64 1 0 = demod a nrz/direct tag from GraphBuffer using a clock of RF/64, inverting data and allowing 0 demod errors");
947 return NRZrawDemod(Cmd
, true);
951 // takes 3 arguments - clock, invert, maxErr as integers
952 // attempts to demodulate psk only
953 // prints binary found and saves in demodbuffer for further commands
954 int CmdPSK1rawDemod(const char *Cmd
)
957 char cmdp
= param_getchar(Cmd
, 0);
958 if (strlen(Cmd
) > 16 || cmdp
== 'h' || cmdp
== 'H') {
959 PrintAndLog("Usage: data rawdemod p1 [clock] <0|1> [maxError]");
960 PrintAndLog(" [set clock as integer] optional, if not set, autodetect.");
961 PrintAndLog(" <invert>, 1 for invert output");
962 PrintAndLog(" [set maximum allowed errors], default = 100.");
964 PrintAndLog(" sample: data rawdemod p1 = demod a psk1 tag from GraphBuffer");
965 PrintAndLog(" : data rawdemod p1 32 = demod a psk1 tag from GraphBuffer using a clock of RF/32");
966 PrintAndLog(" : data rawdemod p1 32 1 = demod a psk1 tag from GraphBuffer using a clock of RF/32 and inverting data");
967 PrintAndLog(" : data rawdemod p1 1 = demod a psk1 tag from GraphBuffer while inverting data");
968 PrintAndLog(" : data rawdemod p1 64 1 0 = demod a psk1 tag from GraphBuffer using a clock of RF/64, inverting data and allowing 0 demod errors");
971 ans
= PSKDemod(Cmd
, true);
974 if (g_debugMode
) PrintAndLog("Error demoding: %d",ans
);
978 PrintAndLog("PSK1 demoded bitstream:");
979 // Now output the bitstream to the scrollback by line of 16 bits
985 // takes same args as cmdpsk1rawdemod
986 int CmdPSK2rawDemod(const char *Cmd
)
989 char cmdp
= param_getchar(Cmd
, 0);
990 if (strlen(Cmd
) > 16 || cmdp
== 'h' || cmdp
== 'H') {
991 PrintAndLog("Usage: data rawdemod p2 [clock] <0|1> [maxError]");
992 PrintAndLog(" [set clock as integer] optional, if not set, autodetect.");
993 PrintAndLog(" <invert>, 1 for invert output");
994 PrintAndLog(" [set maximum allowed errors], default = 100.");
996 PrintAndLog(" sample: data rawdemod p2 = demod a psk2 tag from GraphBuffer, autodetect clock");
997 PrintAndLog(" : data rawdemod p2 32 = demod a psk2 tag from GraphBuffer using a clock of RF/32");
998 PrintAndLog(" : data rawdemod p2 32 1 = demod a psk2 tag from GraphBuffer using a clock of RF/32 and inverting output");
999 PrintAndLog(" : data rawdemod p2 1 = demod a psk2 tag from GraphBuffer, autodetect clock and invert output");
1000 PrintAndLog(" : data rawdemod p2 64 1 0 = demod a psk2 tag from GraphBuffer using a clock of RF/64, inverting output and allowing 0 demod errors");
1003 ans
=PSKDemod(Cmd
, true);
1005 if (g_debugMode
) PrintAndLog("Error demoding: %d",ans
);
1008 psk1TOpsk2(DemodBuffer
, DemodBufferLen
);
1009 PrintAndLog("PSK2 demoded bitstream:");
1010 // Now output the bitstream to the scrollback by line of 16 bits
1015 // by marshmellow - combines all raw demod functions into one menu command
1016 int CmdRawDemod(const char *Cmd
)
1018 char cmdp
= Cmd
[0]; //param_getchar(Cmd, 0);
1020 if (strlen(Cmd
) > 35 || cmdp
== 'h' || cmdp
== 'H' || strlen(Cmd
)<2) {
1021 PrintAndLog("Usage: data rawdemod [modulation] <help>|<options>");
1022 PrintAndLog(" [modulation] as 2 char, 'ab' for ask/biphase, 'am' for ask/manchester, 'ar' for ask/raw, 'fs' for fsk, ...");
1023 PrintAndLog(" 'nr' for nrz/direct, 'p1' for psk1, 'p2' for psk2");
1024 PrintAndLog(" <help> as 'h', prints the help for the specific modulation");
1025 PrintAndLog(" <options> see specific modulation help for optional parameters");
1027 PrintAndLog(" sample: data rawdemod fs h = print help specific to fsk demod");
1028 PrintAndLog(" : data rawdemod fs = demod GraphBuffer using: fsk - autodetect");
1029 PrintAndLog(" : data rawdemod ab = demod GraphBuffer using: ask/biphase - autodetect");
1030 PrintAndLog(" : data rawdemod am = demod GraphBuffer using: ask/manchester - autodetect");
1031 PrintAndLog(" : data rawdemod ar = demod GraphBuffer using: ask/raw - autodetect");
1032 PrintAndLog(" : data rawdemod nr = demod GraphBuffer using: nrz/direct - autodetect");
1033 PrintAndLog(" : data rawdemod p1 = demod GraphBuffer using: psk1 - autodetect");
1034 PrintAndLog(" : data rawdemod p2 = demod GraphBuffer using: psk2 - autodetect");
1037 char cmdp2
= Cmd
[1];
1039 if (cmdp
== 'f' && cmdp2
== 's'){
1040 ans
= CmdFSKrawdemod(Cmd
+2);
1041 } else if(cmdp
== 'a' && cmdp2
== 'b'){
1042 ans
= Cmdaskbiphdemod(Cmd
+2);
1043 } else if(cmdp
== 'a' && cmdp2
== 'm'){
1044 ans
= Cmdaskmandemod(Cmd
+2);
1045 } else if(cmdp
== 'a' && cmdp2
== 'r'){
1046 ans
= Cmdaskrawdemod(Cmd
+2);
1047 } else if(cmdp
== 'n' && cmdp2
== 'r'){
1048 ans
= CmdNRZrawDemod(Cmd
+2);
1049 } else if(cmdp
== 'p' && cmdp2
== '1'){
1050 ans
= CmdPSK1rawDemod(Cmd
+2);
1051 } else if(cmdp
== 'p' && cmdp2
== '2'){
1052 ans
= CmdPSK2rawDemod(Cmd
+2);
1054 PrintAndLog("unknown modulation entered - see help ('h') for parameter structure");
1059 void setClockGrid(int clk
, int offset
) {
1060 if (offset
> clk
) offset
%= clk
;
1061 if (offset
< 0) offset
+= clk
;
1063 if (offset
> GraphTraceLen
|| offset
< 0) return;
1064 if (clk
< 8 || clk
> GraphTraceLen
) {
1068 PlotGridXdefault
= 0;
1069 RepaintGraphWindow();
1072 GridOffset
= offset
;
1074 PlotGridXdefault
= clk
;
1075 RepaintGraphWindow();
1079 int CmdGrid(const char *Cmd
)
1081 sscanf(Cmd
, "%i %i", &PlotGridX
, &PlotGridY
);
1082 PlotGridXdefault
= PlotGridX
;
1083 PlotGridYdefault
= PlotGridY
;
1084 RepaintGraphWindow();
1088 int CmdSetGraphMarkers(const char *Cmd
) {
1089 sscanf(Cmd
, "%i %i", &CursorCPos
, &CursorDPos
);
1090 RepaintGraphWindow();
1094 int CmdHexsamples(const char *Cmd
)
1099 char string_buf
[25];
1100 char* string_ptr
= string_buf
;
1101 uint8_t got
[BIGBUF_SIZE
];
1103 sscanf(Cmd
, "%i %i", &requested
, &offset
);
1105 /* if no args send something */
1106 if (requested
== 0) {
1109 if (offset
+ requested
> sizeof(got
)) {
1110 PrintAndLog("Tried to read past end of buffer, <bytes> + <offset> > %d", BIGBUF_SIZE
);
1114 GetFromBigBuf(got
,requested
,offset
);
1115 WaitForResponse(CMD_ACK
,NULL
);
1118 for (j
= 0; j
< requested
; j
++) {
1120 string_ptr
+= sprintf(string_ptr
, "%02x ", got
[j
]);
1122 *(string_ptr
- 1) = '\0'; // remove the trailing space
1123 PrintAndLog("%s", string_buf
);
1124 string_buf
[0] = '\0';
1125 string_ptr
= string_buf
;
1128 if (j
== requested
- 1 && string_buf
[0] != '\0') { // print any remaining bytes
1129 *(string_ptr
- 1) = '\0';
1130 PrintAndLog("%s", string_buf
);
1131 string_buf
[0] = '\0';
1137 int CmdHide(const char *Cmd
)
1143 //zero mean GraphBuffer
1144 int CmdHpf(const char *Cmd
)
1149 for (i
= 10; i
< GraphTraceLen
; ++i
)
1150 accum
+= GraphBuffer
[i
];
1151 accum
/= (GraphTraceLen
- 10);
1152 for (i
= 0; i
< GraphTraceLen
; ++i
)
1153 GraphBuffer
[i
] -= accum
;
1155 RepaintGraphWindow();
1159 uint8_t getByte(uint8_t bits_per_sample
, BitstreamIn
* b
)
1163 for(i
=0 ; i
< bits_per_sample
; i
++)
1165 val
|= (headBit(b
) << (7-i
));
1170 int getSamples(int n
, bool silent
)
1172 //If we get all but the last byte in bigbuf,
1173 // we don't have to worry about remaining trash
1174 // in the last byte in case the bits-per-sample
1175 // does not line up on byte boundaries
1177 uint8_t got
[BIGBUF_SIZE
-1] = { 0 };
1179 if (n
== 0 || n
> sizeof(got
))
1182 if (!silent
) PrintAndLog("Reading %d bytes from device memory\n", n
);
1183 GetFromBigBuf(got
,n
,0);
1184 if (!silent
) PrintAndLog("Data fetched");
1185 UsbCommand response
;
1186 WaitForResponse(CMD_ACK
, &response
);
1187 uint8_t bits_per_sample
= 8;
1189 //Old devices without this feature would send 0 at arg[0]
1190 if(response
.arg
[0] > 0)
1192 sample_config
*sc
= (sample_config
*) response
.d
.asBytes
;
1193 if (!silent
) PrintAndLog("Samples @ %d bits/smpl, decimation 1:%d ", sc
->bits_per_sample
1195 bits_per_sample
= sc
->bits_per_sample
;
1197 if(bits_per_sample
< 8)
1199 if (!silent
) PrintAndLog("Unpacking...");
1200 BitstreamIn bout
= { got
, bits_per_sample
* n
, 0};
1202 for (j
= 0; j
* bits_per_sample
< n
* 8 && j
< n
; j
++) {
1203 uint8_t sample
= getByte(bits_per_sample
, &bout
);
1204 GraphBuffer
[j
] = ((int) sample
)- 128;
1207 PrintAndLog("Unpacked %d samples" , j
);
1210 for (int j
= 0; j
< n
; j
++) {
1211 GraphBuffer
[j
] = ((int)got
[j
]) - 128;
1216 RepaintGraphWindow();
1220 int CmdSamples(const char *Cmd
)
1222 int n
= strtol(Cmd
, NULL
, 0);
1223 return getSamples(n
, false);
1226 int CmdTuneSamples(const char *Cmd
)
1228 int timeout
= 0, arg
= FLAG_TUNE_ALL
;
1232 } else if (*Cmd
== 'h') {
1234 } else if (*Cmd
!= '\0') {
1235 PrintAndLog("use 'tune' or 'tune l' or 'tune h'");
1239 printf("\nMeasuring antenna characteristics, please wait...");
1241 UsbCommand c
= {CMD_MEASURE_ANTENNA_TUNING
, {arg
, 0, 0}};
1245 while(!WaitForResponseTimeout(CMD_MEASURED_ANTENNA_TUNING
,&resp
,1000)) {
1249 PrintAndLog("\nNo response from Proxmark. Aborting...");
1255 int vLf125
, vLf134
, vHf
;
1256 vLf125
= resp
.arg
[0] & 0xffff;
1257 vLf134
= resp
.arg
[0] >> 16;
1258 vHf
= resp
.arg
[1] & 0xffff;;
1259 peakf
= resp
.arg
[2] & 0xffff;
1260 peakv
= resp
.arg
[2] >> 16;
1262 PrintAndLog("# LF antenna: %5.2f V @ 125.00 kHz", vLf125
/1000.0);
1263 PrintAndLog("# LF antenna: %5.2f V @ 134.00 kHz", vLf134
/1000.0);
1264 PrintAndLog("# LF optimal: %5.2f V @%9.2f kHz", peakv
/1000.0, 12000.0/(peakf
+1));
1265 PrintAndLog("# HF antenna: %5.2f V @ 13.56 MHz", vHf
/1000.0);
1267 #define LF_UNUSABLE_V 2948 // was 2000. Changed due to bugfix in voltage measurements. LF results are now 47% higher.
1268 #define LF_MARGINAL_V 14739 // was 10000. Changed due to bugfix bug in voltage measurements. LF results are now 47% higher.
1269 #define HF_UNUSABLE_V 3167 // was 2000. Changed due to bugfix in voltage measurements. HF results are now 58% higher.
1270 #define HF_MARGINAL_V 7917 // was 5000. Changed due to bugfix in voltage measurements. HF results are now 58% higher.
1272 if (peakv
< LF_UNUSABLE_V
)
1273 PrintAndLog("# Your LF antenna is unusable.");
1274 else if (peakv
< LF_MARGINAL_V
)
1275 PrintAndLog("# Your LF antenna is marginal.");
1276 if (vHf
< HF_UNUSABLE_V
)
1277 PrintAndLog("# Your HF antenna is unusable.");
1278 else if (vHf
< HF_MARGINAL_V
)
1279 PrintAndLog("# Your HF antenna is marginal.");
1281 if (peakv
>= LF_UNUSABLE_V
) {
1282 for (int i
= 0; i
< 256; i
++) {
1283 GraphBuffer
[i
] = resp
.d
.asBytes
[i
] - 128;
1285 PrintAndLog("Displaying LF tuning graph. Divisor 89 is 134khz, 95 is 125khz.\n");
1287 GraphTraceLen
= 256;
1289 RepaintGraphWindow();
1296 int CmdLoad(const char *Cmd
)
1298 char filename
[FILE_PATH_SIZE
] = {0x00};
1302 if (len
> FILE_PATH_SIZE
) len
= FILE_PATH_SIZE
;
1303 memcpy(filename
, Cmd
, len
);
1305 FILE *f
= fopen(filename
, "r");
1307 PrintAndLog("couldn't open '%s'", filename
);
1313 while (fgets(line
, sizeof (line
), f
)) {
1314 GraphBuffer
[GraphTraceLen
] = atoi(line
);
1318 PrintAndLog("loaded %d samples", GraphTraceLen
);
1319 RepaintGraphWindow();
1323 int CmdLtrim(const char *Cmd
)
1326 if (GraphTraceLen
<=0) return 0;
1327 for (int i
= ds
; i
< GraphTraceLen
; ++i
)
1328 GraphBuffer
[i
-ds
] = GraphBuffer
[i
];
1329 GraphTraceLen
-= ds
;
1331 RepaintGraphWindow();
1335 // trim graph to input argument length
1336 int CmdRtrim(const char *Cmd
)
1342 RepaintGraphWindow();
1346 // trim graph (middle) piece
1347 int CmdMtrim(const char *Cmd
) {
1348 int start
= 0, stop
= 0;
1349 sscanf(Cmd
, "%i %i", &start
, &stop
);
1351 if (start
> GraphTraceLen
|| stop
> GraphTraceLen
|| start
> stop
) return 0;
1352 start
++; //leave start position sample
1354 GraphTraceLen
= stop
- start
;
1355 for (int i
= 0; i
< GraphTraceLen
; i
++) {
1356 GraphBuffer
[i
] = GraphBuffer
[start
+i
];
1362 int CmdNorm(const char *Cmd
)
1365 int max
= INT_MIN
, min
= INT_MAX
;
1367 for (i
= 10; i
< GraphTraceLen
; ++i
) {
1368 if (GraphBuffer
[i
] > max
)
1369 max
= GraphBuffer
[i
];
1370 if (GraphBuffer
[i
] < min
)
1371 min
= GraphBuffer
[i
];
1375 for (i
= 0; i
< GraphTraceLen
; ++i
) {
1376 GraphBuffer
[i
] = (GraphBuffer
[i
] - ((max
+ min
) / 2)) * 256 /
1378 //marshmelow: adjusted *1000 to *256 to make +/- 128 so demod commands still work
1381 RepaintGraphWindow();
1385 int CmdPlot(const char *Cmd
)
1391 int CmdSave(const char *Cmd
)
1393 char filename
[FILE_PATH_SIZE
] = {0x00};
1397 if (len
> FILE_PATH_SIZE
) len
= FILE_PATH_SIZE
;
1398 memcpy(filename
, Cmd
, len
);
1401 FILE *f
= fopen(filename
, "w");
1403 PrintAndLog("couldn't open '%s'", filename
);
1407 for (i
= 0; i
< GraphTraceLen
; i
++) {
1408 fprintf(f
, "%d\n", GraphBuffer
[i
]);
1411 PrintAndLog("saved to '%s'", Cmd
);
1415 int CmdScale(const char *Cmd
)
1417 CursorScaleFactor
= atoi(Cmd
);
1418 if (CursorScaleFactor
== 0) {
1419 PrintAndLog("bad, can't have zero scale");
1420 CursorScaleFactor
= 1;
1422 RepaintGraphWindow();
1426 int CmdDirectionalThreshold(const char *Cmd
)
1428 int8_t upThres
= param_get8(Cmd
, 0);
1429 int8_t downThres
= param_get8(Cmd
, 1);
1431 printf("Applying Up Threshold: %d, Down Threshold: %d\n", upThres
, downThres
);
1433 int lastValue
= GraphBuffer
[0];
1434 GraphBuffer
[0] = 0; // Will be changed at the end, but init 0 as we adjust to last samples value if no threshold kicks in.
1436 for (int i
= 1; i
< GraphTraceLen
; ++i
) {
1437 // Apply first threshold to samples heading up
1438 if (GraphBuffer
[i
] >= upThres
&& GraphBuffer
[i
] > lastValue
)
1440 lastValue
= GraphBuffer
[i
]; // Buffer last value as we overwrite it.
1441 GraphBuffer
[i
] = 127;
1443 // Apply second threshold to samples heading down
1444 else if (GraphBuffer
[i
] <= downThres
&& GraphBuffer
[i
] < lastValue
)
1446 lastValue
= GraphBuffer
[i
]; // Buffer last value as we overwrite it.
1447 GraphBuffer
[i
] = -127;
1451 lastValue
= GraphBuffer
[i
]; // Buffer last value as we overwrite it.
1452 GraphBuffer
[i
] = GraphBuffer
[i
-1];
1456 GraphBuffer
[0] = GraphBuffer
[1]; // Aline with first edited sample.
1457 RepaintGraphWindow();
1461 int CmdZerocrossings(const char *Cmd
)
1463 // Zero-crossings aren't meaningful unless the signal is zero-mean.
1470 for (int i
= 0; i
< GraphTraceLen
; ++i
) {
1471 if (GraphBuffer
[i
] * sign
>= 0) {
1472 // No change in sign, reproduce the previous sample count.
1474 GraphBuffer
[i
] = lastZc
;
1476 // Change in sign, reset the sample count.
1478 GraphBuffer
[i
] = lastZc
;
1486 RepaintGraphWindow();
1490 int usage_data_bin2hex(){
1491 PrintAndLog("Usage: data bin2hex <binary_digits>");
1492 PrintAndLog(" This function will ignore all characters not 1 or 0 (but stop reading on whitespace)");
1497 * @brief Utility for conversion via cmdline.
1501 int Cmdbin2hex(const char *Cmd
)
1504 if(param_getptr(Cmd
, &bg
, &en
, 0))
1506 return usage_data_bin2hex();
1508 //Number of digits supplied as argument
1509 size_t length
= en
- bg
+1;
1510 size_t bytelen
= (length
+7) / 8;
1511 uint8_t* arr
= (uint8_t *) malloc(bytelen
);
1512 memset(arr
, 0, bytelen
);
1513 BitstreamOut bout
= { arr
, 0, 0 };
1515 for(; bg
<= en
;bg
++)
1518 if( c
== '1') pushBit(&bout
, 1);
1519 else if( c
== '0') pushBit(&bout
, 0);
1520 else PrintAndLog("Ignoring '%c'", c
);
1523 if(bout
.numbits
% 8 != 0)
1525 printf("[padded with %d zeroes]\n", 8-(bout
.numbits
% 8));
1528 //Uses printf instead of PrintAndLog since the latter
1529 // adds linebreaks to each printout - this way was more convenient since we don't have to
1530 // allocate a string and write to that first...
1531 for(size_t x
= 0; x
< bytelen
; x
++)
1533 printf("%02X", arr
[x
]);
1540 int usage_data_hex2bin() {
1541 PrintAndLog("Usage: data hex2bin <hex_digits>");
1542 PrintAndLog(" This function will ignore all non-hexadecimal characters (but stop reading on whitespace)");
1547 int Cmdhex2bin(const char *Cmd
)
1550 if(param_getptr(Cmd
, &bg
, &en
, 0))
1552 return usage_data_hex2bin();
1560 if (x
>= 'a' && x
<= 'f')
1562 // convert to numeric value
1563 if (x
>= '0' && x
<= '9')
1565 else if (x
>= 'A' && x
<= 'F')
1570 //Uses printf instead of PrintAndLog since the latter
1571 // adds linebreaks to each printout - this way was more convenient since we don't have to
1572 // allocate a string and write to that first...
1574 for(int i
= 0 ; i
< 4 ; ++i
)
1575 printf("%d",(x
>> (3 - i
)) & 1);
1582 static command_t CommandTable
[] =
1584 {"help", CmdHelp
, 1, "This help"},
1585 {"askedgedetect", CmdAskEdgeDetect
, 1, "[threshold] Adjust Graph for manual ask demod using the length of sample differences to detect the edge of a wave (use 20-45, def:25)"},
1586 {"autocorr", CmdAutoCorr
, 1, "[window length] [g] -- Autocorrelation over window - g to save back to GraphBuffer (overwrite)"},
1587 {"biphaserawdecode",CmdBiphaseDecodeRaw
,1, "[offset] [invert<0|1>] [maxErr] -- Biphase decode bin stream in DemodBuffer (offset = 0|1 bits to shift the decode start)"},
1588 {"bin2hex", Cmdbin2hex
, 1, "bin2hex <digits> -- Converts binary to hexadecimal"},
1589 {"bitsamples", CmdBitsamples
, 0, "Get raw samples as bitstring"},
1590 {"buffclear", CmdBuffClear
, 1, "Clear sample buffer and graph window"},
1591 {"dec", CmdDec
, 1, "Decimate samples"},
1592 {"detectclock", CmdDetectClockRate
, 1, "[modulation] Detect clock rate of wave in GraphBuffer (options: 'a','f','n','p' for ask, fsk, nrz, psk respectively)"},
1593 {"getbitstream", CmdGetBitStream
, 1, "Convert GraphBuffer's >=1 values to 1 and <1 to 0"},
1594 {"grid", CmdGrid
, 1, "<x> <y> -- overlay grid on graph window, use zero value to turn off either"},
1595 {"hexsamples", CmdHexsamples
, 0, "<bytes> [<offset>] -- Dump big buffer as hex bytes"},
1596 {"hex2bin", Cmdhex2bin
, 1, "hex2bin <hexadecimal> -- Converts hexadecimal to binary"},
1597 {"hide", CmdHide
, 1, "Hide graph window"},
1598 {"hpf", CmdHpf
, 1, "Remove DC offset from trace"},
1599 {"load", CmdLoad
, 1, "<filename> -- Load trace (to graph window"},
1600 {"ltrim", CmdLtrim
, 1, "<samples> -- Trim samples from left of trace"},
1601 {"rtrim", CmdRtrim
, 1, "<location to end trace> -- Trim samples from right of trace"},
1602 {"mtrim", CmdMtrim
, 1, "<start> <stop> -- Trim out samples from the specified start to the specified stop"},
1603 {"manrawdecode", Cmdmandecoderaw
, 1, "[invert] [maxErr] -- Manchester decode binary stream in DemodBuffer"},
1604 {"norm", CmdNorm
, 1, "Normalize max/min to +/-128"},
1605 {"plot", CmdPlot
, 1, "Show graph window (hit 'h' in window for keystroke help)"},
1606 {"printdemodbuffer",CmdPrintDemodBuff
, 1, "[x] [o] <offset> [l] <length> -- print the data in the DemodBuffer - 'x' for hex output"},
1607 {"rawdemod", CmdRawDemod
, 1, "[modulation] ... <options> -see help (h option) -- Demodulate the data in the GraphBuffer and output binary"},
1608 {"samples", CmdSamples
, 0, "[512 - 40000] -- Get raw samples for graph window (GraphBuffer)"},
1609 {"save", CmdSave
, 1, "<filename> -- Save trace (from graph window)"},
1610 {"setgraphmarkers", CmdSetGraphMarkers
, 1, "[orange_marker] [blue_marker] (in graph window)"},
1611 {"scale", CmdScale
, 1, "<int> -- Set cursor display scale"},
1612 {"setdebugmode", CmdSetDebugMode
, 1, "<0|1|2> -- Turn on or off Debugging Level for lf demods"},
1613 {"shiftgraphzero", CmdGraphShiftZero
, 1, "<shift> -- Shift 0 for Graphed wave + or - shift value"},
1614 {"dirthreshold", CmdDirectionalThreshold
, 1, "<thres up> <thres down> -- Max rising higher up-thres/ Min falling lower down-thres, keep rest as prev."},
1615 {"tune", CmdTuneSamples
, 0, "Get hw tune samples for graph window"},
1616 {"undec", CmdUndec
, 1, "Un-decimate samples by 2"},
1617 {"zerocrossings", CmdZerocrossings
, 1, "Count time between zero-crossings"},
1618 {NULL
, NULL
, 0, NULL
}
1621 int CmdData(const char *Cmd
)
1623 CmdsParse(CommandTable
, Cmd
);
1627 int CmdHelp(const char *Cmd
)
1629 CmdsHelp(CommandTable
);