1 /*
2  * Copyright (c) 2023-2024 Nordic Semiconductor ASA
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <sample_usbd.h>
8 
9 #include <zephyr/sys/byteorder.h>
10 #include <zephyr/usb/usbd.h>
11 #include <zephyr/usb/class/usbd_hid.h>
12 #include <zephyr/usb/msos_desc.h>
13 
14 #include <zephyr/logging/log.h>
15 LOG_MODULE_REGISTER(main, LOG_LEVEL_INF);
16 
17 /*
18  * There are three BOS descriptors used in the sample, a USB 2.0 EXTENSION from
19  * the USB samples common code, a Microsoft OS 2.0 platform capability
20  * descriptor, and a WebUSB platform capability descriptor.
21  */
22 #include "webusb.h"
23 #include "msosv2.h"
24 
msg_cb(struct usbd_context * const usbd_ctx,const struct usbd_msg * const msg)25 static void msg_cb(struct usbd_context *const usbd_ctx,
26 		   const struct usbd_msg *const msg)
27 {
28 	LOG_INF("USBD message: %s", usbd_msg_type_string(msg->type));
29 
30 	if (usbd_can_detect_vbus(usbd_ctx)) {
31 		if (msg->type == USBD_MSG_VBUS_READY) {
32 			if (usbd_enable(usbd_ctx)) {
33 				LOG_ERR("Failed to enable device support");
34 			}
35 		}
36 
37 		if (msg->type == USBD_MSG_VBUS_REMOVED) {
38 			if (usbd_disable(usbd_ctx)) {
39 				LOG_ERR("Failed to disable device support");
40 			}
41 		}
42 	}
43 }
44 
main(void)45 int main(void)
46 {
47 	struct usbd_context *sample_usbd;
48 	int ret;
49 
50 	sample_usbd = sample_usbd_setup_device(msg_cb);
51 	if (sample_usbd == NULL) {
52 		LOG_ERR("Failed to setup USB device");
53 		return -ENODEV;
54 	}
55 
56 	ret = usbd_add_descriptor(sample_usbd, &bos_vreq_msosv2);
57 	if (ret) {
58 		LOG_ERR("Failed to add MSOSv2 capability descriptor");
59 		return ret;
60 	}
61 
62 	ret = usbd_add_descriptor(sample_usbd, &bos_vreq_webusb);
63 	if (ret) {
64 		LOG_ERR("Failed to add WebUSB capability descriptor");
65 		return ret;
66 	}
67 
68 	ret = usbd_init(sample_usbd);
69 	if (ret) {
70 		LOG_ERR("Failed to initialize device support");
71 		return ret;
72 	}
73 
74 	if (!usbd_can_detect_vbus(sample_usbd)) {
75 		ret = usbd_enable(sample_usbd);
76 		if (ret) {
77 			LOG_ERR("Failed to enable device support");
78 			return ret;
79 		}
80 	}
81 
82 	return 0;
83 }
84