The Audio_Device_IsSampleReceived() and Audio_Device_IsReadyForNextSample() functions...
[pub/USBasp.git] / Demos / Host / Incomplete / BluetoothHost / Lib / BluetoothHCICommands.c
1 /*
2 LUFA Library
3 Copyright (C) Dean Camera, 2010.
4
5 dean [at] fourwalledcubicle [dot] com
6 www.fourwalledcubicle.com
7 */
8
9 /*
10 Copyright 2010 Dean Camera (dean [at] fourwalledcubicle [dot] com)
11
12 Permission to use, copy, modify, distribute, and sell this
13 software and its documentation for any purpose is hereby granted
14 without fee, provided that the above copyright notice appear in
15 all copies and that both that the copyright notice and this
16 permission notice and warranty disclaimer appear in supporting
17 documentation, and that the name of the author not be used in
18 advertising or publicity pertaining to distribution of the
19 software without specific, written prior permission.
20
21 The author disclaim all warranties with regard to this
22 software, including all implied warranties of merchantability
23 and fitness. In no event shall the author be liable for any
24 special, indirect or consequential damages or any damages
25 whatsoever resulting from loss of use, data or profits, whether
26 in an action of contract, negligence or other tortious action,
27 arising out of or in connection with the use or performance of
28 this software.
29 */
30
31 /*
32 TODO: Add local to remote device connections
33 */
34
35 #define INCLUDE_FROM_BLUETOOTHHCICOMMANDS_C
36 #include "BluetoothHCICommands.h"
37
38 /** Temporary Bluetooth Device Address, for HCI responses which much include the detination address */
39 static uint8_t Bluetooth_TempDeviceAddress[6];
40
41 /** Bluetooth HCI processing task. This task should be called repeatedly the main Bluetooth
42 * stack task to manage the HCI processing state.
43 */
44 void Bluetooth_HCITask(void)
45 {
46 BT_HCICommand_Header_t HCICommandHeader;
47
48 switch (Bluetooth_State.CurrentHCIState)
49 {
50 case Bluetooth_ProcessEvents:
51 Pipe_SelectPipe(BLUETOOTH_EVENTS_PIPE);
52 Pipe_Unfreeze();
53
54 if (Pipe_IsReadWriteAllowed())
55 {
56 BT_HCIEvent_Header_t HCIEventHeader;
57
58 /* Read in the event header to fetch the event code and payload length */
59 Pipe_Read_Stream_LE(&HCIEventHeader, sizeof(HCIEventHeader));
60
61 /* Create a temporary buffer for the event parameters */
62 uint8_t EventParams[HCIEventHeader.ParameterLength];
63
64 /* Read in the event parameters into the temporary buffer */
65 Pipe_Read_Stream_LE(&EventParams, HCIEventHeader.ParameterLength);
66 Pipe_ClearIN();
67
68 BT_HCI_DEBUG(1, "Event Received (0x%02X)", HCIEventHeader.EventCode);
69
70 switch (HCIEventHeader.EventCode)
71 {
72 case EVENT_COMMAND_COMPLETE:
73 BT_HCI_DEBUG(1, "<< Command Complete");
74
75 /* Check which operation was completed in case we need to process the even parameters */
76 switch (((BT_HCIEvent_CommandComplete_t*)&EventParams)->Opcode)
77 {
78 case (OGF_CTRLR_INFORMATIONAL | OCF_CTRLR_INFORMATIONAL_READBDADDR):
79 /* A READ BDADDR command completed, copy over the local device's BDADDR from the response */
80 memcpy(Bluetooth_State.LocalBDADDR,
81 &((BT_HCIEvent_CommandComplete_t*)&EventParams)->ReturnParams[1],
82 sizeof(Bluetooth_State.LocalBDADDR));
83 break;
84 }
85
86 Bluetooth_State.CurrentHCIState = Bluetooth_State.NextHCIState;
87 break;
88 case EVENT_COMMAND_STATUS:
89 BT_HCI_DEBUG(1, "<< Command Status");
90 BT_HCI_DEBUG(2, "-- Status Code: 0x%02X", (((BT_HCIEvent_CommandStatus_t*)&EventParams)->Status));
91
92 /* If the execution of a command failed, reset the stack */
93 if (((BT_HCIEvent_CommandStatus_t*)&EventParams)->Status)
94 Bluetooth_State.CurrentHCIState = Bluetooth_Init;
95 break;
96 case EVENT_CONNECTION_REQUEST:
97 BT_HCI_DEBUG(1, "<< Connection Request");
98 BT_HCI_DEBUG(2, "-- Link Type: 0x%02X", (((BT_HCIEvent_ConnectionRequest_t*)&EventParams)->LinkType));
99
100 /* Need to store the remote device's BT address in a temporary buffer for later use */
101 memcpy(Bluetooth_TempDeviceAddress,
102 &((BT_HCIEvent_ConnectionRequest_t*)&EventParams)->RemoteAddress,
103 sizeof(Bluetooth_TempDeviceAddress));
104
105 bool IsACLConnection = (((BT_HCIEvent_ConnectionRequest_t*)&EventParams)->LinkType == 0x01);
106
107 /* Only accept the connection if it is a ACL (data) connection, a device is not already connected
108 and the user application has indicated that the connection should be allowed */
109 Bluetooth_State.CurrentHCIState = (Bluetooth_Connection.IsConnected || !(IsACLConnection) ||
110 !(Bluetooth_ConnectionRequest(Bluetooth_TempDeviceAddress))) ?
111 Bluetooth_Conn_RejectConnection : Bluetooth_Conn_AcceptConnection;
112
113 BT_HCI_DEBUG(2, "-- Connection %S", (Bluetooth_State.CurrentHCIState == Bluetooth_Conn_RejectConnection) ?
114 PSTR("REJECTED") : PSTR("ACCEPTED"));
115
116 break;
117 case EVENT_PIN_CODE_REQUEST:
118 BT_HCI_DEBUG(1, "<< Pin Code Request");
119
120 /* Need to store the remote device's BT address in a temporary buffer for later use */
121 memcpy(Bluetooth_TempDeviceAddress,
122 &((BT_HCIEvent_PinCodeReq_t*)&EventParams)->RemoteAddress,
123 sizeof(Bluetooth_TempDeviceAddress));
124
125 Bluetooth_State.CurrentHCIState = Bluetooth_Conn_SendPINCode;
126 break;
127 case EVENT_LINK_KEY_REQUEST:
128 BT_HCI_DEBUG(1, "<< Link Key Request");
129
130 /* Need to store the remote device's BT address in a temporary buffer for later use */
131 memcpy(Bluetooth_TempDeviceAddress,
132 &((BT_HCIEvent_LinkKeyReq_t*)&EventParams)->RemoteAddress,
133 sizeof(Bluetooth_TempDeviceAddress));
134
135 Bluetooth_State.CurrentHCIState = Bluetooth_Conn_SendLinkKeyNAK;
136 break;
137 case EVENT_CONNECTION_COMPLETE:
138 BT_HCI_DEBUG(1, "<< Connection Complete");
139 BT_HCI_DEBUG(2, "-- Handle: 0x%04X", ((BT_HCIEvent_ConnectionComplete_t*)&EventParams)->ConnectionHandle);
140
141 /* Need to store the remote device's BT address in a temporary buffer for later use */
142 memcpy(Bluetooth_Connection.RemoteAddress,
143 &((BT_HCIEvent_ConnectionComplete_t*)&EventParams)->RemoteAddress,
144 sizeof(Bluetooth_TempDeviceAddress));
145
146 /* Store the created connection handle and indicate that the connection has been established */
147 Bluetooth_Connection.ConnectionHandle = ((BT_HCIEvent_ConnectionComplete_t*)&EventParams)->ConnectionHandle;
148 Bluetooth_Connection.IsConnected = true;
149
150 Bluetooth_ConnectionComplete();
151 break;
152 case EVENT_DISCONNECTION_COMPLETE:
153 BT_HCI_DEBUG(1, "<< Disconnection Complete");
154
155 /* Device disconnected, indicate connection information no longer valid */
156 Bluetooth_Connection.IsConnected = false;
157
158 Bluetooth_DisconnectionComplete();
159
160 Bluetooth_State.CurrentHCIState = Bluetooth_Init;
161 break;
162 }
163 }
164
165 Pipe_Freeze();
166
167 break;
168 case Bluetooth_Init:
169 BT_HCI_DEBUG(1, "# Init");
170
171 Bluetooth_State.IsInitialized = false;
172
173 /* Reset the connection information structure to destroy any previous connection state */
174 memset(&Bluetooth_Connection, 0x00, sizeof(Bluetooth_Connection));
175
176 Bluetooth_State.CurrentHCIState = Bluetooth_Init_Reset;
177 break;
178 case Bluetooth_Init_Reset:
179 BT_HCI_DEBUG(1, "# Reset");
180
181 HCICommandHeader = (BT_HCICommand_Header_t)
182 {
183 OpCode: (OGF_CTRLR_BASEBAND | OCF_CTRLR_BASEBAND_RESET),
184 ParameterLength: 0,
185 };
186
187 /* Send the command to reset the bluetooth dongle controller */
188 Bluetooth_SendHCICommand(&HCICommandHeader, NULL, 0);
189
190 Bluetooth_State.NextHCIState = Bluetooth_Init_ReadBufferSize;
191 Bluetooth_State.CurrentHCIState = Bluetooth_ProcessEvents;
192 break;
193 case Bluetooth_Init_ReadBufferSize:
194 BT_HCI_DEBUG(1, "# Read Buffer Size");
195
196 HCICommandHeader = (BT_HCICommand_Header_t)
197 {
198 OpCode: (OGF_CTRLR_INFORMATIONAL | OCF_CTRLR_INFORMATIONAL_READBUFFERSIZE),
199 ParameterLength: 0,
200 };
201
202 /* Send the command to read the bluetooth buffer size (mandatory before device sends any data) */
203 Bluetooth_SendHCICommand(&HCICommandHeader, NULL, 0);
204
205 Bluetooth_State.NextHCIState = Bluetooth_Init_GetBDADDR;
206 Bluetooth_State.CurrentHCIState = Bluetooth_ProcessEvents;
207 break;
208 case Bluetooth_Init_GetBDADDR:
209 BT_HCI_DEBUG(1, "# Get BDADDR");
210
211 HCICommandHeader = (BT_HCICommand_Header_t)
212 {
213 OpCode: (OGF_CTRLR_INFORMATIONAL | OCF_CTRLR_INFORMATIONAL_READBDADDR),
214 ParameterLength: 0,
215 };
216
217 /* Send the command to retrieve the BDADDR of the inserted bluetooth dongle */
218 Bluetooth_SendHCICommand(&HCICommandHeader, NULL, 0);
219
220 Bluetooth_State.NextHCIState = Bluetooth_Init_SetLocalName;
221 Bluetooth_State.CurrentHCIState = Bluetooth_ProcessEvents;
222 break;
223 case Bluetooth_Init_SetLocalName:
224 BT_HCI_DEBUG(1, "# Set Local Name");
225
226 HCICommandHeader = (BT_HCICommand_Header_t)
227 {
228 OpCode: (OGF_CTRLR_BASEBAND | OCF_CTRLR_BASEBAND_WRITE_LOCAL_NAME),
229 ParameterLength: 248,
230 };
231
232 /* Send the command to set the bluetooth dongle's name for other devices to see */
233 Bluetooth_SendHCICommand(&HCICommandHeader, Bluetooth_DeviceConfiguration.Name, strlen(Bluetooth_DeviceConfiguration.Name));
234
235 Bluetooth_State.NextHCIState = Bluetooth_Init_SetDeviceClass;
236 Bluetooth_State.CurrentHCIState = Bluetooth_ProcessEvents;
237 break;
238 case Bluetooth_Init_SetDeviceClass:
239 BT_HCI_DEBUG(1, "# Set Device Class");
240
241 HCICommandHeader = (BT_HCICommand_Header_t)
242 {
243 OpCode: (OGF_CTRLR_BASEBAND | OCF_CTRLR_BASEBAND_WRITE_CLASS_OF_DEVICE),
244 ParameterLength: 3,
245 };
246
247 /* Send the command to set the class of the device for other devices to see */
248 Bluetooth_SendHCICommand(&HCICommandHeader, &Bluetooth_DeviceConfiguration.Class, 3);
249
250 Bluetooth_State.NextHCIState = Bluetooth_Init_WriteScanEnable;
251 Bluetooth_State.CurrentHCIState = Bluetooth_ProcessEvents;
252 break;
253 case Bluetooth_Init_WriteScanEnable:
254 BT_HCI_DEBUG(1, "# Write Scan Enable");
255
256 HCICommandHeader = (BT_HCICommand_Header_t)
257 {
258 OpCode: (OGF_CTRLR_BASEBAND | OCF_CTRLR_BASEBAND_WRITE_SCAN_ENABLE),
259 ParameterLength: 1,
260 };
261
262 uint8_t Interval = BT_SCANMODE_InquiryAndPageScans;
263
264 /* Send the command to set the remote device scanning mode */
265 Bluetooth_SendHCICommand(&HCICommandHeader, &Interval, 1);
266
267 Bluetooth_State.NextHCIState = Bluetooth_Init_FinalizeInit;
268 Bluetooth_State.CurrentHCIState = Bluetooth_ProcessEvents;
269 break;
270 case Bluetooth_Init_FinalizeInit:
271 Bluetooth_State.IsInitialized = true;
272
273 /* Fire the user application callback to indicate that the stack is now fully initialized */
274 Bluetooth_StackInitialized();
275
276 Bluetooth_State.NextHCIState = Bluetooth_ProcessEvents;
277 Bluetooth_State.CurrentHCIState = Bluetooth_ProcessEvents;
278 break;
279 case Bluetooth_Conn_AcceptConnection:
280 BT_HCI_DEBUG(1, "# Accept Connection");
281
282 HCICommandHeader = (BT_HCICommand_Header_t)
283 {
284 OpCode: (OGF_LINK_CONTROL | OCF_LINK_CONTROL_ACCEPT_CONNECTION_REQUEST),
285 ParameterLength: sizeof(BT_HCICommand_AcceptConnectionReq_t),
286 };
287
288 /* Copy over the temporary BT device address saved from the Connection Request event, indicate slave
289 connection role */
290 BT_HCICommand_AcceptConnectionReq_t AcceptConnectionParams;
291 memcpy(AcceptConnectionParams.RemoteAddress, Bluetooth_TempDeviceAddress,
292 sizeof(AcceptConnectionParams.RemoteAddress));
293 AcceptConnectionParams.SlaveRole = true;
294
295 /* Send the command to accept the remote connection request */
296 Bluetooth_SendHCICommand(&HCICommandHeader, &AcceptConnectionParams, sizeof(BT_HCICommand_AcceptConnectionReq_t));
297
298 Bluetooth_State.CurrentHCIState = Bluetooth_ProcessEvents;
299 break;
300 case Bluetooth_Conn_RejectConnection:
301 BT_HCI_DEBUG(1, "# Reject Connection");
302
303 HCICommandHeader = (BT_HCICommand_Header_t)
304 {
305 OpCode: (OGF_LINK_CONTROL | OCF_LINK_CONTROL_REJECT_CONNECTION_REQUEST),
306 ParameterLength: sizeof(BT_HCICommand_RejectConnectionReq_t),
307 };
308
309 /* Copy over the temporary BT device address saved from the Connection Request event, indicate failure
310 to accept the connection due to limited device resources or incorrect device address */
311 BT_HCICommand_RejectConnectionReq_t RejectConnectionParams;
312 memcpy(RejectConnectionParams.RemoteAddress, Bluetooth_TempDeviceAddress, sizeof(RejectConnectionParams.RemoteAddress));
313 RejectConnectionParams.Reason = Bluetooth_Connection.IsConnected ? ERROR_LIMITED_RESOURCES : ERROR_UNACCEPTABLE_BDADDR;
314
315 /* Send the command to reject the remote connection request */
316 Bluetooth_SendHCICommand(&HCICommandHeader, &RejectConnectionParams, sizeof(BT_HCICommand_RejectConnectionReq_t));
317
318 Bluetooth_State.CurrentHCIState = Bluetooth_ProcessEvents;
319 break;
320 case Bluetooth_Conn_SendPINCode:
321 BT_HCI_DEBUG(1, "# Send Pin Code");
322
323 HCICommandHeader = (BT_HCICommand_Header_t)
324 {
325 OpCode: (OGF_LINK_CONTROL | OCF_LINK_CONTROL_PIN_CODE_REQUEST_REPLY),
326 ParameterLength: sizeof(BT_HCICommand_PinCodeResp_t),
327 };
328
329 /* Copy over the temporary BT device address saved from the PIN Code Request event, copy over the
330 local PIN authentication code to the response */
331 BT_HCICommand_PinCodeResp_t PINCodeRequestParams;
332 memcpy(PINCodeRequestParams.RemoteAddress, Bluetooth_TempDeviceAddress, sizeof(PINCodeRequestParams.RemoteAddress));
333 PINCodeRequestParams.PINCodeLength = strlen(Bluetooth_DeviceConfiguration.PINCode);
334 memcpy(PINCodeRequestParams.PINCode, Bluetooth_DeviceConfiguration.PINCode, sizeof(PINCodeRequestParams.PINCode));
335
336 /* Send the command to transmit the device's local PIN number for authentication */
337 Bluetooth_SendHCICommand(&HCICommandHeader, &PINCodeRequestParams, sizeof(BT_HCICommand_PinCodeResp_t));
338
339 Bluetooth_State.CurrentHCIState = Bluetooth_ProcessEvents;
340 break;
341 case Bluetooth_Conn_SendLinkKeyNAK:
342 BT_HCI_DEBUG(1, "# Send Link Key NAK");
343
344 HCICommandHeader = (BT_HCICommand_Header_t)
345 {
346 OpCode: (OGF_LINK_CONTROL | OCF_LINK_CONTROL_LINK_KEY_REQUEST_NEG_REPLY),
347 ParameterLength: sizeof(BT_HCICommand_LinkKeyNAKResp_t),
348 };
349
350 /* Copy over the temporary BT device address saved from the Link Key Request event */
351 BT_HCICommand_LinkKeyNAKResp_t LinkKeyNAKParams;
352 memcpy(LinkKeyNAKParams.RemoteAddress, Bluetooth_TempDeviceAddress, sizeof(LinkKeyNAKParams.RemoteAddress));
353
354 /* Send the command to transmit the link key NAK to the receiver */
355 Bluetooth_SendHCICommand(&HCICommandHeader, &LinkKeyNAKParams, sizeof(BT_HCICommand_LinkKeyNAKResp_t));
356
357 Bluetooth_State.CurrentHCIState = Bluetooth_ProcessEvents;
358 break;
359 }
360 }
361
362 /** Sends a Bluetooth HCI control command to the attached Bluetooth device.
363 *
364 * \param[in] HCICommandHeader HCI command header to send to the attached device
365 * \param[in] Parameters Pointer to the source of the control parameters (if any)
366 * \param[in] ParameterLength Length of the parameters to send in bytes
367 *
368 * \return A value from the USB_Host_SendControlErrorCodes_t enum.
369 */
370 static uint8_t Bluetooth_SendHCICommand(const BT_HCICommand_Header_t* const HCICommandHeader, const void* Parameters, const uint16_t ParameterLength)
371 {
372 /* Need to reserve the amount of bytes given in the header for the complete payload */
373 uint8_t CommandBuffer[sizeof(BT_HCICommand_Header_t) + HCICommandHeader->ParameterLength];
374
375 USB_ControlRequest = (USB_Request_Header_t)
376 {
377 .bmRequestType = (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_DEVICE),
378 .bRequest = 0,
379 .wValue = 0,
380 .wIndex = 0,
381 .wLength = sizeof(CommandBuffer)
382 };
383
384 /* Copy over the HCI command header to the allocated buffer */
385 memcpy(CommandBuffer, HCICommandHeader, sizeof(BT_HCICommand_Header_t));
386
387 /* Zero out the parameter section of the response so that all padding bytes are known to be zero */
388 memset(&CommandBuffer[sizeof(BT_HCICommand_Header_t)], 0x00, HCICommandHeader->ParameterLength);
389
390 /* Copy over the command parameters (if any) to the command buffer - note, the number of actual source parameter bytes
391 may differ to those in the header; any difference in length is filled with 0x00 padding bytes */
392 memcpy(&CommandBuffer[sizeof(BT_HCICommand_Header_t)], Parameters, ParameterLength);
393
394 Pipe_SelectPipe(PIPE_CONTROLPIPE);
395 return USB_Host_SendControlRequest(CommandBuffer);
396 }