fix for client crash in lf hitag eload. Hitag simulation still now working (wip)
[RRG-proxmark3.git] / armsrc / appmain.c
blobaf5c01c72b03bb6861455b8aa7c47c30aa99c755
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: {
1117 lf_hitag_t *payload = (lf_hitag_t *) packet->data.asBytes;
1118 uint8_t *mem = BigBuf_get_EM_addr();
1119 memcpy((uint8_t *)mem, payload->data, payload->len);
1120 break;
1122 #endif
1124 #ifdef WITH_EM4x50
1125 case CMD_LF_EM4X50_INFO: {
1126 em4x50_info((em4x50_data_t *)packet->data.asBytes);
1127 break;
1129 case CMD_LF_EM4X50_WRITE: {
1130 em4x50_write((em4x50_data_t *)packet->data.asBytes);
1131 break;
1133 case CMD_LF_EM4X50_WRITEPWD: {
1134 em4x50_writepwd((em4x50_data_t *)packet->data.asBytes);
1135 break;
1137 case CMD_LF_EM4X50_READ: {
1138 em4x50_read((em4x50_data_t *)packet->data.asBytes);
1139 break;
1141 case CMD_LF_EM4X50_BRUTE: {
1142 em4x50_brute((em4x50_data_t *)packet->data.asBytes);
1143 break;
1145 case CMD_LF_EM4X50_LOGIN: {
1146 em4x50_login((uint32_t *)packet->data.asBytes);
1147 break;
1149 case CMD_LF_EM4X50_SIM: {
1150 //-----------------------------------------------------------------------------
1151 // Note: we call FpgaDownloadAndGo(FPGA_BITSTREAM_LF) here although FPGA is not
1152 // involved in dealing with emulator memory. But if it is called later, it might
1153 // destroy the Emulator Memory.
1154 //-----------------------------------------------------------------------------
1155 FpgaDownloadAndGo(FPGA_BITSTREAM_LF);
1156 em4x50_sim((uint32_t *)packet->data.asBytes);
1157 break;
1159 case CMD_LF_EM4X50_READER: {
1160 em4x50_reader();
1161 break;
1163 case CMD_LF_EM4X50_ESET: {
1164 //-----------------------------------------------------------------------------
1165 // Note: we call FpgaDownloadAndGo(FPGA_BITSTREAM_LF) here although FPGA is not
1166 // involved in dealing with emulator memory. But if it is called later, it might
1167 // destroy the Emulator Memory.
1168 //-----------------------------------------------------------------------------
1169 FpgaDownloadAndGo(FPGA_BITSTREAM_LF);
1170 emlSet(packet->data.asBytes, packet->oldarg[0], packet->oldarg[1]);
1171 break;
1173 case CMD_LF_EM4X50_CHK: {
1174 //-----------------------------------------------------------------------------
1175 // Note: we call FpgaDownloadAndGo(FPGA_BITSTREAM_LF) here although FPGA is not
1176 // involved in dealing with emulator memory. But if it is called later, it might
1177 // destroy the Emulator Memory.
1178 //-----------------------------------------------------------------------------
1179 FpgaDownloadAndGo(FPGA_BITSTREAM_LF);
1180 em4x50_chk((uint8_t *)packet->data.asBytes);
1181 break;
1183 #endif
1185 #ifdef WITH_EM4x70
1186 case CMD_LF_EM4X70_INFO: {
1187 em4x70_info((em4x70_data_t *)packet->data.asBytes);
1188 break;
1190 case CMD_LF_EM4X70_WRITE: {
1191 em4x70_write((em4x70_data_t *)packet->data.asBytes);
1192 break;
1194 case CMD_LF_EM4X70_UNLOCK: {
1195 em4x70_unlock((em4x70_data_t *)packet->data.asBytes);
1196 break;
1198 case CMD_LF_EM4X70_AUTH: {
1199 em4x70_auth((em4x70_data_t *)packet->data.asBytes);
1200 break;
1202 case CMD_LF_EM4X70_WRITEPIN: {
1203 em4x70_write_pin((em4x70_data_t *)packet->data.asBytes);
1204 break;
1206 case CMD_LF_EM4X70_WRITEKEY: {
1207 em4x70_write_key((em4x70_data_t *)packet->data.asBytes);
1208 break;
1210 #endif
1212 #ifdef WITH_ISO15693
1213 case CMD_HF_ISO15693_ACQ_RAW_ADC: {
1214 AcquireRawAdcSamplesIso15693();
1215 break;
1217 case CMD_HF_ISO15693_SNIFF: {
1218 SniffIso15693(0, NULL);
1219 reply_ng(CMD_HF_ISO15693_SNIFF, PM3_SUCCESS, NULL, 0);
1220 break;
1222 case CMD_HF_ISO15693_COMMAND: {
1223 DirectTag15693Command(packet->oldarg[0], packet->oldarg[1], packet->oldarg[2], packet->data.asBytes);
1224 break;
1226 case CMD_HF_ISO15693_FINDAFI: {
1227 BruteforceIso15693Afi(packet->oldarg[0]);
1228 break;
1230 case CMD_HF_ISO15693_READER: {
1231 ReaderIso15693(packet->oldarg[0], NULL);
1232 break;
1234 case CMD_HF_ISO15693_SIMULATE: {
1235 struct p {
1236 uint8_t uid[8];
1237 } PACKED;
1238 struct p *payload = (struct p *) packet->data.asBytes;
1239 SimTagIso15693(payload->uid);
1240 break;
1242 case CMD_HF_ISO15693_CSETUID: {
1243 struct p {
1244 uint8_t uid[8];
1245 } PACKED;
1246 struct p *payload = (struct p *) packet->data.asBytes;
1247 SetTag15693Uid(payload->uid);
1248 break;
1250 case CMD_HF_ISO15693_SLIX_L_DISABLE_PRIVACY: {
1251 struct p {
1252 uint8_t pwd[4];
1253 } PACKED;
1254 struct p *payload = (struct p *) packet->data.asBytes;
1255 DisablePrivacySlixLIso15693(payload->pwd);
1256 break;
1259 #endif
1261 #ifdef WITH_LEGICRF
1262 case CMD_HF_LEGIC_SIMULATE: {
1263 struct p {
1264 uint8_t tagtype;
1265 bool send_reply;
1266 } PACKED;
1267 struct p *payload = (struct p *) packet->data.asBytes;
1268 LegicRfSimulate(payload->tagtype, payload->send_reply);
1269 break;
1271 case CMD_HF_LEGIC_WRITER: {
1272 LegicRfWriter(packet->oldarg[0], packet->oldarg[1], packet->oldarg[2], packet->data.asBytes);
1273 break;
1275 case CMD_HF_LEGIC_READER: {
1276 LegicRfReader(packet->oldarg[0], packet->oldarg[1], packet->oldarg[2]);
1277 break;
1279 case CMD_HF_LEGIC_INFO: {
1280 LegicRfInfo();
1281 break;
1283 case CMD_HF_LEGIC_ESET: {
1284 //-----------------------------------------------------------------------------
1285 // Note: we call FpgaDownloadAndGo(FPGA_BITSTREAM_HF) here although FPGA is not
1286 // involved in dealing with emulator memory. But if it is called later, it might
1287 // destroy the Emulator Memory.
1288 //-----------------------------------------------------------------------------
1289 // arg0 = offset
1290 // arg1 = num of bytes
1291 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
1292 emlSet(packet->data.asBytes, packet->oldarg[0], packet->oldarg[1]);
1293 break;
1295 #endif
1297 #ifdef WITH_ISO14443b
1298 case CMD_HF_SRI_READ: {
1299 struct p {
1300 uint8_t blockno;
1301 } PACKED;
1302 struct p *payload = (struct p *) packet->data.asBytes;
1303 ReadSTBlock(payload->blockno);
1304 break;
1306 case CMD_HF_ISO14443B_SNIFF: {
1307 SniffIso14443b();
1308 reply_ng(CMD_HF_ISO14443B_SNIFF, PM3_SUCCESS, NULL, 0);
1309 break;
1311 case CMD_HF_ISO14443B_SIMULATE: {
1312 SimulateIso14443bTag(packet->data.asBytes);
1313 break;
1315 case CMD_HF_ISO14443B_COMMAND: {
1316 iso14b_raw_cmd_t *payload = (iso14b_raw_cmd_t *)packet->data.asBytes;
1317 SendRawCommand14443B_Ex(payload);
1318 break;
1320 case CMD_HF_CRYPTORF_SIM : {
1321 // simulate_crf_tag();
1322 break;
1324 #endif
1326 #ifdef WITH_FELICA
1327 case CMD_HF_FELICA_COMMAND: {
1328 felica_sendraw(packet);
1329 break;
1331 case CMD_HF_FELICALITE_SIMULATE: {
1332 struct p {
1333 uint8_t uid[8];
1334 } PACKED;
1335 struct p *payload = (struct p *) packet->data.asBytes;
1336 felica_sim_lite(payload->uid);
1337 break;
1339 case CMD_HF_FELICA_SNIFF: {
1340 struct p {
1341 uint32_t samples;
1342 uint32_t triggers;
1343 } PACKED;
1344 struct p *payload = (struct p *) packet->data.asBytes;
1345 felica_sniff(payload->samples, payload->triggers);
1346 break;
1348 case CMD_HF_FELICALITE_DUMP: {
1349 felica_dump_lite_s();
1350 break;
1352 #endif
1354 #ifdef WITH_ISO14443a
1355 case CMD_HF_ISO14443A_PRINT_CONFIG: {
1356 printHf14aConfig();
1357 break;
1359 case CMD_HF_ISO14443A_GET_CONFIG: {
1360 hf14a_config *hf14aconfig = getHf14aConfig();
1361 reply_ng(CMD_HF_ISO14443A_GET_CONFIG, PM3_SUCCESS, (uint8_t *)hf14aconfig, sizeof(hf14a_config));
1362 break;
1364 case CMD_HF_ISO14443A_SET_CONFIG: {
1365 hf14a_config c;
1366 memcpy(&c, packet->data.asBytes, sizeof(hf14a_config));
1367 setHf14aConfig(&c);
1368 break;
1370 case CMD_HF_ISO14443A_SNIFF: {
1371 SniffIso14443a(packet->data.asBytes[0]);
1372 reply_ng(CMD_HF_ISO14443A_SNIFF, PM3_SUCCESS, NULL, 0);
1373 break;
1375 case CMD_HF_ISO14443A_READER: {
1376 ReaderIso14443a(packet);
1377 break;
1379 case CMD_HF_ISO14443A_SIMULATE: {
1380 struct p {
1381 uint8_t tagtype;
1382 uint8_t flags;
1383 uint8_t uid[10];
1384 uint8_t exitAfter;
1385 } PACKED;
1386 struct p *payload = (struct p *) packet->data.asBytes;
1387 SimulateIso14443aTag(payload->tagtype, payload->flags, payload->uid, payload->exitAfter); // ## Simulate iso14443a tag - pass tag type & UID
1388 break;
1390 case CMD_HF_ISO14443A_ANTIFUZZ: {
1391 struct p {
1392 uint8_t flag;
1393 } PACKED;
1394 struct p *payload = (struct p *) packet->data.asBytes;
1395 iso14443a_antifuzz(payload->flag);
1396 break;
1398 case CMD_HF_EPA_COLLECT_NONCE: {
1399 EPA_PACE_Collect_Nonce(packet);
1400 break;
1402 case CMD_HF_EPA_REPLAY: {
1403 EPA_PACE_Replay(packet);
1404 break;
1406 case CMD_HF_MIFARE_READER: {
1407 struct p {
1408 uint8_t first_run;
1409 uint8_t blockno;
1410 uint8_t key_type;
1411 } PACKED;
1412 struct p *payload = (struct p *) packet->data.asBytes;
1413 ReaderMifare(payload->first_run, payload->blockno, payload->key_type);
1414 break;
1416 case CMD_HF_MIFARE_READBL: {
1417 mf_readblock_t *payload = (mf_readblock_t *)packet->data.asBytes;
1418 MifareReadBlock(payload->blockno, payload->keytype, payload->key);
1419 break;
1421 case CMD_HF_MIFAREU_READBL: {
1422 MifareUReadBlock(packet->oldarg[0], packet->oldarg[1], packet->data.asBytes);
1423 break;
1425 case CMD_HF_MIFAREUC_AUTH: {
1426 MifareUC_Auth(packet->oldarg[0], packet->data.asBytes);
1427 break;
1429 case CMD_HF_MIFAREU_READCARD: {
1430 MifareUReadCard(packet->oldarg[0], packet->oldarg[1], packet->oldarg[2], packet->data.asBytes);
1431 break;
1433 case CMD_HF_MIFAREUC_SETPWD: {
1434 MifareUSetPwd(packet->oldarg[0], packet->data.asBytes);
1435 break;
1437 case CMD_HF_MIFARE_READSC: {
1438 MifareReadSector(packet->oldarg[0], packet->oldarg[1], packet->data.asBytes);
1439 break;
1441 case CMD_HF_MIFARE_WRITEBL: {
1442 MifareWriteBlock(packet->oldarg[0], packet->oldarg[1], packet->data.asBytes);
1443 break;
1445 case CMD_HF_MIFAREU_WRITEBL: {
1446 MifareUWriteBlock(packet->oldarg[0], packet->oldarg[1], packet->data.asBytes);
1447 break;
1449 case CMD_HF_MIFAREU_WRITEBL_COMPAT: {
1450 MifareUWriteBlockCompat(packet->oldarg[0], packet->oldarg[1], packet->data.asBytes);
1451 break;
1453 case CMD_HF_MIFARE_ACQ_ENCRYPTED_NONCES: {
1454 MifareAcquireEncryptedNonces(packet->oldarg[0], packet->oldarg[1], packet->oldarg[2], packet->data.asBytes);
1455 break;
1457 case CMD_HF_MIFARE_ACQ_NONCES: {
1458 MifareAcquireNonces(packet->oldarg[0], packet->oldarg[2]);
1459 break;
1461 case CMD_HF_MIFARE_NESTED: {
1462 struct p {
1463 uint8_t block;
1464 uint8_t keytype;
1465 uint8_t target_block;
1466 uint8_t target_keytype;
1467 bool calibrate;
1468 uint8_t key[6];
1469 } PACKED;
1470 struct p *payload = (struct p *) packet->data.asBytes;
1471 MifareNested(payload->block, payload->keytype, payload->target_block, payload->target_keytype, payload->calibrate, payload->key);
1472 break;
1474 case CMD_HF_MIFARE_STATIC_NESTED: {
1475 struct p {
1476 uint8_t block;
1477 uint8_t keytype;
1478 uint8_t target_block;
1479 uint8_t target_keytype;
1480 uint8_t key[6];
1481 } PACKED;
1482 struct p *payload = (struct p *) packet->data.asBytes;
1483 MifareStaticNested(payload->block, payload->keytype, payload->target_block, payload->target_keytype, payload->key);
1484 break;
1486 case CMD_HF_MIFARE_CHKKEYS: {
1487 MifareChkKeys(packet->data.asBytes, false);
1488 break;
1490 case CMD_HF_MIFARE_CHKKEYS_FAST: {
1491 MifareChkKeys_fast(packet->oldarg[0], packet->oldarg[1], packet->oldarg[2], packet->data.asBytes);
1492 break;
1494 case CMD_HF_MIFARE_CHKKEYS_FILE: {
1495 struct p {
1496 uint8_t filename[32];
1497 } PACKED;
1498 struct p *payload = (struct p *) packet->data.asBytes;
1499 MifareChkKeys_file(payload->filename);
1500 break;
1502 case CMD_HF_MIFARE_SIMULATE: {
1503 struct p {
1504 uint16_t flags;
1505 uint8_t exitAfter;
1506 uint8_t uid[10];
1507 uint16_t atqa;
1508 uint8_t sak;
1509 } PACKED;
1510 struct p *payload = (struct p *) packet->data.asBytes;
1511 Mifare1ksim(payload->flags, payload->exitAfter, payload->uid, payload->atqa, payload->sak);
1512 break;
1514 case CMD_HF_MIFARE_EML_MEMCLR: {
1515 MifareEMemClr();
1516 reply_ng(CMD_HF_MIFARE_EML_MEMCLR, PM3_SUCCESS, NULL, 0);
1517 break;
1519 case CMD_HF_MIFARE_EML_MEMSET: {
1520 struct p {
1521 uint8_t blockno;
1522 uint8_t blockcnt;
1523 uint8_t blockwidth;
1524 uint8_t data[];
1525 } PACKED;
1526 struct p *payload = (struct p *) packet->data.asBytes;
1527 MifareEMemSet(payload->blockno, payload->blockcnt, payload->blockwidth, payload->data);
1528 break;
1530 case CMD_HF_MIFARE_EML_MEMGET: {
1531 struct p {
1532 uint8_t blockno;
1533 uint8_t blockcnt;
1534 } PACKED;
1535 struct p *payload = (struct p *) packet->data.asBytes;
1536 MifareEMemGet(payload->blockno, payload->blockcnt);
1537 break;
1539 case CMD_HF_MIFARE_EML_LOAD: {
1540 mfc_eload_t *payload = (mfc_eload_t *) packet->data.asBytes;
1541 MifareECardLoadExt(payload->sectorcnt, payload->keytype);
1542 break;
1544 // Work with "magic Chinese" card
1545 case CMD_HF_MIFARE_CSETBL: {
1546 MifareCSetBlock(packet->oldarg[0], packet->oldarg[1], packet->data.asBytes);
1547 break;
1549 case CMD_HF_MIFARE_CGETBL: {
1550 MifareCGetBlock(packet->oldarg[0], packet->oldarg[1], packet->data.asBytes);
1551 break;
1553 case CMD_HF_MIFARE_CIDENT: {
1554 bool is_mfc = packet->data.asBytes[0];
1555 MifareCIdent(is_mfc);
1556 break;
1558 // Gen 3 magic cards
1559 case CMD_HF_MIFARE_GEN3UID: {
1560 MifareGen3UID(packet->oldarg[0], packet->data.asBytes);
1561 break;
1563 case CMD_HF_MIFARE_GEN3BLK: {
1564 MifareGen3Blk(packet->oldarg[0], packet->data.asBytes);
1565 break;
1567 case CMD_HF_MIFARE_GEN3FREEZ: {
1568 MifareGen3Freez();
1569 break;
1571 case CMD_HF_MIFARE_PERSONALIZE_UID: {
1572 struct p {
1573 uint8_t keytype;
1574 uint8_t pers_option;
1575 uint8_t key[6];
1576 } PACKED;
1577 struct p *payload = (struct p *) packet->data.asBytes;
1578 uint64_t authkey = bytes_to_num(payload->key, 6);
1579 MifarePersonalizeUID(payload->keytype, payload->pers_option, authkey);
1580 break;
1582 case CMD_HF_MIFARE_SETMOD: {
1583 MifareSetMod(packet->data.asBytes);
1584 break;
1586 //mifare desfire
1587 case CMD_HF_DESFIRE_READBL: {
1588 break;
1590 case CMD_HF_DESFIRE_WRITEBL: {
1591 break;
1593 case CMD_HF_DESFIRE_AUTH1: {
1594 MifareDES_Auth1(packet->data.asBytes);
1595 break;
1597 case CMD_HF_DESFIRE_AUTH2: {
1598 //MifareDES_Auth2(packet->oldarg[0],packet->data.asBytes);
1599 break;
1601 case CMD_HF_DESFIRE_READER: {
1602 //readermifaredes(packet->oldarg[0], packet->oldarg[1], packet->data.asBytes);
1603 break;
1605 case CMD_HF_DESFIRE_INFO: {
1606 MifareDesfireGetInformation();
1607 break;
1609 case CMD_HF_DESFIRE_COMMAND: {
1610 MifareSendCommand(packet->data.asBytes);
1611 break;
1613 case CMD_HF_MIFARE_NACK_DETECT: {
1614 DetectNACKbug();
1615 break;
1617 case CMD_HF_MFU_OTP_TEAROFF: {
1618 MifareU_Otp_Tearoff(packet->oldarg[0], packet->oldarg[1], packet->data.asBytes);
1619 break;
1621 case CMD_HF_MFU_COUNTER_TEAROFF: {
1622 struct p {
1623 uint8_t counter;
1624 uint32_t tearoff_time;
1625 uint8_t value[4];
1626 } PACKED;
1627 struct p *payload = (struct p *) packet->data.asBytes;
1628 MifareU_Counter_Tearoff(payload->counter, payload->tearoff_time, payload->value);
1629 break;
1631 case CMD_HF_MIFARE_STATIC_NONCE: {
1632 MifareHasStaticNonce();
1633 break;
1635 #endif
1637 #ifdef WITH_NFCBARCODE
1638 case CMD_HF_THINFILM_READ: {
1639 ReadThinFilm();
1640 break;
1642 case CMD_HF_THINFILM_SIMULATE: {
1643 SimulateThinFilm(packet->data.asBytes, packet->length);
1644 break;
1646 #endif
1648 #ifdef WITH_ICLASS
1649 // Makes use of ISO14443a FPGA Firmware
1650 case CMD_HF_ICLASS_SNIFF: {
1651 struct p {
1652 uint8_t jam_search_len;
1653 uint8_t jam_search_string[];
1654 } PACKED;
1655 struct p *payload = (struct p *) packet->data.asBytes;
1656 SniffIClass(payload->jam_search_len, payload->jam_search_string);
1657 reply_ng(CMD_HF_ICLASS_SNIFF, PM3_SUCCESS, NULL, 0);
1658 break;
1660 case CMD_HF_ICLASS_SIMULATE: {
1662 struct p {
1663 uint8_t reader[4];
1664 uint8_t mac[4];
1665 } PACKED;
1666 struct p *payload = (struct p *) packet->data.asBytes;
1669 SimulateIClass(packet->oldarg[0], packet->oldarg[1], packet->oldarg[2], packet->data.asBytes);
1670 break;
1672 case CMD_HF_ICLASS_READER: {
1673 ReaderIClass(packet->oldarg[0]);
1674 break;
1676 case CMD_HF_ICLASS_EML_MEMSET: {
1677 //iceman, should call FPGADOWNLOAD before, since it corrupts BigBuf
1678 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
1679 struct p {
1680 uint16_t offset;
1681 uint16_t len;
1682 uint8_t data[];
1683 } PACKED;
1684 struct p *payload = (struct p *) packet->data.asBytes;
1685 emlSet(payload->data, payload->offset, payload->len);
1686 break;
1688 case CMD_HF_ICLASS_WRITEBL: {
1689 iClass_WriteBlock(packet->data.asBytes);
1690 break;
1692 case CMD_HF_ICLASS_READBL: {
1693 iClass_ReadBlock(packet->data.asBytes);
1694 break;
1696 case CMD_HF_ICLASS_CHKKEYS: {
1697 iClass_Authentication_fast((iclass_chk_t *)packet->data.asBytes);
1698 break;
1700 case CMD_HF_ICLASS_DUMP: {
1701 iClass_Dump(packet->data.asBytes);
1702 break;
1704 case CMD_HF_ICLASS_RESTORE: {
1705 iClass_Restore((iclass_restore_req_t *)packet->data.asBytes);
1706 break;
1708 #endif
1710 #ifdef WITH_HFSNIFF
1711 case CMD_HF_SNIFF: {
1712 struct p {
1713 uint32_t samplesToSkip;
1714 uint32_t triggersToSkip;
1715 } PACKED;
1716 struct p *payload = (struct p *)packet->data.asBytes;
1718 uint16_t len = 0;
1719 int res = HfSniff(payload->samplesToSkip, payload->triggersToSkip, &len);
1721 struct {
1722 uint16_t len;
1723 } PACKED retval;
1724 retval.len = len;
1725 reply_ng(CMD_HF_SNIFF, res, (uint8_t *)&retval, sizeof(retval));
1726 break;
1728 #endif
1730 #ifdef WITH_HFPLOT
1731 case CMD_FPGAMEM_DOWNLOAD: {
1732 HfPlotDownload();
1733 break;
1735 #endif
1737 #ifdef WITH_SMARTCARD
1738 case CMD_SMART_ATR: {
1739 SmartCardAtr();
1740 break;
1742 case CMD_SMART_SETBAUD: {
1743 SmartCardSetBaud(packet->oldarg[0]);
1744 break;
1746 case CMD_SMART_SETCLOCK: {
1747 struct p {
1748 uint32_t new_clk;
1749 } PACKED;
1750 struct p *payload = (struct p *)packet->data.asBytes;
1751 SmartCardSetClock(payload->new_clk);
1752 break;
1754 case CMD_SMART_RAW: {
1755 SmartCardRaw((smart_card_raw_t *)packet->data.asBytes);
1756 break;
1758 case CMD_SMART_UPLOAD: {
1759 // upload file from client
1760 struct p {
1761 uint32_t idx;
1762 uint32_t bytes_in_packet;
1763 uint16_t crc;
1764 uint8_t data[400];
1765 } PACKED;
1766 struct p *payload = (struct p *)packet->data.asBytes;
1767 uint8_t *mem = BigBuf_get_addr();
1768 memcpy(mem + payload->idx, payload->data, payload->bytes_in_packet);
1770 uint8_t a = 0, b = 0;
1771 compute_crc(CRC_14443_A, mem + payload->idx, payload->bytes_in_packet, &a, &b);
1772 int res = PM3_SUCCESS;
1773 if (payload->crc != (a << 8 | b)) {
1774 DbpString("CRC Failed");
1775 res = PM3_ESOFT;
1777 reply_ng(CMD_SMART_UPLOAD, res, NULL, 0);
1778 break;
1780 case CMD_SMART_UPGRADE: {
1781 struct p {
1782 uint16_t fw_size;
1783 uint16_t crc;
1784 } PACKED;
1785 struct p *payload = (struct p *)packet->data.asBytes;
1787 uint8_t *fwdata = BigBuf_get_addr();
1788 uint8_t a = 0, b = 0;
1789 compute_crc(CRC_14443_A, fwdata, payload->fw_size, &a, &b);
1791 if (payload->crc != (a << 8 | b)) {
1792 Dbprintf("CRC Failed, 0x[%04x] != 0x[%02x%02x]", payload->crc, a, b);
1793 reply_ng(CMD_SMART_UPGRADE, PM3_ESOFT, NULL, 0);
1794 } else {
1795 SmartCardUpgrade(payload->fw_size);
1797 fwdata = NULL;
1798 break;
1800 #endif
1802 #ifdef WITH_FPC_USART
1803 case CMD_USART_TX: {
1804 LED_B_ON();
1805 usart_writebuffer_sync(packet->data.asBytes, packet->length);
1806 reply_ng(CMD_USART_TX, PM3_SUCCESS, NULL, 0);
1807 LED_B_OFF();
1808 break;
1810 case CMD_USART_RX: {
1811 LED_B_ON();
1812 struct p {
1813 uint32_t waittime;
1814 } PACKED;
1815 struct p *payload = (struct p *) &packet->data.asBytes;
1816 uint16_t available;
1817 uint16_t pre_available = 0;
1818 uint8_t *dest = BigBuf_malloc(USART_FIFOLEN);
1819 uint32_t wait = payload->waittime;
1820 uint32_t ti = GetTickCount();
1821 while (true) {
1822 WaitMS(50);
1823 available = usart_rxdata_available();
1824 if (available > pre_available) {
1825 // When receiving data, reset timer and shorten timeout
1826 ti = GetTickCount();
1827 wait = 50;
1828 pre_available = available;
1829 continue;
1831 // We stop either after waittime if no data or 50ms after last data received
1832 if (GetTickCountDelta(ti) > wait)
1833 break;
1835 if (available > 0) {
1836 uint16_t len = usart_read_ng(dest, available);
1837 reply_ng(CMD_USART_RX, PM3_SUCCESS, dest, len);
1838 } else {
1839 reply_ng(CMD_USART_RX, PM3_ENODATA, NULL, 0);
1841 BigBuf_free();
1842 LED_B_OFF();
1843 break;
1845 case CMD_USART_TXRX: {
1846 LED_B_ON();
1847 struct p {
1848 uint32_t waittime;
1849 uint8_t data[];
1850 } PACKED;
1851 struct p *payload = (struct p *) &packet->data.asBytes;
1852 usart_writebuffer_sync(payload->data, packet->length - sizeof(payload));
1853 uint16_t available;
1854 uint16_t pre_available = 0;
1855 uint8_t *dest = BigBuf_malloc(USART_FIFOLEN);
1856 uint32_t wait = payload->waittime;
1857 uint32_t ti = GetTickCount();
1858 while (true) {
1859 WaitMS(50);
1860 available = usart_rxdata_available();
1861 if (available > pre_available) {
1862 // When receiving data, reset timer and shorten timeout
1863 ti = GetTickCount();
1864 wait = 50;
1865 pre_available = available;
1866 continue;
1868 // We stop either after waittime if no data or 50ms after last data received
1869 if (GetTickCountDelta(ti) > wait)
1870 break;
1872 if (available > 0) {
1873 uint16_t len = usart_read_ng(dest, available);
1874 reply_ng(CMD_USART_TXRX, PM3_SUCCESS, dest, len);
1875 } else {
1876 reply_ng(CMD_USART_TXRX, PM3_ENODATA, NULL, 0);
1878 BigBuf_free();
1879 LED_B_OFF();
1880 break;
1882 case CMD_USART_CONFIG: {
1883 struct p {
1884 uint32_t baudrate;
1885 uint8_t parity;
1886 } PACKED;
1887 struct p *payload = (struct p *) &packet->data.asBytes;
1888 usart_init(payload->baudrate, payload->parity);
1889 reply_ng(CMD_USART_CONFIG, PM3_SUCCESS, NULL, 0);
1890 break;
1892 #endif
1893 case CMD_BUFF_CLEAR: {
1894 BigBuf_Clear();
1895 BigBuf_free();
1896 break;
1898 case CMD_MEASURE_ANTENNA_TUNING: {
1899 MeasureAntennaTuning();
1900 break;
1902 case CMD_MEASURE_ANTENNA_TUNING_HF: {
1903 if (packet->length != 1)
1904 reply_ng(CMD_MEASURE_ANTENNA_TUNING_HF, PM3_EINVARG, NULL, 0);
1906 switch (packet->data.asBytes[0]) {
1907 case 1: // MEASURE_ANTENNA_TUNING_HF_START
1908 // Let the FPGA drive the high-frequency antenna around 13.56 MHz.
1909 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
1910 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER);
1911 reply_ng(CMD_MEASURE_ANTENNA_TUNING_HF, PM3_SUCCESS, NULL, 0);
1912 break;
1913 case 2:
1914 if (button_status == BUTTON_SINGLE_CLICK)
1915 reply_ng(CMD_MEASURE_ANTENNA_TUNING_HF, PM3_EOPABORTED, NULL, 0);
1916 uint16_t volt = MeasureAntennaTuningHfData();
1917 reply_ng(CMD_MEASURE_ANTENNA_TUNING_HF, PM3_SUCCESS, (uint8_t *)&volt, sizeof(volt));
1918 break;
1919 case 3:
1920 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1921 reply_ng(CMD_MEASURE_ANTENNA_TUNING_HF, PM3_SUCCESS, NULL, 0);
1922 break;
1923 default:
1924 reply_ng(CMD_MEASURE_ANTENNA_TUNING_HF, PM3_EINVARG, NULL, 0);
1925 break;
1927 break;
1929 case CMD_MEASURE_ANTENNA_TUNING_LF: {
1930 if (packet->length != 2)
1931 reply_ng(CMD_MEASURE_ANTENNA_TUNING_LF, PM3_EINVARG, NULL, 0);
1933 switch (packet->data.asBytes[0]) {
1934 case 1: // MEASURE_ANTENNA_TUNING_LF_START
1935 // Let the FPGA drive the low-frequency antenna around 125kHz
1936 FpgaDownloadAndGo(FPGA_BITSTREAM_LF);
1937 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_READER | FPGA_LF_ADC_READER_FIELD);
1938 FpgaSendCommand(FPGA_CMD_SET_DIVISOR, packet->data.asBytes[1]);
1939 reply_ng(CMD_MEASURE_ANTENNA_TUNING_LF, PM3_SUCCESS, NULL, 0);
1940 break;
1941 case 2:
1942 if (button_status == BUTTON_SINGLE_CLICK)
1943 reply_ng(CMD_MEASURE_ANTENNA_TUNING_LF, PM3_EOPABORTED, NULL, 0);
1945 uint32_t volt = MeasureAntennaTuningLfData();
1946 reply_ng(CMD_MEASURE_ANTENNA_TUNING_LF, PM3_SUCCESS, (uint8_t *)&volt, sizeof(volt));
1947 break;
1948 case 3:
1949 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1950 reply_ng(CMD_MEASURE_ANTENNA_TUNING_LF, PM3_SUCCESS, NULL, 0);
1951 break;
1952 default:
1953 reply_ng(CMD_MEASURE_ANTENNA_TUNING_LF, PM3_EINVARG, NULL, 0);
1954 break;
1956 break;
1958 case CMD_LISTEN_READER_FIELD: {
1959 if (packet->length != sizeof(uint8_t))
1960 break;
1961 ListenReaderField(packet->data.asBytes[0]);
1962 break;
1964 case CMD_FPGA_MAJOR_MODE_OFF: { // ## FPGA Control
1965 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1966 SpinDelay(200);
1967 LED_D_OFF(); // LED D indicates field ON or OFF
1968 break;
1970 case CMD_DOWNLOAD_BIGBUF: {
1971 LED_B_ON();
1972 uint8_t *mem = BigBuf_get_addr();
1973 uint32_t startidx = packet->oldarg[0];
1974 uint32_t numofbytes = packet->oldarg[1];
1976 // arg0 = startindex
1977 // arg1 = length bytes to transfer
1978 // arg2 = BigBuf tracelen
1979 //Dbprintf("transfer to client parameters: %" PRIu32 " | %" PRIu32 " | %" PRIu32, startidx, numofbytes, packet->oldarg[2]);
1981 for (size_t i = 0; i < numofbytes; i += PM3_CMD_DATA_SIZE) {
1982 size_t len = MIN((numofbytes - i), PM3_CMD_DATA_SIZE);
1983 int result = reply_old(CMD_DOWNLOADED_BIGBUF, i, len, BigBuf_get_traceLen(), mem + startidx + i, len);
1984 if (result != PM3_SUCCESS)
1985 Dbprintf("transfer to client failed :: | bytes between %d - %d (%d) | result: %d", i, i + len, len, result);
1987 // Trigger a finish downloading signal with an ACK frame
1988 // iceman, when did sending samplingconfig array got attached here?!?
1989 // arg0 = status of download transfer
1990 // arg1 = RFU
1991 // arg2 = tracelen?
1992 // asbytes = samplingconfig array
1993 reply_mix(CMD_ACK, 1, 0, BigBuf_get_traceLen(), getSamplingConfig(), sizeof(sample_config));
1994 LED_B_OFF();
1995 break;
1997 #ifdef WITH_LF
1998 case CMD_LF_UPLOAD_SIM_SAMPLES: {
1999 // iceman; since changing fpga_bitstreams clears bigbuff, Its better to call it before.
2000 // to be able to use this one for uploading data to device
2001 // flag =
2002 // b0 0 skip
2003 // 1 clear bigbuff
2004 struct p {
2005 uint8_t flag;
2006 uint16_t offset;
2007 uint8_t data[PM3_CMD_DATA_SIZE - sizeof(uint8_t) - sizeof(uint16_t)];
2008 } PACKED;
2009 struct p *payload = (struct p *)packet->data.asBytes;
2011 FpgaDownloadAndGo(FPGA_BITSTREAM_LF);
2013 if ((payload->flag & 0x1) == 0x1) {
2014 BigBuf_Clear_ext(false);
2015 BigBuf_free();
2018 // offset should not be over buffer
2019 if (payload->offset >= BigBuf_get_size()) {
2020 reply_ng(CMD_LF_UPLOAD_SIM_SAMPLES, PM3_EOVFLOW, NULL, 0);
2021 break;
2023 // ensure len bytes copied wont go past end of bigbuf
2024 uint16_t len = MIN(BigBuf_get_size() - payload->offset, sizeof(payload->data));
2026 uint8_t *mem = BigBuf_get_addr();
2028 memcpy(mem + payload->offset, &payload->data, len);
2029 reply_ng(CMD_LF_UPLOAD_SIM_SAMPLES, PM3_SUCCESS, NULL, 0);
2030 break;
2032 #endif
2033 case CMD_DOWNLOAD_EML_BIGBUF: {
2034 LED_B_ON();
2035 uint8_t *mem = BigBuf_get_EM_addr();
2036 uint32_t startidx = packet->oldarg[0];
2037 uint32_t numofbytes = packet->oldarg[1];
2039 // arg0 = startindex
2040 // arg1 = length bytes to transfer
2041 // arg2 = RFU
2043 for (size_t i = 0; i < numofbytes; i += PM3_CMD_DATA_SIZE) {
2044 size_t len = MIN((numofbytes - i), PM3_CMD_DATA_SIZE);
2045 int result = reply_old(CMD_DOWNLOADED_EML_BIGBUF, i, len, 0, mem + startidx + i, len);
2046 if (result != PM3_SUCCESS)
2047 Dbprintf("transfer to client failed :: | bytes between %d - %d (%d) | result: %d", i, i + len, len, result);
2049 // Trigger a finish downloading signal with an ACK frame
2050 reply_mix(CMD_ACK, 1, 0, 0, 0, 0);
2051 LED_B_OFF();
2052 break;
2054 case CMD_READ_MEM: {
2055 if (packet->length != sizeof(uint32_t))
2056 break;
2057 ReadMem(packet->data.asDwords[0]);
2058 break;
2060 #ifdef WITH_FLASH
2061 case CMD_SPIFFS_TEST: {
2062 test_spiffs();
2063 break;
2065 case CMD_SPIFFS_CHECK: {
2066 rdv40_spiffs_check();
2067 break;
2069 case CMD_SPIFFS_MOUNT: {
2070 rdv40_spiffs_lazy_mount();
2071 break;
2073 case CMD_SPIFFS_UNMOUNT: {
2074 rdv40_spiffs_lazy_unmount();
2075 break;
2077 case CMD_SPIFFS_PRINT_TREE: {
2078 rdv40_spiffs_safe_print_tree();
2079 break;
2081 case CMD_SPIFFS_PRINT_FSINFO: {
2082 rdv40_spiffs_safe_print_fsinfo();
2083 break;
2085 case CMD_SPIFFS_DOWNLOAD: {
2086 LED_B_ON();
2087 uint8_t filename[32];
2088 uint8_t *pfilename = packet->data.asBytes;
2089 memcpy(filename, pfilename, SPIFFS_OBJ_NAME_LEN);
2090 if (DBGLEVEL >= DBG_DEBUG) Dbprintf("Filename received for spiffs dump : %s", filename);
2092 uint32_t size = packet->oldarg[1];
2094 uint8_t *buff = BigBuf_malloc(size);
2095 rdv40_spiffs_read_as_filetype((char *)filename, (uint8_t *)buff, size, RDV40_SPIFFS_SAFETY_SAFE);
2097 // arg0 = filename
2098 // arg1 = size
2099 // arg2 = RFU
2101 for (size_t i = 0; i < size; i += PM3_CMD_DATA_SIZE) {
2102 size_t len = MIN((size - i), PM3_CMD_DATA_SIZE);
2103 int result = reply_old(CMD_SPIFFS_DOWNLOADED, i, len, 0, buff + i, len);
2104 if (result != PM3_SUCCESS)
2105 Dbprintf("transfer to client failed :: | bytes between %d - %d (%d) | result: %d", i, i + len, len, result);
2107 // Trigger a finish downloading signal with an ACK frame
2108 reply_ng(CMD_SPIFFS_DOWNLOAD, PM3_SUCCESS, NULL, 0);
2109 LED_B_OFF();
2110 break;
2112 case CMD_SPIFFS_STAT: {
2113 LED_B_ON();
2114 uint8_t filename[32];
2115 uint8_t *pfilename = packet->data.asBytes;
2116 memcpy(filename, pfilename, SPIFFS_OBJ_NAME_LEN);
2117 if (DBGLEVEL >= DBG_DEBUG) {
2118 Dbprintf("Filename received for spiffs STAT : %s", filename);
2121 int changed = rdv40_spiffs_lazy_mount();
2122 uint32_t size = size_in_spiffs((char *)filename);
2123 if (changed) {
2124 rdv40_spiffs_lazy_unmount();
2127 reply_ng(CMD_SPIFFS_STAT, PM3_SUCCESS, (uint8_t *)&size, sizeof(uint32_t));
2128 LED_B_OFF();
2129 break;
2131 case CMD_SPIFFS_REMOVE: {
2132 LED_B_ON();
2134 struct p {
2135 uint8_t len;
2136 uint8_t fn[32];
2137 } PACKED;
2138 struct p *payload = (struct p *) packet->data.asBytes;
2140 if (DBGLEVEL >= DBG_DEBUG) {
2141 Dbprintf("Filename received for spiffs REMOVE : %s", payload->fn);
2144 rdv40_spiffs_remove((char *)payload->fn, RDV40_SPIFFS_SAFETY_SAFE);
2145 reply_ng(CMD_SPIFFS_REMOVE, PM3_SUCCESS, NULL, 0);
2146 LED_B_OFF();
2147 break;
2149 case CMD_SPIFFS_RENAME: {
2150 LED_B_ON();
2151 struct p {
2152 uint8_t slen;
2153 uint8_t src[32];
2154 uint8_t dlen;
2155 uint8_t dest[32];
2156 } PACKED;
2157 struct p *payload = (struct p *) packet->data.asBytes;
2159 if (DBGLEVEL >= DBG_DEBUG) {
2160 Dbprintf("SPIFFS RENAME");
2161 Dbprintf("Source........ %s", payload->src);
2162 Dbprintf("Destination... %s", payload->dest);
2164 rdv40_spiffs_rename((char *)payload->src, (char *)payload->dest, RDV40_SPIFFS_SAFETY_SAFE);
2165 reply_ng(CMD_SPIFFS_RENAME, PM3_SUCCESS, NULL, 0);
2166 LED_B_OFF();
2167 break;
2169 case CMD_SPIFFS_COPY: {
2170 LED_B_ON();
2171 struct p {
2172 uint8_t slen;
2173 uint8_t src[32];
2174 uint8_t dlen;
2175 uint8_t dest[32];
2176 } PACKED;
2177 struct p *payload = (struct p *) packet->data.asBytes;
2179 if (DBGLEVEL >= DBG_DEBUG) {
2180 Dbprintf("SPIFFS COPY");
2181 Dbprintf("Source........ %s", payload->src);
2182 Dbprintf("Destination... %s", payload->dest);
2184 rdv40_spiffs_copy((char *)payload->src, (char *)payload->dest, RDV40_SPIFFS_SAFETY_SAFE);
2185 reply_ng(CMD_SPIFFS_COPY, PM3_SUCCESS, NULL, 0);
2186 LED_B_OFF();
2187 break;
2189 case CMD_SPIFFS_WRITE: {
2190 LED_B_ON();
2192 flashmem_write_t *payload = (flashmem_write_t *)packet->data.asBytes;
2194 if (DBGLEVEL >= DBG_DEBUG) {
2195 Dbprintf("SPIFFS WRITE, dest `%s` with APPEND set to: %c", payload->fn, payload->append ? 'Y' : 'N');
2198 if (payload->append) {
2199 rdv40_spiffs_append((char *) payload->fn, payload->data, payload->bytes_in_packet, RDV40_SPIFFS_SAFETY_SAFE);
2200 } else {
2201 rdv40_spiffs_write((char *) payload->fn, payload->data, payload->bytes_in_packet, RDV40_SPIFFS_SAFETY_SAFE);
2204 reply_ng(CMD_SPIFFS_WRITE, PM3_SUCCESS, NULL, 0);
2205 LED_B_OFF();
2206 break;
2208 case CMD_SPIFFS_WIPE: {
2209 LED_B_ON();
2210 rdv40_spiffs_safe_wipe();
2211 reply_ng(CMD_SPIFFS_WIPE, PM3_SUCCESS, NULL, 0);
2212 LED_B_OFF();
2213 break;
2215 case CMD_FLASHMEM_SET_SPIBAUDRATE: {
2216 if (packet->length != sizeof(uint32_t))
2217 break;
2218 FlashmemSetSpiBaudrate(packet->data.asDwords[0]);
2219 break;
2221 case CMD_FLASHMEM_WRITE: {
2222 LED_B_ON();
2224 flashmem_old_write_t *payload = (flashmem_old_write_t *)packet->data.asBytes;
2226 if (FlashInit() == false) {
2227 reply_ng(CMD_FLASHMEM_WRITE, PM3_EIO, NULL, 0);
2228 LED_B_OFF();
2229 break;
2232 if (payload->startidx == DEFAULT_T55XX_KEYS_OFFSET) {
2233 Flash_CheckBusy(BUSY_TIMEOUT);
2234 Flash_WriteEnable();
2235 Flash_Erase4k(3, 0xC);
2236 } else if (payload->startidx == DEFAULT_MF_KEYS_OFFSET) {
2237 Flash_CheckBusy(BUSY_TIMEOUT);
2238 Flash_WriteEnable();
2239 Flash_Erase4k(3, 0x9);
2240 Flash_CheckBusy(BUSY_TIMEOUT);
2241 Flash_WriteEnable();
2242 Flash_Erase4k(3, 0xA);
2243 } else if (payload->startidx == DEFAULT_ICLASS_KEYS_OFFSET) {
2244 Flash_CheckBusy(BUSY_TIMEOUT);
2245 Flash_WriteEnable();
2246 Flash_Erase4k(3, 0xB);
2247 } else if (payload->startidx == FLASH_MEM_SIGNATURE_OFFSET) {
2248 Flash_CheckBusy(BUSY_TIMEOUT);
2249 Flash_WriteEnable();
2250 Flash_Erase4k(3, 0xF);
2253 uint16_t res = Flash_Write(payload->startidx, payload->data, payload->len);
2255 reply_ng(CMD_FLASHMEM_WRITE, (res == payload->len) ? PM3_SUCCESS : PM3_ESOFT, NULL, 0);
2256 LED_B_OFF();
2257 break;
2259 case CMD_FLASHMEM_WIPE: {
2260 LED_B_ON();
2261 uint8_t page = packet->oldarg[0];
2262 uint8_t initalwipe = packet->oldarg[1];
2263 bool isok = false;
2264 if (initalwipe) {
2265 isok = Flash_WipeMemory();
2266 reply_mix(CMD_ACK, isok, 0, 0, 0, 0);
2267 LED_B_OFF();
2268 break;
2270 if (page < 3)
2271 isok = Flash_WipeMemoryPage(page);
2273 reply_mix(CMD_ACK, isok, 0, 0, 0, 0);
2274 LED_B_OFF();
2275 break;
2277 case CMD_FLASHMEM_DOWNLOAD: {
2279 LED_B_ON();
2280 uint8_t *mem = BigBuf_malloc(PM3_CMD_DATA_SIZE);
2281 uint32_t startidx = packet->oldarg[0];
2282 uint32_t numofbytes = packet->oldarg[1];
2283 // arg0 = startindex
2284 // arg1 = length bytes to transfer
2285 // arg2 = RFU
2287 if (FlashInit() == false) {
2288 break;
2291 for (size_t i = 0; i < numofbytes; i += PM3_CMD_DATA_SIZE) {
2292 size_t len = MIN((numofbytes - i), PM3_CMD_DATA_SIZE);
2293 Flash_CheckBusy(BUSY_TIMEOUT);
2294 bool isok = Flash_ReadDataCont(startidx + i, mem, len);
2295 if (isok == false)
2296 Dbprintf("reading flash memory failed :: | bytes between %d - %d", i, len);
2298 isok = reply_old(CMD_FLASHMEM_DOWNLOADED, i, len, 0, mem, len);
2299 if (isok != 0)
2300 Dbprintf("transfer to client failed :: | bytes between %d - %d", i, len);
2302 FlashStop();
2304 reply_mix(CMD_ACK, 1, 0, 0, 0, 0);
2305 BigBuf_free();
2306 LED_B_OFF();
2307 break;
2309 case CMD_FLASHMEM_INFO: {
2311 LED_B_ON();
2312 rdv40_validation_t *info = (rdv40_validation_t *)BigBuf_malloc(sizeof(rdv40_validation_t));
2314 bool isok = Flash_ReadData(FLASH_MEM_SIGNATURE_OFFSET, info->signature, FLASH_MEM_SIGNATURE_LEN);
2316 if (FlashInit()) {
2317 Flash_UniqueID(info->flashid);
2318 FlashStop();
2320 reply_mix(CMD_ACK, isok, 0, 0, info, sizeof(rdv40_validation_t));
2321 BigBuf_free();
2323 LED_B_OFF();
2324 break;
2326 #endif
2327 case CMD_LF_SET_DIVISOR: {
2328 FpgaDownloadAndGo(FPGA_BITSTREAM_LF);
2329 FpgaSendCommand(FPGA_CMD_SET_DIVISOR, packet->data.asBytes[0]);
2330 break;
2332 case CMD_SET_ADC_MUX: {
2333 switch (packet->data.asBytes[0]) {
2334 case 0:
2335 SetAdcMuxFor(GPIO_MUXSEL_LOPKD);
2336 break;
2337 case 2:
2338 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
2339 break;
2340 #ifndef WITH_FPC_USART
2341 case 1:
2342 SetAdcMuxFor(GPIO_MUXSEL_LORAW);
2343 break;
2344 case 3:
2345 SetAdcMuxFor(GPIO_MUXSEL_HIRAW);
2346 break;
2347 #endif
2349 break;
2351 case CMD_VERSION: {
2352 SendVersion();
2353 break;
2355 case CMD_STATUS: {
2356 SendStatus();
2357 break;
2359 case CMD_TIA: {
2361 while ((AT91C_BASE_PMC->PMC_MCFR & AT91C_CKGR_MAINRDY) == 0); // Wait for MAINF value to become available...
2362 uint16_t mainf = AT91C_BASE_PMC->PMC_MCFR & AT91C_CKGR_MAINF;
2363 Dbprintf(" Slow clock old measured value:.........%d Hz", (16 * MAINCK) / mainf);
2364 TimingIntervalAcquisition();
2366 while ((AT91C_BASE_PMC->PMC_MCFR & AT91C_CKGR_MAINRDY) == 0); // Wait for MAINF value to become available...
2367 mainf = AT91C_BASE_PMC->PMC_MCFR & AT91C_CKGR_MAINF;
2368 Dbprintf(""); // first message gets lost
2369 Dbprintf(" Slow clock new measured value:.........%d Hz", (16 * MAINCK) / mainf);
2370 reply_ng(CMD_TIA, PM3_SUCCESS, NULL, 0);
2371 break;
2373 case CMD_STANDALONE: {
2374 uint8_t *bb = BigBuf_get_EM_addr();
2375 bb[0] = packet->data.asBytes[0];
2376 RunMod();
2377 break;
2379 case CMD_CAPABILITIES: {
2380 SendCapabilities();
2381 break;
2383 case CMD_PING: {
2384 reply_ng(CMD_PING, PM3_SUCCESS, packet->data.asBytes, packet->length);
2385 break;
2387 #ifdef WITH_LCD
2388 case CMD_LCD_RESET: {
2389 LCDReset();
2390 break;
2392 case CMD_LCD: {
2393 LCDSend(packet->oldarg[0]);
2394 break;
2396 #endif
2397 case CMD_FINISH_WRITE:
2398 case CMD_HARDWARE_RESET: {
2399 usb_disable();
2401 // (iceman) why this wait?
2402 SpinDelay(1000);
2403 AT91C_BASE_RSTC->RSTC_RCR = RST_CONTROL_KEY | AT91C_RSTC_PROCRST;
2404 // We're going to reset, and the bootrom will take control.
2405 for (;;) {}
2406 break;
2408 case CMD_START_FLASH: {
2409 if (common_area.flags.bootrom_present) {
2410 common_area.command = COMMON_AREA_COMMAND_ENTER_FLASH_MODE;
2412 usb_disable();
2413 AT91C_BASE_RSTC->RSTC_RCR = RST_CONTROL_KEY | AT91C_RSTC_PROCRST;
2414 // We're going to flash, and the bootrom will take control.
2415 for (;;) {}
2416 break;
2418 case CMD_DEVICE_INFO: {
2419 uint32_t dev_info = DEVICE_INFO_FLAG_OSIMAGE_PRESENT | DEVICE_INFO_FLAG_CURRENT_MODE_OS;
2420 if (common_area.flags.bootrom_present) {
2421 dev_info |= DEVICE_INFO_FLAG_BOOTROM_PRESENT;
2423 reply_old(CMD_DEVICE_INFO, dev_info, 0, 0, 0, 0);
2424 break;
2426 default: {
2427 Dbprintf("%s: 0x%04x", "unknown command:", packet->cmd);
2428 break;
2433 void __attribute__((noreturn)) AppMain(void) {
2435 SpinDelay(100);
2436 BigBuf_initialize();
2438 for (uint32_t *p = _stack_start; p < _stack_end - 0x200; ++p) {
2439 *p = 0xdeadbeef;
2442 LEDsoff();
2444 // The FPGA gets its clock from us from PCK0 output, so set that up.
2445 AT91C_BASE_PIOA->PIO_BSR = GPIO_PCK0;
2446 AT91C_BASE_PIOA->PIO_PDR = GPIO_PCK0;
2447 AT91C_BASE_PMC->PMC_SCER |= AT91C_PMC_PCK0;
2448 // PCK0 is PLL clock / 4 = 96MHz / 4 = 24MHz
2449 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
2450 AT91C_BASE_PIOA->PIO_OER = GPIO_PCK0;
2452 // Reset SPI
2453 AT91C_BASE_SPI->SPI_CR = AT91C_SPI_SWRST;
2454 AT91C_BASE_SPI->SPI_CR = AT91C_SPI_SWRST; // errata says it needs twice to be correctly set.
2456 // Reset SSC
2457 AT91C_BASE_SSC->SSC_CR = AT91C_SSC_SWRST;
2459 // Configure MUX
2460 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
2462 // Load the FPGA image, which we have stored in our flash.
2463 // (the HF version by default)
2464 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
2466 StartTickCount();
2468 #ifdef WITH_LCD
2469 LCDInit();
2470 #endif
2472 #ifdef WITH_SMARTCARD
2473 I2C_init();
2474 #endif
2476 #ifdef WITH_FPC_USART
2477 usart_init(USART_BAUD_RATE, USART_PARITY);
2478 #endif
2480 // This is made as late as possible to ensure enumeration without timeout
2481 // against device such as http://www.hobbytronics.co.uk/usb-host-board-v2
2482 usb_disable();
2483 usb_enable();
2484 allow_send_wtx = true;
2486 #ifdef WITH_FLASH
2487 // If flash is not present, BUSY_TIMEOUT kicks in, let's do it after USB
2488 loadT55xxConfig();
2491 // Enforce a spiffs check/garbage collection at boot so we are likely to never
2492 // fall under the 2 contigous free blocks availables
2493 rdv40_spiffs_check();
2494 #endif
2496 for (;;) {
2497 WDT_HIT();
2499 if (*_stack_start != 0xdeadbeef) {
2500 Dbprintf("Stack overflow detected! Please increase stack size, currently %d bytes", (uint32_t)_stack_end - (uint32_t)_stack_start);
2501 Dbprintf("Unplug your device now.");
2502 while (1);
2505 // Check if there is a packet available
2506 PacketCommandNG rx;
2507 memset(&rx.data, 0, sizeof(rx.data));
2509 int ret = receive_ng(&rx);
2510 if (ret == PM3_SUCCESS) {
2511 PacketReceived(&rx);
2512 } else if (ret != PM3_ENODATA) {
2514 Dbprintf("Error in frame reception: %d %s", ret, (ret == PM3_EIO) ? "PM3_EIO" : "");
2515 // TODO if error, shall we resync ?
2518 // Press button for one second to enter a possible standalone mode
2519 button_status = BUTTON_HELD(1000);
2520 if (button_status == BUTTON_HOLD) {
2522 * So this is the trigger to execute a standalone mod. Generic entrypoint by following the standalone/standalone.h headerfile
2523 * All standalone mod "main loop" should be the RunMod() function.
2525 allow_send_wtx = false;
2526 RunMod();
2527 allow_send_wtx = true;