1 /*
2  * Copyright (c) 2020 Nordic Semiconductor ASA
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 /**
8  * @file
9  * @brief Sample app for Audio class
10  */
11 
12 #include <zephyr/kernel.h>
13 #include <zephyr/logging/log.h>
14 #include <zephyr/usb/usb_device.h>
15 #include <zephyr/usb/class/usb_audio.h>
16 
17 LOG_MODULE_REGISTER(main, LOG_LEVEL_INF);
18 
data_received(const struct device * dev,struct net_buf * buffer,size_t size)19 static void data_received(const struct device *dev,
20 			  struct net_buf *buffer,
21 			  size_t size)
22 {
23 	int ret;
24 
25 	if (!buffer || !size) {
26 		/* This should never happen */
27 		return;
28 	}
29 
30 	LOG_DBG("Received %d data, buffer %p", size, buffer);
31 
32 	/* Check if the device OUT buffer can be used for input */
33 	if (size == usb_audio_get_in_frame_size(dev)) {
34 		ret = usb_audio_send(dev, buffer, size);
35 		if (ret) {
36 			net_buf_unref(buffer);
37 		}
38 	} else {
39 		net_buf_unref(buffer);
40 	}
41 }
42 
feature_update(const struct device * dev,const struct usb_audio_fu_evt * evt)43 static void feature_update(const struct device *dev,
44 			   const struct usb_audio_fu_evt *evt)
45 {
46 	int16_t volume = 0;
47 
48 	LOG_DBG("Control selector %d for channel %d updated",
49 		evt->cs, evt->channel);
50 	switch (evt->cs) {
51 	case USB_AUDIO_FU_MUTE_CONTROL:
52 		break;
53 	case USB_AUDIO_FU_VOLUME_CONTROL:
54 		volume = UNALIGNED_GET((int16_t *)evt->val);
55 		LOG_INF("set volume: %d", volume);
56 		break;
57 	default:
58 		break;
59 	}
60 }
61 
62 static const struct usb_audio_ops ops = {
63 	.data_received_cb = data_received,
64 	.feature_update_cb = feature_update,
65 };
66 
main(void)67 int main(void)
68 {
69 	const struct device *hs_dev;
70 	int ret;
71 
72 	LOG_INF("Entered %s", __func__);
73 	hs_dev = DEVICE_DT_GET_ONE(usb_audio_hs);
74 
75 	if (!device_is_ready(hs_dev)) {
76 		LOG_ERR("Device USB Headset is not ready");
77 		return 0;
78 	}
79 
80 	LOG_INF("Found USB Headset Device");
81 
82 	usb_audio_register(hs_dev, &ops);
83 
84 	ret = usb_enable(NULL);
85 	if (ret != 0) {
86 		LOG_ERR("Failed to enable USB");
87 		return 0;
88 	}
89 
90 	LOG_INF("USB enabled");
91 	return 0;
92 }
93