1 /*
2  * Copyright 2025 Google LLC
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <sample_usbd.h>
8 
9 #include <stdio.h>
10 #include <string.h>
11 #include <zephyr/device.h>
12 #include <zephyr/drivers/uart/uart_bridge.h>
13 #include <zephyr/kernel.h>
14 
15 #include <zephyr/usb/usb_device.h>
16 #include <zephyr/usb/usbd.h>
17 #include <zephyr/logging/log.h>
18 LOG_MODULE_REGISTER(cdc_acm_bridge, LOG_LEVEL_INF);
19 
20 const struct device *const uart_dev = DEVICE_DT_GET_ONE(zephyr_cdc_acm_uart);
21 
22 static struct usbd_context *sample_usbd;
23 
24 #define DEVICE_DT_GET_COMMA(node_id) DEVICE_DT_GET(node_id),
25 
26 const struct device *uart_bridges[] = {
27 	DT_FOREACH_STATUS_OKAY(zephyr_uart_bridge, DEVICE_DT_GET_COMMA)
28 };
29 
sample_msg_cb(struct usbd_context * const ctx,const struct usbd_msg * msg)30 static void sample_msg_cb(struct usbd_context *const ctx, const struct usbd_msg *msg)
31 {
32 	LOG_INF("USBD message: %s", usbd_msg_type_string(msg->type));
33 
34 	if (usbd_can_detect_vbus(ctx)) {
35 		if (msg->type == USBD_MSG_VBUS_READY) {
36 			if (usbd_enable(ctx)) {
37 				LOG_ERR("Failed to enable device support");
38 			}
39 		}
40 
41 		if (msg->type == USBD_MSG_VBUS_REMOVED) {
42 			if (usbd_disable(ctx)) {
43 				LOG_ERR("Failed to disable device support");
44 			}
45 		}
46 	}
47 
48 	if (msg->type == USBD_MSG_CDC_ACM_LINE_CODING ||
49 	    msg->type == USBD_MSG_CDC_ACM_CONTROL_LINE_STATE) {
50 		for (uint8_t i = 0; i < ARRAY_SIZE(uart_bridges); i++) {
51 			/* update all bridges, non valid combinations are
52 			 * skipped automatically.
53 			 */
54 			uart_bridge_settings_update(msg->dev, uart_bridges[i]);
55 		}
56 	}
57 }
58 
main(void)59 int main(void)
60 {
61 	int err;
62 
63 	sample_usbd = sample_usbd_init_device(sample_msg_cb);
64 	if (sample_usbd == NULL) {
65 		LOG_ERR("Failed to initialize USB device");
66 		return -ENODEV;
67 	}
68 
69 	if (!usbd_can_detect_vbus(sample_usbd)) {
70 		err = usbd_enable(sample_usbd);
71 		if (err) {
72 			LOG_ERR("Failed to enable device support");
73 			return err;
74 		}
75 	}
76 
77 	LOG_INF("USB device support enabled");
78 
79 	k_sleep(K_FOREVER);
80 
81 	return 0;
82 }
83