]> git.zerfleddert.de Git - proxmark3-svn/blob - client/command.cpp
0214a0ab94af36d895f3c72f145155ffb7b718ea
[proxmark3-svn] / client / command.cpp
1 //-----------------------------------------------------------------------------
2 // The actual command interpeter for what the user types at the command line.
3 // Jonathan Westhues, Sept 2005
4 // Edits by Gerhard de Koning Gans, Sep 2007 (##)
5 //-----------------------------------------------------------------------------
6 #include <windows.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <stdio.h>
10 #include <limits.h>
11 #include <math.h>
12
13 #include "prox.h"
14 #include "../common/iso14443_crc.c"
15 #include "../common/crc16.c"
16
17 #define arraylen(x) (sizeof(x)/sizeof((x)[0]))
18 #define BIT(x) GraphBuffer[x * clock]
19 #define BITS (GraphTraceLen / clock)
20
21 int go = 0;
22 static int CmdHisamplest(char *str, int nrlow);
23
24 static void GetFromBigBuf(BYTE *dest, int bytes)
25 {
26 int n = bytes/4;
27
28 if(n % 48 != 0) {
29 PrintToScrollback("bad len in GetFromBigBuf");
30 return;
31 }
32
33 int i;
34 for(i = 0; i < n; i += 12) {
35 UsbCommand c;
36 c.cmd = CMD_DOWNLOAD_RAW_ADC_SAMPLES_125K;
37 c.ext1 = i;
38 SendCommand(&c, FALSE);
39 ReceiveCommand(&c);
40 if(c.cmd != CMD_DOWNLOADED_RAW_ADC_SAMPLES_125K) {
41 PrintToScrollback("bad resp");
42 return;
43 }
44
45 memcpy(dest+(i*4), c.d.asBytes, 48);
46 }
47 }
48
49 static void CmdReset(char *str)
50 {
51 UsbCommand c;
52 c.cmd = CMD_HARDWARE_RESET;
53 SendCommand(&c, FALSE);
54 }
55
56 static void CmdBuffClear(char *str)
57 {
58 UsbCommand c;
59 c.cmd = CMD_BUFF_CLEAR;
60 SendCommand(&c, FALSE);
61 CmdClearGraph(TRUE);
62 }
63
64 static void CmdQuit(char *str)
65 {
66 exit(0);
67 }
68
69 static void CmdHIDdemodFSK(char *str)
70 {
71 UsbCommand c;
72 c.cmd = CMD_HID_DEMOD_FSK;
73 SendCommand(&c, FALSE);
74 }
75
76 static void CmdTune(char *str)
77 {
78 UsbCommand c;
79 c.cmd = CMD_MEASURE_ANTENNA_TUNING;
80 SendCommand(&c, FALSE);
81 }
82
83 static void CmdHi15read(char *str)
84 {
85 UsbCommand c;
86 c.cmd = CMD_ACQUIRE_RAW_ADC_SAMPLES_ISO_15693;
87 SendCommand(&c, FALSE);
88 }
89
90 static void CmdHi14read(char *str)
91 {
92 UsbCommand c;
93 c.cmd = CMD_ACQUIRE_RAW_ADC_SAMPLES_ISO_14443;
94 c.ext1 = atoi(str);
95 SendCommand(&c, FALSE);
96 }
97
98
99 /* New command to read the contents of a SRI512 tag
100 * SRI512 tags are ISO14443-B modulated memory tags,
101 * this command just dumps the contents of the memory/
102 */
103 static void CmdSri512read(char *str)
104 {
105 UsbCommand c;
106 c.cmd = CMD_READ_SRI512_TAG;
107 c.ext1 = atoi(str);
108 SendCommand(&c, FALSE);
109 }
110
111 /* New command to read the contents of a SRIX4K tag
112 * SRIX4K tags are ISO14443-B modulated memory tags,
113 * this command just dumps the contents of the memory/
114 */
115 static void CmdSrix4kread(char *str)
116 {
117 UsbCommand c;
118 c.cmd = CMD_READ_SRIX4K_TAG;
119 c.ext1 = atoi(str);
120 SendCommand(&c, FALSE);
121 }
122
123
124
125 // ## New command
126 static void CmdHi14areader(char *str)
127 {
128 UsbCommand c;
129 c.cmd = CMD_READER_ISO_14443a;
130 c.ext1 = atoi(str);
131 SendCommand(&c, FALSE);
132 }
133
134 // ## New command
135 static void CmdHi15reader(char *str)
136 {
137 UsbCommand c;
138 c.cmd = CMD_READER_ISO_15693;
139 c.ext1 = atoi(str);
140 SendCommand(&c, FALSE);
141 }
142
143 // ## New command
144 static void CmdHi15tag(char *str)
145 {
146 UsbCommand c;
147 c.cmd = CMD_SIMTAG_ISO_15693;
148 c.ext1 = atoi(str);
149 SendCommand(&c, FALSE);
150 }
151
152 static void CmdHi14read_sim(char *str)
153 {
154 UsbCommand c;
155 c.cmd = CMD_ACQUIRE_RAW_ADC_SAMPLES_ISO_14443_SIM;
156 c.ext1 = atoi(str);
157 SendCommand(&c, FALSE);
158 }
159
160 static void CmdHi14readt(char *str)
161 {
162 UsbCommand c;
163 c.cmd = CMD_ACQUIRE_RAW_ADC_SAMPLES_ISO_14443;
164 c.ext1 = atoi(str);
165 SendCommand(&c, FALSE);
166
167 //CmdHisamplest(str);
168 while(CmdHisamplest(str,atoi(str))==0) {
169 c.cmd = CMD_ACQUIRE_RAW_ADC_SAMPLES_ISO_14443;
170 c.ext1 = atoi(str);
171 SendCommand(&c, FALSE);
172 }
173 RepaintGraphWindow();
174 }
175
176 static void CmdHisimlisten(char *str)
177 {
178 UsbCommand c;
179 c.cmd = CMD_SIMULATE_TAG_HF_LISTEN;
180 SendCommand(&c, FALSE);
181 }
182
183 static void CmdHi14sim(char *str)
184 {
185 UsbCommand c;
186 c.cmd = CMD_SIMULATE_TAG_ISO_14443;
187 SendCommand(&c, FALSE);
188 }
189
190 static void CmdHi14asim(char *str) // ## simulate iso14443a tag
191 { // ## greg - added ability to specify tag UID
192
193 unsigned int hi=0, lo=0;
194 int n=0, i=0;
195 UsbCommand c;
196
197 while (sscanf(&str[i++], "%1x", &n ) == 1) {
198 hi=(hi<<4)|(lo>>28);
199 lo=(lo<<4)|(n&0xf);
200 }
201
202 c.cmd = CMD_SIMULATE_TAG_ISO_14443a;
203 // c.ext should be set to *str or convert *str to the correct format for a uid
204 c.ext1 = hi;
205 c.ext2 = lo;
206 PrintToScrollback("Emulating 14443A TAG with UID %x%16x", hi, lo);
207 SendCommand(&c, FALSE);
208 }
209
210 static void CmdHi14snoop(char *str)
211 {
212 UsbCommand c;
213 c.cmd = CMD_SNOOP_ISO_14443;
214 SendCommand(&c, FALSE);
215 }
216
217 static void CmdHi14asnoop(char *str)
218 {
219 UsbCommand c;
220 c.cmd = CMD_SNOOP_ISO_14443a;
221 SendCommand(&c, FALSE);
222 }
223
224 static void CmdLegicRfSim(char *str)
225 {
226 UsbCommand c;
227 c.cmd = CMD_SIMULATE_TAG_LEGIC_RF;
228 SendCommand(&c, FALSE);
229 }
230
231 static void CmdLegicRfRead(char *str)
232 {
233 UsbCommand c;
234 c.cmd = CMD_READER_LEGIC_RF;
235 SendCommand(&c, FALSE);
236 }
237
238 static void CmdFPGAOff(char *str) // ## FPGA Control
239 {
240 UsbCommand c;
241 c.cmd = CMD_FPGA_MAJOR_MODE_OFF;
242 SendCommand(&c, FALSE);
243 }
244
245 /* clear out our graph window */
246 int CmdClearGraph(int redraw)
247 {
248 int gtl = GraphTraceLen;
249 GraphTraceLen = 0;
250
251 if (redraw)
252 RepaintGraphWindow();
253
254 return gtl;
255 }
256
257 /* write a bit to the graph */
258 static void CmdAppendGraph(int redraw, int clock, int bit)
259 {
260 int i;
261
262 for (i = 0; i < (int)(clock/2); i++)
263 GraphBuffer[GraphTraceLen++] = bit ^ 1;
264
265 for (i = (int)(clock/2); i < clock; i++)
266 GraphBuffer[GraphTraceLen++] = bit;
267
268 if (redraw)
269 RepaintGraphWindow();
270 }
271
272 /* Function is equivalent of loread + losamples + em410xread
273 * looped until an EM410x tag is detected */
274 static void CmdEM410xwatch(char *str)
275 {
276 char *zero = "";
277 char *twok = "2000";
278 go = 1;
279
280 do
281 {
282 CmdLoread(zero);
283 CmdLosamples(twok);
284 CmdEM410xread(zero);
285 } while (go);
286 }
287
288 /* Read the transmitted data of an EM4x50 tag
289 * Format:
290 *
291 * XXXXXXXX [row parity bit (even)] <- 8 bits plus parity
292 * XXXXXXXX [row parity bit (even)] <- 8 bits plus parity
293 * XXXXXXXX [row parity bit (even)] <- 8 bits plus parity
294 * XXXXXXXX [row parity bit (even)] <- 8 bits plus parity
295 * CCCCCCCC <- column parity bits
296 * 0 <- stop bit
297 * LW <- Listen Window
298 *
299 * This pattern repeats for every block of data being transmitted.
300 * Transmission starts with two Listen Windows (LW - a modulated
301 * pattern of 320 cycles each (32/32/128/64/64)).
302 *
303 * Note that this data may or may not be the UID. It is whatever data
304 * is stored in the blocks defined in the control word First and Last
305 * Word Read values. UID is stored in block 32.
306 */
307 static void CmdEM4x50read(char *str)
308 {
309 int i, j, startblock, clock, skip, block, start, end, low, high;
310 BOOL complete= FALSE;
311 int tmpbuff[MAX_GRAPH_TRACE_LEN / 64];
312 char tmp[6];
313
314 high= low= 0;
315 clock= 64;
316
317 /* first get high and low values */
318 for (i = 0; i < GraphTraceLen; i++)
319 {
320 if (GraphBuffer[i] > high)
321 high = GraphBuffer[i];
322 else if (GraphBuffer[i] < low)
323 low = GraphBuffer[i];
324 }
325
326 /* populate a buffer with pulse lengths */
327 i= 0;
328 j= 0;
329 while(i < GraphTraceLen)
330 {
331 // measure from low to low
332 while((GraphBuffer[i] > low) && (i<GraphTraceLen))
333 ++i;
334 start= i;
335 while((GraphBuffer[i] < high) && (i<GraphTraceLen))
336 ++i;
337 while((GraphBuffer[i] > low) && (i<GraphTraceLen))
338 ++i;
339 if (j>(MAX_GRAPH_TRACE_LEN/64)) {
340 break;
341 }
342 tmpbuff[j++]= i - start;
343 }
344
345 /* look for data start - should be 2 pairs of LW (pulses of 192,128) */
346 start= -1;
347 skip= 0;
348 for (i= 0; i < j - 4 ; ++i)
349 {
350 skip += tmpbuff[i];
351 if (tmpbuff[i] >= 190 && tmpbuff[i] <= 194)
352 if (tmpbuff[i+1] >= 126 && tmpbuff[i+1] <= 130)
353 if (tmpbuff[i+2] >= 190 && tmpbuff[i+2] <= 194)
354 if (tmpbuff[i+3] >= 126 && tmpbuff[i+3] <= 130)
355 {
356 start= i + 3;
357 break;
358 }
359 }
360 startblock= i + 3;
361
362 /* skip over the remainder of the LW */
363 skip += tmpbuff[i+1]+tmpbuff[i+2];
364 while(skip < MAX_GRAPH_TRACE_LEN && GraphBuffer[skip] > low)
365 ++skip;
366 skip += 8;
367
368 /* now do it again to find the end */
369 end= start;
370 for (i += 3; i < j - 4 ; ++i)
371 {
372 end += tmpbuff[i];
373 if (tmpbuff[i] >= 190 && tmpbuff[i] <= 194)
374 if (tmpbuff[i+1] >= 126 && tmpbuff[i+1] <= 130)
375 if (tmpbuff[i+2] >= 190 && tmpbuff[i+2] <= 194)
376 if (tmpbuff[i+3] >= 126 && tmpbuff[i+3] <= 130)
377 {
378 complete= TRUE;
379 break;
380 }
381 }
382
383 if (start >= 0)
384 PrintToScrollback("Found data at sample: %i",skip);
385 else
386 {
387 PrintToScrollback("No data found!");
388 PrintToScrollback("Try again with more samples.");
389 return;
390 }
391
392 if (!complete)
393 {
394 PrintToScrollback("*** Warning!");
395 PrintToScrollback("Partial data - no end found!");
396 PrintToScrollback("Try again with more samples.");
397 }
398
399 /* get rid of leading crap */
400 sprintf(tmp,"%i",skip);
401 CmdLtrim(tmp);
402
403 /* now work through remaining buffer printing out data blocks */
404 block= 0;
405 i= startblock;
406 while(block < 6)
407 {
408 PrintToScrollback("Block %i:", block);
409 // mandemod routine needs to be split so we can call it for data
410 // just print for now for debugging
411 Cmdmanchesterdemod("i 64");
412 skip= 0;
413 /* look for LW before start of next block */
414 for ( ; i < j - 4 ; ++i)
415 {
416 skip += tmpbuff[i];
417 if (tmpbuff[i] >= 190 && tmpbuff[i] <= 194)
418 if (tmpbuff[i+1] >= 126 && tmpbuff[i+1] <= 130)
419 break;
420 }
421 while(GraphBuffer[skip] > low)
422 ++skip;
423 skip += 8;
424 sprintf(tmp,"%i",skip);
425 CmdLtrim(tmp);
426 start += skip;
427 block++;
428 }
429 }
430
431
432 /* Read the ID of an EM410x tag.
433 * Format:
434 * 1111 1111 1 <-- standard non-repeatable header
435 * XXXX [row parity bit] <-- 10 rows of 5 bits for our 40 bit tag ID
436 * ....
437 * CCCC <-- each bit here is parity for the 10 bits above in corresponding column
438 * 0 <-- stop bit, end of tag
439 */
440 static void CmdEM410xread(char *str)
441 {
442 int i, j, clock, header, rows, bit, hithigh, hitlow, first, bit2idx, high, low;
443 int parity[4];
444 char id[11];
445 int retested = 0;
446 int BitStream[MAX_GRAPH_TRACE_LEN];
447 high = low = 0;
448
449 /* Detect high and lows and clock */
450 for (i = 0; i < GraphTraceLen; i++)
451 {
452 if (GraphBuffer[i] > high)
453 high = GraphBuffer[i];
454 else if (GraphBuffer[i] < low)
455 low = GraphBuffer[i];
456 }
457
458 /* get clock */
459 clock = GetClock(str, high);
460
461 /* parity for our 4 columns */
462 parity[0] = parity[1] = parity[2] = parity[3] = 0;
463 header = rows = 0;
464
465 /* manchester demodulate */
466 bit = bit2idx = 0;
467 for (i = 0; i < (int)(GraphTraceLen / clock); i++)
468 {
469 hithigh = 0;
470 hitlow = 0;
471 first = 1;
472
473 /* Find out if we hit both high and low peaks */
474 for (j = 0; j < clock; j++)
475 {
476 if (GraphBuffer[(i * clock) + j] == high)
477 hithigh = 1;
478 else if (GraphBuffer[(i * clock) + j] == low)
479 hitlow = 1;
480
481 /* it doesn't count if it's the first part of our read
482 because it's really just trailing from the last sequence */
483 if (first && (hithigh || hitlow))
484 hithigh = hitlow = 0;
485 else
486 first = 0;
487
488 if (hithigh && hitlow)
489 break;
490 }
491
492 /* If we didn't hit both high and low peaks, we had a bit transition */
493 if (!hithigh || !hitlow)
494 bit ^= 1;
495
496 BitStream[bit2idx++] = bit;
497 }
498
499 retest:
500 /* We go till 5 before the graph ends because we'll get that far below */
501 for (i = 1; i < bit2idx - 5; i++)
502 {
503 /* Step 2: We have our header but need our tag ID */
504 if (header == 9 && rows < 10)
505 {
506 /* Confirm parity is correct */
507 if ((BitStream[i] ^ BitStream[i+1] ^ BitStream[i+2] ^ BitStream[i+3]) == BitStream[i+4])
508 {
509 /* Read another byte! */
510 sprintf(id+rows, "%x", (8 * BitStream[i]) + (4 * BitStream[i+1]) + (2 * BitStream[i+2]) + (1 * BitStream[i+3]));
511 rows++;
512
513 /* Keep parity info */
514 parity[0] ^= BitStream[i];
515 parity[1] ^= BitStream[i+1];
516 parity[2] ^= BitStream[i+2];
517 parity[3] ^= BitStream[i+3];
518
519 /* Move 4 bits ahead */
520 i += 4;
521 }
522
523 /* Damn, something wrong! reset */
524 else
525 {
526 PrintToScrollback("Thought we had a valid tag but failed at word %d (i=%d)", rows + 1, i);
527
528 /* Start back rows * 5 + 9 header bits, -1 to not start at same place */
529 i -= 9 + (5 * rows) - 5;
530
531 rows = header = 0;
532 }
533 }
534
535 /* Step 3: Got our 40 bits! confirm column parity */
536 else if (rows == 10)
537 {
538 /* We need to make sure our 4 bits of parity are correct and we have a stop bit */
539 if (BitStream[i] == parity[0] && BitStream[i+1] == parity[1] &&
540 BitStream[i+2] == parity[2] && BitStream[i+3] == parity[3] &&
541 BitStream[i+4] == 0)
542 {
543 /* Sweet! */
544 PrintToScrollback("EM410x Tag ID: %s", id);
545
546 /* Stop any loops */
547 go = 0;
548 return;
549 }
550
551 /* Crap! Incorrect parity or no stop bit, start all over */
552 else
553 {
554 rows = header = 0;
555
556 /* Go back 59 bits (9 header bits + 10 rows at 4+1 parity) */
557 i -= 59;
558 }
559 }
560
561 /* Step 1: get our header */
562 else if (header < 9)
563 {
564 /* Need 9 consecutive 1's */
565 if (BitStream[i] == 1)
566 header++;
567
568 /* We don't have a header, not enough consecutive 1 bits */
569 else
570 header = 0;
571 }
572 }
573
574 /* if we've already retested after flipping bits, return */
575 if (retested++)
576 return;
577
578 /* if this didn't work, try flipping bits */
579 for (i = 0; i < bit2idx; i++)
580 BitStream[i] ^= 1;
581
582 goto retest;
583 }
584
585 /* emulate an EM410X tag
586 * Format:
587 * 1111 1111 1 <-- standard non-repeatable header
588 * XXXX [row parity bit] <-- 10 rows of 5 bits for our 40 bit tag ID
589 * ....
590 * CCCC <-- each bit here is parity for the 10 bits above in corresponding column
591 * 0 <-- stop bit, end of tag
592 */
593 static void CmdEM410xsim(char *str)
594 {
595 int i, n, j, h, binary[4], parity[4];
596 char *s = "0";
597
598 /* clock is 64 in EM410x tags */
599 int clock = 64;
600
601 /* clear our graph */
602 CmdClearGraph(0);
603
604 /* write it out a few times */
605 for (h = 0; h < 4; h++)
606 {
607 /* write 9 start bits */
608 for (i = 0; i < 9; i++)
609 CmdAppendGraph(0, clock, 1);
610
611 /* for each hex char */
612 parity[0] = parity[1] = parity[2] = parity[3] = 0;
613 for (i = 0; i < 10; i++)
614 {
615 /* read each hex char */
616 sscanf(&str[i], "%1x", &n);
617 for (j = 3; j >= 0; j--, n/= 2)
618 binary[j] = n % 2;
619
620 /* append each bit */
621 CmdAppendGraph(0, clock, binary[0]);
622 CmdAppendGraph(0, clock, binary[1]);
623 CmdAppendGraph(0, clock, binary[2]);
624 CmdAppendGraph(0, clock, binary[3]);
625
626 /* append parity bit */
627 CmdAppendGraph(0, clock, binary[0] ^ binary[1] ^ binary[2] ^ binary[3]);
628
629 /* keep track of column parity */
630 parity[0] ^= binary[0];
631 parity[1] ^= binary[1];
632 parity[2] ^= binary[2];
633 parity[3] ^= binary[3];
634 }
635
636 /* parity columns */
637 CmdAppendGraph(0, clock, parity[0]);
638 CmdAppendGraph(0, clock, parity[1]);
639 CmdAppendGraph(0, clock, parity[2]);
640 CmdAppendGraph(0, clock, parity[3]);
641
642 /* stop bit */
643 CmdAppendGraph(0, clock, 0);
644 }
645
646 /* modulate that biatch */
647 Cmdmanchestermod(s);
648
649 /* booyah! */
650 RepaintGraphWindow();
651
652 CmdLosim(s);
653 }
654
655 static void ChkBitstream(char *str)
656 {
657 int i;
658
659 /* convert to bitstream if necessary */
660 for (i = 0; i < (int)(GraphTraceLen / 2); i++)
661 {
662 if (GraphBuffer[i] > 1 || GraphBuffer[i] < 0)
663 {
664 Cmdbitstream(str);
665 break;
666 }
667 }
668 }
669
670 static void CmdLosim(char *str)
671 {
672 int i;
673
674 /* convert to bitstream if necessary */
675 ChkBitstream(str);
676
677 for (i = 0; i < GraphTraceLen; i += 48) {
678 UsbCommand c;
679 int j;
680 for(j = 0; j < 48; j++) {
681 c.d.asBytes[j] = GraphBuffer[i+j];
682 }
683 c.cmd = CMD_DOWNLOADED_SIM_SAMPLES_125K;
684 c.ext1 = i;
685 SendCommand(&c, FALSE);
686 }
687
688 UsbCommand c;
689 c.cmd = CMD_SIMULATE_TAG_125K;
690 c.ext1 = GraphTraceLen;
691 SendCommand(&c, FALSE);
692 }
693
694 static void CmdLosimBidir(char *str)
695 {
696 UsbCommand c;
697 c.cmd = CMD_LF_SIMULATE_BIDIR;
698 c.ext1 = 47; /* Set ADC to twice the carrier for a slight supersampling */
699 c.ext2 = 384;
700 SendCommand(&c, FALSE);
701 }
702
703 static void CmdLoread(char *str)
704 {
705 UsbCommand c;
706 // 'h' means higher-low-frequency, 134 kHz
707 if(*str == 'h') {
708 c.ext1 = 1;
709 } else if (*str == '\0') {
710 c.ext1 = 0;
711 } else {
712 PrintToScrollback("use 'loread' or 'loread h'");
713 return;
714 }
715 c.cmd = CMD_ACQUIRE_RAW_ADC_SAMPLES_125K;
716 SendCommand(&c, FALSE);
717 }
718
719 static void CmdDetectReader(char *str)
720 {
721 UsbCommand c;
722 // 'l' means LF - 125/134 kHz
723 if(*str == 'l') {
724 c.ext1 = 1;
725 } else if (*str == 'h') {
726 c.ext1 = 2;
727 } else if (*str != '\0') {
728 PrintToScrollback("use 'detectreader' or 'detectreader l' or 'detectreader h'");
729 return;
730 }
731 c.cmd = CMD_LISTEN_READER_FIELD;
732 SendCommand(&c, FALSE);
733 }
734
735 /* send a command before reading */
736 static void CmdLoCommandRead(char *str)
737 {
738 static char dummy[3];
739
740 dummy[0]= ' ';
741
742 UsbCommand c;
743 c.cmd = CMD_MOD_THEN_ACQUIRE_RAW_ADC_SAMPLES_125K;
744 sscanf(str, "%i %i %i %s %s", &c.ext1, &c.ext2, &c.ext3, (char *) &c.d.asBytes,(char *) &dummy+1);
745 // in case they specified 'h'
746 strcpy((char *)&c.d.asBytes + strlen((char *)c.d.asBytes), dummy);
747 SendCommand(&c, FALSE);
748 }
749
750 static void CmdLosamples(char *str)
751 {
752 int cnt = 0;
753 int i;
754 int n;
755
756 n=atoi(str);
757 if (n==0) n=128;
758 if (n>16000) n=16000;
759
760 for(i = 0; i < n; i += 12) {
761 UsbCommand c;
762 c.cmd = CMD_DOWNLOAD_RAW_ADC_SAMPLES_125K;
763 c.ext1 = i;
764 SendCommand(&c, FALSE);
765 ReceiveCommand(&c);
766 if(c.cmd != CMD_DOWNLOADED_RAW_ADC_SAMPLES_125K) {
767 if (!go)
768 PrintToScrollback("bad resp");
769 return;
770 }
771 int j;
772 for(j = 0; j < 48; j++) {
773 GraphBuffer[cnt++] = ((int)c.d.asBytes[j]) - 128;
774 }
775 }
776 GraphTraceLen = n*4;
777 RepaintGraphWindow();
778 }
779
780 static void CmdBitsamples(char *str)
781 {
782 int cnt = 0;
783 int i;
784 int n;
785
786 n = 3072;
787 for(i = 0; i < n; i += 12) {
788 UsbCommand c;
789 c.cmd = CMD_DOWNLOAD_RAW_ADC_SAMPLES_125K;
790 c.ext1 = i;
791 SendCommand(&c, FALSE);
792 ReceiveCommand(&c);
793 if(c.cmd != CMD_DOWNLOADED_RAW_ADC_SAMPLES_125K) {
794 PrintToScrollback("bad resp");
795 return;
796 }
797 int j, k;
798 for(j = 0; j < 48; j++) {
799 for(k = 0; k < 8; k++) {
800 if(c.d.asBytes[j] & (1 << (7 - k))) {
801 GraphBuffer[cnt++] = 1;
802 } else {
803 GraphBuffer[cnt++] = 0;
804 }
805 }
806 }
807 }
808 GraphTraceLen = cnt;
809 RepaintGraphWindow();
810 }
811
812 static void CmdHisamples(char *str)
813 {
814 int cnt = 0;
815 int i;
816 int n;
817 n = 1000;
818 for(i = 0; i < n; i += 12) {
819 UsbCommand c;
820 c.cmd = CMD_DOWNLOAD_RAW_ADC_SAMPLES_125K;
821 c.ext1 = i;
822 SendCommand(&c, FALSE);
823 ReceiveCommand(&c);
824 if(c.cmd != CMD_DOWNLOADED_RAW_ADC_SAMPLES_125K) {
825 PrintToScrollback("bad resp");
826 return;
827 }
828 int j;
829 for(j = 0; j < 48; j++) {
830 GraphBuffer[cnt++] = (int)((BYTE)c.d.asBytes[j]);
831 }
832 }
833 GraphTraceLen = n*4;
834
835 RepaintGraphWindow();
836 }
837
838 static int CmdHisamplest(char *str, int nrlow)
839 {
840 int cnt = 0;
841 int t1, t2;
842 int i;
843 int n;
844 int hasbeennull;
845 int show;
846
847
848 n = 1000;
849 hasbeennull = 0;
850 for(i = 0; i < n; i += 12) {
851 UsbCommand c;
852 c.cmd = CMD_DOWNLOAD_RAW_ADC_SAMPLES_125K;
853 c.ext1 = i;
854 SendCommand(&c, FALSE);
855 ReceiveCommand(&c);
856 if(c.cmd != CMD_DOWNLOADED_RAW_ADC_SAMPLES_125K) {
857 PrintToScrollback("bad resp");
858 return 0;
859 }
860 int j;
861 for(j = 0; j < 48; j++) {
862 t2 = (int)((BYTE)c.d.asBytes[j]);
863 if((t2 ^ 0xC0) & 0xC0) { hasbeennull++; }
864
865 show = 0;
866 switch(show) {
867 case 0:
868 // combined
869 t1 = (t2 & 0x80) ^ (t2 & 0x20);
870 t2 = ((t2 << 1) & 0x80) ^ ((t2 << 1) & 0x20);
871 break;
872
873 case 1:
874 // only reader
875 t1 = (t2 & 0x80);
876 t2 = ((t2 << 1) & 0x80);
877 break;
878
879 case 2:
880 // only tag
881 t1 = (t2 & 0x20);
882 t2 = ((t2 << 1) & 0x20);
883 break;
884
885 case 3:
886 // both, but tag with other algorithm
887 t1 = (t2 & 0x80) ^ (t2 & 0x08);
888 t2 = ((t2 << 1) & 0x80) ^ ((t2 << 1) & 0x08);
889 break;
890 }
891
892 GraphBuffer[cnt++] = t1;
893 GraphBuffer[cnt++] = t2;
894 }
895 }
896 GraphTraceLen = n*4;
897 // 1130
898 if(hasbeennull>nrlow || nrlow==0) {
899 PrintToScrollback("hasbeennull=%d", hasbeennull);
900 return 1;
901 }
902 else {
903 return 0;
904 }
905 }
906
907
908 static void CmdHexsamples(char *str)
909 {
910 int i;
911 int n;
912 int requested = atoi(str);
913 int delivered = 0;
914
915 if(atoi(str) == 0) {
916 n = 12;
917 requested = 12;
918 } else {
919 n = atoi(str)/4;
920 }
921
922 for(i = 0; i < n; i += 12) {
923 UsbCommand c;
924 c.cmd = CMD_DOWNLOAD_RAW_ADC_SAMPLES_125K;
925 c.ext1 = i;
926 SendCommand(&c, FALSE);
927 ReceiveCommand(&c);
928 if(c.cmd != CMD_DOWNLOADED_RAW_ADC_SAMPLES_125K) {
929 PrintToScrollback("bad resp");
930 return;
931 }
932 int j;
933 for(j = 0; j < 48; j += 8) {
934 PrintToScrollback("%02x %02x %02x %02x %02x %02x %02x %02x",
935 c.d.asBytes[j+0],
936 c.d.asBytes[j+1],
937 c.d.asBytes[j+2],
938 c.d.asBytes[j+3],
939 c.d.asBytes[j+4],
940 c.d.asBytes[j+5],
941 c.d.asBytes[j+6],
942 c.d.asBytes[j+7],
943 c.d.asBytes[j+8]
944 );
945 delivered += 8;
946 if(delivered >= requested)
947 break;
948 }
949 if(delivered >= requested)
950 break;
951 }
952 }
953
954 static void CmdHisampless(char *str)
955 {
956 int cnt = 0;
957 int i;
958 int n;
959
960 if(atoi(str) == 0) {
961 n = 1000;
962 } else {
963 n = atoi(str)/4;
964 }
965
966 for(i = 0; i < n; i += 12) {
967 UsbCommand c;
968 c.cmd = CMD_DOWNLOAD_RAW_ADC_SAMPLES_125K;
969 c.ext1 = i;
970 SendCommand(&c, FALSE);
971 ReceiveCommand(&c);
972 if(c.cmd != CMD_DOWNLOADED_RAW_ADC_SAMPLES_125K) {
973 PrintToScrollback("bad resp");
974 return;
975 }
976 int j;
977 for(j = 0; j < 48; j++) {
978 GraphBuffer[cnt++] = (int)((signed char)c.d.asBytes[j]);
979 }
980 }
981 GraphTraceLen = cnt;
982
983 RepaintGraphWindow();
984 }
985
986 static WORD Iso15693Crc(BYTE *v, int n)
987 {
988 DWORD reg;
989 int i, j;
990
991 reg = 0xffff;
992 for(i = 0; i < n; i++) {
993 reg = reg ^ ((DWORD)v[i]);
994 for (j = 0; j < 8; j++) {
995 if (reg & 0x0001) {
996 reg = (reg >> 1) ^ 0x8408;
997 } else {
998 reg = (reg >> 1);
999 }
1000 }
1001 }
1002
1003 return (WORD)~reg;
1004 }
1005
1006 static void CmdHi14bdemod(char *str)
1007 {
1008 int i, j, iold;
1009 int isum, qsum;
1010 int outOfWeakAt;
1011 BOOL negateI, negateQ;
1012
1013 BYTE data[256];
1014 int dataLen=0;
1015
1016 // As received, the samples are pairs, correlations against I and Q
1017 // square waves. So estimate angle of initial carrier (or just
1018 // quadrant, actually), and then do the demod.
1019
1020 // First, estimate where the tag starts modulating.
1021 for(i = 0; i < GraphTraceLen; i += 2) {
1022 if(abs(GraphBuffer[i]) + abs(GraphBuffer[i+1]) > 40) {
1023 break;
1024 }
1025 }
1026 if(i >= GraphTraceLen) {
1027 PrintToScrollback("too weak to sync");
1028 return;
1029 }
1030 PrintToScrollback("out of weak at %d", i);
1031 outOfWeakAt = i;
1032
1033 // Now, estimate the phase in the initial modulation of the tag
1034 isum = 0;
1035 qsum = 0;
1036 for(; i < (outOfWeakAt + 16); i += 2) {
1037 isum += GraphBuffer[i+0];
1038 qsum += GraphBuffer[i+1];
1039 }
1040 negateI = (isum < 0);
1041 negateQ = (qsum < 0);
1042
1043 // Turn the correlation pairs into soft decisions on the bit.
1044 j = 0;
1045 for(i = 0; i < GraphTraceLen/2; i++) {
1046 int si = GraphBuffer[j];
1047 int sq = GraphBuffer[j+1];
1048 if(negateI) si = -si;
1049 if(negateQ) sq = -sq;
1050 GraphBuffer[i] = si + sq;
1051 j += 2;
1052 }
1053 GraphTraceLen = i;
1054
1055 i = outOfWeakAt/2;
1056 while(GraphBuffer[i] > 0 && i < GraphTraceLen)
1057 i++;
1058 if(i >= GraphTraceLen) goto demodError;
1059
1060 iold = i;
1061 while(GraphBuffer[i] < 0 && i < GraphTraceLen)
1062 i++;
1063 if(i >= GraphTraceLen) goto demodError;
1064 if((i - iold) > 23) goto demodError;
1065
1066 PrintToScrollback("make it to demod loop");
1067
1068 for(;;) {
1069 iold = i;
1070 while(GraphBuffer[i] >= 0 && i < GraphTraceLen)
1071 i++;
1072 if(i >= GraphTraceLen) goto demodError;
1073 if((i - iold) > 6) goto demodError;
1074
1075 WORD shiftReg = 0;
1076 if(i + 20 >= GraphTraceLen) goto demodError;
1077
1078 for(j = 0; j < 10; j++) {
1079 int soft = GraphBuffer[i] + GraphBuffer[i+1];
1080
1081 if(abs(soft) < ((abs(isum) + abs(qsum))/20)) {
1082 PrintToScrollback("weak bit");
1083 }
1084
1085 shiftReg >>= 1;
1086 if(GraphBuffer[i] + GraphBuffer[i+1] >= 0) {
1087 shiftReg |= 0x200;
1088 }
1089
1090 i+= 2;
1091 }
1092
1093 if( (shiftReg & 0x200) &&
1094 !(shiftReg & 0x001))
1095 {
1096 // valid data byte, start and stop bits okay
1097 PrintToScrollback(" %02x", (shiftReg >> 1) & 0xff);
1098 data[dataLen++] = (shiftReg >> 1) & 0xff;
1099 if(dataLen >= sizeof(data)) {
1100 return;
1101 }
1102 } else if(shiftReg == 0x000) {
1103 // this is EOF
1104 break;
1105 } else {
1106 goto demodError;
1107 }
1108 }
1109
1110 BYTE first, second;
1111 ComputeCrc14443(CRC_14443_B, data, dataLen-2, &first, &second);
1112 PrintToScrollback("CRC: %02x %02x (%s)\n", first, second,
1113 (first == data[dataLen-2] && second == data[dataLen-1]) ?
1114 "ok" : "****FAIL****");
1115
1116 RepaintGraphWindow();
1117 return;
1118
1119 demodError:
1120 PrintToScrollback("demod error");
1121 RepaintGraphWindow();
1122 }
1123
1124 static void CmdHi14list(char *str)
1125 {
1126 BYTE got[960];
1127 GetFromBigBuf(got, sizeof(got));
1128
1129 PrintToScrollback("recorded activity:");
1130 PrintToScrollback(" time :rssi: who bytes");
1131 PrintToScrollback("---------+----+----+-----------");
1132
1133 int i = 0;
1134 int prev = -1;
1135
1136 for(;;) {
1137 if(i >= 900) {
1138 break;
1139 }
1140
1141 BOOL isResponse;
1142 int timestamp = *((DWORD *)(got+i));
1143 if(timestamp & 0x80000000) {
1144 timestamp &= 0x7fffffff;
1145 isResponse = 1;
1146 } else {
1147 isResponse = 0;
1148 }
1149 int metric = *((DWORD *)(got+i+4));
1150
1151 int len = got[i+8];
1152
1153 if(len > 100) {
1154 break;
1155 }
1156 if(i + len >= 900) {
1157 break;
1158 }
1159
1160 BYTE *frame = (got+i+9);
1161
1162 char line[1000] = "";
1163 int j;
1164 for(j = 0; j < len; j++) {
1165 sprintf(line+(j*3), "%02x ", frame[j]);
1166 }
1167
1168 char *crc;
1169 if(len > 2) {
1170 BYTE b1, b2;
1171 ComputeCrc14443(CRC_14443_B, frame, len-2, &b1, &b2);
1172 if(b1 != frame[len-2] || b2 != frame[len-1]) {
1173 crc = "**FAIL CRC**";
1174 } else {
1175 crc = "";
1176 }
1177 } else {
1178 crc = "(SHORT)";
1179 }
1180
1181 char metricString[100];
1182 if(isResponse) {
1183 sprintf(metricString, "%3d", metric);
1184 } else {
1185 strcpy(metricString, " ");
1186 }
1187
1188 PrintToScrollback(" +%7d: %s: %s %s %s",
1189 (prev < 0 ? 0 : timestamp - prev),
1190 metricString,
1191 (isResponse ? "TAG" : " "), line, crc);
1192
1193 prev = timestamp;
1194 i += (len + 9);
1195 }
1196 }
1197
1198 static void CmdHi14alist(char *str)
1199 {
1200 BYTE got[1920];
1201 GetFromBigBuf(got, sizeof(got));
1202
1203 PrintToScrollback("recorded activity:");
1204 PrintToScrollback(" ETU :rssi: who bytes");
1205 PrintToScrollback("---------+----+----+-----------");
1206
1207 int i = 0;
1208 int prev = -1;
1209
1210 for(;;) {
1211 if(i >= 1900) {
1212 break;
1213 }
1214
1215 BOOL isResponse;
1216 int timestamp = *((DWORD *)(got+i));
1217 if(timestamp & 0x80000000) {
1218 timestamp &= 0x7fffffff;
1219 isResponse = 1;
1220 } else {
1221 isResponse = 0;
1222 }
1223
1224 int metric = 0;
1225 int parityBits = *((DWORD *)(got+i+4));
1226 // 4 bytes of additional information...
1227 // maximum of 32 additional parity bit information
1228 //
1229 // TODO:
1230 // at each quarter bit period we can send power level (16 levels)
1231 // or each half bit period in 256 levels.
1232
1233
1234 int len = got[i+8];
1235
1236 if(len > 100) {
1237 break;
1238 }
1239 if(i + len >= 1900) {
1240 break;
1241 }
1242
1243 BYTE *frame = (got+i+9);
1244
1245 // Break and stick with current result if buffer was not completely full
1246 if(frame[0] == 0x44 && frame[1] == 0x44 && frame[3] == 0x44) { break; }
1247
1248 char line[1000] = "";
1249 int j;
1250 for(j = 0; j < len; j++) {
1251 int oddparity = 0x01;
1252 int k;
1253
1254 for(k=0;k<8;k++) {
1255 oddparity ^= (((frame[j] & 0xFF) >> k) & 0x01);
1256 }
1257
1258 //if((parityBits >> (len - j - 1)) & 0x01) {
1259 if(isResponse && (oddparity != ((parityBits >> (len - j - 1)) & 0x01))) {
1260 sprintf(line+(j*4), "%02x! ", frame[j]);
1261 }
1262 else {
1263 sprintf(line+(j*4), "%02x ", frame[j]);
1264 }
1265 }
1266
1267 char *crc;
1268 crc = "";
1269 if(len > 2) {
1270 BYTE b1, b2;
1271 for(j = 0; j < (len - 1); j++) {
1272 // gives problems... search for the reason..
1273 /*if(frame[j] == 0xAA) {
1274 switch(frame[j+1]) {
1275 case 0x01:
1276 crc = "[1] Two drops close after each other";
1277 break;
1278 case 0x02:
1279 crc = "[2] Potential SOC with a drop in second half of bitperiod";
1280 break;
1281 case 0x03:
1282 crc = "[3] Segment Z after segment X is not possible";
1283 break;
1284 case 0x04:
1285 crc = "[4] Parity bit of a fully received byte was wrong";
1286 break;
1287 default:
1288 crc = "[?] Unknown error";
1289 break;
1290 }
1291 break;
1292 }*/
1293 }
1294
1295 if(strlen(crc)==0) {
1296 ComputeCrc14443(CRC_14443_A, frame, len-2, &b1, &b2);
1297 if(b1 != frame[len-2] || b2 != frame[len-1]) {
1298 crc = (isResponse & (len < 6)) ? "" : " !crc";
1299 } else {
1300 crc = "";
1301 }
1302 }
1303 } else {
1304 crc = ""; // SHORT
1305 }
1306
1307 char metricString[100];
1308 if(isResponse) {
1309 sprintf(metricString, "%3d", metric);
1310 } else {
1311 strcpy(metricString, " ");
1312 }
1313
1314 PrintToScrollback(" +%7d: %s: %s %s %s",
1315 (prev < 0 ? 0 : (timestamp - prev)),
1316 metricString,
1317 (isResponse ? "TAG" : " "), line, crc);
1318
1319 prev = timestamp;
1320 i += (len + 9);
1321 }
1322 CommandFinished = 1;
1323 }
1324
1325 static void CmdHi15demod(char *str)
1326 {
1327 // The sampling rate is 106.353 ksps/s, for T = 18.8 us
1328
1329 // SOF defined as
1330 // 1) Unmodulated time of 56.64us
1331 // 2) 24 pulses of 423.75khz
1332 // 3) logic '1' (unmodulated for 18.88us followed by 8 pulses of 423.75khz)
1333
1334 static const int FrameSOF[] = {
1335 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
1336 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
1337 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1338 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1339 -1, -1, -1, -1,
1340 -1, -1, -1, -1,
1341 1, 1, 1, 1,
1342 1, 1, 1, 1
1343 };
1344 static const int Logic0[] = {
1345 1, 1, 1, 1,
1346 1, 1, 1, 1,
1347 -1, -1, -1, -1,
1348 -1, -1, -1, -1
1349 };
1350 static const int Logic1[] = {
1351 -1, -1, -1, -1,
1352 -1, -1, -1, -1,
1353 1, 1, 1, 1,
1354 1, 1, 1, 1
1355 };
1356
1357 // EOF defined as
1358 // 1) logic '0' (8 pulses of 423.75khz followed by unmodulated for 18.88us)
1359 // 2) 24 pulses of 423.75khz
1360 // 3) Unmodulated time of 56.64us
1361
1362 static const int FrameEOF[] = {
1363 1, 1, 1, 1,
1364 1, 1, 1, 1,
1365 -1, -1, -1, -1,
1366 -1, -1, -1, -1,
1367 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1368 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1369 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
1370 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
1371 };
1372
1373 int i, j;
1374 int max = 0, maxPos;
1375
1376 int skip = 4;
1377
1378 if(GraphTraceLen < 1000) return;
1379
1380 // First, correlate for SOF
1381 for(i = 0; i < 100; i++) {
1382 int corr = 0;
1383 for(j = 0; j < arraylen(FrameSOF); j += skip) {
1384 corr += FrameSOF[j]*GraphBuffer[i+(j/skip)];
1385 }
1386 if(corr > max) {
1387 max = corr;
1388 maxPos = i;
1389 }
1390 }
1391 PrintToScrollback("SOF at %d, correlation %d", maxPos,
1392 max/(arraylen(FrameSOF)/skip));
1393
1394 i = maxPos + arraylen(FrameSOF)/skip;
1395 int k = 0;
1396 BYTE outBuf[20];
1397 memset(outBuf, 0, sizeof(outBuf));
1398 BYTE mask = 0x01;
1399 for(;;) {
1400 int corr0 = 0, corr1 = 0, corrEOF = 0;
1401 for(j = 0; j < arraylen(Logic0); j += skip) {
1402 corr0 += Logic0[j]*GraphBuffer[i+(j/skip)];
1403 }
1404 for(j = 0; j < arraylen(Logic1); j += skip) {
1405 corr1 += Logic1[j]*GraphBuffer[i+(j/skip)];
1406 }
1407 for(j = 0; j < arraylen(FrameEOF); j += skip) {
1408 corrEOF += FrameEOF[j]*GraphBuffer[i+(j/skip)];
1409 }
1410 // Even things out by the length of the target waveform.
1411 corr0 *= 4;
1412 corr1 *= 4;
1413
1414 if(corrEOF > corr1 && corrEOF > corr0) {
1415 PrintToScrollback("EOF at %d", i);
1416 break;
1417 } else if(corr1 > corr0) {
1418 i += arraylen(Logic1)/skip;
1419 outBuf[k] |= mask;
1420 } else {
1421 i += arraylen(Logic0)/skip;
1422 }
1423 mask <<= 1;
1424 if(mask == 0) {
1425 k++;
1426 mask = 0x01;
1427 }
1428 if((i+(int)arraylen(FrameEOF)) >= GraphTraceLen) {
1429 PrintToScrollback("ran off end!");
1430 break;
1431 }
1432 }
1433 if(mask != 0x01) {
1434 PrintToScrollback("error, uneven octet! (discard extra bits!)");
1435 PrintToScrollback(" mask=%02x", mask);
1436 }
1437 PrintToScrollback("%d octets", k);
1438
1439 for(i = 0; i < k; i++) {
1440 PrintToScrollback("# %2d: %02x ", i, outBuf[i]);
1441 }
1442 PrintToScrollback("CRC=%04x", Iso15693Crc(outBuf, k-2));
1443 }
1444
1445 static void CmdFSKdemod(char *cmdline)
1446 {
1447 static const int LowTone[] = {
1448 1, 1, 1, 1, 1, -1, -1, -1, -1, -1,
1449 1, 1, 1, 1, 1, -1, -1, -1, -1, -1,
1450 1, 1, 1, 1, 1, -1, -1, -1, -1, -1,
1451 1, 1, 1, 1, 1, -1, -1, -1, -1, -1,
1452 1, 1, 1, 1, 1, -1, -1, -1, -1, -1
1453 };
1454 static const int HighTone[] = {
1455 1, 1, 1, 1, 1, -1, -1, -1, -1,
1456 1, 1, 1, 1, -1, -1, -1, -1,
1457 1, 1, 1, 1, -1, -1, -1, -1,
1458 1, 1, 1, 1, -1, -1, -1, -1,
1459 1, 1, 1, 1, -1, -1, -1, -1,
1460 1, 1, 1, 1, -1, -1, -1, -1, -1,
1461 };
1462
1463 int lowLen = sizeof(LowTone)/sizeof(int);
1464 int highLen = sizeof(HighTone)/sizeof(int);
1465 int convLen = (highLen>lowLen)?highLen:lowLen;
1466 DWORD hi = 0, lo = 0;
1467
1468 int i, j;
1469 int minMark=0, maxMark=0;
1470
1471 for(i = 0; i < GraphTraceLen - convLen; i++) {
1472 int lowSum = 0, highSum = 0;
1473
1474 for(j = 0; j < lowLen; j++) {
1475 lowSum += LowTone[j]*GraphBuffer[i+j];
1476 }
1477 for(j = 0; j < highLen; j++) {
1478 highSum += HighTone[j]*GraphBuffer[i+j];
1479 }
1480 lowSum = abs((100*lowSum) / lowLen);
1481 highSum = abs((100*highSum) / highLen);
1482 GraphBuffer[i] = (highSum << 16) | lowSum;
1483 }
1484
1485 for(i = 0; i < GraphTraceLen - convLen - 16; i++) {
1486 int j;
1487 int lowTot = 0, highTot = 0;
1488 // 10 and 8 are f_s divided by f_l and f_h, rounded
1489 for(j = 0; j < 10; j++) {
1490 lowTot += (GraphBuffer[i+j] & 0xffff);
1491 }
1492 for(j = 0; j < 8; j++) {
1493 highTot += (GraphBuffer[i+j] >> 16);
1494 }
1495 GraphBuffer[i] = lowTot - highTot;
1496 if (GraphBuffer[i]>maxMark) maxMark=GraphBuffer[i];
1497 if (GraphBuffer[i]<minMark) minMark=GraphBuffer[i];
1498 }
1499
1500 GraphTraceLen -= (convLen + 16);
1501
1502 RepaintGraphWindow();
1503
1504 // Find bit-sync (3 lo followed by 3 high)
1505 int max = 0, maxPos = 0;
1506 for(i = 0; i < 6000; i++) {
1507 int dec = 0;
1508 for(j = 0; j < 3*lowLen; j++) {
1509 dec -= GraphBuffer[i+j];
1510 }
1511 for(; j < 3*(lowLen + highLen ); j++) {
1512 dec += GraphBuffer[i+j];
1513 }
1514 if(dec > max) {
1515 max = dec;
1516 maxPos = i;
1517 }
1518 }
1519
1520 // place start of bit sync marker in graph
1521 GraphBuffer[maxPos] = maxMark;
1522 GraphBuffer[maxPos+1] = minMark;
1523
1524 maxPos += j;
1525
1526 // place end of bit sync marker in graph
1527 GraphBuffer[maxPos] = maxMark;
1528 GraphBuffer[maxPos+1] = minMark;
1529
1530 PrintToScrollback("actual data bits start at sample %d", maxPos);
1531 PrintToScrollback("length %d/%d", highLen, lowLen);
1532
1533 BYTE bits[46];
1534 bits[sizeof(bits)-1] = '\0';
1535
1536 // find bit pairs and manchester decode them
1537 for(i = 0; i < arraylen(bits)-1; i++) {
1538 int dec = 0;
1539 for(j = 0; j < lowLen; j++) {
1540 dec -= GraphBuffer[maxPos+j];
1541 }
1542 for(; j < lowLen + highLen; j++) {
1543 dec += GraphBuffer[maxPos+j];
1544 }
1545 maxPos += j;
1546 // place inter bit marker in graph
1547 GraphBuffer[maxPos] = maxMark;
1548 GraphBuffer[maxPos+1] = minMark;
1549
1550 // hi and lo form a 64 bit pair
1551 hi = (hi<<1)|(lo>>31);
1552 lo = (lo<<1);
1553 // store decoded bit as binary (in hi/lo) and text (in bits[])
1554 if(dec<0) {
1555 bits[i] = '1';
1556 lo|=1;
1557 } else {
1558 bits[i] = '0';
1559 }
1560 }
1561 PrintToScrollback("bits: '%s'", bits);
1562 PrintToScrollback("hex: %08x %08x", hi, lo);
1563 }
1564
1565 // read a TI tag and return its ID
1566 static void CmdTIRead(char *str)
1567 {
1568 UsbCommand c;
1569 c.cmd = CMD_READ_TI_TYPE;
1570 SendCommand(&c, FALSE);
1571 }
1572
1573 // write new data to a r/w TI tag
1574 static void CmdTIWrite(char *str)
1575 {
1576 UsbCommand c;
1577 int res=0;
1578
1579 c.cmd = CMD_WRITE_TI_TYPE;
1580 res = sscanf(str, "0x%x 0x%x 0x%x ", &c.ext1, &c.ext2, &c.ext3);
1581 if (res == 2) c.ext3=0;
1582 if (res<2)
1583 PrintToScrollback("Please specify the data as two hex strings, optionally the CRC as a third");
1584 else
1585 SendCommand(&c, FALSE);
1586 }
1587
1588 static void CmdTIDemod(char *cmdline)
1589 {
1590 /* MATLAB as follows:
1591 f_s = 2000000; % sampling frequency
1592 f_l = 123200; % low FSK tone
1593 f_h = 134200; % high FSK tone
1594
1595 T_l = 119e-6; % low bit duration
1596 T_h = 130e-6; % high bit duration
1597
1598 l = 2*pi*ones(1, floor(f_s*T_l))*(f_l/f_s);
1599 h = 2*pi*ones(1, floor(f_s*T_h))*(f_h/f_s);
1600
1601 l = sign(sin(cumsum(l)));
1602 h = sign(sin(cumsum(h)));
1603 */
1604
1605 // 2M*16/134.2k = 238
1606 static const int LowTone[] = {
1607 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1,
1608 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1,
1609 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1,
1610 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1,
1611 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1,
1612 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1,
1613 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1,
1614 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1,
1615 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1,
1616 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1,
1617 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1,
1618 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1,
1619 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1,
1620 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1,
1621 1, 1, 1, 1, 1, 1, 1, 1, -1, -1
1622 };
1623 // 2M*16/123.2k = 260
1624 static const int HighTone[] = {
1625 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1,
1626 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1,
1627 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1,
1628 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1,
1629 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1,
1630 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1,
1631 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1,
1632 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1,
1633 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1,
1634 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1,
1635 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1,
1636 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1,
1637 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1,
1638 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1,
1639 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1,
1640 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1,
1641 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1,
1642 1, 1, 1, 1, 1, 1, 1, 1
1643 };
1644 int lowLen = sizeof(LowTone)/sizeof(int);
1645 int highLen = sizeof(HighTone)/sizeof(int);
1646 int convLen = (highLen>lowLen)?highLen:lowLen;
1647 WORD crc;
1648 int i, j, TagType;
1649 int lowSum = 0, highSum = 0;;
1650 int lowTot = 0, highTot = 0;
1651
1652 for(i = 0; i < GraphTraceLen - convLen; i++) {
1653 lowSum = 0;
1654 highSum = 0;;
1655
1656 for(j = 0; j < lowLen; j++) {
1657 lowSum += LowTone[j]*GraphBuffer[i+j];
1658 }
1659 for(j = 0; j < highLen; j++) {
1660 highSum += HighTone[j]*GraphBuffer[i+j];
1661 }
1662 lowSum = abs((100*lowSum) / lowLen);
1663 highSum = abs((100*highSum) / highLen);
1664 lowSum = (lowSum<0)?-lowSum:lowSum;
1665 highSum = (highSum<0)?-highSum:highSum;
1666
1667 GraphBuffer[i] = (highSum << 16) | lowSum;
1668 }
1669
1670 for(i = 0; i < GraphTraceLen - convLen - 16; i++) {
1671 lowTot = 0;
1672 highTot = 0;
1673 // 16 and 15 are f_s divided by f_l and f_h, rounded
1674 for(j = 0; j < 16; j++) {
1675 lowTot += (GraphBuffer[i+j] & 0xffff);
1676 }
1677 for(j = 0; j < 15; j++) {
1678 highTot += (GraphBuffer[i+j] >> 16);
1679 }
1680 GraphBuffer[i] = lowTot - highTot;
1681 }
1682
1683 GraphTraceLen -= (convLen + 16);
1684
1685 RepaintGraphWindow();
1686
1687 // TI tag data format is 16 prebits, 8 start bits, 64 data bits,
1688 // 16 crc CCITT bits, 8 stop bits, 15 end bits
1689
1690 // the 16 prebits are always low
1691 // the 8 start and stop bits of a tag must match
1692 // the start/stop prebits of a ro tag are 01111110
1693 // the start/stop prebits of a rw tag are 11111110
1694 // the 15 end bits of a ro tag are all low
1695 // the 15 end bits of a rw tag match bits 15-1 of the data bits
1696
1697 // Okay, so now we have unsliced soft decisions;
1698 // find bit-sync, and then get some bits.
1699 // look for 17 low bits followed by 6 highs (common pattern for ro and rw tags)
1700 int max = 0, maxPos = 0;
1701 for(i = 0; i < 6000; i++) {
1702 int j;
1703 int dec = 0;
1704 // searching 17 consecutive lows
1705 for(j = 0; j < 17*lowLen; j++) {
1706 dec -= GraphBuffer[i+j];
1707 }
1708 // searching 7 consecutive highs
1709 for(; j < 17*lowLen + 6*highLen; j++) {
1710 dec += GraphBuffer[i+j];
1711 }
1712 if(dec > max) {
1713 max = dec;
1714 maxPos = i;
1715 }
1716 }
1717
1718 // place a marker in the buffer to visually aid location
1719 // of the start of sync
1720 GraphBuffer[maxPos] = 800;
1721 GraphBuffer[maxPos+1] = -800;
1722
1723 // advance pointer to start of actual data stream (after 16 pre and 8 start bits)
1724 maxPos += 17*lowLen;
1725 maxPos += 6*highLen;
1726
1727 // place a marker in the buffer to visually aid location
1728 // of the end of sync
1729 GraphBuffer[maxPos] = 800;
1730 GraphBuffer[maxPos+1] = -800;
1731
1732 PrintToScrollback("actual data bits start at sample %d", maxPos);
1733
1734 PrintToScrollback("length %d/%d", highLen, lowLen);
1735
1736 BYTE bits[1+64+16+8+16];
1737 bits[sizeof(bits)-1] = '\0';
1738
1739 DWORD shift3 = 0x7e000000, shift2 = 0, shift1 = 0, shift0 = 0;
1740
1741 for(i = 0; i < arraylen(bits)-1; i++) {
1742 int high = 0;
1743 int low = 0;
1744 int j;
1745 for(j = 0; j < lowLen; j++) {
1746 low -= GraphBuffer[maxPos+j];
1747 }
1748 for(j = 0; j < highLen; j++) {
1749 high += GraphBuffer[maxPos+j];
1750 }
1751
1752 if(high > low) {
1753 bits[i] = '1';
1754 maxPos += highLen;
1755 // bitstream arrives lsb first so shift right
1756 shift3 |= (1<<31);
1757 } else {
1758 bits[i] = '.';
1759 maxPos += lowLen;
1760 }
1761
1762 // 128 bit right shift register
1763 shift0 = (shift0>>1) | (shift1 << 31);
1764 shift1 = (shift1>>1) | (shift2 << 31);
1765 shift2 = (shift2>>1) | (shift3 << 31);
1766 shift3 >>= 1;
1767
1768 // place a marker in the buffer between bits to visually aid location
1769 GraphBuffer[maxPos] = 800;
1770 GraphBuffer[maxPos+1] = -800;
1771 }
1772 PrintToScrollback("Info: raw tag bits = %s", bits);
1773
1774 TagType = (shift3>>8)&0xff;
1775 if ( TagType != ((shift0>>16)&0xff) ) {
1776 PrintToScrollback("Error: start and stop bits do not match!");
1777 return;
1778 }
1779 else if (TagType == 0x7e) {
1780 PrintToScrollback("Info: Readonly TI tag detected.");
1781 return;
1782 }
1783 else if (TagType == 0xfe) {
1784 PrintToScrollback("Info: Rewriteable TI tag detected.");
1785
1786 // put 64 bit data into shift1 and shift0
1787 shift0 = (shift0>>24) | (shift1 << 8);
1788 shift1 = (shift1>>24) | (shift2 << 8);
1789
1790 // align 16 bit crc into lower half of shift2
1791 shift2 = ((shift2>>24) | (shift3 << 8)) & 0x0ffff;
1792
1793 // align 16 bit "end bits" or "ident" into lower half of shift3
1794 shift3 >>= 16;
1795
1796 // only 15 bits compare, last bit of ident is not valid
1797 if ( (shift3^shift0)&0x7fff ) {
1798 PrintToScrollback("Error: Ident mismatch!");
1799 }
1800 // WARNING the order of the bytes in which we calc crc below needs checking
1801 // i'm 99% sure the crc algorithm is correct, but it may need to eat the
1802 // bytes in reverse or something
1803 // calculate CRC
1804 crc=0;
1805 crc = update_crc16(crc, (shift0)&0xff);
1806 crc = update_crc16(crc, (shift0>>8)&0xff);
1807 crc = update_crc16(crc, (shift0>>16)&0xff);
1808 crc = update_crc16(crc, (shift0>>24)&0xff);
1809 crc = update_crc16(crc, (shift1)&0xff);
1810 crc = update_crc16(crc, (shift1>>8)&0xff);
1811 crc = update_crc16(crc, (shift1>>16)&0xff);
1812 crc = update_crc16(crc, (shift1>>24)&0xff);
1813 PrintToScrollback("Info: Tag data = %08X%08X", shift1, shift0);
1814 if (crc != (shift2&0xffff)) {
1815 PrintToScrollback("Error: CRC mismatch, calculated %04X, got ^04X", crc, shift2&0xffff);
1816 } else {
1817 PrintToScrollback("Info: CRC %04X is good", crc);
1818 }
1819 }
1820 else {
1821 PrintToScrollback("Unknown tag type.");
1822 return;
1823 }
1824 }
1825
1826 static void CmdNorm(char *str)
1827 {
1828 int i;
1829 int max = INT_MIN, min = INT_MAX;
1830 for(i = 10; i < GraphTraceLen; i++) {
1831 if(GraphBuffer[i] > max) {
1832 max = GraphBuffer[i];
1833 }
1834 if(GraphBuffer[i] < min) {
1835 min = GraphBuffer[i];
1836 }
1837 }
1838 if(max != min) {
1839 for(i = 0; i < GraphTraceLen; i++) {
1840 GraphBuffer[i] = (GraphBuffer[i] - ((max + min)/2))*1000/
1841 (max - min);
1842 }
1843 }
1844 RepaintGraphWindow();
1845 }
1846
1847 static void CmdAmp(char *str)
1848 {
1849 int i, rising, falling;
1850 int max = INT_MIN, min = INT_MAX;
1851 for(i = 10; i < GraphTraceLen; i++) {
1852 if(GraphBuffer[i] > max) {
1853 max = GraphBuffer[i];
1854 }
1855 if(GraphBuffer[i] < min) {
1856 min = GraphBuffer[i];
1857 }
1858 }
1859 if(max != min) {
1860 rising= falling= 0;
1861 for(i = 0; i < GraphTraceLen; i++) {
1862 if(GraphBuffer[i+1] < GraphBuffer[i]) {
1863 if(rising) {
1864 GraphBuffer[i]= max;
1865 rising= 0;
1866 }
1867 falling= 1;
1868 }
1869 if(GraphBuffer[i+1] > GraphBuffer[i]) {
1870 if(falling) {
1871 GraphBuffer[i]= min;
1872 falling= 0;
1873 }
1874 rising= 1;
1875 }
1876 }
1877 }
1878 RepaintGraphWindow();
1879 }
1880
1881 static void CmdDec(char *str)
1882 {
1883 int i;
1884 for(i = 0; i < (GraphTraceLen/2); i++) {
1885 GraphBuffer[i] = GraphBuffer[i*2];
1886 }
1887 GraphTraceLen /= 2;
1888 PrintToScrollback("decimated by 2");
1889 RepaintGraphWindow();
1890 }
1891
1892 static void CmdHpf(char *str)
1893 {
1894 int i;
1895 int accum = 0;
1896 for(i = 10; i < GraphTraceLen; i++) {
1897 accum += GraphBuffer[i];
1898 }
1899 accum /= (GraphTraceLen - 10);
1900 for(i = 0; i < GraphTraceLen; i++) {
1901 GraphBuffer[i] -= accum;
1902 }
1903
1904 RepaintGraphWindow();
1905 }
1906
1907 static void CmdZerocrossings(char *str)
1908 {
1909 int i;
1910 // Zero-crossings aren't meaningful unless the signal is zero-mean.
1911 CmdHpf("");
1912
1913 int sign = 1;
1914 int zc = 0;
1915 int lastZc = 0;
1916 for(i = 0; i < GraphTraceLen; i++) {
1917 if(GraphBuffer[i]*sign >= 0) {
1918 // No change in sign, reproduce the previous sample count.
1919 zc++;
1920 GraphBuffer[i] = lastZc;
1921 } else {
1922 // Change in sign, reset the sample count.
1923 sign = -sign;
1924 GraphBuffer[i] = lastZc;
1925 if(sign > 0) {
1926 lastZc = zc;
1927 zc = 0;
1928 }
1929 }
1930 }
1931
1932 RepaintGraphWindow();
1933 }
1934
1935 static void CmdThreshold(char *str)
1936 {
1937 int i;
1938 int threshold = atoi(str);
1939
1940 for(i = 0; i < GraphTraceLen; i++) {
1941 if(GraphBuffer[i]>= threshold)
1942 GraphBuffer[i]=1;
1943 else
1944 GraphBuffer[i]=-1;
1945 }
1946 RepaintGraphWindow();
1947 }
1948
1949 static void CmdLtrim(char *str)
1950 {
1951 int i;
1952 int ds = atoi(str);
1953
1954 for(i = ds; i < GraphTraceLen; i++) {
1955 GraphBuffer[i-ds] = GraphBuffer[i];
1956 }
1957 GraphTraceLen -= ds;
1958
1959 RepaintGraphWindow();
1960 }
1961
1962 static void CmdAutoCorr(char *str)
1963 {
1964 static int CorrelBuffer[MAX_GRAPH_TRACE_LEN];
1965
1966 int window = atoi(str);
1967
1968 if(window == 0) {
1969 PrintToScrollback("needs a window");
1970 return;
1971 }
1972
1973 if(window >= GraphTraceLen) {
1974 PrintToScrollback("window must be smaller than trace (%d samples)",
1975 GraphTraceLen);
1976 return;
1977 }
1978
1979 PrintToScrollback("performing %d correlations", GraphTraceLen - window);
1980
1981 int i;
1982 for(i = 0; i < GraphTraceLen - window; i++) {
1983 int sum = 0;
1984 int j;
1985 for(j = 0; j < window; j++) {
1986 sum += (GraphBuffer[j]*GraphBuffer[i+j]) / 256;
1987 }
1988 CorrelBuffer[i] = sum;
1989 }
1990 GraphTraceLen = GraphTraceLen - window;
1991 memcpy(GraphBuffer, CorrelBuffer, GraphTraceLen*sizeof(int));
1992
1993 RepaintGraphWindow();
1994 }
1995
1996 static void CmdVchdemod(char *str)
1997 {
1998 // Is this the entire sync pattern, or does this also include some
1999 // data bits that happen to be the same everywhere? That would be
2000 // lovely to know.
2001 static const int SyncPattern[] = {
2002 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2003 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
2004 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2005 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
2006 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2007 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
2008 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2009 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
2010 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2011 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
2012 };
2013
2014 // So first, we correlate for the sync pattern, and mark that.
2015 int bestCorrel = 0, bestPos = 0;
2016 int i;
2017 // It does us no good to find the sync pattern, with fewer than
2018 // 2048 samples after it...
2019 for(i = 0; i < (GraphTraceLen-2048); i++) {
2020 int sum = 0;
2021 int j;
2022 for(j = 0; j < arraylen(SyncPattern); j++) {
2023 sum += GraphBuffer[i+j]*SyncPattern[j];
2024 }
2025 if(sum > bestCorrel) {
2026 bestCorrel = sum;
2027 bestPos = i;
2028 }
2029 }
2030 PrintToScrollback("best sync at %d [metric %d]", bestPos, bestCorrel);
2031
2032 char bits[257];
2033 bits[256] = '\0';
2034
2035 int worst = INT_MAX;
2036 int worstPos;
2037
2038 for(i = 0; i < 2048; i += 8) {
2039 int sum = 0;
2040 int j;
2041 for(j = 0; j < 8; j++) {
2042 sum += GraphBuffer[bestPos+i+j];
2043 }
2044 if(sum < 0) {
2045 bits[i/8] = '.';
2046 } else {
2047 bits[i/8] = '1';
2048 }
2049 if(abs(sum) < worst) {
2050 worst = abs(sum);
2051 worstPos = i;
2052 }
2053 }
2054 PrintToScrollback("bits:");
2055 PrintToScrollback("%s", bits);
2056 PrintToScrollback("worst metric: %d at pos %d", worst, worstPos);
2057
2058 if(strcmp(str, "clone")==0) {
2059 GraphTraceLen = 0;
2060 char *s;
2061 for(s = bits; *s; s++) {
2062 int j;
2063 for(j = 0; j < 16; j++) {
2064 GraphBuffer[GraphTraceLen++] = (*s == '1') ? 1 : 0;
2065 }
2066 }
2067 RepaintGraphWindow();
2068 }
2069 }
2070
2071 static void CmdIndalademod(char *str)
2072 {
2073 // Usage: recover 64bit UID by default, specify "224" as arg to recover a 224bit UID
2074
2075 int state = -1;
2076 int count = 0;
2077 int i, j;
2078 // worst case with GraphTraceLen=64000 is < 4096
2079 // under normal conditions it's < 2048
2080 BYTE rawbits[4096];
2081 int rawbit = 0;
2082 int worst = 0, worstPos = 0;
2083 PrintToScrollback("Expecting a bit less than %d raw bits", GraphTraceLen/32);
2084 for(i = 0; i < GraphTraceLen-1; i += 2) {
2085 count+=1;
2086 if((GraphBuffer[i] > GraphBuffer[i + 1]) && (state != 1)) {
2087 if (state == 0) {
2088 for(j = 0; j < count - 8; j += 16) {
2089 rawbits[rawbit++] = 0;
2090 }
2091 if ((abs(count - j)) > worst) {
2092 worst = abs(count - j);
2093 worstPos = i;
2094 }
2095 }
2096 state = 1;
2097 count=0;
2098 } else if((GraphBuffer[i] < GraphBuffer[i + 1]) && (state != 0)) {
2099 if (state == 1) {
2100 for(j = 0; j < count - 8; j += 16) {
2101 rawbits[rawbit++] = 1;
2102 }
2103 if ((abs(count - j)) > worst) {
2104 worst = abs(count - j);
2105 worstPos = i;
2106 }
2107 }
2108 state = 0;
2109 count=0;
2110 }
2111 }
2112 PrintToScrollback("Recovered %d raw bits", rawbit);
2113 PrintToScrollback("worst metric (0=best..7=worst): %d at pos %d", worst, worstPos);
2114
2115 // Finding the start of a UID
2116 int uidlen, long_wait;
2117 if(strcmp(str, "224") == 0) {
2118 uidlen=224;
2119 long_wait=30;
2120 } else {
2121 uidlen=64;
2122 long_wait=29;
2123 }
2124 int start;
2125 int first = 0;
2126 for(start = 0; start <= rawbit - uidlen; start++) {
2127 first = rawbits[start];
2128 for(i = start; i < start + long_wait; i++) {
2129 if(rawbits[i] != first) {
2130 break;
2131 }
2132 }
2133 if(i == (start + long_wait)) {
2134 break;
2135 }
2136 }
2137 if(start == rawbit - uidlen + 1) {
2138 PrintToScrollback("nothing to wait for");
2139 return;
2140 }
2141
2142 // Inverting signal if needed
2143 if(first == 1) {
2144 for(i = start; i < rawbit; i++) {
2145 rawbits[i] = !rawbits[i];
2146 }
2147 }
2148
2149 // Dumping UID
2150 BYTE bits[224];
2151 char showbits[225];
2152 showbits[uidlen]='\0';
2153 int bit;
2154 i = start;
2155 int times = 0;
2156 if(uidlen > rawbit) {
2157 PrintToScrollback("Warning: not enough raw bits to get a full UID");
2158 for(bit = 0; bit < rawbit; bit++) {
2159 bits[bit] = rawbits[i++];
2160 // As we cannot know the parity, let's use "." and "/"
2161 showbits[bit] = '.' + bits[bit];
2162 }
2163 showbits[bit+1]='\0';
2164 PrintToScrollback("Partial UID=%s", showbits);
2165 return;
2166 } else {
2167 for(bit = 0; bit < uidlen; bit++) {
2168 bits[bit] = rawbits[i++];
2169 showbits[bit] = '0' + bits[bit];
2170 }
2171 times = 1;
2172 }
2173 PrintToScrollback("UID=%s", showbits);
2174
2175 // Checking UID against next occurences
2176 for(; i + uidlen <= rawbit;) {
2177 int failed = 0;
2178 for(bit = 0; bit < uidlen; bit++) {
2179 if(bits[bit] != rawbits[i++]) {
2180 failed = 1;
2181 break;
2182 }
2183 }
2184 if (failed == 1) {
2185 break;
2186 }
2187 times += 1;
2188 }
2189 PrintToScrollback("Occurences: %d (expected %d)", times, (rawbit - start) / uidlen);
2190
2191 // Remodulating for tag cloning
2192 GraphTraceLen = 32*uidlen;
2193 i = 0;
2194 int phase = 0;
2195 for(bit = 0; bit < uidlen; bit++) {
2196 if(bits[bit] == 0) {
2197 phase = 0;
2198 } else {
2199 phase = 1;
2200 }
2201 int j;
2202 for(j = 0; j < 32; j++) {
2203 GraphBuffer[i++] = phase;
2204 phase = !phase;
2205 }
2206 }
2207
2208 RepaintGraphWindow();
2209 }
2210
2211 static void CmdFlexdemod(char *str)
2212 {
2213 int i;
2214 for(i = 0; i < GraphTraceLen; i++) {
2215 if(GraphBuffer[i] < 0) {
2216 GraphBuffer[i] = -1;
2217 } else {
2218 GraphBuffer[i] = 1;
2219 }
2220 }
2221
2222 #define LONG_WAIT 100
2223 int start;
2224 for(start = 0; start < GraphTraceLen - LONG_WAIT; start++) {
2225 int first = GraphBuffer[start];
2226 for(i = start; i < start + LONG_WAIT; i++) {
2227 if(GraphBuffer[i] != first) {
2228 break;
2229 }
2230 }
2231 if(i == (start + LONG_WAIT)) {
2232 break;
2233 }
2234 }
2235 if(start == GraphTraceLen - LONG_WAIT) {
2236 PrintToScrollback("nothing to wait for");
2237 return;
2238 }
2239
2240 GraphBuffer[start] = 2;
2241 GraphBuffer[start+1] = -2;
2242
2243 BYTE bits[64];
2244
2245 int bit;
2246 i = start;
2247 for(bit = 0; bit < 64; bit++) {
2248 int j;
2249 int sum = 0;
2250 for(j = 0; j < 16; j++) {
2251 sum += GraphBuffer[i++];
2252 }
2253 if(sum > 0) {
2254 bits[bit] = 1;
2255 } else {
2256 bits[bit] = 0;
2257 }
2258 PrintToScrollback("bit %d sum %d", bit, sum);
2259 }
2260
2261 for(bit = 0; bit < 64; bit++) {
2262 int j;
2263 int sum = 0;
2264 for(j = 0; j < 16; j++) {
2265 sum += GraphBuffer[i++];
2266 }
2267 if(sum > 0 && bits[bit] != 1) {
2268 PrintToScrollback("oops1 at %d", bit);
2269 }
2270 if(sum < 0 && bits[bit] != 0) {
2271 PrintToScrollback("oops2 at %d", bit);
2272 }
2273 }
2274
2275 GraphTraceLen = 32*64;
2276 i = 0;
2277 int phase = 0;
2278 for(bit = 0; bit < 64; bit++) {
2279 if(bits[bit] == 0) {
2280 phase = 0;
2281 } else {
2282 phase = 1;
2283 }
2284 int j;
2285 for(j = 0; j < 32; j++) {
2286 GraphBuffer[i++] = phase;
2287 phase = !phase;
2288 }
2289 }
2290
2291 RepaintGraphWindow();
2292 }
2293
2294 /*
2295 * Generic command to demodulate ASK.
2296 *
2297 * Argument is convention: positive or negative (High mod means zero
2298 * or high mod means one)
2299 *
2300 * Updates the Graph trace with 0/1 values
2301 *
2302 * Arguments:
2303 * c : 0 or 1
2304 */
2305
2306 static void Cmdaskdemod(char *str) {
2307 int i;
2308 int c, high = 0, low = 0;
2309
2310 // TODO: complain if we do not give 2 arguments here !
2311 // (AL - this doesn't make sense! we're only using one argument!!!)
2312 sscanf(str, "%i", &c);
2313
2314 /* Detect high and lows and clock */
2315 // (AL - clock???)
2316 for (i = 0; i < GraphTraceLen; i++)
2317 {
2318 if (GraphBuffer[i] > high)
2319 high = GraphBuffer[i];
2320 else if (GraphBuffer[i] < low)
2321 low = GraphBuffer[i];
2322 }
2323 if(c != 0 && c != 1) {
2324 PrintToScrollback("Invalid argument: %s",str);
2325 return;
2326 }
2327
2328 if (GraphBuffer[0] > 0) {
2329 GraphBuffer[0] = 1-c;
2330 } else {
2331 GraphBuffer[0] = c;
2332 }
2333 for(i=1;i<GraphTraceLen;i++) {
2334 /* Transitions are detected at each peak
2335 * Transitions are either:
2336 * - we're low: transition if we hit a high
2337 * - we're high: transition if we hit a low
2338 * (we need to do it this way because some tags keep high or
2339 * low for long periods, others just reach the peak and go
2340 * down)
2341 */
2342 if ((GraphBuffer[i]==high) && (GraphBuffer[i-1] == c)) {
2343 GraphBuffer[i]=1-c;
2344 } else if ((GraphBuffer[i]==low) && (GraphBuffer[i-1] == (1-c))){
2345 GraphBuffer[i] = c;
2346 } else {
2347 /* No transition */
2348 GraphBuffer[i] = GraphBuffer[i-1];
2349 }
2350 }
2351 RepaintGraphWindow();
2352 }
2353
2354 /* Print our clock rate */
2355 static void Cmddetectclockrate(char *str)
2356 {
2357 int clock = detectclock(0);
2358 PrintToScrollback("Auto-detected clock rate: %d", clock);
2359 }
2360
2361 /*
2362 * Detect clock rate
2363 */
2364 int detectclock(int peak)
2365 {
2366 int i;
2367 int clock = 0xFFFF;
2368 int lastpeak = 0;
2369
2370 /* Detect peak if we don't have one */
2371 if (!peak)
2372 for (i = 0; i < GraphTraceLen; i++)
2373 if (GraphBuffer[i] > peak)
2374 peak = GraphBuffer[i];
2375
2376 for (i = 1; i < GraphTraceLen; i++)
2377 {
2378 /* If this is the beginning of a peak */
2379 if (GraphBuffer[i-1] != GraphBuffer[i] && GraphBuffer[i] == peak)
2380 {
2381 /* Find lowest difference between peaks */
2382 if (lastpeak && i - lastpeak < clock)
2383 {
2384 clock = i - lastpeak;
2385 }
2386 lastpeak = i;
2387 }
2388 }
2389
2390 return clock;
2391 }
2392
2393 /* Get or auto-detect clock rate */
2394 int GetClock(char *str, int peak)
2395 {
2396 int clock;
2397
2398 sscanf(str, "%i", &clock);
2399 if (!strcmp(str, ""))
2400 clock = 0;
2401
2402 /* Auto-detect clock */
2403 if (!clock)
2404 {
2405 clock = detectclock(peak);
2406
2407 /* Only print this message if we're not looping something */
2408 if (!go)
2409 PrintToScrollback("Auto-detected clock rate: %d", clock);
2410 }
2411
2412 return clock;
2413 }
2414
2415 /*
2416 * Convert to a bitstream
2417 */
2418 static void Cmdbitstream(char *str) {
2419 int i, j;
2420 int bit;
2421 int gtl;
2422 int clock;
2423 int low = 0;
2424 int high = 0;
2425 int hithigh, hitlow, first;
2426
2427 /* Detect high and lows and clock */
2428 for (i = 0; i < GraphTraceLen; i++)
2429 {
2430 if (GraphBuffer[i] > high)
2431 high = GraphBuffer[i];
2432 else if (GraphBuffer[i] < low)
2433 low = GraphBuffer[i];
2434 }
2435
2436 /* Get our clock */
2437 clock = GetClock(str, high);
2438
2439 gtl = CmdClearGraph(0);
2440
2441 bit = 0;
2442 for (i = 0; i < (int)(gtl / clock); i++)
2443 {
2444 hithigh = 0;
2445 hitlow = 0;
2446 first = 1;
2447
2448 /* Find out if we hit both high and low peaks */
2449 for (j = 0; j < clock; j++)
2450 {
2451 if (GraphBuffer[(i * clock) + j] == high)
2452 hithigh = 1;
2453 else if (GraphBuffer[(i * clock) + j] == low)
2454 hitlow = 1;
2455
2456 /* it doesn't count if it's the first part of our read
2457 because it's really just trailing from the last sequence */
2458 if (first && (hithigh || hitlow))
2459 hithigh = hitlow = 0;
2460 else
2461 first = 0;
2462
2463 if (hithigh && hitlow)
2464 break;
2465 }
2466
2467 /* If we didn't hit both high and low peaks, we had a bit transition */
2468 if (!hithigh || !hitlow)
2469 bit ^= 1;
2470
2471 CmdAppendGraph(0, clock, bit);
2472 // for (j = 0; j < (int)(clock/2); j++)
2473 // GraphBuffer[(i * clock) + j] = bit ^ 1;
2474 // for (j = (int)(clock/2); j < clock; j++)
2475 // GraphBuffer[(i * clock) + j] = bit;
2476 }
2477
2478 RepaintGraphWindow();
2479 }
2480
2481 /* Modulate our data into manchester */
2482 static void Cmdmanchestermod(char *str)
2483 {
2484 int i, j;
2485 int clock;
2486 int bit, lastbit, wave;
2487
2488 /* Get our clock */
2489 clock = GetClock(str, 0);
2490
2491 wave = 0;
2492 lastbit = 1;
2493 for (i = 0; i < (int)(GraphTraceLen / clock); i++)
2494 {
2495 bit = GraphBuffer[i * clock] ^ 1;
2496
2497 for (j = 0; j < (int)(clock/2); j++)
2498 GraphBuffer[(i * clock) + j] = bit ^ lastbit ^ wave;
2499 for (j = (int)(clock/2); j < clock; j++)
2500 GraphBuffer[(i * clock) + j] = bit ^ lastbit ^ wave ^ 1;
2501
2502 /* Keep track of how we start our wave and if we changed or not this time */
2503 wave ^= bit ^ lastbit;
2504 lastbit = bit;
2505 }
2506
2507 RepaintGraphWindow();
2508 }
2509
2510 /*
2511 * Manchester demodulate a bitstream. The bitstream needs to be already in
2512 * the GraphBuffer as 0 and 1 values
2513 *
2514 * Give the clock rate as argument in order to help the sync - the algorithm
2515 * resyncs at each pulse anyway.
2516 *
2517 * Not optimized by any means, this is the 1st time I'm writing this type of
2518 * routine, feel free to improve...
2519 *
2520 * 1st argument: clock rate (as number of samples per clock rate)
2521 * Typical values can be 64, 32, 128...
2522 */
2523 static void Cmdmanchesterdemod(char *str) {
2524 int i, j, invert= 0;
2525 int bit;
2526 int clock;
2527 int lastval;
2528 int low = 0;
2529 int high = 0;
2530 int hithigh, hitlow, first;
2531 int lc = 0;
2532 int bitidx = 0;
2533 int bit2idx = 0;
2534 int warnings = 0;
2535
2536 /* check if we're inverting output */
2537 if(*str == 'i')
2538 {
2539 PrintToScrollback("Inverting output");
2540 invert= 1;
2541 do
2542 ++str;
2543 while(*str == ' '); // in case a 2nd argument was given
2544 }
2545
2546 /* Holds the decoded bitstream: each clock period contains 2 bits */
2547 /* later simplified to 1 bit after manchester decoding. */
2548 /* Add 10 bits to allow for noisy / uncertain traces without aborting */
2549 /* int BitStream[GraphTraceLen*2/clock+10]; */
2550
2551 /* But it does not work if compiling on WIndows: therefore we just allocate a */
2552 /* large array */
2553 int BitStream[MAX_GRAPH_TRACE_LEN];
2554
2555 /* Detect high and lows */
2556 for (i = 0; i < GraphTraceLen; i++)
2557 {
2558 if (GraphBuffer[i] > high)
2559 high = GraphBuffer[i];
2560 else if (GraphBuffer[i] < low)
2561 low = GraphBuffer[i];
2562 }
2563
2564 /* Get our clock */
2565 clock = GetClock(str, high);
2566
2567 int tolerance = clock/4;
2568
2569 /* Detect first transition */
2570 /* Lo-Hi (arbitrary) */
2571 /* skip to the first high */
2572 for (i= 0; i < GraphTraceLen; i++)
2573 if(GraphBuffer[i] == high)
2574 break;
2575 /* now look for the first low */
2576 for (; i < GraphTraceLen; i++)
2577 {
2578 if (GraphBuffer[i] == low)
2579 {
2580 lastval = i;
2581 break;
2582 }
2583 }
2584
2585 /* If we're not working with 1/0s, demod based off clock */
2586 if (high != 1)
2587 {
2588 bit = 0; /* We assume the 1st bit is zero, it may not be
2589 * the case: this routine (I think) has an init problem.
2590 * Ed.
2591 */
2592 for (; i < (int)(GraphTraceLen / clock); i++)
2593 {
2594 hithigh = 0;
2595 hitlow = 0;
2596 first = 1;
2597
2598 /* Find out if we hit both high and low peaks */
2599 for (j = 0; j < clock; j++)
2600 {
2601 if (GraphBuffer[(i * clock) + j] == high)
2602 hithigh = 1;
2603 else if (GraphBuffer[(i * clock) + j] == low)
2604 hitlow = 1;
2605
2606 /* it doesn't count if it's the first part of our read
2607 because it's really just trailing from the last sequence */
2608 if (first && (hithigh || hitlow))
2609 hithigh = hitlow = 0;
2610 else
2611 first = 0;
2612
2613 if (hithigh && hitlow)
2614 break;
2615 }
2616
2617 /* If we didn't hit both high and low peaks, we had a bit transition */
2618 if (!hithigh || !hitlow)
2619 bit ^= 1;
2620
2621 BitStream[bit2idx++] = bit ^ invert;
2622 }
2623 }
2624
2625 /* standard 1/0 bitstream */
2626 else
2627 {
2628
2629 /* Then detect duration between 2 successive transitions */
2630 for (bitidx = 1; i < GraphTraceLen; i++)
2631 {
2632 if (GraphBuffer[i-1] != GraphBuffer[i])
2633 {
2634 lc = i-lastval;
2635 lastval = i;
2636
2637 // Error check: if bitidx becomes too large, we do not
2638 // have a Manchester encoded bitstream or the clock is really
2639 // wrong!
2640 if (bitidx > (GraphTraceLen*2/clock+8) ) {
2641 PrintToScrollback("Error: the clock you gave is probably wrong, aborting.");
2642 return;
2643 }
2644 // Then switch depending on lc length:
2645 // Tolerance is 1/4 of clock rate (arbitrary)
2646 if (abs(lc-clock/2) < tolerance) {
2647 // Short pulse : either "1" or "0"
2648 BitStream[bitidx++]=GraphBuffer[i-1];
2649 } else if (abs(lc-clock) < tolerance) {
2650 // Long pulse: either "11" or "00"
2651 BitStream[bitidx++]=GraphBuffer[i-1];
2652 BitStream[bitidx++]=GraphBuffer[i-1];
2653 } else {
2654 // Error
2655 warnings++;
2656 PrintToScrollback("Warning: Manchester decode error for pulse width detection.");
2657 PrintToScrollback("(too many of those messages mean either the stream is not Manchester encoded, or clock is wrong)");
2658
2659 if (warnings > 100)
2660 {
2661 PrintToScrollback("Error: too many detection errors, aborting.");
2662 return;
2663 }
2664 }
2665 }
2666 }
2667
2668 // At this stage, we now have a bitstream of "01" ("1") or "10" ("0"), parse it into final decoded bitstream
2669 // Actually, we overwrite BitStream with the new decoded bitstream, we just need to be careful
2670 // to stop output at the final bitidx2 value, not bitidx
2671 for (i = 0; i < bitidx; i += 2) {
2672 if ((BitStream[i] == 0) && (BitStream[i+1] == 1)) {
2673 BitStream[bit2idx++] = 1 ^ invert;
2674 } else if ((BitStream[i] == 1) && (BitStream[i+1] == 0)) {
2675 BitStream[bit2idx++] = 0 ^ invert;
2676 } else {
2677 // We cannot end up in this state, this means we are unsynchronized,
2678 // move up 1 bit:
2679 i++;
2680 warnings++;
2681 PrintToScrollback("Unsynchronized, resync...");
2682 PrintToScrollback("(too many of those messages mean the stream is not Manchester encoded)");
2683
2684 if (warnings > 100)
2685 {
2686 PrintToScrollback("Error: too many decode errors, aborting.");
2687 return;
2688 }
2689 }
2690 }
2691 }
2692
2693 PrintToScrollback("Manchester decoded bitstream");
2694 // Now output the bitstream to the scrollback by line of 16 bits
2695 for (i = 0; i < (bit2idx-16); i+=16) {
2696 PrintToScrollback("%i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i",
2697 BitStream[i],
2698 BitStream[i+1],
2699 BitStream[i+2],
2700 BitStream[i+3],
2701 BitStream[i+4],
2702 BitStream[i+5],
2703 BitStream[i+6],
2704 BitStream[i+7],
2705 BitStream[i+8],
2706 BitStream[i+9],
2707 BitStream[i+10],
2708 BitStream[i+11],
2709 BitStream[i+12],
2710 BitStream[i+13],
2711 BitStream[i+14],
2712 BitStream[i+15]);
2713 }
2714 }
2715
2716 /*
2717 * Usage ???
2718 */
2719 static void CmdHiddemod(char *str)
2720 {
2721 if(GraphTraceLen < 4800) {
2722 PrintToScrollback("too short; need at least 4800 samples");
2723 return;
2724 }
2725
2726 GraphTraceLen = 4800;
2727 int i;
2728 for(i = 0; i < GraphTraceLen; i++) {
2729 if(GraphBuffer[i] < 0) {
2730 GraphBuffer[i] = 0;
2731 } else {
2732 GraphBuffer[i] = 1;
2733 }
2734 }
2735 RepaintGraphWindow();
2736 }
2737
2738 static void CmdPlot(char *str)
2739 {
2740 ShowGraphWindow();
2741 }
2742
2743 static void CmdGrid(char *str)
2744 {
2745 sscanf(str, "%i %i", &PlotGridX, &PlotGridY);
2746 RepaintGraphWindow();
2747 }
2748
2749 static void CmdHide(char *str)
2750 {
2751 HideGraphWindow();
2752 }
2753
2754 static void CmdScale(char *str)
2755 {
2756 CursorScaleFactor = atoi(str);
2757 if(CursorScaleFactor == 0) {
2758 PrintToScrollback("bad, can't have zero scale");
2759 CursorScaleFactor = 1;
2760 }
2761 RepaintGraphWindow();
2762 }
2763
2764 static void CmdSave(char *str)
2765 {
2766 FILE *f = fopen(str, "w");
2767 if(!f) {
2768 PrintToScrollback("couldn't open '%s'", str);
2769 return;
2770 }
2771 int i;
2772 for(i = 0; i < GraphTraceLen; i++) {
2773 fprintf(f, "%d\n", GraphBuffer[i]);
2774 }
2775 fclose(f);
2776 PrintToScrollback("saved to '%s'", str);
2777 }
2778
2779 static void CmdLoad(char *str)
2780 {
2781 FILE *f = fopen(str, "r");
2782 if(!f) {
2783 PrintToScrollback("couldn't open '%s'", str);
2784 return;
2785 }
2786
2787 GraphTraceLen = 0;
2788 char line[80];
2789 while(fgets(line, sizeof(line), f)) {
2790 GraphBuffer[GraphTraceLen] = atoi(line);
2791 GraphTraceLen++;
2792 }
2793 fclose(f);
2794 PrintToScrollback("loaded %d samples", GraphTraceLen);
2795 RepaintGraphWindow();
2796 }
2797
2798 static void CmdHIDsimTAG(char *str)
2799 {
2800 unsigned int hi=0, lo=0;
2801 int n=0, i=0;
2802 UsbCommand c;
2803
2804 while (sscanf(&str[i++], "%1x", &n ) == 1) {
2805 hi=(hi<<4)|(lo>>28);
2806 lo=(lo<<4)|(n&0xf);
2807 }
2808
2809 PrintToScrollback("Emulating tag with ID %x%16x", hi, lo);
2810
2811 c.cmd = CMD_HID_SIM_TAG;
2812 c.ext1 = hi;
2813 c.ext2 = lo;
2814 SendCommand(&c, FALSE);
2815 }
2816
2817 static void CmdReadmem(char *str)
2818 {
2819 UsbCommand c;
2820 c.cmd = CMD_READ_MEM;
2821 c.ext1 = atoi(str);
2822 SendCommand(&c, FALSE);
2823 }
2824
2825 static void CmdVersion(char *str)
2826 {
2827 UsbCommand c;
2828 c.cmd = CMD_VERSION;
2829 SendCommand(&c, FALSE);
2830 }
2831
2832 static void CmdLcdReset(char *str)
2833 {
2834 UsbCommand c;
2835 c.cmd = CMD_LCD_RESET;
2836 c.ext1 = atoi(str);
2837 SendCommand(&c, FALSE);
2838 }
2839
2840 static void CmdLcd(char *str)
2841 {
2842 int i, j;
2843 UsbCommand c;
2844 c.cmd = CMD_LCD;
2845 sscanf(str, "%x %d", &i, &j);
2846 while (j--) {
2847 c.ext1 = i&0x1ff;
2848 SendCommand(&c, FALSE);
2849 }
2850 }
2851
2852 /*
2853 * Sets the divisor for LF frequency clock: lets the user choose any LF frequency below
2854 * 600kHz.
2855 */
2856 static void CmdSetDivisor(char *str)
2857 {
2858 UsbCommand c;
2859 c.cmd = CMD_SET_LF_DIVISOR;
2860 c.ext1 = atoi(str);
2861 if (( c.ext1<0) || (c.ext1>255)) {
2862 PrintToScrollback("divisor must be between 19 and 255");
2863 } else {
2864 SendCommand(&c, FALSE);
2865 PrintToScrollback("Divisor set, expected freq=%dHz", 12000000/(c.ext1+1));
2866 }
2867 }
2868
2869 static void CmdSetMux(char *str)
2870 {
2871 UsbCommand c;
2872 c.cmd = CMD_SET_ADC_MUX;
2873 if(strcmp(str, "lopkd") == 0) {
2874 c.ext1 = 0;
2875 } else if(strcmp(str, "loraw") == 0) {
2876 c.ext1 = 1;
2877 } else if(strcmp(str, "hipkd") == 0) {
2878 c.ext1 = 2;
2879 } else if(strcmp(str, "hiraw") == 0) {
2880 c.ext1 = 3;
2881 }
2882 SendCommand(&c, FALSE);
2883 }
2884
2885 typedef void HandlerFunction(char *cmdline);
2886
2887 /* in alphabetic order */
2888 static struct {
2889 char *name;
2890 HandlerFunction *handler;
2891 int offline; // 1 if the command can be used when in offline mode
2892 char *docString;
2893 } CommandTable[] = {
2894 {"amp", CmdAmp, 1, "Amplify peaks"},
2895 {"askdemod", Cmdaskdemod, 1, "<0|1> -- Attempt to demodulate simple ASK tags"},
2896 {"autocorr", CmdAutoCorr, 1, "<window length> -- Autocorrelation over window"},
2897 {"bitsamples", CmdBitsamples, 0, "Get raw samples as bitstring"},
2898 {"bitstream", Cmdbitstream, 1, "[clock rate] -- Convert waveform into a bitstream"},
2899 {"buffclear", CmdBuffClear, 1, "Clear sample buffer and graph window"},
2900 {"dec", CmdDec, 1, "Decimate samples"},
2901 {"detectclock", Cmddetectclockrate, 1, "Detect clock rate"},
2902 {"detectreader", CmdDetectReader, 0, "['l'|'h'] -- Detect external reader field (option 'l' or 'h' to limit to LF or HF)"},
2903 {"em410xsim", CmdEM410xsim, 1, "<UID> -- Simulate EM410x tag"},
2904 {"em410xread", CmdEM410xread, 1, "[clock rate] -- Extract ID from EM410x tag"},
2905 {"em410xwatch", CmdEM410xwatch, 0, "Watches for EM410x tags"},
2906 {"em4x50read", CmdEM4x50read, 1, "Extract data from EM4x50 tag"},
2907 {"exit", CmdQuit, 1, "Exit program"},
2908 {"flexdemod", CmdFlexdemod, 1, "Demodulate samples for FlexPass"},
2909 {"fpgaoff", CmdFPGAOff, 0, "Set FPGA off"},
2910 {"fskdemod", CmdFSKdemod, 1, "Demodulate graph window as a HID FSK"},
2911 {"grid", CmdGrid, 1, "<x> <y> -- overlay grid on graph window, use zero value to turn off either"},
2912 {"hexsamples", CmdHexsamples, 0, "<blocks> -- Dump big buffer as hex bytes"},
2913 {"hi14alist", CmdHi14alist, 0, "List ISO 14443a history"},
2914 {"hi14areader", CmdHi14areader, 0, "Act like an ISO14443 Type A reader"},
2915 {"hi14asim", CmdHi14asim, 0, "<UID> -- Fake ISO 14443a tag"},
2916 {"hi14asnoop", CmdHi14asnoop, 0, "Eavesdrop ISO 14443 Type A"},
2917 {"hi14bdemod", CmdHi14bdemod, 1, "Demodulate ISO14443 Type B from tag"},
2918 {"hi14list", CmdHi14list, 0, "List ISO 14443 history"},
2919 {"hi14read", CmdHi14read, 0, "Read HF tag (ISO 14443)"},
2920 {"hi14sim", CmdHi14sim, 0, "Fake ISO 14443 tag"},
2921 {"hi14snoop", CmdHi14snoop, 0, "Eavesdrop ISO 14443"},
2922 {"hi15demod", CmdHi15demod, 1, "Demodulate ISO15693 from tag"},
2923 {"hi15read", CmdHi15read, 0, "Read HF tag (ISO 15693)"},
2924 {"hi15reader", CmdHi15reader, 0, "Act like an ISO15693 reader"},
2925 {"hi15sim", CmdHi15tag, 0, "Fake an ISO15693 tag"},
2926 {"hiddemod", CmdHiddemod, 1, "Demodulate HID Prox Card II (not optimal)"},
2927 {"hide", CmdHide, 1, "Hide graph window"},
2928 {"hidfskdemod", CmdHIDdemodFSK, 0, "Realtime HID FSK demodulator"},
2929 {"hidsimtag", CmdHIDsimTAG, 0, "<ID> -- HID tag simulator"},
2930 {"higet", CmdHi14read_sim, 0, "<samples> -- Get samples HF, 'analog'"},
2931 {"hisamples", CmdHisamples, 0, "Get raw samples for HF tag"},
2932 {"hisampless", CmdHisampless, 0, "<samples> -- Get signed raw samples, HF tag"},
2933 {"hisamplest", CmdHi14readt, 0, "Get samples HF, for testing"},
2934 {"hisimlisten", CmdHisimlisten, 0, "Get HF samples as fake tag"},
2935 {"hpf", CmdHpf, 1, "Remove DC offset from trace"},
2936 {"indalademod", CmdIndalademod, 0, "['224'] -- Demodulate samples for Indala 64 bit UID (option '224' for 224 bit)"},
2937 {"lcd", CmdLcd, 0, "<HEX command> <count> -- Send command/data to LCD"},
2938 {"lcdreset", CmdLcdReset, 0, "Hardware reset LCD"},
2939 {"legicrfsim", CmdLegicRfSim, 0, "Start the LEGIC RF tag simulator"},
2940 {"legicrfread", CmdLegicRfRead, 0, "Start the LEGIC RF reader"},
2941 {"load", CmdLoad, 1, "<filename> -- Load trace (to graph window"},
2942 {"locomread", CmdLoCommandRead, 0, "<off period> <'0' period> <'1' period> <command> ['h'] -- Modulate LF reader field to send command before read (all periods in microseconds) (option 'h' for 134)"},
2943 {"loread", CmdLoread, 0, "['h'] -- Read 125/134 kHz LF ID-only tag (option 'h' for 134)"},
2944 {"losamples", CmdLosamples, 0, "[128 - 16000] -- Get raw samples for LF tag"},
2945 {"losim", CmdLosim, 0, "Simulate LF tag"},
2946 {"losimbidir", CmdLosimBidir, 0, "Simulate LF tag (with bidirectional data transmission between reader and tag)"},
2947 {"ltrim", CmdLtrim, 1, "<samples> -- Trim samples from left of trace"},
2948 {"mandemod", Cmdmanchesterdemod, 1, "[i] [clock rate] -- Manchester demodulate binary stream (option 'i' to invert output)"},
2949 {"manmod", Cmdmanchestermod, 1, "[clock rate] -- Manchester modulate a binary stream"},
2950 {"norm", CmdNorm, 1, "Normalize max/min to +/-500"},
2951 {"plot", CmdPlot, 1, "Show graph window"},
2952 {"quit", CmdQuit, 1, "Quit program"},
2953 {"readmem", CmdReadmem, 0, "[address] -- Read memory at decimal address from flash"},
2954 {"reset", CmdReset, 0, "Reset the Proxmark3"},
2955 {"save", CmdSave, 1, "<filename> -- Save trace (from graph window)"},
2956 {"scale", CmdScale, 1, "<int> -- Set cursor display scale"},
2957 {"setlfdivisor", CmdSetDivisor, 0, "<19 - 255> -- Drive LF antenna at 12Mhz/(divisor+1)"},
2958 {"setmux", CmdSetMux, 0, "<loraw|hiraw|lopkd|hipkd> -- Set the ADC mux to a specific value"},
2959 {"sri512read", CmdSri512read, 0, "<int> -- Read contents of a SRI512 tag"},
2960 {"srix4kread", CmdSrix4kread, 0, "<int> -- Read contents of a SRIX4K tag"},
2961 {"tidemod", CmdTIDemod, 1, "Demodulate raw bits for TI-type LF tag"},
2962 {"tiread", CmdTIRead, 0, "Read and decode a TI 134 kHz tag"},
2963 {"tiwrite", CmdTIWrite, 0, "Write new data to a r/w TI 134 kHz tag"},
2964 {"threshold", CmdThreshold, 1, "Maximize/minimize every value in the graph window depending on threshold"},
2965 {"tune", CmdTune, 0, "Measure antenna tuning"},
2966 {"vchdemod", CmdVchdemod, 0, "['clone'] -- Demodulate samples for VeriChip"},
2967 {"version", CmdVersion, 0, "Show version inforation about the connected Proxmark"},
2968 {"zerocrossings", CmdZerocrossings, 1, "Count time between zero-crossings"},
2969 };
2970
2971 static struct {
2972 char *name;
2973 char *args;
2974 char *argshelp;
2975 char *description;
2976 } CommandExtendedHelp[]= {
2977 {"detectreader","'l'|'h'","'l' specifies LF antenna scan only, 'h' specifies HF antenna scan only.","Monitor antenna for changes in voltage. Output is in three fields: CHANGED, CURRENT, PERIOD,\nwhere CHANGED is the value just changed from, CURRENT is the current value and PERIOD is the\nnumber of program loops since the last change.\n\nThe RED LED indicates LF field detected, and the GREEN LED indicates HF field detected."},
2978 {"tune","","","Drive LF antenna at all divisor range values (19 - 255) and store the results in the output\nbuffer. Issuing 'losamples' and then 'plot' commands will display the resulting peak. 12MHz\ndivided by the peak's position plus one gives the antenna's resonant frequency. For convenience,\nthis value is also printed out by the command."},
2979 };
2980
2981 //-----------------------------------------------------------------------------
2982 // Entry point into our code: called whenever the user types a command and
2983 // then presses Enter, which the full command line that they typed.
2984 //-----------------------------------------------------------------------------
2985 void CommandReceived(char *cmd)
2986 {
2987 int i;
2988 char line[256];
2989
2990 PrintToScrollback("> %s", cmd);
2991
2992 if(strcmp(cmd, "help") == 0 || strncmp(cmd,"help ",strlen("help ")) == 0) {
2993 // check if we're doing extended help
2994 if(strlen(cmd) > strlen("help ")) {
2995 cmd += strlen("help ");
2996 for(i = 0; i < sizeof(CommandExtendedHelp) / sizeof(CommandExtendedHelp[0]); i++) {
2997 if(strcmp(CommandExtendedHelp[i].name,cmd) == 0) {
2998 PrintToScrollback("\nExtended help for '%s':\n", cmd);
2999 PrintToScrollback("Args: %s\t- %s\n",CommandExtendedHelp[i].args,CommandExtendedHelp[i].argshelp);
3000 PrintToScrollback(CommandExtendedHelp[i].description);
3001 PrintToScrollback("");
3002 return;
3003 }
3004 }
3005 PrintToScrollback("No extended help available for '%s'", cmd);
3006 return;
3007 }
3008 if (offline) PrintToScrollback("Operating in OFFLINE mode (no device connected)");
3009 PrintToScrollback("\r\nAvailable commands:");
3010 for(i = 0; i < sizeof(CommandTable) / sizeof(CommandTable[0]); i++) {
3011 if (offline && (CommandTable[i].offline==0)) continue;
3012 memset(line, ' ', sizeof(line));
3013 strcpy(line+2, CommandTable[i].name);
3014 line[strlen(line)] = ' ';
3015 sprintf(line+15, " -- %s", CommandTable[i].docString);
3016 PrintToScrollback("%s", line);
3017 }
3018 PrintToScrollback("");
3019 PrintToScrollback("'help <command>' for extended help on that command\n");
3020 return;
3021 }
3022
3023 for(i = 0; i < sizeof(CommandTable) / sizeof(CommandTable[0]); i++) {
3024 char *name = CommandTable[i].name;
3025 if(memcmp(cmd, name, strlen(name))==0 &&
3026 (cmd[strlen(name)] == ' ' || cmd[strlen(name)] == '\0'))
3027 {
3028 cmd += strlen(name);
3029 while(*cmd == ' ') {
3030 cmd++;
3031 }
3032 if (offline && (CommandTable[i].offline==0)) {
3033 PrintToScrollback("Offline mode, cannot use this command.");
3034 return;
3035 }
3036 (CommandTable[i].handler)(cmd);
3037 return;
3038 }
3039 }
3040 PrintToScrollback(">> bad command '%s'", cmd);
3041 }
3042
3043 //-----------------------------------------------------------------------------
3044 // Entry point into our code: called whenever we received a packet over USB
3045 // that we weren't necessarily expecting, for example a debug print.
3046 //-----------------------------------------------------------------------------
3047 void UsbCommandReceived(UsbCommand *c)
3048 {
3049 switch(c->cmd) {
3050 case CMD_DEBUG_PRINT_STRING: {
3051 char s[100];
3052 if(c->ext1 > 70 || c->ext1 < 0) {
3053 c->ext1 = 0;
3054 }
3055 memcpy(s, c->d.asBytes, c->ext1);
3056 s[c->ext1] = '\0';
3057 PrintToScrollback("#db# %s", s);
3058 break;
3059 }
3060
3061 case CMD_DEBUG_PRINT_INTEGERS:
3062 PrintToScrollback("#db# %08x, %08x, %08x\r\n", c->ext1, c->ext2, c->ext3);
3063 break;
3064
3065 case CMD_MEASURED_ANTENNA_TUNING: {
3066 int peakv, peakf;
3067 int vLf125, vLf134, vHf;
3068 vLf125 = c->ext1 & 0xffff;
3069 vLf134 = c->ext1 >> 16;
3070 vHf = c->ext2 & 0xffff;;
3071 peakf = c->ext3 & 0xffff;
3072 peakv = c->ext3 >> 16;
3073 PrintToScrollback("");
3074 PrintToScrollback("");
3075 PrintToScrollback("# LF antenna: %5.2f V @ 125.00 kHz", vLf125/1000.0);
3076 PrintToScrollback("# LF antenna: %5.2f V @ 134.00 kHz", vLf134/1000.0);
3077 PrintToScrollback("# LF optimal: %5.2f V @%9.2f kHz", peakv/1000.0, 12000.0/(peakf+1));
3078 PrintToScrollback("# HF antenna: %5.2f V @ 13.56 MHz", vHf/1000.0);
3079 if (peakv<2000)
3080 PrintToScrollback("# Your LF antenna is unusable.");
3081 else if (peakv<10000)
3082 PrintToScrollback("# Your LF antenna is marginal.");
3083 if (vHf<2000)
3084 PrintToScrollback("# Your HF antenna is unusable.");
3085 else if (vHf<5000)
3086 PrintToScrollback("# Your HF antenna is marginal.");
3087 break;
3088 }
3089 default:
3090 PrintToScrollback("unrecognized command %08x\n", c->cmd);
3091 break;
3092 }
3093 }
Impressum, Datenschutz