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