maur keys
[RRG-proxmark3.git] / armsrc / appmain.c
bloba419617d1bab2b0673147eb9c0b14817b15e90dd
1 //-----------------------------------------------------------------------------
2 // Jonathan Westhues, Mar 2006
3 // Edits by Gerhard de Koning Gans, Sep 2007 (##)
4 //
5 // This code is licensed to you under the terms of the GNU GPL, version 2 or,
6 // at your option, any later version. See the LICENSE.txt file for the text of
7 // the license.
8 //-----------------------------------------------------------------------------
9 // The main application code. This is the first thing called after start.c
10 // executes.
11 //-----------------------------------------------------------------------------
12 #include "appmain.h"
14 #include "clocks.h"
15 #include "usb_cdc.h"
16 #include "proxmark3_arm.h"
17 #include "dbprint.h"
18 #include "pmflash.h"
19 #include "fpga.h"
20 #include "fpga.h"
21 #include "fpgaloader.h"
22 #include "string.h"
23 #include "printf.h"
24 #include "legicrf.h"
25 #include "BigBuf.h"
26 #include "iso14443a.h"
27 #include "iso14443b.h"
28 #include "iso15693.h"
29 #include "thinfilm.h"
30 #include "felica.h"
31 #include "hitag2.h"
32 #include "hitagS.h"
33 #include "em4x50.h"
34 #include "em4x70.h"
35 #include "iclass.h"
36 #include "legicrfsim.h"
37 //#include "cryptorfsim.h"
38 #include "epa.h"
39 #include "hfsnoop.h"
40 #include "lfops.h"
41 #include "lfsampling.h"
42 #include "mifarecmd.h"
43 #include "mifaredesfire.h"
44 #include "mifaresim.h"
45 #include "pcf7931.h"
46 #include "Standalone/standalone.h"
47 #include "util.h"
48 #include "ticks.h"
49 #include "commonutil.h"
50 #include "crc16.h"
53 #ifdef WITH_LCD
54 #include "LCD_disabled.h"
55 #endif
57 #ifdef WITH_SMARTCARD
58 #include "i2c.h"
59 #endif
61 #ifdef WITH_FPC_USART
62 #include "usart.h"
63 #endif
65 #ifdef WITH_FLASH
66 #include "flashmem.h"
67 #include "spiffs.h"
68 #endif
70 int DBGLEVEL = DBG_ERROR;
71 uint8_t g_trigger = 0;
72 bool g_hf_field_active = false;
73 extern uint32_t _stack_start[], _stack_end[];
74 struct common_area common_area __attribute__((section(".commonarea")));
75 static int button_status = BUTTON_NO_CLICK;
76 static bool allow_send_wtx = false;
77 uint16_t tearoff_delay_us = 0;
78 bool tearoff_enabled = false;
80 int tearoff_hook(void) {
81 if (tearoff_enabled) {
82 if (tearoff_delay_us == 0) {
83 Dbprintf(_RED_("No tear-off delay configured!"));
84 return PM3_SUCCESS; // SUCCESS = the hook didn't do anything
86 SpinDelayUsPrecision(tearoff_delay_us);
87 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
88 tearoff_enabled = false;
89 Dbprintf(_YELLOW_("Tear-off triggered!"));
90 return PM3_ETEAROFF;
91 } else {
92 return PM3_SUCCESS; // SUCCESS = the hook didn't do anything
96 void hf_field_off(void) {
97 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
98 LEDsoff();
99 g_hf_field_active = false;
102 void send_wtx(uint16_t wtx) {
103 if (allow_send_wtx) {
104 reply_ng(CMD_WTX, PM3_SUCCESS, (uint8_t *)&wtx, sizeof(wtx));
108 //-----------------------------------------------------------------------------
109 // Read an ADC channel and block till it completes, then return the result
110 // in ADC units (0 to 1023). Also a routine to sum up a number of samples and
111 // return that.
112 //-----------------------------------------------------------------------------
113 static uint16_t ReadAdc(int ch) {
115 // Note: ADC_MODE_PRESCALE and ADC_MODE_SAMPLE_HOLD_TIME are set to the maximum allowed value.
116 // AMPL_HI is are high impedance (10MOhm || 1MOhm) output, the input capacitance of the ADC is 12pF (typical). This results in a time constant
117 // of RC = (0.91MOhm) * 12pF = 10.9us. Even after the maximum configurable sample&hold time of 40us the input capacitor will not be fully charged.
119 // The maths are:
120 // If there is a voltage v_in at the input, the voltage v_cap at the capacitor (this is what we are measuring) will be
122 // v_cap = v_in * (1 - exp(-SHTIM/RC)) = v_in * (1 - exp(-40us/10.9us)) = v_in * 0,97 (i.e. an error of 3%)
124 AT91C_BASE_ADC->ADC_CR = AT91C_ADC_SWRST;
125 AT91C_BASE_ADC->ADC_MR =
126 ADC_MODE_PRESCALE(63) // ADC_CLK = MCK / ((63+1) * 2) = 48MHz / 128 = 375kHz
127 | ADC_MODE_STARTUP_TIME(1) // Startup Time = (1+1) * 8 / ADC_CLK = 16 / 375kHz = 42,7us Note: must be > 20us
128 | ADC_MODE_SAMPLE_HOLD_TIME(15); // Sample & Hold Time SHTIM = 15 / ADC_CLK = 15 / 375kHz = 40us
130 AT91C_BASE_ADC->ADC_CHER = ADC_CHANNEL(ch);
131 AT91C_BASE_ADC->ADC_CR = AT91C_ADC_START;
133 while (!(AT91C_BASE_ADC->ADC_SR & ADC_END_OF_CONVERSION(ch))) {};
135 return (AT91C_BASE_ADC->ADC_CDR[ch] & 0x3FF);
138 // was static - merlok
139 uint16_t AvgAdc(int ch) {
140 return SumAdc(ch, 32) >> 5;
143 uint16_t SumAdc(int ch, int NbSamples) {
144 uint16_t a = 0;
145 for (uint8_t i = 0; i < NbSamples; i++)
146 a += ReadAdc(ch);
147 return (a + (NbSamples >> 1) - 1);
150 static void MeasureAntennaTuning(void) {
152 uint32_t peak = 0;
154 // in mVolt
155 struct p {
156 uint32_t v_lf134;
157 uint32_t v_lf125;
158 uint32_t v_lfconf;
159 uint32_t v_hf;
160 uint32_t peak_v;
161 uint32_t peak_f;
162 int divisor;
163 uint8_t results[256];
164 } PACKED payload;
166 memset(payload.results, 0, sizeof(payload.results));
168 sample_config *sc = getSamplingConfig();
169 payload.divisor = sc->divisor;
171 LED_B_ON();
174 * Sweeps the useful LF range of the proxmark from
175 * 46.8kHz (divisor=255) to 600kHz (divisor=19) and
176 * read the voltage in the antenna, the result left
177 * in the buffer is a graph which should clearly show
178 * the resonating frequency of your LF antenna
179 * ( hopefully around 95 if it is tuned to 125kHz!)
182 FpgaDownloadAndGo(FPGA_BITSTREAM_LF);
183 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_READER | FPGA_LF_ADC_READER_FIELD);
184 SpinDelay(50);
186 for (uint8_t i = 255; i >= 19; i--) {
187 WDT_HIT();
188 FpgaSendCommand(FPGA_CMD_SET_DIVISOR, i);
189 SpinDelay(20);
190 uint32_t adcval = ((MAX_ADC_LF_VOLTAGE * (SumAdc(ADC_CHAN_LF, 32) >> 1)) >> 14);
191 if (i == LF_DIVISOR_125)
192 payload.v_lf125 = adcval; // voltage at 125kHz
194 if (i == LF_DIVISOR_134)
195 payload.v_lf134 = adcval; // voltage at 134kHz
197 if (i == sc->divisor)
198 payload.v_lfconf = adcval; // voltage at `lf config --divisor`
200 payload.results[i] = adcval >> 9; // scale int to fit in byte for graphing purposes
202 if (payload.results[i] > peak) {
203 payload.peak_v = adcval;
204 payload.peak_f = i;
205 peak = payload.results[i];
209 LED_A_ON();
210 // Let the FPGA drive the high-frequency antenna around 13.56 MHz.
211 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
212 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER);
213 SpinDelay(50);
215 #if defined RDV4
216 payload.v_hf = (MAX_ADC_HF_VOLTAGE_RDV40 * SumAdc(ADC_CHAN_HF_RDV40, 32)) >> 15;
217 #else
218 payload.v_hf = (MAX_ADC_HF_VOLTAGE * SumAdc(ADC_CHAN_HF, 32)) >> 15;
219 #endif
221 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
222 reply_ng(CMD_MEASURE_ANTENNA_TUNING, PM3_SUCCESS, (uint8_t *)&payload, sizeof(payload));
223 LEDsoff();
226 // Measure HF in milliVolt
227 static uint16_t MeasureAntennaTuningHfData(void) {
229 #if defined RDV4
230 return (MAX_ADC_HF_VOLTAGE_RDV40 * SumAdc(ADC_CHAN_HF_RDV40, 32)) >> 15;
231 #else
232 return (MAX_ADC_HF_VOLTAGE * SumAdc(ADC_CHAN_HF, 32)) >> 15;
233 #endif
237 // Measure LF in milliVolt
238 static uint32_t MeasureAntennaTuningLfData(void) {
239 return (MAX_ADC_LF_VOLTAGE * (SumAdc(ADC_CHAN_LF, 32) >> 1)) >> 14;
242 void print_stack_usage(void) {
243 for (uint32_t *p = _stack_start; ; ++p) {
244 if (*p != 0xdeadbeef) {
245 Dbprintf(" Max stack usage......... %d / %d bytes", (uint32_t)_stack_end - (uint32_t)p, (uint32_t)_stack_end - (uint32_t)_stack_start);
246 break;
251 void ReadMem(int addr) {
252 const uint8_t *data = ((uint8_t *)addr);
254 Dbprintf("%x: %02x %02x %02x %02x %02x %02x %02x %02x", addr, data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7]);
257 /* osimage version information is linked in, cf commonutil.h */
258 /* bootrom version information is pointed to from _bootphase1_version_pointer */
259 extern uint32_t _bootphase1_version_pointer[], _flash_start[], _flash_end[], __data_src_start__[];
260 #ifdef WITH_NO_COMPRESSION
261 extern uint32_t _bootrom_end[], _bootrom_start[], __os_size__[];
262 #endif
263 static void SendVersion(void) {
264 char temp[PM3_CMD_DATA_SIZE - 12]; /* Limited data payload in USB packets */
265 char VersionString[PM3_CMD_DATA_SIZE - 12] = { '\0' };
267 /* Try to find the bootrom version information. Expect to find a pointer at
268 * symbol _bootphase1_version_pointer, perform slight sanity checks on the
269 * pointer, then use it.
271 // dummy casting to avoid "dereferencing type-punned pointer breaking strict-aliasing rules" errors
272 uint32_t bootrom_version_ptr = (uint32_t)_bootphase1_version_pointer;
273 char *bootrom_version = *(char **)(bootrom_version_ptr);
275 strncat(VersionString, " [ "_YELLOW_("ARM")" ]\n", sizeof(VersionString) - strlen(VersionString) - 1);
277 if ((uint32_t)bootrom_version < (uint32_t)_flash_start || (uint32_t)bootrom_version >= (uint32_t)_flash_end) {
278 strcat(VersionString, "bootrom version information appears invalid\n");
279 } else {
280 FormatVersionInformation(temp, sizeof(temp), " bootrom: ", bootrom_version);
281 strncat(VersionString, temp, sizeof(VersionString) - strlen(VersionString) - 1);
282 strncat(VersionString, "\n", sizeof(VersionString) - strlen(VersionString) - 1);
285 FormatVersionInformation(temp, sizeof(temp), " os: ", &version_information);
286 strncat(VersionString, temp, sizeof(VersionString) - strlen(VersionString) - 1);
287 strncat(VersionString, "\n", sizeof(VersionString) - strlen(VersionString) - 1);
289 #if defined(__clang__)
290 strncat(VersionString, " compiled with Clang/LLVM "__VERSION__"\n", sizeof(VersionString) - strlen(VersionString) - 1);
291 #elif defined(__GNUC__) || defined(__GNUG__)
292 strncat(VersionString, " compiled with GCC "__VERSION__"\n", sizeof(VersionString) - strlen(VersionString) - 1);
293 #endif
295 strncat(VersionString, "\n [ "_YELLOW_("FPGA")" ] \n ", sizeof(VersionString) - strlen(VersionString) - 1);
297 for (int i = 0; i < g_fpga_bitstream_num; i++) {
298 strncat(VersionString, g_fpga_version_information[i], sizeof(VersionString) - strlen(VersionString) - 1);
299 if (i < g_fpga_bitstream_num - 1) {
300 strncat(VersionString, "\n ", sizeof(VersionString) - strlen(VersionString) - 1);
303 #ifndef WITH_NO_COMPRESSION
304 // Send Chip ID and used flash memory
305 uint32_t text_and_rodata_section_size = (uint32_t)__data_src_start__ - (uint32_t)_flash_start;
306 uint32_t compressed_data_section_size = common_area.arg1;
307 #endif
309 struct p {
310 uint32_t id;
311 uint32_t section_size;
312 uint32_t versionstr_len;
313 char versionstr[PM3_CMD_DATA_SIZE - 12];
314 } PACKED;
316 struct p payload;
317 payload.id = *(AT91C_DBGU_CIDR);
318 #ifdef WITH_NO_COMPRESSION
319 payload.section_size = (uint32_t)_bootrom_end - (uint32_t)_bootrom_start + (uint32_t)__os_size__;
320 #else
321 payload.section_size = text_and_rodata_section_size + compressed_data_section_size;
322 #endif
323 payload.versionstr_len = strlen(VersionString) + 1;
324 memcpy(payload.versionstr, VersionString, payload.versionstr_len);
326 reply_ng(CMD_VERSION, PM3_SUCCESS, (uint8_t *)&payload, 12 + payload.versionstr_len);
329 static void TimingIntervalAcquisition(void) {
330 // trigger new acquisition by turning main oscillator off and on
331 mck_from_pll_to_slck();
332 mck_from_slck_to_pll();
333 // wait for MCFR and recompute RTMR scaler
334 StartTickCount();
337 static void print_debug_level(void) {
338 char dbglvlstr[20] = {0};
339 switch (DBGLEVEL) {
340 case DBG_NONE:
341 sprintf(dbglvlstr, "none");
342 break;
343 case DBG_ERROR:
344 sprintf(dbglvlstr, "error");
345 break;
346 case DBG_INFO:
347 sprintf(dbglvlstr, "info");
348 break;
349 case DBG_DEBUG:
350 sprintf(dbglvlstr, "debug");
351 break;
352 case DBG_EXTENDED:
353 sprintf(dbglvlstr, "extended");
354 break;
356 Dbprintf(" Debug log level......... %d ( " _YELLOW_("%s")" )", DBGLEVEL, dbglvlstr);
359 // measure the Connection Speed by sending SpeedTestBufferSize bytes to client and measuring the elapsed time.
360 // Note: this mimics GetFromBigbuf(), i.e. we have the overhead of the PacketCommandNG structure included.
361 static void printConnSpeed(void) {
362 DbpString(_CYAN_("Transfer Speed"));
363 Dbprintf(" Sending packets to client...");
365 #define CONN_SPEED_TEST_MIN_TIME 500 // in milliseconds
366 uint8_t *test_data = BigBuf_get_addr();
367 uint32_t start_time = GetTickCount();
368 uint32_t delta_time = 0;
369 uint32_t bytes_transferred = 0;
371 LED_B_ON();
373 while (delta_time < CONN_SPEED_TEST_MIN_TIME) {
374 reply_ng(CMD_DOWNLOADED_BIGBUF, PM3_SUCCESS, test_data, PM3_CMD_DATA_SIZE);
375 bytes_transferred += PM3_CMD_DATA_SIZE;
376 delta_time = GetTickCountDelta(start_time);
378 LED_B_OFF();
380 Dbprintf(" Time elapsed................... %dms", delta_time);
381 Dbprintf(" Bytes transferred.............. %d", bytes_transferred);
382 Dbprintf(" Transfer Speed PM3 -> Client... " _YELLOW_("%d") " bytes/s", 1000 * bytes_transferred / delta_time);
386 * Prints runtime information about the PM3.
388 static void SendStatus(void) {
389 BigBuf_print_status();
390 Fpga_print_status();
391 #ifdef WITH_FLASH
392 Flashmem_print_status();
393 #endif
394 #ifdef WITH_SMARTCARD
395 I2C_print_status();
396 #endif
397 #ifdef WITH_LF
398 printLFConfig(); // LF Sampling config
399 printT55xxConfig(); // LF T55XX Config
400 #endif
401 #ifdef WITH_ISO14443a
402 printHf14aConfig(); // HF 14a config
403 #endif
404 printConnSpeed();
405 DbpString(_CYAN_("Various"));
407 print_stack_usage();
408 print_debug_level();
410 tosend_t *ts = get_tosend();
411 Dbprintf(" ToSendMax............... %d", ts->max);
412 Dbprintf(" ToSend BUFFERSIZE....... %d", TOSEND_BUFFER_SIZE);
413 while ((AT91C_BASE_PMC->PMC_MCFR & AT91C_CKGR_MAINRDY) == 0); // Wait for MAINF value to become available...
414 uint16_t mainf = AT91C_BASE_PMC->PMC_MCFR & AT91C_CKGR_MAINF; // Get # main clocks within 16 slow clocks
415 Dbprintf(" Slow clock.............. %d Hz", (16 * MAINCK) / mainf);
416 uint32_t delta_time = 0;
417 uint32_t start_time = GetTickCount();
418 #define SLCK_CHECK_MS 50
419 SpinDelay(SLCK_CHECK_MS);
420 delta_time = GetTickCountDelta(start_time);
421 if ((delta_time < SLCK_CHECK_MS - 1) || (delta_time > SLCK_CHECK_MS + 1)) {
422 // error > 2% with SLCK_CHECK_MS=50
423 Dbprintf(_RED_(" Slow Clock speed change detected, TIA needed"));
424 Dbprintf(_YELLOW_(" Slow Clock actual speed seems closer to %d kHz"),
425 (16 * MAINCK / 1000) / mainf * delta_time / SLCK_CHECK_MS);
427 DbpString(_CYAN_("Installed StandAlone Mode"));
428 ModInfo();
430 #ifdef WITH_FLASH
431 Flashmem_print_info();
432 #endif
433 DbpString("");
434 reply_ng(CMD_STATUS, PM3_SUCCESS, NULL, 0);
437 static void SendCapabilities(void) {
438 capabilities_t capabilities;
439 capabilities.version = CAPABILITIES_VERSION;
440 capabilities.via_fpc = g_reply_via_fpc;
441 capabilities.via_usb = g_reply_via_usb;
442 capabilities.bigbuf_size = BigBuf_get_size();
443 capabilities.baudrate = 0; // no real baudrate for USB-CDC
444 #ifdef WITH_FPC_USART
445 if (g_reply_via_fpc)
446 capabilities.baudrate = g_usart_baudrate;
447 #endif
449 #ifdef WITH_FLASH
450 capabilities.compiled_with_flash = true;
451 capabilities.hw_available_flash = FlashInit();
452 #else
453 capabilities.compiled_with_flash = false;
454 capabilities.hw_available_flash = false;
455 #endif
456 #ifdef WITH_SMARTCARD
457 capabilities.compiled_with_smartcard = true;
458 uint8_t maj, min;
459 capabilities.hw_available_smartcard = I2C_get_version(&maj, &min) == PM3_SUCCESS;
460 #else
461 capabilities.compiled_with_smartcard = false;
462 capabilities.hw_available_smartcard = false;
463 #endif
464 #ifdef WITH_FPC_USART
465 capabilities.compiled_with_fpc_usart = true;
466 #else
467 capabilities.compiled_with_fpc_usart = false;
468 #endif
469 #ifdef WITH_FPC_USART_DEV
470 capabilities.compiled_with_fpc_usart_dev = true;
471 #else
472 capabilities.compiled_with_fpc_usart_dev = false;
473 #endif
474 #ifdef WITH_FPC_USART_HOST
475 capabilities.compiled_with_fpc_usart_host = true;
476 #else
477 capabilities.compiled_with_fpc_usart_host = false;
478 #endif
479 #ifdef WITH_LF
480 capabilities.compiled_with_lf = true;
481 #else
482 capabilities.compiled_with_lf = false;
483 #endif
484 #ifdef WITH_HITAG
485 capabilities.compiled_with_hitag = true;
486 #else
487 capabilities.compiled_with_hitag = false;
488 #endif
489 #ifdef WITH_EM4x50
490 capabilities.compiled_with_em4x50 = true;
491 #else
492 capabilities.compiled_with_em4x50 = false;
493 #endif
494 #ifdef WITH_EM4x70
495 capabilities.compiled_with_em4x70 = true;
496 #else
497 capabilities.compiled_with_em4x70 = false;
498 #endif
500 #ifdef WITH_HFSNIFF
501 capabilities.compiled_with_hfsniff = true;
502 #else
503 capabilities.compiled_with_hfsniff = false;
504 #endif
505 #ifdef WITH_HFPLOT
506 capabilities.compiled_with_hfplot = true;
507 #else
508 capabilities.compiled_with_hfplot = false;
509 #endif
510 #ifdef WITH_ISO14443a
511 capabilities.compiled_with_iso14443a = true;
512 #else
513 capabilities.compiled_with_iso14443a = false;
514 #endif
515 #ifdef WITH_ISO14443b
516 capabilities.compiled_with_iso14443b = true;
517 #else
518 capabilities.compiled_with_iso14443b = false;
519 #endif
520 #ifdef WITH_ISO15693
521 capabilities.compiled_with_iso15693 = true;
522 #else
523 capabilities.compiled_with_iso15693 = false;
524 #endif
525 #ifdef WITH_FELICA
526 capabilities.compiled_with_felica = true;
527 #else
528 capabilities.compiled_with_felica = false;
529 #endif
530 #ifdef WITH_LEGICRF
531 capabilities.compiled_with_legicrf = true;
532 #else
533 capabilities.compiled_with_legicrf = false;
534 #endif
535 #ifdef WITH_ICLASS
536 capabilities.compiled_with_iclass = true;
537 #else
538 capabilities.compiled_with_iclass = false;
539 #endif
540 #ifdef WITH_NFCBARCODE
541 capabilities.compiled_with_nfcbarcode = true;
542 #else
543 capabilities.compiled_with_nfcbarcode = false;
544 #endif
545 #ifdef WITH_LCD
546 capabilities.compiled_with_lcd = true;
547 #else
548 capabilities.compiled_with_lcd = false;
549 #endif
550 reply_ng(CMD_CAPABILITIES, PM3_SUCCESS, (uint8_t *)&capabilities, sizeof(capabilities));
553 // Show some leds in a pattern to identify StandAlone mod is running
554 void StandAloneMode(void) {
555 DbpString("");
556 DbpString("Stand-alone mode, no computer necessary");
557 SpinDown(50);
558 SpinDelay(50);
559 SpinUp(50);
560 SpinDelay(50);
561 SpinDown(50);
565 OBJECTIVE
566 Listen and detect an external reader. Determine the best location
567 for the antenna.
569 INSTRUCTIONS:
570 Inside the ListenReaderField() function, there is two mode.
571 By default, when you call the function, you will enter mode 1.
572 If you press the PM3 button one time, you will enter mode 2.
573 If you press the PM3 button a second time, you will exit the function.
575 DESCRIPTION OF MODE 1:
576 This mode just listens for an external reader field and lights up green
577 for HF and/or red for LF. This is the original mode of the detectreader
578 function.
580 DESCRIPTION OF MODE 2:
581 This mode will visually represent, using the LEDs, the actual strength of the
582 current compared to the maximum current detected. Basically, once you know
583 what kind of external reader is present, it will help you spot the best location to place
584 your antenna. You will probably not get some good results if there is a LF and a HF reader
585 at the same place! :-)
587 #define LIGHT_LEVELS 20
589 void ListenReaderField(uint8_t limit) {
590 #define LF_ONLY 1
591 #define HF_ONLY 2
592 #define REPORT_CHANGE 1000 // report new values only if they have changed at least by REPORT_CHANGE mV
594 uint16_t lf_av = 0, lf_av_new, lf_baseline = 0, lf_max = 0;
595 uint16_t hf_av = 0, hf_av_new, hf_baseline = 0, hf_max = 0;
596 uint16_t mode = 1, display_val, display_max;
598 // switch off FPGA - we don't want to measure our own signal
599 // 20180315 - iceman, why load this before and then turn off?
600 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
601 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
603 LEDsoff();
605 if (limit == LF_ONLY) {
606 lf_av = lf_max = (MAX_ADC_LF_VOLTAGE * SumAdc(ADC_CHAN_LF, 32)) >> 15;
607 Dbprintf("LF 125/134kHz Baseline: %dmV", lf_av);
608 lf_baseline = lf_av;
611 if (limit == HF_ONLY) {
613 #if defined RDV4
614 // iceman, useless, since we are measuring readerfield, not our field. My tests shows a max of 20v from a reader.
615 hf_av = hf_max = (MAX_ADC_HF_VOLTAGE_RDV40 * SumAdc(ADC_CHAN_HF_RDV40, 32)) >> 15;
616 #else
617 hf_av = hf_max = (MAX_ADC_HF_VOLTAGE * SumAdc(ADC_CHAN_HF, 32)) >> 15;
618 #endif
619 Dbprintf("HF 13.56MHz Baseline: %dmV", hf_av);
620 hf_baseline = hf_av;
623 for (;;) {
625 // Switch modes with button
626 if (BUTTON_PRESS()) {
627 SpinDelay(500);
628 switch (mode) {
629 case 1:
630 mode = 2;
631 DbpString("Signal Strength Mode");
632 break;
633 case 2:
634 default:
635 DbpString("Stopped");
636 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
637 LEDsoff();
638 return;
641 WDT_HIT();
643 if (limit == LF_ONLY) {
644 if (mode == 1) {
645 if (ABS(lf_av - lf_baseline) > REPORT_CHANGE)
646 LED_D_ON();
647 else
648 LED_D_OFF();
651 lf_av_new = (MAX_ADC_LF_VOLTAGE * SumAdc(ADC_CHAN_LF, 32)) >> 15;
652 // see if there's a significant change
653 if (ABS(lf_av - lf_av_new) > REPORT_CHANGE) {
654 Dbprintf("LF 125/134kHz Field Change: %5dmV", lf_av_new);
655 lf_av = lf_av_new;
656 if (lf_av > lf_max)
657 lf_max = lf_av;
661 if (limit == HF_ONLY) {
662 if (mode == 1) {
663 if (ABS(hf_av - hf_baseline) > REPORT_CHANGE)
664 LED_B_ON();
665 else
666 LED_B_OFF();
669 #if defined RDV4
670 hf_av_new = (MAX_ADC_HF_VOLTAGE_RDV40 * SumAdc(ADC_CHAN_HF_RDV40, 32)) >> 15;
671 #else
672 hf_av_new = (MAX_ADC_HF_VOLTAGE * SumAdc(ADC_CHAN_HF, 32)) >> 15;
673 #endif
674 // see if there's a significant change
675 if (ABS(hf_av - hf_av_new) > REPORT_CHANGE) {
676 Dbprintf("HF 13.56MHz Field Change: %5dmV", hf_av_new);
677 hf_av = hf_av_new;
678 if (hf_av > hf_max)
679 hf_max = hf_av;
683 if (mode == 2) {
684 if (limit == LF_ONLY) {
685 display_val = lf_av;
686 display_max = lf_max;
687 } else if (limit == HF_ONLY) {
688 display_val = hf_av;
689 display_max = hf_max;
690 } else { /* Pick one at random */
691 if ((hf_max - hf_baseline) > (lf_max - lf_baseline)) {
692 display_val = hf_av;
693 display_max = hf_max;
694 } else {
695 display_val = lf_av;
696 display_max = lf_max;
700 display_val = display_val * (4 * LIGHT_LEVELS) / MAX(1, display_max);
701 uint32_t duty_a = MIN(MAX(display_val, 0 * LIGHT_LEVELS), 1 * LIGHT_LEVELS) - 0 * LIGHT_LEVELS;
702 uint32_t duty_b = MIN(MAX(display_val, 1 * LIGHT_LEVELS), 2 * LIGHT_LEVELS) - 1 * LIGHT_LEVELS;
703 uint32_t duty_c = MIN(MAX(display_val, 2 * LIGHT_LEVELS), 3 * LIGHT_LEVELS) - 2 * LIGHT_LEVELS;
704 uint32_t duty_d = MIN(MAX(display_val, 3 * LIGHT_LEVELS), 4 * LIGHT_LEVELS) - 3 * LIGHT_LEVELS;
706 // LED A
707 if (duty_a == 0) {
708 LED_A_OFF();
709 } else if (duty_a == LIGHT_LEVELS) {
710 LED_A_ON();
711 } else {
712 LED_A_ON();
713 SpinDelay(duty_a);
714 LED_A_OFF();
715 SpinDelay(LIGHT_LEVELS - duty_a);
718 // LED B
719 if (duty_b == 0) {
720 LED_B_OFF();
721 } else if (duty_b == LIGHT_LEVELS) {
722 LED_B_ON();
723 } else {
724 LED_B_ON();
725 SpinDelay(duty_b);
726 LED_B_OFF();
727 SpinDelay(LIGHT_LEVELS - duty_b);
730 // LED C
731 if (duty_c == 0) {
732 LED_C_OFF();
733 } else if (duty_c == LIGHT_LEVELS) {
734 LED_C_ON();
735 } else {
736 LED_C_ON();
737 SpinDelay(duty_c);
738 LED_C_OFF();
739 SpinDelay(LIGHT_LEVELS - duty_c);
742 // LED D
743 if (duty_d == 0) {
744 LED_D_OFF();
745 } else if (duty_d == LIGHT_LEVELS) {
746 LED_D_ON();
747 } else {
748 LED_D_ON();
749 SpinDelay(duty_d);
750 LED_D_OFF();
751 SpinDelay(LIGHT_LEVELS - duty_d);
756 static void PacketReceived(PacketCommandNG *packet) {
758 if (packet->ng) {
759 Dbprintf("received NG frame with %d bytes payload, with command: 0x%04x", packet->length, cmd);
760 } else {
761 Dbprintf("received OLD frame of %d bytes, with command: 0x%04x and args: %d %d %d", packet->length, packet->cmd, packet->oldarg[0], packet->oldarg[1], packet->oldarg[2]);
765 switch (packet->cmd) {
766 case CMD_BREAK_LOOP:
767 break;
768 case CMD_QUIT_SESSION: {
769 g_reply_via_fpc = false;
770 g_reply_via_usb = false;
771 break;
773 // emulator
774 case CMD_SET_DBGMODE: {
775 DBGLEVEL = packet->data.asBytes[0];
776 print_debug_level();
777 reply_ng(CMD_SET_DBGMODE, PM3_SUCCESS, NULL, 0);
778 break;
780 case CMD_SET_TEAROFF: {
781 struct p {
782 uint16_t delay_us;
783 bool on;
784 bool off;
785 } PACKED;
786 struct p *payload = (struct p *)packet->data.asBytes;
787 if (payload->on && payload->off)
788 reply_ng(CMD_SET_TEAROFF, PM3_EINVARG, NULL, 0);
789 if (payload->on)
790 tearoff_enabled = true;
791 if (payload->off)
792 tearoff_enabled = false;
793 if (payload->delay_us > 0)
794 tearoff_delay_us = payload->delay_us;
795 reply_ng(CMD_SET_TEAROFF, PM3_SUCCESS, NULL, 0);
796 break;
798 // always available
799 case CMD_HF_DROPFIELD: {
800 hf_field_off();
801 break;
803 #ifdef WITH_LF
804 case CMD_LF_T55XX_SET_CONFIG: {
805 setT55xxConfig(packet->oldarg[0], (t55xx_configurations_t *) packet->data.asBytes);
806 break;
808 case CMD_LF_SAMPLING_PRINT_CONFIG: {
809 printLFConfig();
810 break;
812 case CMD_LF_SAMPLING_GET_CONFIG: {
813 sample_config *config = getSamplingConfig();
814 reply_ng(CMD_LF_SAMPLING_GET_CONFIG, PM3_SUCCESS, (uint8_t *)config, sizeof(sample_config));
815 break;
817 case CMD_LF_SAMPLING_SET_CONFIG: {
818 sample_config c;
819 memcpy(&c, packet->data.asBytes, sizeof(sample_config));
820 setSamplingConfig(&c);
821 // setSamplingConfig((sample_config *) packet->data.asBytes);
822 break;
824 case CMD_LF_ACQ_RAW_ADC: {
825 struct p {
826 uint32_t samples : 31;
827 bool verbose : 1;
828 } PACKED;
829 struct p *payload = (struct p *)packet->data.asBytes;
830 uint32_t bits = SampleLF(payload->verbose, payload->samples);
831 reply_ng(CMD_LF_ACQ_RAW_ADC, PM3_SUCCESS, (uint8_t *)&bits, sizeof(bits));
832 break;
834 case CMD_LF_MOD_THEN_ACQ_RAW_ADC: {
835 struct p {
836 uint32_t delay;
837 uint16_t period_0;
838 uint16_t period_1;
839 uint8_t symbol_extra[LF_CMDREAD_MAX_EXTRA_SYMBOLS];
840 uint16_t period_extra[LF_CMDREAD_MAX_EXTRA_SYMBOLS];
841 uint32_t samples : 31;
842 bool verbose : 1;
843 } PACKED;
844 struct p *payload = (struct p *)packet->data.asBytes;
845 uint8_t symbol_extra[LF_CMDREAD_MAX_EXTRA_SYMBOLS];
846 uint16_t period_extra[LF_CMDREAD_MAX_EXTRA_SYMBOLS];
847 memcpy(symbol_extra, payload->symbol_extra, sizeof(symbol_extra));
848 memcpy(period_extra, payload->period_extra, sizeof(period_extra));
849 ModThenAcquireRawAdcSamples125k(payload->delay, payload->period_0, payload->period_1, symbol_extra, period_extra, packet->data.asBytes + sizeof(struct p), payload->verbose, payload->samples);
850 break;
852 case CMD_LF_SNIFF_RAW_ADC: {
853 struct p {
854 uint32_t samples : 31;
855 bool verbose : 1;
856 } PACKED;
857 struct p *payload = (struct p *)packet->data.asBytes;
858 uint32_t bits = SniffLF(payload->verbose, payload->samples);
859 reply_ng(CMD_LF_SNIFF_RAW_ADC, PM3_SUCCESS, (uint8_t *)&bits, sizeof(bits));
860 break;
862 case CMD_LF_HID_WATCH: {
863 uint32_t high, low;
864 int res = lf_hid_watch(0, &high, &low);
865 reply_ng(CMD_LF_HID_WATCH, res, NULL, 0);
866 break;
868 case CMD_LF_HID_SIMULATE: {
869 lf_hidsim_t *payload = (lf_hidsim_t *)packet->data.asBytes;
870 CmdHIDsimTAG(payload->hi2, payload->hi, payload->lo, payload->longFMT, 1);
871 break;
873 case CMD_LF_FSK_SIMULATE: {
874 lf_fsksim_t *payload = (lf_fsksim_t *)packet->data.asBytes;
875 CmdFSKsimTAG(payload->fchigh, payload->fclow, payload->separator, payload->clock, packet->length - sizeof(lf_fsksim_t), payload->data, true);
876 break;
878 case CMD_LF_ASK_SIMULATE: {
879 lf_asksim_t *payload = (lf_asksim_t *)packet->data.asBytes;
880 CmdASKsimTAG(payload->encoding, payload->invert, payload->separator, payload->clock, packet->length - sizeof(lf_asksim_t), payload->data, true);
881 break;
883 case CMD_LF_PSK_SIMULATE: {
884 lf_psksim_t *payload = (lf_psksim_t *)packet->data.asBytes;
885 CmdPSKsimTAG(payload->carrier, payload->invert, payload->clock, packet->length - sizeof(lf_psksim_t), payload->data, true);
886 break;
888 case CMD_LF_NRZ_SIMULATE: {
889 lf_nrzsim_t *payload = (lf_nrzsim_t *)packet->data.asBytes;
890 CmdNRZsimTAG(payload->invert, payload->separator, payload->clock, packet->length - sizeof(lf_nrzsim_t), payload->data, true);
891 break;
893 case CMD_LF_HID_CLONE: {
894 lf_hidsim_t *payload = (lf_hidsim_t *)packet->data.asBytes;
895 CopyHIDtoT55x7(payload->hi2, payload->hi, payload->lo, payload->longFMT, payload->Q5, payload->EM);
896 break;
898 case CMD_LF_IO_WATCH: {
899 uint32_t high, low;
900 int res = lf_io_watch(0, &high, &low);
901 reply_ng(CMD_LF_IO_WATCH, res, NULL, 0);
902 break;
904 case CMD_LF_EM410X_WATCH: {
905 uint32_t high;
906 uint64_t low;
907 int res = lf_em410x_watch(0, &high, &low);
908 reply_ng(CMD_LF_EM410X_WATCH, res, NULL, 0);
909 break;
911 case CMD_LF_EM410X_WRITE: {
912 struct p {
913 uint8_t card;
914 uint8_t clock;
915 uint32_t high;
916 uint32_t low;
917 } PACKED;
918 struct p *payload = (struct p *)packet->data.asBytes;
919 int res = copy_em410x_to_t55xx(payload->card, payload->clock, payload->high, payload->low);
920 reply_ng(CMD_LF_EM410X_WRITE, res, NULL, 0);
921 break;
923 case CMD_LF_TI_READ: {
924 ReadTItag();
925 break;
927 case CMD_LF_TI_WRITE: {
928 struct p {
929 uint32_t high;
930 uint32_t low;
931 uint16_t crc;
932 } PACKED;
933 struct p *payload = (struct p *)packet->data.asBytes;
934 WriteTItag(payload->high, payload->low, packet->crc);
935 break;
937 case CMD_LF_SIMULATE: {
938 LED_A_ON();
939 struct p {
940 uint16_t len;
941 uint16_t gap;
942 } PACKED;
943 struct p *payload = (struct p *)packet->data.asBytes;
944 // length, start gap, led control
945 SimulateTagLowFrequency(payload->len, payload->gap, true);
946 reply_ng(CMD_LF_SIMULATE, PM3_EOPABORTED, NULL, 0);
947 LED_A_OFF();
948 break;
950 case CMD_LF_SIMULATE_BIDIR: {
951 SimulateTagLowFrequencyBidir(packet->oldarg[0], packet->oldarg[1]);
952 break;
954 case CMD_LF_T55XX_READBL: {
955 struct p {
956 uint32_t password;
957 uint8_t blockno;
958 uint8_t page;
959 bool pwdmode;
960 uint8_t downlink_mode;
961 } PACKED;
962 struct p *payload = (struct p *) packet->data.asBytes;
963 T55xxReadBlock(payload->page, payload->pwdmode, false, payload->blockno, payload->password, payload->downlink_mode);
964 break;
966 case CMD_LF_T55XX_WRITEBL: {
967 // uses NG format
968 T55xxWriteBlock(packet->data.asBytes);
969 break;
971 case CMD_LF_T55XX_DANGERRAW: {
972 T55xxDangerousRawTest(packet->data.asBytes);
973 break;
975 case CMD_LF_T55XX_WAKEUP: {
976 struct p {
977 uint32_t password;
978 uint8_t flags;
979 } PACKED;
980 struct p *payload = (struct p *) packet->data.asBytes;
981 T55xxWakeUp(payload->password, payload->flags);
982 break;
984 case CMD_LF_T55XX_RESET_READ: {
985 T55xxResetRead(packet->data.asBytes[0] & 0xff);
986 break;
988 case CMD_LF_T55XX_CHK_PWDS: {
989 T55xx_ChkPwds(packet->data.asBytes[0] & 0xff);
990 break;
992 case CMD_LF_PCF7931_READ: {
993 ReadPCF7931();
994 break;
996 case CMD_LF_PCF7931_WRITE: {
997 WritePCF7931(
998 packet->data.asBytes[0], packet->data.asBytes[1], packet->data.asBytes[2], packet->data.asBytes[3],
999 packet->data.asBytes[4], packet->data.asBytes[5], packet->data.asBytes[6], packet->data.asBytes[9],
1000 packet->data.asBytes[7] - 128, packet->data.asBytes[8] - 128,
1001 packet->oldarg[0],
1002 packet->oldarg[1],
1003 packet->oldarg[2]
1005 break;
1007 case CMD_LF_EM4X_LOGIN: {
1008 struct p {
1009 uint32_t password;
1010 } PACKED;
1011 struct p *payload = (struct p *) packet->data.asBytes;
1012 EM4xLogin(payload->password);
1013 break;
1015 case CMD_LF_EM4X_BF: {
1016 struct p {
1017 uint32_t start_pwd;
1018 uint32_t n;
1019 } PACKED;
1020 struct p *payload = (struct p *) packet->data.asBytes;
1021 EM4xBruteforce(payload->start_pwd, payload->n);
1022 break;
1024 case CMD_LF_EM4X_READWORD: {
1025 struct p {
1026 uint32_t password;
1027 uint8_t address;
1028 uint8_t usepwd;
1029 } PACKED;
1030 struct p *payload = (struct p *) packet->data.asBytes;
1031 EM4xReadWord(payload->address, payload->password, payload->usepwd);
1032 break;
1034 case CMD_LF_EM4X_WRITEWORD: {
1035 struct p {
1036 uint32_t password;
1037 uint32_t data;
1038 uint8_t address;
1039 uint8_t usepwd;
1040 } PACKED;
1041 struct p *payload = (struct p *) packet->data.asBytes;
1042 EM4xWriteWord(payload->address, payload->data, payload->password, payload->usepwd);
1043 break;
1045 case CMD_LF_EM4X_PROTECTWORD: {
1046 struct p {
1047 uint32_t password;
1048 uint32_t data;
1049 uint8_t usepwd;
1050 } PACKED;
1051 struct p *payload = (struct p *) packet->data.asBytes;
1052 EM4xProtectWord(payload->data, payload->password, payload->usepwd);
1053 break;
1055 case CMD_LF_AWID_WATCH: {
1056 uint32_t high, low;
1057 int res = lf_awid_watch(0, &high, &low);
1058 reply_ng(CMD_LF_AWID_WATCH, res, NULL, 0);
1059 break;
1061 case CMD_LF_VIKING_CLONE: {
1062 struct p {
1063 bool Q5;
1064 bool EM;
1065 uint8_t blocks[8];
1066 } PACKED;
1067 struct p *payload = (struct p *)packet->data.asBytes;
1068 CopyVikingtoT55xx(payload->blocks, payload->Q5, payload->EM);
1069 break;
1071 case CMD_LF_COTAG_READ: {
1072 struct p {
1073 uint8_t mode;
1074 } PACKED;
1075 struct p *payload = (struct p *)packet->data.asBytes;
1076 Cotag(payload->mode);
1077 break;
1079 #endif
1081 #ifdef WITH_HITAG
1082 case CMD_LF_HITAG_SNIFF: { // Eavesdrop Hitag tag, args = type
1083 SniffHitag2();
1084 // SniffHitag2(packet->oldarg[0]);
1085 reply_ng(CMD_LF_HITAG_SNIFF, PM3_SUCCESS, NULL, 0);
1086 break;
1088 case CMD_LF_HITAG_SIMULATE: { // Simulate Hitag tag, args = memory content
1089 SimulateHitag2();
1090 break;
1092 case CMD_LF_HITAG_READER: { // Reader for Hitag tags, args = type and function
1093 ReaderHitag((hitag_function)packet->oldarg[0], (hitag_data *)packet->data.asBytes);
1094 break;
1096 case CMD_LF_HITAGS_SIMULATE: { // Simulate Hitag s tag, args = memory content
1097 SimulateHitagSTag((bool)packet->oldarg[0], packet->data.asBytes);
1098 break;
1100 case CMD_LF_HITAGS_TEST_TRACES: { // Tests every challenge within the given file
1101 check_challenges((bool)packet->oldarg[0], packet->data.asBytes);
1102 break;
1104 case CMD_LF_HITAGS_READ: { //Reader for only Hitag S tags, args = key or challenge
1105 ReadHitagS((hitag_function)packet->oldarg[0], (hitag_data *)packet->data.asBytes);
1106 break;
1108 case CMD_LF_HITAGS_WRITE: { //writer for Hitag tags args=data to write,page and key or challenge
1109 if ((hitag_function)packet->oldarg[0] < 10) {
1110 WritePageHitagS((hitag_function)packet->oldarg[0], (hitag_data *)packet->data.asBytes, packet->oldarg[2]);
1111 } else {
1112 WriterHitag((hitag_function)packet->oldarg[0], (hitag_data *)packet->data.asBytes, packet->oldarg[2]);
1114 break;
1116 case CMD_LF_HITAG_ELOAD: {
1118 struct p {
1119 uint16_t len;
1120 uint8_t *data;
1121 } PACKED;
1122 struct p *payload = (struct p *) packet->data.asBytes;
1123 uint8_t *mem = BigBuf_get_EM_addr();
1124 memcpy((uint8_t *)mem.sectors, payload->data, payload->len);
1126 break;
1128 #endif
1130 #ifdef WITH_EM4x50
1131 case CMD_LF_EM4X50_INFO: {
1132 em4x50_info((em4x50_data_t *)packet->data.asBytes);
1133 break;
1135 case CMD_LF_EM4X50_WRITE: {
1136 em4x50_write((em4x50_data_t *)packet->data.asBytes);
1137 break;
1139 case CMD_LF_EM4X50_WRITEPWD: {
1140 em4x50_writepwd((em4x50_data_t *)packet->data.asBytes);
1141 break;
1143 case CMD_LF_EM4X50_READ: {
1144 em4x50_read((em4x50_data_t *)packet->data.asBytes);
1145 break;
1147 case CMD_LF_EM4X50_BRUTE: {
1148 em4x50_brute((em4x50_data_t *)packet->data.asBytes);
1149 break;
1151 case CMD_LF_EM4X50_LOGIN: {
1152 em4x50_login((uint32_t *)packet->data.asBytes);
1153 break;
1155 case CMD_LF_EM4X50_SIM: {
1156 //-----------------------------------------------------------------------------
1157 // Note: we call FpgaDownloadAndGo(FPGA_BITSTREAM_LF) here although FPGA is not
1158 // involved in dealing with emulator memory. But if it is called later, it might
1159 // destroy the Emulator Memory.
1160 //-----------------------------------------------------------------------------
1161 FpgaDownloadAndGo(FPGA_BITSTREAM_LF);
1162 em4x50_sim((uint32_t *)packet->data.asBytes);
1163 break;
1165 case CMD_LF_EM4X50_READER: {
1166 em4x50_reader();
1167 break;
1169 case CMD_LF_EM4X50_ESET: {
1170 //-----------------------------------------------------------------------------
1171 // Note: we call FpgaDownloadAndGo(FPGA_BITSTREAM_LF) here although FPGA is not
1172 // involved in dealing with emulator memory. But if it is called later, it might
1173 // destroy the Emulator Memory.
1174 //-----------------------------------------------------------------------------
1175 FpgaDownloadAndGo(FPGA_BITSTREAM_LF);
1176 emlSet(packet->data.asBytes, packet->oldarg[0], packet->oldarg[1]);
1177 break;
1179 case CMD_LF_EM4X50_CHK: {
1180 //-----------------------------------------------------------------------------
1181 // Note: we call FpgaDownloadAndGo(FPGA_BITSTREAM_LF) here although FPGA is not
1182 // involved in dealing with emulator memory. But if it is called later, it might
1183 // destroy the Emulator Memory.
1184 //-----------------------------------------------------------------------------
1185 FpgaDownloadAndGo(FPGA_BITSTREAM_LF);
1186 em4x50_chk((uint8_t *)packet->data.asBytes);
1187 break;
1189 #endif
1191 #ifdef WITH_EM4x70
1192 case CMD_LF_EM4X70_INFO: {
1193 em4x70_info((em4x70_data_t *)packet->data.asBytes);
1194 break;
1196 case CMD_LF_EM4X70_WRITE: {
1197 em4x70_write((em4x70_data_t *)packet->data.asBytes);
1198 break;
1200 case CMD_LF_EM4X70_UNLOCK: {
1201 em4x70_unlock((em4x70_data_t *)packet->data.asBytes);
1202 break;
1204 case CMD_LF_EM4X70_AUTH: {
1205 em4x70_auth((em4x70_data_t *)packet->data.asBytes);
1206 break;
1208 case CMD_LF_EM4X70_WRITEPIN: {
1209 em4x70_write_pin((em4x70_data_t *)packet->data.asBytes);
1210 break;
1212 case CMD_LF_EM4X70_WRITEKEY: {
1213 em4x70_write_key((em4x70_data_t *)packet->data.asBytes);
1214 break;
1216 #endif
1218 #ifdef WITH_ISO15693
1219 case CMD_HF_ISO15693_ACQ_RAW_ADC: {
1220 AcquireRawAdcSamplesIso15693();
1221 break;
1223 case CMD_HF_ISO15693_SNIFF: {
1224 SniffIso15693(0, NULL);
1225 reply_ng(CMD_HF_ISO15693_SNIFF, PM3_SUCCESS, NULL, 0);
1226 break;
1228 case CMD_HF_ISO15693_COMMAND: {
1229 DirectTag15693Command(packet->oldarg[0], packet->oldarg[1], packet->oldarg[2], packet->data.asBytes);
1230 break;
1232 case CMD_HF_ISO15693_FINDAFI: {
1233 BruteforceIso15693Afi(packet->oldarg[0]);
1234 break;
1236 case CMD_HF_ISO15693_READER: {
1237 ReaderIso15693(packet->oldarg[0], NULL);
1238 break;
1240 case CMD_HF_ISO15693_SIMULATE: {
1241 struct p {
1242 uint8_t uid[8];
1243 } PACKED;
1244 struct p *payload = (struct p *) packet->data.asBytes;
1245 SimTagIso15693(payload->uid);
1246 break;
1248 case CMD_HF_ISO15693_CSETUID: {
1249 struct p {
1250 uint8_t uid[8];
1251 } PACKED;
1252 struct p *payload = (struct p *) packet->data.asBytes;
1253 SetTag15693Uid(payload->uid);
1254 break;
1256 case CMD_HF_ISO15693_SLIX_L_DISABLE_PRIVACY: {
1257 struct p {
1258 uint8_t pwd[4];
1259 } PACKED;
1260 struct p *payload = (struct p *) packet->data.asBytes;
1261 DisablePrivacySlixLIso15693(payload->pwd);
1262 break;
1265 #endif
1267 #ifdef WITH_LEGICRF
1268 case CMD_HF_LEGIC_SIMULATE: {
1269 struct p {
1270 uint8_t tagtype;
1271 bool send_reply;
1272 } PACKED;
1273 struct p *payload = (struct p *) packet->data.asBytes;
1274 LegicRfSimulate(payload->tagtype, payload->send_reply);
1275 break;
1277 case CMD_HF_LEGIC_WRITER: {
1278 LegicRfWriter(packet->oldarg[0], packet->oldarg[1], packet->oldarg[2], packet->data.asBytes);
1279 break;
1281 case CMD_HF_LEGIC_READER: {
1282 LegicRfReader(packet->oldarg[0], packet->oldarg[1], packet->oldarg[2]);
1283 break;
1285 case CMD_HF_LEGIC_INFO: {
1286 LegicRfInfo();
1287 break;
1289 case CMD_HF_LEGIC_ESET: {
1290 //-----------------------------------------------------------------------------
1291 // Note: we call FpgaDownloadAndGo(FPGA_BITSTREAM_HF) here although FPGA is not
1292 // involved in dealing with emulator memory. But if it is called later, it might
1293 // destroy the Emulator Memory.
1294 //-----------------------------------------------------------------------------
1295 // arg0 = offset
1296 // arg1 = num of bytes
1297 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
1298 emlSet(packet->data.asBytes, packet->oldarg[0], packet->oldarg[1]);
1299 break;
1301 #endif
1303 #ifdef WITH_ISO14443b
1304 case CMD_HF_SRI_READ: {
1305 struct p {
1306 uint8_t blockno;
1307 } PACKED;
1308 struct p *payload = (struct p *) packet->data.asBytes;
1309 ReadSTBlock(payload->blockno);
1310 break;
1312 case CMD_HF_ISO14443B_SNIFF: {
1313 SniffIso14443b();
1314 reply_ng(CMD_HF_ISO14443B_SNIFF, PM3_SUCCESS, NULL, 0);
1315 break;
1317 case CMD_HF_ISO14443B_SIMULATE: {
1318 SimulateIso14443bTag(packet->data.asBytes);
1319 break;
1321 case CMD_HF_ISO14443B_COMMAND: {
1322 iso14b_raw_cmd_t *payload = (iso14b_raw_cmd_t *)packet->data.asBytes;
1323 SendRawCommand14443B_Ex(payload);
1324 break;
1326 case CMD_HF_CRYPTORF_SIM : {
1327 // simulate_crf_tag();
1328 break;
1330 #endif
1332 #ifdef WITH_FELICA
1333 case CMD_HF_FELICA_COMMAND: {
1334 felica_sendraw(packet);
1335 break;
1337 case CMD_HF_FELICALITE_SIMULATE: {
1338 struct p {
1339 uint8_t uid[8];
1340 } PACKED;
1341 struct p *payload = (struct p *) packet->data.asBytes;
1342 felica_sim_lite(payload->uid);
1343 break;
1345 case CMD_HF_FELICA_SNIFF: {
1346 struct p {
1347 uint32_t samples;
1348 uint32_t triggers;
1349 } PACKED;
1350 struct p *payload = (struct p *) packet->data.asBytes;
1351 felica_sniff(payload->samples, payload->triggers);
1352 break;
1354 case CMD_HF_FELICALITE_DUMP: {
1355 felica_dump_lite_s();
1356 break;
1358 #endif
1360 #ifdef WITH_ISO14443a
1361 case CMD_HF_ISO14443A_PRINT_CONFIG: {
1362 printHf14aConfig();
1363 break;
1365 case CMD_HF_ISO14443A_GET_CONFIG: {
1366 hf14a_config *hf14aconfig = getHf14aConfig();
1367 reply_ng(CMD_HF_ISO14443A_GET_CONFIG, PM3_SUCCESS, (uint8_t *)hf14aconfig, sizeof(hf14a_config));
1368 break;
1370 case CMD_HF_ISO14443A_SET_CONFIG: {
1371 hf14a_config c;
1372 memcpy(&c, packet->data.asBytes, sizeof(hf14a_config));
1373 setHf14aConfig(&c);
1374 break;
1376 case CMD_HF_ISO14443A_SNIFF: {
1377 SniffIso14443a(packet->data.asBytes[0]);
1378 reply_ng(CMD_HF_ISO14443A_SNIFF, PM3_SUCCESS, NULL, 0);
1379 break;
1381 case CMD_HF_ISO14443A_READER: {
1382 ReaderIso14443a(packet);
1383 break;
1385 case CMD_HF_ISO14443A_SIMULATE: {
1386 struct p {
1387 uint8_t tagtype;
1388 uint8_t flags;
1389 uint8_t uid[10];
1390 uint8_t exitAfter;
1391 } PACKED;
1392 struct p *payload = (struct p *) packet->data.asBytes;
1393 SimulateIso14443aTag(payload->tagtype, payload->flags, payload->uid, payload->exitAfter); // ## Simulate iso14443a tag - pass tag type & UID
1394 break;
1396 case CMD_HF_ISO14443A_ANTIFUZZ: {
1397 struct p {
1398 uint8_t flag;
1399 } PACKED;
1400 struct p *payload = (struct p *) packet->data.asBytes;
1401 iso14443a_antifuzz(payload->flag);
1402 break;
1404 case CMD_HF_EPA_COLLECT_NONCE: {
1405 EPA_PACE_Collect_Nonce(packet);
1406 break;
1408 case CMD_HF_EPA_REPLAY: {
1409 EPA_PACE_Replay(packet);
1410 break;
1412 case CMD_HF_MIFARE_READER: {
1413 struct p {
1414 uint8_t first_run;
1415 uint8_t blockno;
1416 uint8_t key_type;
1417 } PACKED;
1418 struct p *payload = (struct p *) packet->data.asBytes;
1419 ReaderMifare(payload->first_run, payload->blockno, payload->key_type);
1420 break;
1422 case CMD_HF_MIFARE_READBL: {
1423 mf_readblock_t *payload = (mf_readblock_t *)packet->data.asBytes;
1424 MifareReadBlock(payload->blockno, payload->keytype, payload->key);
1425 break;
1427 case CMD_HF_MIFAREU_READBL: {
1428 MifareUReadBlock(packet->oldarg[0], packet->oldarg[1], packet->data.asBytes);
1429 break;
1431 case CMD_HF_MIFAREUC_AUTH: {
1432 MifareUC_Auth(packet->oldarg[0], packet->data.asBytes);
1433 break;
1435 case CMD_HF_MIFAREU_READCARD: {
1436 MifareUReadCard(packet->oldarg[0], packet->oldarg[1], packet->oldarg[2], packet->data.asBytes);
1437 break;
1439 case CMD_HF_MIFAREUC_SETPWD: {
1440 MifareUSetPwd(packet->oldarg[0], packet->data.asBytes);
1441 break;
1443 case CMD_HF_MIFARE_READSC: {
1444 MifareReadSector(packet->oldarg[0], packet->oldarg[1], packet->data.asBytes);
1445 break;
1447 case CMD_HF_MIFARE_WRITEBL: {
1448 MifareWriteBlock(packet->oldarg[0], packet->oldarg[1], packet->data.asBytes);
1449 break;
1451 case CMD_HF_MIFAREU_WRITEBL: {
1452 MifareUWriteBlock(packet->oldarg[0], packet->oldarg[1], packet->data.asBytes);
1453 break;
1455 case CMD_HF_MIFAREU_WRITEBL_COMPAT: {
1456 MifareUWriteBlockCompat(packet->oldarg[0], packet->oldarg[1], packet->data.asBytes);
1457 break;
1459 case CMD_HF_MIFARE_ACQ_ENCRYPTED_NONCES: {
1460 MifareAcquireEncryptedNonces(packet->oldarg[0], packet->oldarg[1], packet->oldarg[2], packet->data.asBytes);
1461 break;
1463 case CMD_HF_MIFARE_ACQ_NONCES: {
1464 MifareAcquireNonces(packet->oldarg[0], packet->oldarg[2]);
1465 break;
1467 case CMD_HF_MIFARE_NESTED: {
1468 struct p {
1469 uint8_t block;
1470 uint8_t keytype;
1471 uint8_t target_block;
1472 uint8_t target_keytype;
1473 bool calibrate;
1474 uint8_t key[6];
1475 } PACKED;
1476 struct p *payload = (struct p *) packet->data.asBytes;
1477 MifareNested(payload->block, payload->keytype, payload->target_block, payload->target_keytype, payload->calibrate, payload->key);
1478 break;
1480 case CMD_HF_MIFARE_STATIC_NESTED: {
1481 struct p {
1482 uint8_t block;
1483 uint8_t keytype;
1484 uint8_t target_block;
1485 uint8_t target_keytype;
1486 uint8_t key[6];
1487 } PACKED;
1488 struct p *payload = (struct p *) packet->data.asBytes;
1489 MifareStaticNested(payload->block, payload->keytype, payload->target_block, payload->target_keytype, payload->key);
1490 break;
1492 case CMD_HF_MIFARE_CHKKEYS: {
1493 MifareChkKeys(packet->data.asBytes, false);
1494 break;
1496 case CMD_HF_MIFARE_CHKKEYS_FAST: {
1497 MifareChkKeys_fast(packet->oldarg[0], packet->oldarg[1], packet->oldarg[2], packet->data.asBytes);
1498 break;
1500 case CMD_HF_MIFARE_CHKKEYS_FILE: {
1501 struct p {
1502 uint8_t filename[32];
1503 } PACKED;
1504 struct p *payload = (struct p *) packet->data.asBytes;
1505 MifareChkKeys_file(payload->filename);
1506 break;
1508 case CMD_HF_MIFARE_SIMULATE: {
1509 struct p {
1510 uint16_t flags;
1511 uint8_t exitAfter;
1512 uint8_t uid[10];
1513 uint16_t atqa;
1514 uint8_t sak;
1515 } PACKED;
1516 struct p *payload = (struct p *) packet->data.asBytes;
1517 Mifare1ksim(payload->flags, payload->exitAfter, payload->uid, payload->atqa, payload->sak);
1518 break;
1520 case CMD_HF_MIFARE_EML_MEMCLR: {
1521 MifareEMemClr();
1522 reply_ng(CMD_HF_MIFARE_EML_MEMCLR, PM3_SUCCESS, NULL, 0);
1523 break;
1525 case CMD_HF_MIFARE_EML_MEMSET: {
1526 struct p {
1527 uint8_t blockno;
1528 uint8_t blockcnt;
1529 uint8_t blockwidth;
1530 uint8_t data[];
1531 } PACKED;
1532 struct p *payload = (struct p *) packet->data.asBytes;
1533 MifareEMemSet(payload->blockno, payload->blockcnt, payload->blockwidth, payload->data);
1534 break;
1536 case CMD_HF_MIFARE_EML_MEMGET: {
1537 struct p {
1538 uint8_t blockno;
1539 uint8_t blockcnt;
1540 } PACKED;
1541 struct p *payload = (struct p *) packet->data.asBytes;
1542 MifareEMemGet(payload->blockno, payload->blockcnt);
1543 break;
1545 case CMD_HF_MIFARE_EML_LOAD: {
1546 mfc_eload_t *payload = (mfc_eload_t *) packet->data.asBytes;
1547 MifareECardLoadExt(payload->sectorcnt, payload->keytype);
1548 break;
1550 // Work with "magic Chinese" card
1551 case CMD_HF_MIFARE_CSETBL: {
1552 MifareCSetBlock(packet->oldarg[0], packet->oldarg[1], packet->data.asBytes);
1553 break;
1555 case CMD_HF_MIFARE_CGETBL: {
1556 MifareCGetBlock(packet->oldarg[0], packet->oldarg[1], packet->data.asBytes);
1557 break;
1559 case CMD_HF_MIFARE_CIDENT: {
1560 bool is_mfc = packet->data.asBytes[0];
1561 MifareCIdent(is_mfc);
1562 break;
1564 // Gen 3 magic cards
1565 case CMD_HF_MIFARE_GEN3UID: {
1566 MifareGen3UID(packet->oldarg[0], packet->data.asBytes);
1567 break;
1569 case CMD_HF_MIFARE_GEN3BLK: {
1570 MifareGen3Blk(packet->oldarg[0], packet->data.asBytes);
1571 break;
1573 case CMD_HF_MIFARE_GEN3FREEZ: {
1574 MifareGen3Freez();
1575 break;
1577 case CMD_HF_MIFARE_PERSONALIZE_UID: {
1578 struct p {
1579 uint8_t keytype;
1580 uint8_t pers_option;
1581 uint8_t key[6];
1582 } PACKED;
1583 struct p *payload = (struct p *) packet->data.asBytes;
1584 uint64_t authkey = bytes_to_num(payload->key, 6);
1585 MifarePersonalizeUID(payload->keytype, payload->pers_option, authkey);
1586 break;
1588 case CMD_HF_MIFARE_SETMOD: {
1589 MifareSetMod(packet->data.asBytes);
1590 break;
1592 //mifare desfire
1593 case CMD_HF_DESFIRE_READBL: {
1594 break;
1596 case CMD_HF_DESFIRE_WRITEBL: {
1597 break;
1599 case CMD_HF_DESFIRE_AUTH1: {
1600 MifareDES_Auth1(packet->data.asBytes);
1601 break;
1603 case CMD_HF_DESFIRE_AUTH2: {
1604 //MifareDES_Auth2(packet->oldarg[0],packet->data.asBytes);
1605 break;
1607 case CMD_HF_DESFIRE_READER: {
1608 //readermifaredes(packet->oldarg[0], packet->oldarg[1], packet->data.asBytes);
1609 break;
1611 case CMD_HF_DESFIRE_INFO: {
1612 MifareDesfireGetInformation();
1613 break;
1615 case CMD_HF_DESFIRE_COMMAND: {
1616 MifareSendCommand(packet->data.asBytes);
1617 break;
1619 case CMD_HF_MIFARE_NACK_DETECT: {
1620 DetectNACKbug();
1621 break;
1623 case CMD_HF_MFU_OTP_TEAROFF: {
1624 MifareU_Otp_Tearoff(packet->oldarg[0], packet->oldarg[1], packet->data.asBytes);
1625 break;
1627 case CMD_HF_MFU_COUNTER_TEAROFF: {
1628 struct p {
1629 uint8_t counter;
1630 uint32_t tearoff_time;
1631 uint8_t value[4];
1632 } PACKED;
1633 struct p *payload = (struct p *) packet->data.asBytes;
1634 MifareU_Counter_Tearoff(payload->counter, payload->tearoff_time, payload->value);
1635 break;
1637 case CMD_HF_MIFARE_STATIC_NONCE: {
1638 MifareHasStaticNonce();
1639 break;
1641 #endif
1643 #ifdef WITH_NFCBARCODE
1644 case CMD_HF_THINFILM_READ: {
1645 ReadThinFilm();
1646 break;
1648 case CMD_HF_THINFILM_SIMULATE: {
1649 SimulateThinFilm(packet->data.asBytes, packet->length);
1650 break;
1652 #endif
1654 #ifdef WITH_ICLASS
1655 // Makes use of ISO14443a FPGA Firmware
1656 case CMD_HF_ICLASS_SNIFF: {
1657 struct p {
1658 uint8_t jam_search_len;
1659 uint8_t jam_search_string[];
1660 } PACKED;
1661 struct p *payload = (struct p *) packet->data.asBytes;
1662 SniffIClass(payload->jam_search_len, payload->jam_search_string);
1663 reply_ng(CMD_HF_ICLASS_SNIFF, PM3_SUCCESS, NULL, 0);
1664 break;
1666 case CMD_HF_ICLASS_SIMULATE: {
1668 struct p {
1669 uint8_t reader[4];
1670 uint8_t mac[4];
1671 } PACKED;
1672 struct p *payload = (struct p *) packet->data.asBytes;
1675 SimulateIClass(packet->oldarg[0], packet->oldarg[1], packet->oldarg[2], packet->data.asBytes);
1676 break;
1678 case CMD_HF_ICLASS_READER: {
1679 ReaderIClass(packet->oldarg[0]);
1680 break;
1682 case CMD_HF_ICLASS_EML_MEMSET: {
1683 //iceman, should call FPGADOWNLOAD before, since it corrupts BigBuf
1684 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
1685 struct p {
1686 uint16_t offset;
1687 uint16_t len;
1688 uint8_t data[];
1689 } PACKED;
1690 struct p *payload = (struct p *) packet->data.asBytes;
1691 emlSet(payload->data, payload->offset, payload->len);
1692 break;
1694 case CMD_HF_ICLASS_WRITEBL: {
1695 iClass_WriteBlock(packet->data.asBytes);
1696 break;
1698 case CMD_HF_ICLASS_READBL: {
1699 iClass_ReadBlock(packet->data.asBytes);
1700 break;
1702 case CMD_HF_ICLASS_CHKKEYS: {
1703 iClass_Authentication_fast((iclass_chk_t *)packet->data.asBytes);
1704 break;
1706 case CMD_HF_ICLASS_DUMP: {
1707 iClass_Dump(packet->data.asBytes);
1708 break;
1710 case CMD_HF_ICLASS_RESTORE: {
1711 iClass_Restore((iclass_restore_req_t *)packet->data.asBytes);
1712 break;
1714 #endif
1716 #ifdef WITH_HFSNIFF
1717 case CMD_HF_SNIFF: {
1718 struct p {
1719 uint32_t samplesToSkip;
1720 uint32_t triggersToSkip;
1721 } PACKED;
1722 struct p *payload = (struct p *)packet->data.asBytes;
1724 uint16_t len = 0;
1725 int res = HfSniff(payload->samplesToSkip, payload->triggersToSkip, &len);
1727 struct {
1728 uint16_t len;
1729 } PACKED retval;
1730 retval.len = len;
1731 reply_ng(CMD_HF_SNIFF, res, (uint8_t *)&retval, sizeof(retval));
1732 break;
1734 #endif
1736 #ifdef WITH_HFPLOT
1737 case CMD_FPGAMEM_DOWNLOAD: {
1738 HfPlotDownload();
1739 break;
1741 #endif
1743 #ifdef WITH_SMARTCARD
1744 case CMD_SMART_ATR: {
1745 SmartCardAtr();
1746 break;
1748 case CMD_SMART_SETBAUD: {
1749 SmartCardSetBaud(packet->oldarg[0]);
1750 break;
1752 case CMD_SMART_SETCLOCK: {
1753 struct p {
1754 uint32_t new_clk;
1755 } PACKED;
1756 struct p *payload = (struct p *)packet->data.asBytes;
1757 SmartCardSetClock(payload->new_clk);
1758 break;
1760 case CMD_SMART_RAW: {
1761 SmartCardRaw((smart_card_raw_t *)packet->data.asBytes);
1762 break;
1764 case CMD_SMART_UPLOAD: {
1765 // upload file from client
1766 struct p {
1767 uint32_t idx;
1768 uint32_t bytes_in_packet;
1769 uint16_t crc;
1770 uint8_t data[400];
1771 } PACKED;
1772 struct p *payload = (struct p *)packet->data.asBytes;
1773 uint8_t *mem = BigBuf_get_addr();
1774 memcpy(mem + payload->idx, payload->data, payload->bytes_in_packet);
1776 uint8_t a = 0, b = 0;
1777 compute_crc(CRC_14443_A, mem + payload->idx, payload->bytes_in_packet, &a, &b);
1778 int res = PM3_SUCCESS;
1779 if (payload->crc != (a << 8 | b)) {
1780 DbpString("CRC Failed");
1781 res = PM3_ESOFT;
1783 reply_ng(CMD_SMART_UPLOAD, res, NULL, 0);
1784 break;
1786 case CMD_SMART_UPGRADE: {
1787 struct p {
1788 uint16_t fw_size;
1789 uint16_t crc;
1790 } PACKED;
1791 struct p *payload = (struct p *)packet->data.asBytes;
1793 uint8_t *fwdata = BigBuf_get_addr();
1794 uint8_t a = 0, b = 0;
1795 compute_crc(CRC_14443_A, fwdata, payload->fw_size, &a, &b);
1797 if (payload->crc != (a << 8 | b)) {
1798 Dbprintf("CRC Failed, 0x[%04x] != 0x[%02x%02x]", payload->crc, a, b);
1799 reply_ng(CMD_SMART_UPGRADE, PM3_ESOFT, NULL, 0);
1800 } else {
1801 SmartCardUpgrade(payload->fw_size);
1803 fwdata = NULL;
1804 break;
1806 #endif
1808 #ifdef WITH_FPC_USART
1809 case CMD_USART_TX: {
1810 LED_B_ON();
1811 usart_writebuffer_sync(packet->data.asBytes, packet->length);
1812 reply_ng(CMD_USART_TX, PM3_SUCCESS, NULL, 0);
1813 LED_B_OFF();
1814 break;
1816 case CMD_USART_RX: {
1817 LED_B_ON();
1818 struct p {
1819 uint32_t waittime;
1820 } PACKED;
1821 struct p *payload = (struct p *) &packet->data.asBytes;
1822 uint16_t available;
1823 uint16_t pre_available = 0;
1824 uint8_t *dest = BigBuf_malloc(USART_FIFOLEN);
1825 uint32_t wait = payload->waittime;
1826 uint32_t ti = GetTickCount();
1827 while (true) {
1828 WaitMS(50);
1829 available = usart_rxdata_available();
1830 if (available > pre_available) {
1831 // When receiving data, reset timer and shorten timeout
1832 ti = GetTickCount();
1833 wait = 50;
1834 pre_available = available;
1835 continue;
1837 // We stop either after waittime if no data or 50ms after last data received
1838 if (GetTickCountDelta(ti) > wait)
1839 break;
1841 if (available > 0) {
1842 uint16_t len = usart_read_ng(dest, available);
1843 reply_ng(CMD_USART_RX, PM3_SUCCESS, dest, len);
1844 } else {
1845 reply_ng(CMD_USART_RX, PM3_ENODATA, NULL, 0);
1847 BigBuf_free();
1848 LED_B_OFF();
1849 break;
1851 case CMD_USART_TXRX: {
1852 LED_B_ON();
1853 struct p {
1854 uint32_t waittime;
1855 uint8_t data[];
1856 } PACKED;
1857 struct p *payload = (struct p *) &packet->data.asBytes;
1858 usart_writebuffer_sync(payload->data, packet->length - sizeof(payload));
1859 uint16_t available;
1860 uint16_t pre_available = 0;
1861 uint8_t *dest = BigBuf_malloc(USART_FIFOLEN);
1862 uint32_t wait = payload->waittime;
1863 uint32_t ti = GetTickCount();
1864 while (true) {
1865 WaitMS(50);
1866 available = usart_rxdata_available();
1867 if (available > pre_available) {
1868 // When receiving data, reset timer and shorten timeout
1869 ti = GetTickCount();
1870 wait = 50;
1871 pre_available = available;
1872 continue;
1874 // We stop either after waittime if no data or 50ms after last data received
1875 if (GetTickCountDelta(ti) > wait)
1876 break;
1878 if (available > 0) {
1879 uint16_t len = usart_read_ng(dest, available);
1880 reply_ng(CMD_USART_TXRX, PM3_SUCCESS, dest, len);
1881 } else {
1882 reply_ng(CMD_USART_TXRX, PM3_ENODATA, NULL, 0);
1884 BigBuf_free();
1885 LED_B_OFF();
1886 break;
1888 case CMD_USART_CONFIG: {
1889 struct p {
1890 uint32_t baudrate;
1891 uint8_t parity;
1892 } PACKED;
1893 struct p *payload = (struct p *) &packet->data.asBytes;
1894 usart_init(payload->baudrate, payload->parity);
1895 reply_ng(CMD_USART_CONFIG, PM3_SUCCESS, NULL, 0);
1896 break;
1898 #endif
1899 case CMD_BUFF_CLEAR: {
1900 BigBuf_Clear();
1901 BigBuf_free();
1902 break;
1904 case CMD_MEASURE_ANTENNA_TUNING: {
1905 MeasureAntennaTuning();
1906 break;
1908 case CMD_MEASURE_ANTENNA_TUNING_HF: {
1909 if (packet->length != 1)
1910 reply_ng(CMD_MEASURE_ANTENNA_TUNING_HF, PM3_EINVARG, NULL, 0);
1912 switch (packet->data.asBytes[0]) {
1913 case 1: // MEASURE_ANTENNA_TUNING_HF_START
1914 // Let the FPGA drive the high-frequency antenna around 13.56 MHz.
1915 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
1916 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER);
1917 reply_ng(CMD_MEASURE_ANTENNA_TUNING_HF, PM3_SUCCESS, NULL, 0);
1918 break;
1919 case 2:
1920 if (button_status == BUTTON_SINGLE_CLICK)
1921 reply_ng(CMD_MEASURE_ANTENNA_TUNING_HF, PM3_EOPABORTED, NULL, 0);
1922 uint16_t volt = MeasureAntennaTuningHfData();
1923 reply_ng(CMD_MEASURE_ANTENNA_TUNING_HF, PM3_SUCCESS, (uint8_t *)&volt, sizeof(volt));
1924 break;
1925 case 3:
1926 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1927 reply_ng(CMD_MEASURE_ANTENNA_TUNING_HF, PM3_SUCCESS, NULL, 0);
1928 break;
1929 default:
1930 reply_ng(CMD_MEASURE_ANTENNA_TUNING_HF, PM3_EINVARG, NULL, 0);
1931 break;
1933 break;
1935 case CMD_MEASURE_ANTENNA_TUNING_LF: {
1936 if (packet->length != 2)
1937 reply_ng(CMD_MEASURE_ANTENNA_TUNING_LF, PM3_EINVARG, NULL, 0);
1939 switch (packet->data.asBytes[0]) {
1940 case 1: // MEASURE_ANTENNA_TUNING_LF_START
1941 // Let the FPGA drive the low-frequency antenna around 125kHz
1942 FpgaDownloadAndGo(FPGA_BITSTREAM_LF);
1943 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_READER | FPGA_LF_ADC_READER_FIELD);
1944 FpgaSendCommand(FPGA_CMD_SET_DIVISOR, packet->data.asBytes[1]);
1945 reply_ng(CMD_MEASURE_ANTENNA_TUNING_LF, PM3_SUCCESS, NULL, 0);
1946 break;
1947 case 2:
1948 if (button_status == BUTTON_SINGLE_CLICK)
1949 reply_ng(CMD_MEASURE_ANTENNA_TUNING_LF, PM3_EOPABORTED, NULL, 0);
1951 uint32_t volt = MeasureAntennaTuningLfData();
1952 reply_ng(CMD_MEASURE_ANTENNA_TUNING_LF, PM3_SUCCESS, (uint8_t *)&volt, sizeof(volt));
1953 break;
1954 case 3:
1955 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1956 reply_ng(CMD_MEASURE_ANTENNA_TUNING_LF, PM3_SUCCESS, NULL, 0);
1957 break;
1958 default:
1959 reply_ng(CMD_MEASURE_ANTENNA_TUNING_LF, PM3_EINVARG, NULL, 0);
1960 break;
1962 break;
1964 case CMD_LISTEN_READER_FIELD: {
1965 if (packet->length != sizeof(uint8_t))
1966 break;
1967 ListenReaderField(packet->data.asBytes[0]);
1968 break;
1970 case CMD_FPGA_MAJOR_MODE_OFF: { // ## FPGA Control
1971 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1972 SpinDelay(200);
1973 LED_D_OFF(); // LED D indicates field ON or OFF
1974 break;
1976 case CMD_DOWNLOAD_BIGBUF: {
1977 LED_B_ON();
1978 uint8_t *mem = BigBuf_get_addr();
1979 uint32_t startidx = packet->oldarg[0];
1980 uint32_t numofbytes = packet->oldarg[1];
1982 // arg0 = startindex
1983 // arg1 = length bytes to transfer
1984 // arg2 = BigBuf tracelen
1985 //Dbprintf("transfer to client parameters: %" PRIu32 " | %" PRIu32 " | %" PRIu32, startidx, numofbytes, packet->oldarg[2]);
1987 for (size_t i = 0; i < numofbytes; i += PM3_CMD_DATA_SIZE) {
1988 size_t len = MIN((numofbytes - i), PM3_CMD_DATA_SIZE);
1989 int result = reply_old(CMD_DOWNLOADED_BIGBUF, i, len, BigBuf_get_traceLen(), mem + startidx + i, len);
1990 if (result != PM3_SUCCESS)
1991 Dbprintf("transfer to client failed :: | bytes between %d - %d (%d) | result: %d", i, i + len, len, result);
1993 // Trigger a finish downloading signal with an ACK frame
1994 // iceman, when did sending samplingconfig array got attached here?!?
1995 // arg0 = status of download transfer
1996 // arg1 = RFU
1997 // arg2 = tracelen?
1998 // asbytes = samplingconfig array
1999 reply_mix(CMD_ACK, 1, 0, BigBuf_get_traceLen(), getSamplingConfig(), sizeof(sample_config));
2000 LED_B_OFF();
2001 break;
2003 #ifdef WITH_LF
2004 case CMD_LF_UPLOAD_SIM_SAMPLES: {
2005 // iceman; since changing fpga_bitstreams clears bigbuff, Its better to call it before.
2006 // to be able to use this one for uploading data to device
2007 // flag =
2008 // b0 0 skip
2009 // 1 clear bigbuff
2010 struct p {
2011 uint8_t flag;
2012 uint16_t offset;
2013 uint8_t data[PM3_CMD_DATA_SIZE - sizeof(uint8_t) - sizeof(uint16_t)];
2014 } PACKED;
2015 struct p *payload = (struct p *)packet->data.asBytes;
2017 FpgaDownloadAndGo(FPGA_BITSTREAM_LF);
2019 if ((payload->flag & 0x1) == 0x1) {
2020 BigBuf_Clear_ext(false);
2021 BigBuf_free();
2024 // offset should not be over buffer
2025 if (payload->offset >= BigBuf_get_size()) {
2026 reply_ng(CMD_LF_UPLOAD_SIM_SAMPLES, PM3_EOVFLOW, NULL, 0);
2027 break;
2029 // ensure len bytes copied wont go past end of bigbuf
2030 uint16_t len = MIN(BigBuf_get_size() - payload->offset, sizeof(payload->data));
2032 uint8_t *mem = BigBuf_get_addr();
2034 memcpy(mem + payload->offset, &payload->data, len);
2035 reply_ng(CMD_LF_UPLOAD_SIM_SAMPLES, PM3_SUCCESS, NULL, 0);
2036 break;
2038 #endif
2039 case CMD_DOWNLOAD_EML_BIGBUF: {
2040 LED_B_ON();
2041 uint8_t *mem = BigBuf_get_EM_addr();
2042 uint32_t startidx = packet->oldarg[0];
2043 uint32_t numofbytes = packet->oldarg[1];
2045 // arg0 = startindex
2046 // arg1 = length bytes to transfer
2047 // arg2 = RFU
2049 for (size_t i = 0; i < numofbytes; i += PM3_CMD_DATA_SIZE) {
2050 size_t len = MIN((numofbytes - i), PM3_CMD_DATA_SIZE);
2051 int result = reply_old(CMD_DOWNLOADED_EML_BIGBUF, i, len, 0, mem + startidx + i, len);
2052 if (result != PM3_SUCCESS)
2053 Dbprintf("transfer to client failed :: | bytes between %d - %d (%d) | result: %d", i, i + len, len, result);
2055 // Trigger a finish downloading signal with an ACK frame
2056 reply_mix(CMD_ACK, 1, 0, 0, 0, 0);
2057 LED_B_OFF();
2058 break;
2060 case CMD_READ_MEM: {
2061 if (packet->length != sizeof(uint32_t))
2062 break;
2063 ReadMem(packet->data.asDwords[0]);
2064 break;
2066 #ifdef WITH_FLASH
2067 case CMD_SPIFFS_TEST: {
2068 test_spiffs();
2069 break;
2071 case CMD_SPIFFS_CHECK: {
2072 rdv40_spiffs_check();
2073 break;
2075 case CMD_SPIFFS_MOUNT: {
2076 rdv40_spiffs_lazy_mount();
2077 break;
2079 case CMD_SPIFFS_UNMOUNT: {
2080 rdv40_spiffs_lazy_unmount();
2081 break;
2083 case CMD_SPIFFS_PRINT_TREE: {
2084 rdv40_spiffs_safe_print_tree();
2085 break;
2087 case CMD_SPIFFS_PRINT_FSINFO: {
2088 rdv40_spiffs_safe_print_fsinfo();
2089 break;
2091 case CMD_SPIFFS_DOWNLOAD: {
2092 LED_B_ON();
2093 uint8_t filename[32];
2094 uint8_t *pfilename = packet->data.asBytes;
2095 memcpy(filename, pfilename, SPIFFS_OBJ_NAME_LEN);
2096 if (DBGLEVEL >= DBG_DEBUG) Dbprintf("Filename received for spiffs dump : %s", filename);
2098 uint32_t size = packet->oldarg[1];
2100 uint8_t *buff = BigBuf_malloc(size);
2101 rdv40_spiffs_read_as_filetype((char *)filename, (uint8_t *)buff, size, RDV40_SPIFFS_SAFETY_SAFE);
2103 // arg0 = filename
2104 // arg1 = size
2105 // arg2 = RFU
2107 for (size_t i = 0; i < size; i += PM3_CMD_DATA_SIZE) {
2108 size_t len = MIN((size - i), PM3_CMD_DATA_SIZE);
2109 int result = reply_old(CMD_SPIFFS_DOWNLOADED, i, len, 0, buff + i, len);
2110 if (result != PM3_SUCCESS)
2111 Dbprintf("transfer to client failed :: | bytes between %d - %d (%d) | result: %d", i, i + len, len, result);
2113 // Trigger a finish downloading signal with an ACK frame
2114 reply_ng(CMD_SPIFFS_DOWNLOAD, PM3_SUCCESS, NULL, 0);
2115 LED_B_OFF();
2116 break;
2118 case CMD_SPIFFS_STAT: {
2119 LED_B_ON();
2120 uint8_t filename[32];
2121 uint8_t *pfilename = packet->data.asBytes;
2122 memcpy(filename, pfilename, SPIFFS_OBJ_NAME_LEN);
2123 if (DBGLEVEL >= DBG_DEBUG) {
2124 Dbprintf("Filename received for spiffs STAT : %s", filename);
2127 int changed = rdv40_spiffs_lazy_mount();
2128 uint32_t size = size_in_spiffs((char *)filename);
2129 if (changed) {
2130 rdv40_spiffs_lazy_unmount();
2133 reply_ng(CMD_SPIFFS_STAT, PM3_SUCCESS, (uint8_t *)&size, sizeof(uint32_t));
2134 LED_B_OFF();
2135 break;
2137 case CMD_SPIFFS_REMOVE: {
2138 LED_B_ON();
2140 struct p {
2141 uint8_t len;
2142 uint8_t fn[32];
2143 } PACKED;
2144 struct p *payload = (struct p *) packet->data.asBytes;
2146 if (DBGLEVEL >= DBG_DEBUG) {
2147 Dbprintf("Filename received for spiffs REMOVE : %s", payload->fn);
2150 rdv40_spiffs_remove((char *)payload->fn, RDV40_SPIFFS_SAFETY_SAFE);
2151 reply_ng(CMD_SPIFFS_REMOVE, PM3_SUCCESS, NULL, 0);
2152 LED_B_OFF();
2153 break;
2155 case CMD_SPIFFS_RENAME: {
2156 LED_B_ON();
2157 struct p {
2158 uint8_t slen;
2159 uint8_t src[32];
2160 uint8_t dlen;
2161 uint8_t dest[32];
2162 } PACKED;
2163 struct p *payload = (struct p *) packet->data.asBytes;
2165 if (DBGLEVEL >= DBG_DEBUG) {
2166 Dbprintf("SPIFFS RENAME");
2167 Dbprintf("Source........ %s", payload->src);
2168 Dbprintf("Destination... %s", payload->dest);
2170 rdv40_spiffs_rename((char *)payload->src, (char *)payload->dest, RDV40_SPIFFS_SAFETY_SAFE);
2171 reply_ng(CMD_SPIFFS_RENAME, PM3_SUCCESS, NULL, 0);
2172 LED_B_OFF();
2173 break;
2175 case CMD_SPIFFS_COPY: {
2176 LED_B_ON();
2177 struct p {
2178 uint8_t slen;
2179 uint8_t src[32];
2180 uint8_t dlen;
2181 uint8_t dest[32];
2182 } PACKED;
2183 struct p *payload = (struct p *) packet->data.asBytes;
2185 if (DBGLEVEL >= DBG_DEBUG) {
2186 Dbprintf("SPIFFS COPY");
2187 Dbprintf("Source........ %s", payload->src);
2188 Dbprintf("Destination... %s", payload->dest);
2190 rdv40_spiffs_copy((char *)payload->src, (char *)payload->dest, RDV40_SPIFFS_SAFETY_SAFE);
2191 reply_ng(CMD_SPIFFS_COPY, PM3_SUCCESS, NULL, 0);
2192 LED_B_OFF();
2193 break;
2195 case CMD_SPIFFS_WRITE: {
2196 LED_B_ON();
2198 flashmem_write_t *payload = (flashmem_write_t *)packet->data.asBytes;
2200 if (DBGLEVEL >= DBG_DEBUG) {
2201 Dbprintf("SPIFFS WRITE, dest `%s` with APPEND set to: %c", payload->fn, payload->append ? 'Y' : 'N');
2204 if (payload->append) {
2205 rdv40_spiffs_append((char *) payload->fn, payload->data, payload->bytes_in_packet, RDV40_SPIFFS_SAFETY_SAFE);
2206 } else {
2207 rdv40_spiffs_write((char *) payload->fn, payload->data, payload->bytes_in_packet, RDV40_SPIFFS_SAFETY_SAFE);
2210 reply_ng(CMD_SPIFFS_WRITE, PM3_SUCCESS, NULL, 0);
2211 LED_B_OFF();
2212 break;
2214 case CMD_SPIFFS_WIPE: {
2215 LED_B_ON();
2216 rdv40_spiffs_safe_wipe();
2217 reply_ng(CMD_SPIFFS_WIPE, PM3_SUCCESS, NULL, 0);
2218 LED_B_OFF();
2219 break;
2221 case CMD_FLASHMEM_SET_SPIBAUDRATE: {
2222 if (packet->length != sizeof(uint32_t))
2223 break;
2224 FlashmemSetSpiBaudrate(packet->data.asDwords[0]);
2225 break;
2227 case CMD_FLASHMEM_WRITE: {
2228 LED_B_ON();
2230 flashmem_old_write_t *payload = (flashmem_old_write_t *)packet->data.asBytes;
2232 if (FlashInit() == false) {
2233 reply_ng(CMD_FLASHMEM_WRITE, PM3_EIO, NULL, 0);
2234 LED_B_OFF();
2235 break;
2238 if (payload->startidx == DEFAULT_T55XX_KEYS_OFFSET) {
2239 Flash_CheckBusy(BUSY_TIMEOUT);
2240 Flash_WriteEnable();
2241 Flash_Erase4k(3, 0xC);
2242 } else if (payload->startidx == DEFAULT_MF_KEYS_OFFSET) {
2243 Flash_CheckBusy(BUSY_TIMEOUT);
2244 Flash_WriteEnable();
2245 Flash_Erase4k(3, 0x9);
2246 Flash_CheckBusy(BUSY_TIMEOUT);
2247 Flash_WriteEnable();
2248 Flash_Erase4k(3, 0xA);
2249 } else if (payload->startidx == DEFAULT_ICLASS_KEYS_OFFSET) {
2250 Flash_CheckBusy(BUSY_TIMEOUT);
2251 Flash_WriteEnable();
2252 Flash_Erase4k(3, 0xB);
2253 } else if (payload->startidx == FLASH_MEM_SIGNATURE_OFFSET) {
2254 Flash_CheckBusy(BUSY_TIMEOUT);
2255 Flash_WriteEnable();
2256 Flash_Erase4k(3, 0xF);
2259 uint16_t res = Flash_Write(payload->startidx, payload->data, payload->len);
2261 reply_ng(CMD_FLASHMEM_WRITE, (res == payload->len) ? PM3_SUCCESS : PM3_ESOFT, NULL, 0);
2262 LED_B_OFF();
2263 break;
2265 case CMD_FLASHMEM_WIPE: {
2266 LED_B_ON();
2267 uint8_t page = packet->oldarg[0];
2268 uint8_t initalwipe = packet->oldarg[1];
2269 bool isok = false;
2270 if (initalwipe) {
2271 isok = Flash_WipeMemory();
2272 reply_mix(CMD_ACK, isok, 0, 0, 0, 0);
2273 LED_B_OFF();
2274 break;
2276 if (page < 3)
2277 isok = Flash_WipeMemoryPage(page);
2279 reply_mix(CMD_ACK, isok, 0, 0, 0, 0);
2280 LED_B_OFF();
2281 break;
2283 case CMD_FLASHMEM_DOWNLOAD: {
2285 LED_B_ON();
2286 uint8_t *mem = BigBuf_malloc(PM3_CMD_DATA_SIZE);
2287 uint32_t startidx = packet->oldarg[0];
2288 uint32_t numofbytes = packet->oldarg[1];
2289 // arg0 = startindex
2290 // arg1 = length bytes to transfer
2291 // arg2 = RFU
2293 if (FlashInit() == false) {
2294 break;
2297 for (size_t i = 0; i < numofbytes; i += PM3_CMD_DATA_SIZE) {
2298 size_t len = MIN((numofbytes - i), PM3_CMD_DATA_SIZE);
2299 Flash_CheckBusy(BUSY_TIMEOUT);
2300 bool isok = Flash_ReadDataCont(startidx + i, mem, len);
2301 if (isok == false)
2302 Dbprintf("reading flash memory failed :: | bytes between %d - %d", i, len);
2304 isok = reply_old(CMD_FLASHMEM_DOWNLOADED, i, len, 0, mem, len);
2305 if (isok != 0)
2306 Dbprintf("transfer to client failed :: | bytes between %d - %d", i, len);
2308 FlashStop();
2310 reply_mix(CMD_ACK, 1, 0, 0, 0, 0);
2311 BigBuf_free();
2312 LED_B_OFF();
2313 break;
2315 case CMD_FLASHMEM_INFO: {
2317 LED_B_ON();
2318 rdv40_validation_t *info = (rdv40_validation_t *)BigBuf_malloc(sizeof(rdv40_validation_t));
2320 bool isok = Flash_ReadData(FLASH_MEM_SIGNATURE_OFFSET, info->signature, FLASH_MEM_SIGNATURE_LEN);
2322 if (FlashInit()) {
2323 Flash_UniqueID(info->flashid);
2324 FlashStop();
2326 reply_mix(CMD_ACK, isok, 0, 0, info, sizeof(rdv40_validation_t));
2327 BigBuf_free();
2329 LED_B_OFF();
2330 break;
2332 #endif
2333 case CMD_LF_SET_DIVISOR: {
2334 FpgaDownloadAndGo(FPGA_BITSTREAM_LF);
2335 FpgaSendCommand(FPGA_CMD_SET_DIVISOR, packet->data.asBytes[0]);
2336 break;
2338 case CMD_SET_ADC_MUX: {
2339 switch (packet->data.asBytes[0]) {
2340 case 0:
2341 SetAdcMuxFor(GPIO_MUXSEL_LOPKD);
2342 break;
2343 case 2:
2344 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
2345 break;
2346 #ifndef WITH_FPC_USART
2347 case 1:
2348 SetAdcMuxFor(GPIO_MUXSEL_LORAW);
2349 break;
2350 case 3:
2351 SetAdcMuxFor(GPIO_MUXSEL_HIRAW);
2352 break;
2353 #endif
2355 break;
2357 case CMD_VERSION: {
2358 SendVersion();
2359 break;
2361 case CMD_STATUS: {
2362 SendStatus();
2363 break;
2365 case CMD_TIA: {
2367 while ((AT91C_BASE_PMC->PMC_MCFR & AT91C_CKGR_MAINRDY) == 0); // Wait for MAINF value to become available...
2368 uint16_t mainf = AT91C_BASE_PMC->PMC_MCFR & AT91C_CKGR_MAINF;
2369 Dbprintf(" Slow clock old measured value:.........%d Hz", (16 * MAINCK) / mainf);
2370 TimingIntervalAcquisition();
2372 while ((AT91C_BASE_PMC->PMC_MCFR & AT91C_CKGR_MAINRDY) == 0); // Wait for MAINF value to become available...
2373 mainf = AT91C_BASE_PMC->PMC_MCFR & AT91C_CKGR_MAINF;
2374 Dbprintf(""); // first message gets lost
2375 Dbprintf(" Slow clock new measured value:.........%d Hz", (16 * MAINCK) / mainf);
2376 reply_ng(CMD_TIA, PM3_SUCCESS, NULL, 0);
2377 break;
2379 case CMD_STANDALONE: {
2380 uint8_t *bb = BigBuf_get_EM_addr();
2381 bb[0] = packet->data.asBytes[0];
2382 RunMod();
2383 break;
2385 case CMD_CAPABILITIES: {
2386 SendCapabilities();
2387 break;
2389 case CMD_PING: {
2390 reply_ng(CMD_PING, PM3_SUCCESS, packet->data.asBytes, packet->length);
2391 break;
2393 #ifdef WITH_LCD
2394 case CMD_LCD_RESET: {
2395 LCDReset();
2396 break;
2398 case CMD_LCD: {
2399 LCDSend(packet->oldarg[0]);
2400 break;
2402 #endif
2403 case CMD_FINISH_WRITE:
2404 case CMD_HARDWARE_RESET: {
2405 usb_disable();
2407 // (iceman) why this wait?
2408 SpinDelay(1000);
2409 AT91C_BASE_RSTC->RSTC_RCR = RST_CONTROL_KEY | AT91C_RSTC_PROCRST;
2410 // We're going to reset, and the bootrom will take control.
2411 for (;;) {}
2412 break;
2414 case CMD_START_FLASH: {
2415 if (common_area.flags.bootrom_present) {
2416 common_area.command = COMMON_AREA_COMMAND_ENTER_FLASH_MODE;
2418 usb_disable();
2419 AT91C_BASE_RSTC->RSTC_RCR = RST_CONTROL_KEY | AT91C_RSTC_PROCRST;
2420 // We're going to flash, and the bootrom will take control.
2421 for (;;) {}
2422 break;
2424 case CMD_DEVICE_INFO: {
2425 uint32_t dev_info = DEVICE_INFO_FLAG_OSIMAGE_PRESENT | DEVICE_INFO_FLAG_CURRENT_MODE_OS;
2426 if (common_area.flags.bootrom_present) {
2427 dev_info |= DEVICE_INFO_FLAG_BOOTROM_PRESENT;
2429 reply_old(CMD_DEVICE_INFO, dev_info, 0, 0, 0, 0);
2430 break;
2432 default: {
2433 Dbprintf("%s: 0x%04x", "unknown command:", packet->cmd);
2434 break;
2439 void __attribute__((noreturn)) AppMain(void) {
2441 SpinDelay(100);
2442 BigBuf_initialize();
2444 for (uint32_t *p = _stack_start; p < _stack_end - 0x200; ++p) {
2445 *p = 0xdeadbeef;
2448 LEDsoff();
2450 // The FPGA gets its clock from us from PCK0 output, so set that up.
2451 AT91C_BASE_PIOA->PIO_BSR = GPIO_PCK0;
2452 AT91C_BASE_PIOA->PIO_PDR = GPIO_PCK0;
2453 AT91C_BASE_PMC->PMC_SCER |= AT91C_PMC_PCK0;
2454 // PCK0 is PLL clock / 4 = 96MHz / 4 = 24MHz
2455 AT91C_BASE_PMC->PMC_PCKR[0] = AT91C_PMC_CSS_PLL_CLK | AT91C_PMC_PRES_CLK_4; // 4 for 24MHz pck0, 2 for 48 MHZ pck0
2456 AT91C_BASE_PIOA->PIO_OER = GPIO_PCK0;
2458 // Reset SPI
2459 AT91C_BASE_SPI->SPI_CR = AT91C_SPI_SWRST;
2460 AT91C_BASE_SPI->SPI_CR = AT91C_SPI_SWRST; // errata says it needs twice to be correctly set.
2462 // Reset SSC
2463 AT91C_BASE_SSC->SSC_CR = AT91C_SSC_SWRST;
2465 // Configure MUX
2466 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
2468 // Load the FPGA image, which we have stored in our flash.
2469 // (the HF version by default)
2470 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
2472 StartTickCount();
2474 #ifdef WITH_LCD
2475 LCDInit();
2476 #endif
2478 #ifdef WITH_SMARTCARD
2479 I2C_init();
2480 #endif
2482 #ifdef WITH_FPC_USART
2483 usart_init(USART_BAUD_RATE, USART_PARITY);
2484 #endif
2486 // This is made as late as possible to ensure enumeration without timeout
2487 // against device such as http://www.hobbytronics.co.uk/usb-host-board-v2
2488 usb_disable();
2489 usb_enable();
2490 allow_send_wtx = true;
2492 #ifdef WITH_FLASH
2493 // If flash is not present, BUSY_TIMEOUT kicks in, let's do it after USB
2494 loadT55xxConfig();
2497 // Enforce a spiffs check/garbage collection at boot so we are likely to never
2498 // fall under the 2 contigous free blocks availables
2499 rdv40_spiffs_check();
2500 #endif
2502 for (;;) {
2503 WDT_HIT();
2505 if (*_stack_start != 0xdeadbeef) {
2506 Dbprintf("Stack overflow detected! Please increase stack size, currently %d bytes", (uint32_t)_stack_end - (uint32_t)_stack_start);
2507 Dbprintf("Unplug your device now.");
2508 while (1);
2511 // Check if there is a packet available
2512 PacketCommandNG rx;
2513 memset(&rx.data, 0, sizeof(rx.data));
2515 int ret = receive_ng(&rx);
2516 if (ret == PM3_SUCCESS) {
2517 PacketReceived(&rx);
2518 } else if (ret != PM3_ENODATA) {
2520 Dbprintf("Error in frame reception: %d %s", ret, (ret == PM3_EIO) ? "PM3_EIO" : "");
2521 // TODO if error, shall we resync ?
2524 // Press button for one second to enter a possible standalone mode
2525 button_status = BUTTON_HELD(1000);
2526 if (button_status == BUTTON_HOLD) {
2528 * So this is the trigger to execute a standalone mod. Generic entrypoint by following the standalone/standalone.h headerfile
2529 * All standalone mod "main loop" should be the RunMod() function.
2531 allow_send_wtx = false;
2532 RunMod();
2533 allow_send_wtx = true;