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 
19 static const struct device *const mic_dev = DEVICE_DT_GET_ONE(usb_audio_mic);
20 
data_received(const struct device * dev,struct net_buf * buffer,size_t size)21 static void data_received(const struct device *dev,
22 			  struct net_buf *buffer,
23 			  size_t size)
24 {
25 	int ret;
26 
27 	if (!buffer || !size) {
28 		/* This should never happen */
29 		return;
30 	}
31 
32 	LOG_DBG("Received %d data, buffer %p", size, buffer);
33 
34 	/* Check if OUT device buffer can be used for IN device */
35 	if (size == usb_audio_get_in_frame_size(mic_dev)) {
36 		ret = usb_audio_send(mic_dev, buffer, size);
37 		if (ret) {
38 			net_buf_unref(buffer);
39 		}
40 	} else {
41 		net_buf_unref(buffer);
42 	}
43 }
44 
feature_update(const struct device * dev,const struct usb_audio_fu_evt * evt)45 static void feature_update(const struct device *dev,
46 			   const struct usb_audio_fu_evt *evt)
47 {
48 	int16_t volume = 0;
49 
50 	LOG_DBG("Control selector %d for channel %d updated",
51 		evt->cs, evt->channel);
52 	switch (evt->cs) {
53 	case USB_AUDIO_FU_MUTE_CONTROL:
54 		break;
55 	case USB_AUDIO_FU_VOLUME_CONTROL:
56 		volume = UNALIGNED_GET((int16_t *)evt->val);
57 		LOG_INF("set volume: %d", volume);
58 		break;
59 	default:
60 		break;
61 	}
62 }
63 
64 static const struct usb_audio_ops hp_ops = {
65 	.data_received_cb = data_received,
66 	.feature_update_cb = feature_update,
67 };
68 
69 static const struct usb_audio_ops mic_ops = {
70 	.feature_update_cb = feature_update,
71 };
72 
main(void)73 int main(void)
74 {
75 	const struct device *const hp_dev = DEVICE_DT_GET_ONE(usb_audio_hp);
76 	int ret;
77 
78 	LOG_INF("Entered %s", __func__);
79 
80 	if (!device_is_ready(hp_dev)) {
81 		LOG_ERR("Device USB Headphones is not ready");
82 		return 0;
83 	}
84 
85 	LOG_INF("Found USB Headphones Device");
86 
87 	if (!device_is_ready(mic_dev)) {
88 		LOG_ERR("Device USB Microphone is not ready");
89 		return 0;
90 	}
91 
92 	LOG_INF("Found USB Microphone Device");
93 
94 	usb_audio_register(hp_dev, &hp_ops);
95 
96 	usb_audio_register(mic_dev, &mic_ops);
97 
98 	ret = usb_enable(NULL);
99 	if (ret != 0) {
100 		LOG_ERR("Failed to enable USB");
101 		return 0;
102 	}
103 
104 	LOG_INF("USB enabled");
105 	return 0;
106 }
107