1 //-----------------------------------------------------------------------------
2 // Copyright (C) 2010 iZsh <izsh at fail0verflow.com>
4 // This code is licensed to you under the terms of the GNU GPL, version 2 or,
5 // at your option, any later version. See the LICENSE.txt file for the text of
7 //-----------------------------------------------------------------------------
8 // Data and Graph commands
9 //-----------------------------------------------------------------------------
19 #include "cmdparser.h"
23 static int CmdHelp(const char *Cmd
);
25 int CmdAmp(const char *Cmd
)
27 int i
, rising
, falling
;
28 int max
= INT_MIN
, min
= INT_MAX
;
30 for (i
= 10; i
< GraphTraceLen
; ++i
) {
31 if (GraphBuffer
[i
] > max
)
33 if (GraphBuffer
[i
] < min
)
39 for (i
= 0; i
< GraphTraceLen
; ++i
) {
40 if (GraphBuffer
[i
+ 1] < GraphBuffer
[i
]) {
47 if (GraphBuffer
[i
+ 1] > GraphBuffer
[i
]) {
61 * Generic command to demodulate ASK.
63 * Argument is convention: positive or negative (High mod means zero
64 * or high mod means one)
66 * Updates the Graph trace with 0/1 values
71 int Cmdaskdemod(const char *Cmd
)
74 int c
, high
= 0, low
= 0;
76 // TODO: complain if we do not give 2 arguments here !
77 // (AL - this doesn't make sense! we're only using one argument!!!)
78 sscanf(Cmd
, "%i", &c
);
80 /* Detect high and lows and clock */
82 for (i
= 0; i
< GraphTraceLen
; ++i
)
84 if (GraphBuffer
[i
] > high
)
85 high
= GraphBuffer
[i
];
86 else if (GraphBuffer
[i
] < low
)
89 if (c
!= 0 && c
!= 1) {
90 PrintAndLog("Invalid argument: %s", Cmd
);
94 if (GraphBuffer
[0] > 0) {
99 for (i
= 1; i
< GraphTraceLen
; ++i
) {
100 /* Transitions are detected at each peak
101 * Transitions are either:
102 * - we're low: transition if we hit a high
103 * - we're high: transition if we hit a low
104 * (we need to do it this way because some tags keep high or
105 * low for long periods, others just reach the peak and go
108 if ((GraphBuffer
[i
] == high
) && (GraphBuffer
[i
- 1] == c
)) {
109 GraphBuffer
[i
] = 1 - c
;
110 } else if ((GraphBuffer
[i
] == low
) && (GraphBuffer
[i
- 1] == (1 - c
))){
114 GraphBuffer
[i
] = GraphBuffer
[i
- 1];
117 RepaintGraphWindow();
121 int CmdAutoCorr(const char *Cmd
)
123 static int CorrelBuffer
[MAX_GRAPH_TRACE_LEN
];
125 int window
= atoi(Cmd
);
128 PrintAndLog("needs a window");
131 if (window
>= GraphTraceLen
) {
132 PrintAndLog("window must be smaller than trace (%d samples)",
137 PrintAndLog("performing %d correlations", GraphTraceLen
- window
);
139 for (int i
= 0; i
< GraphTraceLen
- window
; ++i
) {
141 for (int j
= 0; j
< window
; ++j
) {
142 sum
+= (GraphBuffer
[j
]*GraphBuffer
[i
+ j
]) / 256;
144 CorrelBuffer
[i
] = sum
;
146 GraphTraceLen
= GraphTraceLen
- window
;
147 memcpy(GraphBuffer
, CorrelBuffer
, GraphTraceLen
* sizeof (int));
149 RepaintGraphWindow();
153 int CmdBitsamples(const char *Cmd
)
158 for (int i
= 0; i
< n
; i
+= 12) {
159 UsbCommand c
= {CMD_DOWNLOAD_RAW_ADC_SAMPLES_125K
, {i
, 0, 0}};
161 WaitForResponse(CMD_DOWNLOADED_RAW_ADC_SAMPLES_125K
);
163 for (int j
= 0; j
< 48; j
++) {
164 for (int k
= 0; k
< 8; k
++) {
165 if(sample_buf
[j
] & (1 << (7 - k
))) {
166 GraphBuffer
[cnt
++] = 1;
168 GraphBuffer
[cnt
++] = 0;
174 RepaintGraphWindow();
179 * Convert to a bitstream
181 int CmdBitstream(const char *Cmd
)
189 int hithigh
, hitlow
, first
;
191 /* Detect high and lows and clock */
192 for (i
= 0; i
< GraphTraceLen
; ++i
)
194 if (GraphBuffer
[i
] > high
)
195 high
= GraphBuffer
[i
];
196 else if (GraphBuffer
[i
] < low
)
197 low
= GraphBuffer
[i
];
201 clock
= GetClock(Cmd
, high
, 1);
205 for (i
= 0; i
< (int)(gtl
/ clock
); ++i
)
210 /* Find out if we hit both high and low peaks */
211 for (j
= 0; j
< clock
; ++j
)
213 if (GraphBuffer
[(i
* clock
) + j
] == high
)
215 else if (GraphBuffer
[(i
* clock
) + j
] == low
)
217 /* it doesn't count if it's the first part of our read
218 because it's really just trailing from the last sequence */
219 if (first
&& (hithigh
|| hitlow
))
220 hithigh
= hitlow
= 0;
224 if (hithigh
&& hitlow
)
228 /* If we didn't hit both high and low peaks, we had a bit transition */
229 if (!hithigh
|| !hitlow
)
232 AppendGraph(0, clock
, bit
);
233 // for (j = 0; j < (int)(clock/2); j++)
234 // GraphBuffer[(i * clock) + j] = bit ^ 1;
235 // for (j = (int)(clock/2); j < clock; j++)
236 // GraphBuffer[(i * clock) + j] = bit;
239 RepaintGraphWindow();
243 int CmdBuffClear(const char *Cmd
)
245 UsbCommand c
= {CMD_BUFF_CLEAR
};
251 int CmdDec(const char *Cmd
)
253 for (int i
= 0; i
< (GraphTraceLen
/ 2); ++i
)
254 GraphBuffer
[i
] = GraphBuffer
[i
* 2];
256 PrintAndLog("decimated by 2");
257 RepaintGraphWindow();
261 /* Print our clock rate */
262 int CmdDetectClockRate(const char *Cmd
)
264 int clock
= DetectClock(0);
265 PrintAndLog("Auto-detected clock rate: %d", clock
);
269 int CmdFSKdemod(const char *Cmd
)
271 static const int LowTone
[] = {
272 1, 1, 1, 1, 1, -1, -1, -1, -1, -1,
273 1, 1, 1, 1, 1, -1, -1, -1, -1, -1,
274 1, 1, 1, 1, 1, -1, -1, -1, -1, -1,
275 1, 1, 1, 1, 1, -1, -1, -1, -1, -1,
276 1, 1, 1, 1, 1, -1, -1, -1, -1, -1
278 static const int HighTone
[] = {
279 1, 1, 1, 1, 1, -1, -1, -1, -1,
280 1, 1, 1, 1, -1, -1, -1, -1,
281 1, 1, 1, 1, -1, -1, -1, -1,
282 1, 1, 1, 1, -1, -1, -1, -1,
283 1, 1, 1, 1, -1, -1, -1, -1,
284 1, 1, 1, 1, -1, -1, -1, -1, -1,
287 int lowLen
= sizeof (LowTone
) / sizeof (int);
288 int highLen
= sizeof (HighTone
) / sizeof (int);
289 int convLen
= (highLen
> lowLen
) ? highLen
: lowLen
;
290 uint32_t hi
= 0, lo
= 0;
293 int minMark
= 0, maxMark
= 0;
295 for (i
= 0; i
< GraphTraceLen
- convLen
; ++i
) {
296 int lowSum
= 0, highSum
= 0;
298 for (j
= 0; j
< lowLen
; ++j
) {
299 lowSum
+= LowTone
[j
]*GraphBuffer
[i
+j
];
301 for (j
= 0; j
< highLen
; ++j
) {
302 highSum
+= HighTone
[j
] * GraphBuffer
[i
+ j
];
304 lowSum
= abs(100 * lowSum
/ lowLen
);
305 highSum
= abs(100 * highSum
/ highLen
);
306 GraphBuffer
[i
] = (highSum
<< 16) | lowSum
;
309 for(i
= 0; i
< GraphTraceLen
- convLen
- 16; ++i
) {
310 int lowTot
= 0, highTot
= 0;
311 // 10 and 8 are f_s divided by f_l and f_h, rounded
312 for (j
= 0; j
< 10; ++j
) {
313 lowTot
+= (GraphBuffer
[i
+j
] & 0xffff);
315 for (j
= 0; j
< 8; j
++) {
316 highTot
+= (GraphBuffer
[i
+ j
] >> 16);
318 GraphBuffer
[i
] = lowTot
- highTot
;
319 if (GraphBuffer
[i
] > maxMark
) maxMark
= GraphBuffer
[i
];
320 if (GraphBuffer
[i
] < minMark
) minMark
= GraphBuffer
[i
];
323 GraphTraceLen
-= (convLen
+ 16);
324 RepaintGraphWindow();
326 // Find bit-sync (3 lo followed by 3 high)
327 int max
= 0, maxPos
= 0;
328 for (i
= 0; i
< 6000; ++i
) {
330 for (j
= 0; j
< 3 * lowLen
; ++j
) {
331 dec
-= GraphBuffer
[i
+ j
];
333 for (; j
< 3 * (lowLen
+ highLen
); ++j
) {
334 dec
+= GraphBuffer
[i
+ j
];
342 // place start of bit sync marker in graph
343 GraphBuffer
[maxPos
] = maxMark
;
344 GraphBuffer
[maxPos
+ 1] = minMark
;
348 // place end of bit sync marker in graph
349 GraphBuffer
[maxPos
] = maxMark
;
350 GraphBuffer
[maxPos
+1] = minMark
;
352 PrintAndLog("actual data bits start at sample %d", maxPos
);
353 PrintAndLog("length %d/%d", highLen
, lowLen
);
356 bits
[sizeof(bits
)-1] = '\0';
358 // find bit pairs and manchester decode them
359 for (i
= 0; i
< arraylen(bits
) - 1; ++i
) {
361 for (j
= 0; j
< lowLen
; ++j
) {
362 dec
-= GraphBuffer
[maxPos
+ j
];
364 for (; j
< lowLen
+ highLen
; ++j
) {
365 dec
+= GraphBuffer
[maxPos
+ j
];
368 // place inter bit marker in graph
369 GraphBuffer
[maxPos
] = maxMark
;
370 GraphBuffer
[maxPos
+ 1] = minMark
;
372 // hi and lo form a 64 bit pair
373 hi
= (hi
<< 1) | (lo
>> 31);
375 // store decoded bit as binary (in hi/lo) and text (in bits[])
383 PrintAndLog("bits: '%s'", bits
);
384 PrintAndLog("hex: %08x %08x", hi
, lo
);
388 int CmdGrid(const char *Cmd
)
390 sscanf(Cmd
, "%i %i", &PlotGridX
, &PlotGridY
);
391 RepaintGraphWindow();
395 int CmdHexsamples(const char *Cmd
)
400 sscanf(Cmd
, "%i %i", &requested
, &offset
);
401 if (offset
% 4 != 0) {
402 PrintAndLog("Offset must be a multiple of 4");
409 if (requested
== 0) {
416 for (int i
= offset
; i
< n
+offset
; i
+= 12) {
417 UsbCommand c
= {CMD_DOWNLOAD_RAW_ADC_SAMPLES_125K
, {i
, 0, 0}};
419 WaitForResponse(CMD_DOWNLOADED_RAW_ADC_SAMPLES_125K
);
420 for (int j
= 0; j
< 48; j
+= 8) {
421 PrintAndLog("%02x %02x %02x %02x %02x %02x %02x %02x",
433 if (delivered
>= requested
)
436 if (delivered
>= requested
)
442 int CmdHide(const char *Cmd
)
448 int CmdHpf(const char *Cmd
)
453 for (i
= 10; i
< GraphTraceLen
; ++i
)
454 accum
+= GraphBuffer
[i
];
455 accum
/= (GraphTraceLen
- 10);
456 for (i
= 0; i
< GraphTraceLen
; ++i
)
457 GraphBuffer
[i
] -= accum
;
459 RepaintGraphWindow();
463 int CmdSamples(const char *Cmd
)
468 n
= strtol(Cmd
, NULL
, 0);
470 if (n
> 16000) n
= 16000;
472 PrintAndLog("Reading %d samples\n", n
);
473 for (int i
= 0; i
< n
; i
+= 12) {
474 UsbCommand c
= {CMD_DOWNLOAD_RAW_ADC_SAMPLES_125K
, {i
, 0, 0}};
476 WaitForResponse(CMD_DOWNLOADED_RAW_ADC_SAMPLES_125K
);
477 for (int j
= 0; j
< 48; j
++) {
478 GraphBuffer
[cnt
++] = ((int)sample_buf
[j
]) - 128;
481 PrintAndLog("Done!\n");
483 RepaintGraphWindow();
487 int CmdLoad(const char *Cmd
)
489 FILE *f
= fopen(Cmd
, "r");
491 PrintAndLog("couldn't open '%s'", Cmd
);
497 while (fgets(line
, sizeof (line
), f
)) {
498 GraphBuffer
[GraphTraceLen
] = atoi(line
);
502 PrintAndLog("loaded %d samples", GraphTraceLen
);
503 RepaintGraphWindow();
507 int CmdLtrim(const char *Cmd
)
511 for (int i
= ds
; i
< GraphTraceLen
; ++i
)
512 GraphBuffer
[i
-ds
] = GraphBuffer
[i
];
515 RepaintGraphWindow();
520 * Manchester demodulate a bitstream. The bitstream needs to be already in
521 * the GraphBuffer as 0 and 1 values
523 * Give the clock rate as argument in order to help the sync - the algorithm
524 * resyncs at each pulse anyway.
526 * Not optimized by any means, this is the 1st time I'm writing this type of
527 * routine, feel free to improve...
529 * 1st argument: clock rate (as number of samples per clock rate)
530 * Typical values can be 64, 32, 128...
532 int CmdManchesterDemod(const char *Cmd
)
540 int hithigh
, hitlow
, first
;
546 /* check if we're inverting output */
549 PrintAndLog("Inverting output");
554 while(*Cmd
== ' '); // in case a 2nd argument was given
557 /* Holds the decoded bitstream: each clock period contains 2 bits */
558 /* later simplified to 1 bit after manchester decoding. */
559 /* Add 10 bits to allow for noisy / uncertain traces without aborting */
560 /* int BitStream[GraphTraceLen*2/clock+10]; */
562 /* But it does not work if compiling on WIndows: therefore we just allocate a */
564 int BitStream
[MAX_GRAPH_TRACE_LEN
];
566 /* Detect high and lows */
567 for (i
= 0; i
< GraphTraceLen
; i
++)
569 if (GraphBuffer
[i
] > high
)
570 high
= GraphBuffer
[i
];
571 else if (GraphBuffer
[i
] < low
)
572 low
= GraphBuffer
[i
];
576 clock
= GetClock(Cmd
, high
, 1);
578 int tolerance
= clock
/4;
580 /* Detect first transition */
581 /* Lo-Hi (arbitrary) */
582 /* skip to the first high */
583 for (i
= 0; i
< GraphTraceLen
; i
++)
584 if (GraphBuffer
[i
] == high
)
586 /* now look for the first low */
587 for (; i
< GraphTraceLen
; i
++)
589 if (GraphBuffer
[i
] == low
)
596 /* If we're not working with 1/0s, demod based off clock */
599 bit
= 0; /* We assume the 1st bit is zero, it may not be
600 * the case: this routine (I think) has an init problem.
603 for (; i
< (int)(GraphTraceLen
/ clock
); i
++)
609 /* Find out if we hit both high and low peaks */
610 for (j
= 0; j
< clock
; j
++)
612 if (GraphBuffer
[(i
* clock
) + j
] == high
)
614 else if (GraphBuffer
[(i
* clock
) + j
] == low
)
617 /* it doesn't count if it's the first part of our read
618 because it's really just trailing from the last sequence */
619 if (first
&& (hithigh
|| hitlow
))
620 hithigh
= hitlow
= 0;
624 if (hithigh
&& hitlow
)
628 /* If we didn't hit both high and low peaks, we had a bit transition */
629 if (!hithigh
|| !hitlow
)
632 BitStream
[bit2idx
++] = bit
^ invert
;
636 /* standard 1/0 bitstream */
640 /* Then detect duration between 2 successive transitions */
641 for (bitidx
= 1; i
< GraphTraceLen
; i
++)
643 if (GraphBuffer
[i
-1] != GraphBuffer
[i
])
648 // Error check: if bitidx becomes too large, we do not
649 // have a Manchester encoded bitstream or the clock is really
651 if (bitidx
> (GraphTraceLen
*2/clock
+8) ) {
652 PrintAndLog("Error: the clock you gave is probably wrong, aborting.");
655 // Then switch depending on lc length:
656 // Tolerance is 1/4 of clock rate (arbitrary)
657 if (abs(lc
-clock
/2) < tolerance
) {
658 // Short pulse : either "1" or "0"
659 BitStream
[bitidx
++]=GraphBuffer
[i
-1];
660 } else if (abs(lc
-clock
) < tolerance
) {
661 // Long pulse: either "11" or "00"
662 BitStream
[bitidx
++]=GraphBuffer
[i
-1];
663 BitStream
[bitidx
++]=GraphBuffer
[i
-1];
667 PrintAndLog("Warning: Manchester decode error for pulse width detection.");
668 PrintAndLog("(too many of those messages mean either the stream is not Manchester encoded, or clock is wrong)");
672 PrintAndLog("Error: too many detection errors, aborting.");
679 // At this stage, we now have a bitstream of "01" ("1") or "10" ("0"), parse it into final decoded bitstream
680 // Actually, we overwrite BitStream with the new decoded bitstream, we just need to be careful
681 // to stop output at the final bitidx2 value, not bitidx
682 for (i
= 0; i
< bitidx
; i
+= 2) {
683 if ((BitStream
[i
] == 0) && (BitStream
[i
+1] == 1)) {
684 BitStream
[bit2idx
++] = 1 ^ invert
;
685 } else if ((BitStream
[i
] == 1) && (BitStream
[i
+1] == 0)) {
686 BitStream
[bit2idx
++] = 0 ^ invert
;
688 // We cannot end up in this state, this means we are unsynchronized,
692 PrintAndLog("Unsynchronized, resync...");
693 PrintAndLog("(too many of those messages mean the stream is not Manchester encoded)");
697 PrintAndLog("Error: too many decode errors, aborting.");
704 PrintAndLog("Manchester decoded bitstream");
705 // Now output the bitstream to the scrollback by line of 16 bits
706 for (i
= 0; i
< (bit2idx
-16); i
+=16) {
707 PrintAndLog("%i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i",
728 /* Modulate our data into manchester */
729 int CmdManchesterMod(const char *Cmd
)
733 int bit
, lastbit
, wave
;
736 clock
= GetClock(Cmd
, 0, 1);
740 for (i
= 0; i
< (int)(GraphTraceLen
/ clock
); i
++)
742 bit
= GraphBuffer
[i
* clock
] ^ 1;
744 for (j
= 0; j
< (int)(clock
/2); j
++)
745 GraphBuffer
[(i
* clock
) + j
] = bit
^ lastbit
^ wave
;
746 for (j
= (int)(clock
/2); j
< clock
; j
++)
747 GraphBuffer
[(i
* clock
) + j
] = bit
^ lastbit
^ wave
^ 1;
749 /* Keep track of how we start our wave and if we changed or not this time */
750 wave
^= bit
^ lastbit
;
754 RepaintGraphWindow();
758 int CmdNorm(const char *Cmd
)
761 int max
= INT_MIN
, min
= INT_MAX
;
763 for (i
= 10; i
< GraphTraceLen
; ++i
) {
764 if (GraphBuffer
[i
] > max
)
765 max
= GraphBuffer
[i
];
766 if (GraphBuffer
[i
] < min
)
767 min
= GraphBuffer
[i
];
771 for (i
= 0; i
< GraphTraceLen
; ++i
) {
772 GraphBuffer
[i
] = (GraphBuffer
[i
] - ((max
+ min
) / 2)) * 1000 /
776 RepaintGraphWindow();
780 int CmdPlot(const char *Cmd
)
786 int CmdSave(const char *Cmd
)
788 FILE *f
= fopen(Cmd
, "w");
790 PrintAndLog("couldn't open '%s'", Cmd
);
794 for (i
= 0; i
< GraphTraceLen
; i
++) {
795 fprintf(f
, "%d\n", GraphBuffer
[i
]);
798 PrintAndLog("saved to '%s'", Cmd
);
802 int CmdScale(const char *Cmd
)
804 CursorScaleFactor
= atoi(Cmd
);
805 if (CursorScaleFactor
== 0) {
806 PrintAndLog("bad, can't have zero scale");
807 CursorScaleFactor
= 1;
809 RepaintGraphWindow();
813 int CmdThreshold(const char *Cmd
)
815 int threshold
= atoi(Cmd
);
817 for (int i
= 0; i
< GraphTraceLen
; ++i
) {
818 if (GraphBuffer
[i
] >= threshold
)
823 RepaintGraphWindow();
827 int CmdZerocrossings(const char *Cmd
)
829 // Zero-crossings aren't meaningful unless the signal is zero-mean.
836 for (int i
= 0; i
< GraphTraceLen
; ++i
) {
837 if (GraphBuffer
[i
] * sign
>= 0) {
838 // No change in sign, reproduce the previous sample count.
840 GraphBuffer
[i
] = lastZc
;
842 // Change in sign, reset the sample count.
844 GraphBuffer
[i
] = lastZc
;
852 RepaintGraphWindow();
856 static command_t CommandTable
[] =
858 {"help", CmdHelp
, 1, "This help"},
859 {"amp", CmdAmp
, 1, "Amplify peaks"},
860 {"askdemod", Cmdaskdemod
, 1, "<0|1> -- Attempt to demodulate simple ASK tags"},
861 {"autocorr", CmdAutoCorr
, 1, "<window length> -- Autocorrelation over window"},
862 {"bitsamples", CmdBitsamples
, 0, "Get raw samples as bitstring"},
863 {"bitstream", CmdBitstream
, 1, "[clock rate] -- Convert waveform into a bitstream"},
864 {"buffclear", CmdBuffClear
, 1, "Clear sample buffer and graph window"},
865 {"dec", CmdDec
, 1, "Decimate samples"},
866 {"detectclock", CmdDetectClockRate
, 1, "Detect clock rate"},
867 {"fskdemod", CmdFSKdemod
, 1, "Demodulate graph window as a HID FSK"},
868 {"grid", CmdGrid
, 1, "<x> <y> -- overlay grid on graph window, use zero value to turn off either"},
869 {"hexsamples", CmdHexsamples
, 0, "<blocks> [<offset>] -- Dump big buffer as hex bytes"},
870 {"hide", CmdHide
, 1, "Hide graph window"},
871 {"hpf", CmdHpf
, 1, "Remove DC offset from trace"},
872 {"load", CmdLoad
, 1, "<filename> -- Load trace (to graph window"},
873 {"ltrim", CmdLtrim
, 1, "<samples> -- Trim samples from left of trace"},
874 {"mandemod", CmdManchesterDemod
, 1, "[i] [clock rate] -- Manchester demodulate binary stream (option 'i' to invert output)"},
875 {"manmod", CmdManchesterMod
, 1, "[clock rate] -- Manchester modulate a binary stream"},
876 {"norm", CmdNorm
, 1, "Normalize max/min to +/-500"},
877 {"plot", CmdPlot
, 1, "Show graph window"},
878 {"samples", CmdSamples
, 0, "[128 - 16000] -- Get raw samples for graph window"},
879 {"save", CmdSave
, 1, "<filename> -- Save trace (from graph window)"},
880 {"scale", CmdScale
, 1, "<int> -- Set cursor display scale"},
881 {"threshold", CmdThreshold
, 1, "<threshold> -- Maximize/minimize every value in the graph window depending on threshold"},
882 {"zerocrossings", CmdZerocrossings
, 1, "Count time between zero-crossings"},
883 {NULL
, NULL
, 0, NULL
}
886 int CmdData(const char *Cmd
)
888 CmdsParse(CommandTable
, Cmd
);
892 int CmdHelp(const char *Cmd
)
894 CmdsHelp(CommandTable
);