Better USB connection detection

This commit is contained in:
Lynn Ochs 2021-08-15 17:44:00 +02:00
parent 14ae66d206
commit 6f81461b2c
3 changed files with 17 additions and 9 deletions

8
main.c
View File

@ -104,11 +104,11 @@ int main(void) {
int last_pos = 0;
uint32_t watchdog_counter = 0;
while (tick < 5000) {
while (tick < 5000 && !usb_connected()) {
usbd_poll(g_usbd_dev);
}
if (!usb_got_reset()) {
if (!usb_connected()) {
fast_reset();
}
@ -210,7 +210,7 @@ int main(void) {
/* Send replies */
if ((buf_len = ringbuffer_peek(comm_out_buf, &buf[0], sizeof buf))) {
if (usb_write_cdcacm(ACM_COMM, (void *)buf, buf_len, 1)) {
if (!usb_connected() || usb_write_cdcacm(ACM_COMM, (void *)buf, buf_len, 1)) {
ringbuffer_skip(comm_out_buf, buf_len);
}
}
@ -218,7 +218,7 @@ int main(void) {
/* Send any available data to the NFC CDC */
if (!ringbuffer_empty(uart_to_usb_buf)) {
unsigned len = ringbuffer_peek(uart_to_usb_buf, &buf[0], sizeof buf);
if (usb_write_cdcacm(ACM_NFC, &buf[0], len, 1)) {
if (!usb_connected() || usb_write_cdcacm(ACM_NFC, &buf[0], len, 1)) {
ringbuffer_skip(uart_to_usb_buf, len);
}
}

16
usb.c
View File

@ -11,6 +11,9 @@
extern ringbuffer *usb_to_uart_buf, *comm_in_buf;
static void usb_reset_callback(void);
static void usb_suspend_callback(void);
/* Number of serial devices we want to provide. */
#define NUM_SERIAL 2
@ -40,7 +43,7 @@ static char const *usb_strings[] = {
[3 + ACM_NFC] = "RFID",
};
static int got_reset = 0;
static int connected = 0;
usbd_device *g_usbd_dev;
@ -176,11 +179,15 @@ static void cdcacm_set_config(usbd_device *usbd_dev, uint16_t wValue) {
}
void usb_reset_callback(void) {
got_reset = 1;
connected = 1;
}
bool usb_got_reset(void) {
return got_reset;
void usb_suspend_callback(void) {
connected = 0;
}
bool usb_connected(void) {
return connected;
}
void usb_setup() {
@ -337,6 +344,7 @@ void usb_reinit() {
usbd_control_buffer, sizeof(usbd_control_buffer));
usbd_register_reset_callback(g_usbd_dev, &usb_reset_callback);
usbd_register_suspend_callback(g_usbd_dev, &usb_suspend_callback);
usbd_register_set_config_callback(g_usbd_dev, cdcacm_set_config);
}

2
usb.h
View File

@ -8,7 +8,7 @@ extern usbd_device *g_usbd_dev;
void usb_setup(void);
void usb_reinit(void);
int usb_write_cdcacm(uint8_t acm, void *data, size_t len, int tries);
bool usb_got_reset(void);
bool usb_connected(void);
#define ACM_NFC 1
#define ACM_COMM 0