]> git.zerfleddert.de Git - proxmark3-svn/blob - client/cmddata.c
align clock grid with demods on graph
[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> // also included in util.h
12 #include <string.h> // also included in util.h
13 #include <inttypes.h>
14 #include <limits.h> // for CmdNorm INT_MIN && INT_MAX
15 #include "data.h" // also included in util.h
16 #include "cmddata.h"
17 #include "util.h"
18 #include "cmdmain.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
27
28 uint8_t DemodBuffer[MAX_DEMOD_BUF_LEN];
29 uint8_t g_debugMode=0;
30 size_t DemodBufferLen=0;
31
32 static int CmdHelp(const char *Cmd);
33
34 //set the demod buffer with given array of binary (one bit per byte)
35 //by marshmellow
36 void setDemodBuf(uint8_t *buff, size_t size, size_t startIdx)
37 {
38 if (buff == NULL)
39 return;
40
41 if ( size > MAX_DEMOD_BUF_LEN - startIdx)
42 size = MAX_DEMOD_BUF_LEN - startIdx;
43
44 size_t i = 0;
45 for (; i < size; i++){
46 DemodBuffer[i]=buff[startIdx++];
47 }
48 DemodBufferLen=size;
49 return;
50 }
51
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;
56
57 *size = (*size > DemodBufferLen) ? DemodBufferLen : *size;
58
59 memcpy(buff, DemodBuffer, *size);
60 return true;
61 }
62
63 // option '1' to save DemodBuffer any other to restore
64 void save_restoreDB(uint8_t saveOpt)
65 {
66 static uint8_t SavedDB[MAX_DEMOD_BUF_LEN];
67 static size_t SavedDBlen;
68 static bool DB_Saved = false;
69
70 if (saveOpt==1) { //save
71
72 memcpy(SavedDB, DemodBuffer, sizeof(DemodBuffer));
73 SavedDBlen = DemodBufferLen;
74 DB_Saved=true;
75 } else if (DB_Saved) { //restore
76 memcpy(DemodBuffer, SavedDB, sizeof(DemodBuffer));
77 DemodBufferLen = SavedDBlen;
78 }
79 return;
80 }
81
82 int CmdSetDebugMode(const char *Cmd)
83 {
84 int demod=0;
85 sscanf(Cmd, "%i", &demod);
86 g_debugMode=(uint8_t)demod;
87 return 1;
88 }
89
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");
97 return 0;
98 }
99
100 //by marshmellow
101 void printDemodBuff(void)
102 {
103 int bitLen = DemodBufferLen;
104 if (bitLen<1) {
105 PrintAndLog("no bits found in demod buffer");
106 return;
107 }
108 if (bitLen>512) bitLen=512; //max output to 512 bits if we have more - should be plenty
109
110 char *bin = sprint_bin_break(DemodBuffer,bitLen,16);
111 PrintAndLog("%s",bin);
112
113 return;
114 }
115
116 int CmdPrintDemodBuff(const char *Cmd)
117 {
118 char hex[512]={0x00};
119 bool hexMode = false;
120 bool errors = false;
121 uint32_t offset = 0; //could be size_t but no param_get16...
122 uint32_t length = 512;
123 char cmdp = 0;
124 while(param_getchar(Cmd, cmdp) != 0x00)
125 {
126 switch(param_getchar(Cmd, cmdp))
127 {
128 case 'h':
129 case 'H':
130 return usage_data_printdemodbuf();
131 case 'x':
132 case 'X':
133 hexMode = true;
134 cmdp++;
135 break;
136 case 'o':
137 case 'O':
138 offset = param_get32ex(Cmd, cmdp+1, 0, 10);
139 if (!offset) errors = true;
140 cmdp += 2;
141 break;
142 case 'l':
143 case 'L':
144 length = param_get32ex(Cmd, cmdp+1, 512, 10);
145 if (!length) errors = true;
146 cmdp += 2;
147 break;
148 default:
149 PrintAndLog("Unknown parameter '%c'", param_getchar(Cmd, cmdp));
150 errors = true;
151 break;
152 }
153 if(errors) break;
154 }
155 //Validations
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
159
160 if (hexMode){
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);
166 } else {
167 PrintAndLog("DemodBuffer:\n%s", sprint_bin_break(DemodBuffer+offset,numBits,16));
168 }
169 return 1;
170 }
171
172 //by marshmellow
173 //this function strictly converts >1 to 1 and <1 to 0 for each sample in the graphbuffer
174 int CmdGetBitStream(const char *Cmd)
175 {
176 int i;
177 CmdHpf(Cmd);
178 for (i = 0; i < GraphTraceLen; i++) {
179 if (GraphBuffer[i] >= 1) {
180 GraphBuffer[i] = 1;
181 } else {
182 GraphBuffer[i] = 0;
183 }
184 }
185 RepaintGraphWindow();
186 return 0;
187 }
188
189 //by marshmellow
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) {
196 int invert=0;
197 int clk=0;
198 int maxErr=100;
199 int maxLen=0;
200 uint8_t askamp = 0;
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, &amp);
204 if (!maxLen) maxLen = BIGBUF_SIZE;
205 if (invert != 0 && invert != 1) {
206 PrintAndLog("Invalid argument: %s", Cmd);
207 return 0;
208 }
209 if (clk==1){
210 invert=1;
211 clk=0;
212 }
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;
217 int foundclk = 0;
218 //amp before ST check
219 if (amp == 'a' || amp == 'A') {
220 askAmp(BitStream, BitLen);
221 }
222 bool st = false;
223 size_t ststart = 0, stend = 0;
224 if (*stCheck) st = DetectST(BitStream, &BitLen, &foundclk, &ststart, &stend);
225 *stCheck = st;
226 if (st) {
227 clk = (clk == 0) ? foundclk : clk;
228 CursorCPos = ststart;
229 CursorDPos = stend;
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;
234 //}
235 //RepaintGraphWindow();
236 }
237 int startIdx = 0;
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);
241 return 0;
242 }
243 if (errCnt > maxErr){
244 if (g_debugMode) PrintAndLog("DEBUG: Too many errors found, errors:%d, bits:%d, clock:%d",errCnt, BitLen, clk);
245 return 0;
246 }
247 if (verbose || g_debugMode) PrintAndLog("\nUsing Clock:%d, Invert:%d, Bits Found:%d",clk,invert,BitLen);
248
249 //output
250 setDemodBuf(BitStream,BitLen,0);
251 setClockGrid(clk, startIdx);
252
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
258 printDemodBuff();
259
260 }
261 uint64_t lo = 0;
262 uint32_t hi = 0;
263 if (emSearch){
264 AskEm410xDecode(true, &hi, &lo);
265 }
266 return 1;
267 }
268 int ASKDemod(const char *Cmd, bool verbose, bool emSearch, uint8_t askType) {
269 bool st = false;
270 return ASKDemod_ext(Cmd, verbose, emSearch, askType, &st);
271 }
272
273 //by marshmellow
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)
278 {
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");
288 PrintAndLog("");
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");
294 return 0;
295 }
296 bool st = true;
297 if (Cmd[0]=='s')
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);
301 else
302 return ASKDemod(Cmd, true, true, 1);
303 }
304
305 //by marshmellow
306 //manchester decode
307 //stricktly take 10 and 01 and convert to 0 and 1
308 int Cmdmandecoderaw(const char *Cmd)
309 {
310 int i =0;
311 int errCnt=0;
312 size_t size=0;
313 int invert=0;
314 int maxErr = 20;
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)");
322 PrintAndLog("");
323 PrintAndLog(" sample: data manrawdecode = decode manchester bitstream from the demodbuffer");
324 return 0;
325 }
326 if (DemodBufferLen==0) return 0;
327 uint8_t BitStream[MAX_DEMOD_BUF_LEN]={0};
328 int high=0,low=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];
333 }
334 if (high>7 || low <0 ){
335 PrintAndLog("Error: please raw demod the wave first then manchester raw decode");
336 return 0;
337 }
338
339 sscanf(Cmd, "%i %i", &invert, &maxErr);
340 size=i;
341 uint8_t alignPos = 0;
342 errCnt=manrawdecode(BitStream, &size, invert, &alignPos);
343 if (errCnt>=maxErr){
344 PrintAndLog("Too many errors: %d",errCnt);
345 return 0;
346 }
347 PrintAndLog("Manchester Decoded - # errors:%d - data:",errCnt);
348 PrintAndLog("%s", sprint_bin_break(BitStream, size, 16));
349 if (errCnt==0){
350 uint64_t id = 0;
351 uint32_t hi = 0;
352 size_t idx=0;
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);
356
357 printEM410x(hi, id);
358 }
359 }
360 return 1;
361 }
362
363 //by marshmellow
364 //biphase decode
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)
370 {
371 size_t size=0;
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");
379 PrintAndLog("");
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");
383 PrintAndLog("");
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");
386 return 0;
387 }
388 sscanf(Cmd, "%i %i %i", &offset, &invert, &maxErr);
389 if (DemodBufferLen==0) {
390 PrintAndLog("DemodBuffer Empty - run 'data rawdemod ar' first");
391 return 0;
392 }
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);
397 if (errCnt<0){
398 PrintAndLog("Error during decode:%d", errCnt);
399 return 0;
400 }
401 if (errCnt>maxErr){
402 PrintAndLog("Too many errors attempting to decode: %d",errCnt);
403 return 0;
404 }
405
406 if (errCnt>0){
407 PrintAndLog("# Errors found during Demod (shown as 7 in bit stream): %d",errCnt);
408 }
409 PrintAndLog("Biphase Decoded using offset: %d - # invert:%d - data:",offset,invert);
410 PrintAndLog("%s", sprint_bin_break(BitStream, size, 16));
411
412 if (offset) setDemodBuf(DemodBuffer,DemodBufferLen-offset, offset); //remove first bit from raw demod
413 return 1;
414 }
415
416 //by marshmellow
417 // - ASK Demod then Biphase decode GraphBuffer samples
418 int ASKbiphaseDemod(const char *Cmd, bool verbose)
419 {
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);
423
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);
430 return 0;
431 }
432
433 //attempt to Biphase decode BitStream
434 errCnt = BiphaseRawDecode(BitStream, &size, offset, invert);
435 if (errCnt < 0){
436 if (g_debugMode || verbose) PrintAndLog("Error BiphaseRawDecode: %d", errCnt);
437 return 0;
438 }
439 if (errCnt > maxErr) {
440 if (g_debugMode || verbose) PrintAndLog("Error BiphaseRawDecode too many errors: %d", errCnt);
441 return 0;
442 }
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);
447 printDemodBuff();
448 }
449 return 1;
450 }
451 //by marshmellow - see ASKbiphaseDemod
452 int Cmdaskbiphdemod(const char *Cmd)
453 {
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");
466 PrintAndLog("");
467 PrintAndLog(" NOTE: --invert for Conditional Dephase Encoding (CDP) AKA Differential Manchester");
468 PrintAndLog("");
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");
476 return 0;
477 }
478 return ASKbiphaseDemod(Cmd, true);
479 }
480
481 //by marshmellow - see ASKDemod
482 int Cmdaskrawdemod(const char *Cmd)
483 {
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");
492 PrintAndLog("");
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");
500 return 0;
501 }
502 return ASKDemod(Cmd, true, false, 0);
503 }
504
505 int AutoCorrelate(int window, bool SaveGrph, bool verbose)
506 {
507 static int CorrelBuffer[MAX_GRAPH_TRACE_LEN];
508 size_t Correlation = 0;
509 int maxSum = 0;
510 int lastMax = 0;
511 if (verbose) PrintAndLog("performing %d correlations", GraphTraceLen - window);
512 for (int i = 0; i < GraphTraceLen - window; ++i) {
513 int sum = 0;
514 for (int j = 0; j < window; ++j) {
515 sum += (GraphBuffer[j]*GraphBuffer[i + j]) / 256;
516 }
517 CorrelBuffer[i] = sum;
518 if (sum >= maxSum-100 && sum <= maxSum+100){
519 //another max
520 Correlation = i-lastMax;
521 lastMax = i;
522 if (sum > maxSum) maxSum = sum;
523 } else if (sum > maxSum){
524 maxSum=sum;
525 lastMax = i;
526 }
527 }
528 if (Correlation==0){
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)){
532 //another max
533 Correlation = i-lastMax;
534 lastMax = i;
535 //if (CorrelBuffer[i] > maxSum) maxSum = sum;
536 }
537 }
538 }
539 if (verbose && Correlation > 0) PrintAndLog("Possible Correlation: %d samples",Correlation);
540
541 if (SaveGrph){
542 GraphTraceLen = GraphTraceLen - window;
543 memcpy(GraphBuffer, CorrelBuffer, GraphTraceLen * sizeof (int));
544 RepaintGraphWindow();
545 }
546 return Correlation;
547 }
548
549 int usage_data_autocorr(void)
550 {
551 //print help
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)");
557 return 0;
558 }
559
560 int CmdAutoCorr(const char *Cmd)
561 {
562 char cmdp = param_getchar(Cmd, 0);
563 if (cmdp == 'h' || cmdp == 'H')
564 return usage_data_autocorr();
565 int window = 4000; //set default
566 char grph=0;
567 bool updateGrph = false;
568 sscanf(Cmd, "%i %c", &window, &grph);
569
570 if (window >= GraphTraceLen) {
571 PrintAndLog("window must be smaller than trace (%d samples)",
572 GraphTraceLen);
573 return 0;
574 }
575 if (grph == 'g') updateGrph=true;
576 return AutoCorrelate(window, updateGrph, true);
577 }
578
579 int CmdBitsamples(const char *Cmd)
580 {
581 int cnt = 0;
582 uint8_t got[12288];
583
584 GetFromBigBuf(got,sizeof(got),0);
585 WaitForResponse(CMD_ACK,NULL);
586
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;
591 } else {
592 GraphBuffer[cnt++] = 0;
593 }
594 }
595 }
596 GraphTraceLen = cnt;
597 RepaintGraphWindow();
598 return 0;
599 }
600
601 int CmdBuffClear(const char *Cmd)
602 {
603 UsbCommand c = {CMD_BUFF_CLEAR};
604 SendCommand(&c);
605 ClearGraph(true);
606 return 0;
607 }
608
609 int CmdDec(const char *Cmd)
610 {
611 for (int i = 0; i < (GraphTraceLen / 2); ++i)
612 GraphBuffer[i] = GraphBuffer[i * 2];
613 GraphTraceLen /= 2;
614 PrintAndLog("decimated by 2");
615 RepaintGraphWindow();
616 return 0;
617 }
618 /**
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
622 * @param Cmd
623 * @return
624 */
625 int CmdUndec(const char *Cmd)
626 {
627 if(param_getchar(Cmd, 0) == 'h')
628 {
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'");
635 return 0;
636 }
637
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)
643 {
644 int count = 0;
645 for(count = 0; count < factor && s_index + count < MAX_GRAPH_TRACE_LEN; count++)
646 swap[s_index+count] = GraphBuffer[g_index];
647
648 s_index += count;
649 g_index++;
650 }
651
652 memcpy(GraphBuffer, swap, s_index * sizeof(int));
653 GraphTraceLen = s_index;
654 RepaintGraphWindow();
655 return 0;
656 }
657
658 //by marshmellow
659 //shift graph zero up or down based on input + or -
660 int CmdGraphShiftZero(const char *Cmd)
661 {
662
663 int shift=0;
664 //set options from parameters entered with the command
665 sscanf(Cmd, "%i", &shift);
666 int shiftedVal=0;
667 for(int i = 0; i<GraphTraceLen; i++){
668 shiftedVal=GraphBuffer[i]+shift;
669 if (shiftedVal>127)
670 shiftedVal=127;
671 else if (shiftedVal<-127)
672 shiftedVal=-127;
673 GraphBuffer[i]= shiftedVal;
674 }
675 CmdNorm("");
676 return 0;
677 }
678
679 //by marshmellow
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)
684 {
685 int thresLen = 25;
686 int Last = 0;
687 sscanf(Cmd, "%i", &thresLen);
688
689 for(int i = 1; i<GraphTraceLen; i++){
690 if (GraphBuffer[i]-GraphBuffer[i-1]>=thresLen) //large jump up
691 Last = 127;
692 else if(GraphBuffer[i]-GraphBuffer[i-1]<=-1*thresLen) //large jump down
693 Last = -127;
694 GraphBuffer[i-1] = Last;
695 }
696 RepaintGraphWindow();
697 return 0;
698 }
699
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)
704 {
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");
711 PrintAndLog("");
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");
716 }
717 int ans=0;
718 if (cmdp == 'a'){
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);
726 } else {
727 PrintAndLog ("Please specify a valid modulation to detect the clock of - see option h for help");
728 }
729 return ans;
730 }
731
732 char *GetFSKType(uint8_t fchigh, uint8_t fclow, uint8_t invert)
733 {
734 static char fType[8];
735 memset(fType, 0x00, 8);
736 char *fskType = fType;
737 if (fchigh==10 && fclow==8){
738 if (invert) //fsk2a
739 memcpy(fskType, "FSK2a", 5);
740 else //fsk2
741 memcpy(fskType, "FSK2", 4);
742 } else if (fchigh == 8 && fclow == 5) {
743 if (invert)
744 memcpy(fskType, "FSK1", 4);
745 else
746 memcpy(fskType, "FSK1a", 5);
747 } else {
748 memcpy(fskType, "FSK??", 5);
749 }
750 return fskType;
751 }
752
753 //by marshmellow
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)
758 {
759 //raw fsk demod no manchester decoding no start bit finding just get binary from wave
760 uint8_t rfLen, invert, fchigh, fclow;
761 //set defaults
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);
767
768 if (strlen(Cmd)>0 && strlen(Cmd)<=2) {
769 if (rfLen==1) {
770 invert = 1; //if invert option only is used
771 rfLen = 0;
772 }
773 }
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
778 uint16_t fcs=0;
779 if (!fchigh || !fclow) {
780 fcs = countFC(BitStream, BitLen, 1);
781 if (!fcs) {
782 fchigh = 10;
783 fclow = 8;
784 } else {
785 fchigh = (fcs >> 8) & 0x00FF;
786 fclow = fcs & 0x00FF;
787 }
788 }
789 //get bit clock length
790 if (!rfLen) {
791 int firstClockEdge = 0; //todo - align grid on graph with this...
792 rfLen = detectFSKClk(BitStream, BitLen, fchigh, fclow, &firstClockEdge);
793 if (!rfLen) rfLen = 50;
794 }
795 int startIdx = 0;
796 int size = fskdemod_ext(BitStream, BitLen, rfLen, invert, fchigh, fclow, &startIdx);
797 if (size > 0) {
798 setDemodBuf(BitStream,size,0);
799 setClockGrid(rfLen, startIdx);
800
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));
805 printDemodBuff();
806 }
807
808 return 1;
809 } else {
810 if (g_debugMode) PrintAndLog("no FSK data found");
811 }
812 return 0;
813 }
814
815 //by marshmellow
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)
820 {
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");
828 PrintAndLog("");
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");
836 return 0;
837 }
838 return FSKrawDemod(Cmd, true);
839 }
840
841 //by marshmellow
842 //attempt to psk1 demod graph buffer
843 int PSKDemod(const char *Cmd, bool verbose)
844 {
845 int invert=0;
846 int clk=0;
847 int maxErr=100;
848 sscanf(Cmd, "%i %i %i", &clk, &invert, &maxErr);
849 if (clk==1){
850 invert=1;
851 clk=0;
852 }
853 if (invert != 0 && invert != 1) {
854 if (g_debugMode || verbose) PrintAndLog("Invalid argument: %s", Cmd);
855 return 0;
856 }
857 uint8_t BitStream[MAX_GRAPH_TRACE_LEN]={0};
858 size_t BitLen = getFromGraphBuf(BitStream);
859 if (BitLen==0) return 0;
860 int errCnt=0;
861 int startIdx = 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);
865 return 0;
866 }
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);
869 return 0;
870 }
871 if (verbose || g_debugMode){
872 PrintAndLog("\nUsing Clock:%d, invert:%d, Bits Found:%d",clk,invert,BitLen);
873 if (errCnt>0){
874 PrintAndLog("# Errors during Demoding (shown as 7 in bit stream): %d",errCnt);
875 }
876 }
877 //prime demod buffer for output
878 setDemodBuf(BitStream,BitLen,0);
879 setClockGrid(clk, startIdx);
880
881 return 1;
882 }
883
884 // by marshmellow
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)
889 {
890 int invert=0;
891 int clk=0;
892 int maxErr=100;
893 sscanf(Cmd, "%i %i %i", &clk, &invert, &maxErr);
894 if (clk==1){
895 invert=1;
896 clk=0;
897 }
898 if (invert != 0 && invert != 1) {
899 PrintAndLog("Invalid argument: %s", Cmd);
900 return 0;
901 }
902 uint8_t BitStream[MAX_GRAPH_TRACE_LEN]={0};
903 size_t BitLen = getFromGraphBuf(BitStream);
904 if (BitLen==0) return 0;
905 int errCnt=0;
906 int clkStartIdx = 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);
910 return 0;
911 }
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);
914 return 0;
915 }
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);
920
921
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
926 printDemodBuff();
927 }
928 return 1;
929 }
930
931 int CmdNRZrawDemod(const char *Cmd)
932 {
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.");
939 PrintAndLog("");
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");
945 return 0;
946 }
947 return NRZrawDemod(Cmd, true);
948 }
949
950 // by marshmellow
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)
955 {
956 int ans;
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.");
963 PrintAndLog("");
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");
969 return 0;
970 }
971 ans = PSKDemod(Cmd, true);
972 //output
973 if (!ans){
974 if (g_debugMode) PrintAndLog("Error demoding: %d",ans);
975 return 0;
976 }
977
978 PrintAndLog("PSK1 demoded bitstream:");
979 // Now output the bitstream to the scrollback by line of 16 bits
980 printDemodBuff();
981 return 1;
982 }
983
984 // by marshmellow
985 // takes same args as cmdpsk1rawdemod
986 int CmdPSK2rawDemod(const char *Cmd)
987 {
988 int ans=0;
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.");
995 PrintAndLog("");
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");
1001 return 0;
1002 }
1003 ans=PSKDemod(Cmd, true);
1004 if (!ans){
1005 if (g_debugMode) PrintAndLog("Error demoding: %d",ans);
1006 return 0;
1007 }
1008 psk1TOpsk2(DemodBuffer, DemodBufferLen);
1009 PrintAndLog("PSK2 demoded bitstream:");
1010 // Now output the bitstream to the scrollback by line of 16 bits
1011 printDemodBuff();
1012 return 1;
1013 }
1014
1015 // by marshmellow - combines all raw demod functions into one menu command
1016 int CmdRawDemod(const char *Cmd)
1017 {
1018 char cmdp = Cmd[0]; //param_getchar(Cmd, 0);
1019
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");
1026 PrintAndLog("");
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");
1035 return 0;
1036 }
1037 char cmdp2 = Cmd[1];
1038 int ans = 0;
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);
1053 } else {
1054 PrintAndLog("unknown modulation entered - see help ('h') for parameter structure");
1055 }
1056 return ans;
1057 }
1058
1059 void setClockGrid(int clk, int offset) {
1060 if (offset > clk) offset %= clk;
1061 if (offset < 0) offset += clk;
1062
1063 if (offset > GraphTraceLen || offset < 0) return;
1064 if (clk < 8 || clk > GraphTraceLen) {
1065 GridLocked = false;
1066 GridOffset = 0;
1067 PlotGridX = 0;
1068 PlotGridXdefault = 0;
1069 RepaintGraphWindow();
1070 } else {
1071 GridLocked = true;
1072 GridOffset = offset;
1073 PlotGridX = clk;
1074 PlotGridXdefault = clk;
1075 RepaintGraphWindow();
1076 }
1077 }
1078
1079 int CmdGrid(const char *Cmd)
1080 {
1081 sscanf(Cmd, "%i %i", &PlotGridX, &PlotGridY);
1082 PlotGridXdefault= PlotGridX;
1083 PlotGridYdefault= PlotGridY;
1084 RepaintGraphWindow();
1085 return 0;
1086 }
1087
1088 int CmdSetGraphMarkers(const char *Cmd) {
1089 sscanf(Cmd, "%i %i", &CursorCPos, &CursorDPos);
1090 RepaintGraphWindow();
1091 return 0;
1092 }
1093
1094 int CmdHexsamples(const char *Cmd)
1095 {
1096 int i, j;
1097 int requested = 0;
1098 int offset = 0;
1099 char string_buf[25];
1100 char* string_ptr = string_buf;
1101 uint8_t got[BIGBUF_SIZE];
1102
1103 sscanf(Cmd, "%i %i", &requested, &offset);
1104
1105 /* if no args send something */
1106 if (requested == 0) {
1107 requested = 8;
1108 }
1109 if (offset + requested > sizeof(got)) {
1110 PrintAndLog("Tried to read past end of buffer, <bytes> + <offset> > %d", BIGBUF_SIZE);
1111 return 0;
1112 }
1113
1114 GetFromBigBuf(got,requested,offset);
1115 WaitForResponse(CMD_ACK,NULL);
1116
1117 i = 0;
1118 for (j = 0; j < requested; j++) {
1119 i++;
1120 string_ptr += sprintf(string_ptr, "%02x ", got[j]);
1121 if (i == 8) {
1122 *(string_ptr - 1) = '\0'; // remove the trailing space
1123 PrintAndLog("%s", string_buf);
1124 string_buf[0] = '\0';
1125 string_ptr = string_buf;
1126 i = 0;
1127 }
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';
1132 }
1133 }
1134 return 0;
1135 }
1136
1137 int CmdHide(const char *Cmd)
1138 {
1139 HideGraphWindow();
1140 return 0;
1141 }
1142
1143 //zero mean GraphBuffer
1144 int CmdHpf(const char *Cmd)
1145 {
1146 int i;
1147 int accum = 0;
1148
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;
1154
1155 RepaintGraphWindow();
1156 return 0;
1157 }
1158
1159 uint8_t getByte(uint8_t bits_per_sample, BitstreamIn* b)
1160 {
1161 int i;
1162 uint8_t val = 0;
1163 for(i =0 ; i < bits_per_sample; i++)
1164 {
1165 val |= (headBit(b) << (7-i));
1166 }
1167 return val;
1168 }
1169
1170 int getSamples(int n, bool silent)
1171 {
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
1176
1177 uint8_t got[BIGBUF_SIZE-1] = { 0 };
1178
1179 if (n == 0 || n > sizeof(got))
1180 n = sizeof(got);
1181
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;
1188
1189 //Old devices without this feature would send 0 at arg[0]
1190 if(response.arg[0] > 0)
1191 {
1192 sample_config *sc = (sample_config *) response.d.asBytes;
1193 if (!silent) PrintAndLog("Samples @ %d bits/smpl, decimation 1:%d ", sc->bits_per_sample
1194 , sc->decimation);
1195 bits_per_sample = sc->bits_per_sample;
1196 }
1197 if(bits_per_sample < 8)
1198 {
1199 if (!silent) PrintAndLog("Unpacking...");
1200 BitstreamIn bout = { got, bits_per_sample * n, 0};
1201 int j =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;
1205 }
1206 GraphTraceLen = j;
1207 PrintAndLog("Unpacked %d samples" , j );
1208 }else
1209 {
1210 for (int j = 0; j < n; j++) {
1211 GraphBuffer[j] = ((int)got[j]) - 128;
1212 }
1213 GraphTraceLen = n;
1214 }
1215
1216 RepaintGraphWindow();
1217 return 0;
1218 }
1219
1220 int CmdSamples(const char *Cmd)
1221 {
1222 int n = strtol(Cmd, NULL, 0);
1223 return getSamples(n, false);
1224 }
1225
1226 int CmdTuneSamples(const char *Cmd)
1227 {
1228 int timeout = 0, arg = FLAG_TUNE_ALL;
1229
1230 if(*Cmd == 'l') {
1231 arg = FLAG_TUNE_LF;
1232 } else if (*Cmd == 'h') {
1233 arg = FLAG_TUNE_HF;
1234 } else if (*Cmd != '\0') {
1235 PrintAndLog("use 'tune' or 'tune l' or 'tune h'");
1236 return 0;
1237 }
1238
1239 printf("\nMeasuring antenna characteristics, please wait...");
1240
1241 UsbCommand c = {CMD_MEASURE_ANTENNA_TUNING, {arg, 0, 0}};
1242 SendCommand(&c);
1243
1244 UsbCommand resp;
1245 while(!WaitForResponseTimeout(CMD_MEASURED_ANTENNA_TUNING,&resp,1000)) {
1246 timeout++;
1247 printf(".");
1248 if (timeout > 7) {
1249 PrintAndLog("\nNo response from Proxmark. Aborting...");
1250 return 1;
1251 }
1252 }
1253
1254 int peakv, peakf;
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;
1261 PrintAndLog("");
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);
1266
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.
1271
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.");
1280
1281 if (peakv >= LF_UNUSABLE_V) {
1282 for (int i = 0; i < 256; i++) {
1283 GraphBuffer[i] = resp.d.asBytes[i] - 128;
1284 }
1285 PrintAndLog("Displaying LF tuning graph. Divisor 89 is 134khz, 95 is 125khz.\n");
1286 PrintAndLog("\n");
1287 GraphTraceLen = 256;
1288 ShowGraphWindow();
1289 RepaintGraphWindow();
1290 }
1291
1292 return 0;
1293 }
1294
1295
1296 int CmdLoad(const char *Cmd)
1297 {
1298 char filename[FILE_PATH_SIZE] = {0x00};
1299 int len = 0;
1300
1301 len = strlen(Cmd);
1302 if (len > FILE_PATH_SIZE) len = FILE_PATH_SIZE;
1303 memcpy(filename, Cmd, len);
1304
1305 FILE *f = fopen(filename, "r");
1306 if (!f) {
1307 PrintAndLog("couldn't open '%s'", filename);
1308 return 0;
1309 }
1310
1311 GraphTraceLen = 0;
1312 char line[80];
1313 while (fgets(line, sizeof (line), f)) {
1314 GraphBuffer[GraphTraceLen] = atoi(line);
1315 GraphTraceLen++;
1316 }
1317 fclose(f);
1318 PrintAndLog("loaded %d samples", GraphTraceLen);
1319 RepaintGraphWindow();
1320 return 0;
1321 }
1322
1323 int CmdLtrim(const char *Cmd)
1324 {
1325 int ds = atoi(Cmd);
1326 if (GraphTraceLen<=0) return 0;
1327 for (int i = ds; i < GraphTraceLen; ++i)
1328 GraphBuffer[i-ds] = GraphBuffer[i];
1329 GraphTraceLen -= ds;
1330
1331 RepaintGraphWindow();
1332 return 0;
1333 }
1334
1335 // trim graph to input argument length
1336 int CmdRtrim(const char *Cmd)
1337 {
1338 int ds = atoi(Cmd);
1339
1340 GraphTraceLen = ds;
1341
1342 RepaintGraphWindow();
1343 return 0;
1344 }
1345
1346 // trim graph (middle) piece
1347 int CmdMtrim(const char *Cmd) {
1348 int start = 0, stop = 0;
1349 sscanf(Cmd, "%i %i", &start, &stop);
1350
1351 if (start > GraphTraceLen || stop > GraphTraceLen || start > stop) return 0;
1352 start++; //leave start position sample
1353
1354 GraphTraceLen = stop - start;
1355 for (int i = 0; i < GraphTraceLen; i++) {
1356 GraphBuffer[i] = GraphBuffer[start+i];
1357 }
1358 return 0;
1359 }
1360
1361
1362 int CmdNorm(const char *Cmd)
1363 {
1364 int i;
1365 int max = INT_MIN, min = INT_MAX;
1366
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];
1372 }
1373
1374 if (max != min) {
1375 for (i = 0; i < GraphTraceLen; ++i) {
1376 GraphBuffer[i] = (GraphBuffer[i] - ((max + min) / 2)) * 256 /
1377 (max - min);
1378 //marshmelow: adjusted *1000 to *256 to make +/- 128 so demod commands still work
1379 }
1380 }
1381 RepaintGraphWindow();
1382 return 0;
1383 }
1384
1385 int CmdPlot(const char *Cmd)
1386 {
1387 ShowGraphWindow();
1388 return 0;
1389 }
1390
1391 int CmdSave(const char *Cmd)
1392 {
1393 char filename[FILE_PATH_SIZE] = {0x00};
1394 int len = 0;
1395
1396 len = strlen(Cmd);
1397 if (len > FILE_PATH_SIZE) len = FILE_PATH_SIZE;
1398 memcpy(filename, Cmd, len);
1399
1400
1401 FILE *f = fopen(filename, "w");
1402 if(!f) {
1403 PrintAndLog("couldn't open '%s'", filename);
1404 return 0;
1405 }
1406 int i;
1407 for (i = 0; i < GraphTraceLen; i++) {
1408 fprintf(f, "%d\n", GraphBuffer[i]);
1409 }
1410 fclose(f);
1411 PrintAndLog("saved to '%s'", Cmd);
1412 return 0;
1413 }
1414
1415 int CmdScale(const char *Cmd)
1416 {
1417 CursorScaleFactor = atoi(Cmd);
1418 if (CursorScaleFactor == 0) {
1419 PrintAndLog("bad, can't have zero scale");
1420 CursorScaleFactor = 1;
1421 }
1422 RepaintGraphWindow();
1423 return 0;
1424 }
1425
1426 int CmdDirectionalThreshold(const char *Cmd)
1427 {
1428 int8_t upThres = param_get8(Cmd, 0);
1429 int8_t downThres = param_get8(Cmd, 1);
1430
1431 printf("Applying Up Threshold: %d, Down Threshold: %d\n", upThres, downThres);
1432
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.
1435
1436 for (int i = 1; i < GraphTraceLen; ++i) {
1437 // Apply first threshold to samples heading up
1438 if (GraphBuffer[i] >= upThres && GraphBuffer[i] > lastValue)
1439 {
1440 lastValue = GraphBuffer[i]; // Buffer last value as we overwrite it.
1441 GraphBuffer[i] = 127;
1442 }
1443 // Apply second threshold to samples heading down
1444 else if (GraphBuffer[i] <= downThres && GraphBuffer[i] < lastValue)
1445 {
1446 lastValue = GraphBuffer[i]; // Buffer last value as we overwrite it.
1447 GraphBuffer[i] = -127;
1448 }
1449 else
1450 {
1451 lastValue = GraphBuffer[i]; // Buffer last value as we overwrite it.
1452 GraphBuffer[i] = GraphBuffer[i-1];
1453
1454 }
1455 }
1456 GraphBuffer[0] = GraphBuffer[1]; // Aline with first edited sample.
1457 RepaintGraphWindow();
1458 return 0;
1459 }
1460
1461 int CmdZerocrossings(const char *Cmd)
1462 {
1463 // Zero-crossings aren't meaningful unless the signal is zero-mean.
1464 CmdHpf("");
1465
1466 int sign = 1;
1467 int zc = 0;
1468 int lastZc = 0;
1469
1470 for (int i = 0; i < GraphTraceLen; ++i) {
1471 if (GraphBuffer[i] * sign >= 0) {
1472 // No change in sign, reproduce the previous sample count.
1473 zc++;
1474 GraphBuffer[i] = lastZc;
1475 } else {
1476 // Change in sign, reset the sample count.
1477 sign = -sign;
1478 GraphBuffer[i] = lastZc;
1479 if (sign > 0) {
1480 lastZc = zc;
1481 zc = 0;
1482 }
1483 }
1484 }
1485
1486 RepaintGraphWindow();
1487 return 0;
1488 }
1489
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)");
1493 return 0;
1494 }
1495
1496 /**
1497 * @brief Utility for conversion via cmdline.
1498 * @param Cmd
1499 * @return
1500 */
1501 int Cmdbin2hex(const char *Cmd)
1502 {
1503 int bg =0, en =0;
1504 if(param_getptr(Cmd, &bg, &en, 0))
1505 {
1506 return usage_data_bin2hex();
1507 }
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 };
1514
1515 for(; bg <= en ;bg++)
1516 {
1517 char c = Cmd[bg];
1518 if( c == '1') pushBit(&bout, 1);
1519 else if( c == '0') pushBit(&bout, 0);
1520 else PrintAndLog("Ignoring '%c'", c);
1521 }
1522
1523 if(bout.numbits % 8 != 0)
1524 {
1525 printf("[padded with %d zeroes]\n", 8-(bout.numbits % 8));
1526 }
1527
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++)
1532 {
1533 printf("%02X", arr[x]);
1534 }
1535 printf("\n");
1536 free(arr);
1537 return 0;
1538 }
1539
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)");
1543 return 0;
1544
1545 }
1546
1547 int Cmdhex2bin(const char *Cmd)
1548 {
1549 int bg =0, en =0;
1550 if(param_getptr(Cmd, &bg, &en, 0))
1551 {
1552 return usage_data_hex2bin();
1553 }
1554
1555
1556 while(bg <= en )
1557 {
1558 char x = Cmd[bg++];
1559 // capitalize
1560 if (x >= 'a' && x <= 'f')
1561 x -= 32;
1562 // convert to numeric value
1563 if (x >= '0' && x <= '9')
1564 x -= '0';
1565 else if (x >= 'A' && x <= 'F')
1566 x -= 'A' - 10;
1567 else
1568 continue;
1569
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...
1573
1574 for(int i= 0 ; i < 4 ; ++i)
1575 printf("%d",(x >> (3 - i)) & 1);
1576 }
1577 printf("\n");
1578
1579 return 0;
1580 }
1581
1582 static command_t CommandTable[] =
1583 {
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}
1619 };
1620
1621 int CmdData(const char *Cmd)
1622 {
1623 CmdsParse(CommandTable, Cmd);
1624 return 0;
1625 }
1626
1627 int CmdHelp(const char *Cmd)
1628 {
1629 CmdsHelp(CommandTable);
1630 return 0;
1631 }
Impressum, Datenschutz