summaryrefslogtreecommitdiff
path: root/usb-dfu-experiment/sam3u_chipid_usbserial.c
blob: b81e6b9429030f9b5ef98e287bb274f81afbe6c1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <board.h>

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdint.h>
#include <stdbool.h>

#include <memories/flash/flashd.h>

#include <usb/common/core/USBStringDescriptor.h>

#include <usb/device/dfu/dfu.h>

/* 128bit binary serial, equals 16 bytes -> 32 hex digits */
static uint8_t usb_serial_string[USBStringDescriptor_LENGTH(32)];

/* convert from 7-bit ASCII to USB string */
static int to_usb_string(unsigned char *out, int out_len, const char *in)
{
	int in_len = strlen(in);
	int num_out = USBStringDescriptor_LENGTH(in_len);
	int i;
	unsigned char *cur = out;

	if (num_out > out_len || num_out >= 255 || num_out < 0)
		return -EINVAL;

	*cur++ = num_out;
	*cur++ = USBGenericDescriptor_STRING;

	for (i = 0; i < in_len; i++) {
		*cur++ = in[i];
		*cur++ = 0;
	}

	return cur - out;
}

static int chip_uid_to_usbstring(void)
{
	unsigned char uniqueID[17];
	int rc;

	memset(uniqueID, 0, sizeof(uniqueID));

	FLASHD_Initialize(0);
	rc = FLASHD_ReadUniqueID((unsigned long *) uniqueID);
	if (rc != 0)
		return -EIO;

	/* we skip the step to transform the unique-id into hex before
	 * converting it into a USB string, as it seems to consist of ASCII
	 * characters instead of a true 128 bit binary unique identifier */
	rc = to_usb_string(usb_serial_string, sizeof(usb_serial_string), (char *) uniqueID);
	if (rc > 0)
		return 0;

	return rc;
}

int chipid_to_usbserial(void)
{
	int rc;

	rc = chip_uid_to_usbstring();
	if (rc < 0)
		return rc;

	set_usb_serial_str(usb_serial_string);

	return 0;
}
personal git repositories of Harald Welte. Your mileage may vary