osmo-sdr/firmware/usb-dfu-project/sam3u_chipid_usbserial.c @ master
1 |
#include <board.h>
|
---|---|
2 |
|
3 |
#include <stdio.h>
|
4 |
#include <string.h>
|
5 |
#include <errno.h>
|
6 |
#include <stdint.h>
|
7 |
#include <stdbool.h>
|
8 |
|
9 |
#include <memories/flash/flashd.h>
|
10 |
|
11 |
#include <usb/common/core/USBStringDescriptor.h>
|
12 |
|
13 |
#include <usb/device/dfu/dfu.h>
|
14 |
|
15 |
/* 128bit binary serial, equals 16 bytes -> 32 hex digits */
|
16 |
static uint8_t usb_serial_string[USBStringDescriptor_LENGTH(32)]; |
17 |
|
18 |
/* convert from 7-bit ASCII to USB string */
|
19 |
static int to_usb_string(unsigned char *out, int out_len, const char *in) |
20 |
{
|
21 |
int in_len = strlen(in); |
22 |
int num_out = USBStringDescriptor_LENGTH(in_len); |
23 |
int i; |
24 |
unsigned char *cur = out; |
25 |
|
26 |
if (num_out > out_len || num_out >= 255 || num_out < 0) |
27 |
return -EINVAL; |
28 |
|
29 |
*cur++ = num_out; |
30 |
*cur++ = USBGenericDescriptor_STRING; |
31 |
|
32 |
for (i = 0; i < in_len; i++) { |
33 |
*cur++ = in[i]; |
34 |
*cur++ = 0; |
35 |
}
|
36 |
|
37 |
return cur - out; |
38 |
}
|
39 |
|
40 |
static int chip_uid_to_usbstring(void) |
41 |
{
|
42 |
unsigned char uniqueID[17]; |
43 |
int rc; |
44 |
|
45 |
memset(uniqueID, 0, sizeof(uniqueID)); |
46 |
|
47 |
FLASHD_Initialize(0); |
48 |
rc = FLASHD_ReadUniqueID((unsigned long *) uniqueID); |
49 |
if (rc != 0) |
50 |
return -EIO; |
51 |
|
52 |
/* we skip the step to transform the unique-id into hex before
|
53 |
* converting it into a USB string, as it seems to consist of ASCII
|
54 |
* characters instead of a true 128 bit binary unique identifier */
|
55 |
rc = to_usb_string(usb_serial_string, sizeof(usb_serial_string), (char *) uniqueID); |
56 |
if (rc > 0) |
57 |
return 0; |
58 |
|
59 |
return rc; |
60 |
}
|
61 |
|
62 |
int chipid_to_usbserial(void) |
63 |
{
|
64 |
int rc; |
65 |
|
66 |
rc = chip_uid_to_usbstring(); |
67 |
if (rc < 0) |
68 |
return rc; |
69 |
|
70 |
set_usb_serial_str(usb_serial_string); |
71 |
|
72 |
return 0; |
73 |
}
|