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