Start implementation of RFCOMM decoding layer. Add new service initialize routines...
[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 break;
160 }
161 }
162
163 Pipe_Freeze();
164
165 break;
166 case Bluetooth_Init:
167 BT_HCI_DEBUG(1, "# Init");
168
169 Bluetooth_State.IsInitialized = false;
170
171 /* Reset the connection information structure to destroy any previous connection state */
172 memset(&Bluetooth_Connection, 0x00, sizeof(Bluetooth_Connection));
173
174 Bluetooth_State.CurrentHCIState = Bluetooth_Init_Reset;
175 break;
176 case Bluetooth_Init_Reset:
177 BT_HCI_DEBUG(1, "# Reset");
178
179 HCICommandHeader = (BT_HCICommand_Header_t)
180 {
181 OpCode: (OGF_CTRLR_BASEBAND | OCF_CTRLR_BASEBAND_RESET),
182 ParameterLength: 0,
183 };
184
185 /* Send the command to reset the bluetooth dongle controller */
186 Bluetooth_SendHCICommand(&HCICommandHeader, NULL, 0);
187
188 Bluetooth_State.NextHCIState = Bluetooth_Init_ReadBufferSize;
189 Bluetooth_State.CurrentHCIState = Bluetooth_ProcessEvents;
190 break;
191 case Bluetooth_Init_ReadBufferSize:
192 BT_HCI_DEBUG(1, "# Read Buffer Size");
193
194 HCICommandHeader = (BT_HCICommand_Header_t)
195 {
196 OpCode: (OGF_CTRLR_INFORMATIONAL | OCF_CTRLR_INFORMATIONAL_READBUFFERSIZE),
197 ParameterLength: 0,
198 };
199
200 /* Send the command to read the bluetooth buffer size (mandatory before device sends any data) */
201 Bluetooth_SendHCICommand(&HCICommandHeader, NULL, 0);
202
203 Bluetooth_State.NextHCIState = Bluetooth_Init_GetBDADDR;
204 Bluetooth_State.CurrentHCIState = Bluetooth_ProcessEvents;
205 break;
206 case Bluetooth_Init_GetBDADDR:
207 BT_HCI_DEBUG(1, "# Get BDADDR");
208
209 HCICommandHeader = (BT_HCICommand_Header_t)
210 {
211 OpCode: (OGF_CTRLR_INFORMATIONAL | OCF_CTRLR_INFORMATIONAL_READBDADDR),
212 ParameterLength: 0,
213 };
214
215 /* Send the command to retrieve the BDADDR of the inserted bluetooth dongle */
216 Bluetooth_SendHCICommand(&HCICommandHeader, NULL, 0);
217
218 Bluetooth_State.NextHCIState = Bluetooth_Init_SetLocalName;
219 Bluetooth_State.CurrentHCIState = Bluetooth_ProcessEvents;
220 break;
221 case Bluetooth_Init_SetLocalName:
222 BT_HCI_DEBUG(1, "# Set Local Name");
223
224 HCICommandHeader = (BT_HCICommand_Header_t)
225 {
226 OpCode: (OGF_CTRLR_BASEBAND | OCF_CTRLR_BASEBAND_WRITE_LOCAL_NAME),
227 ParameterLength: 248,
228 };
229
230 /* Send the command to set the bluetooth dongle's name for other devices to see */
231 Bluetooth_SendHCICommand(&HCICommandHeader, Bluetooth_DeviceConfiguration.Name, strlen(Bluetooth_DeviceConfiguration.Name));
232
233 Bluetooth_State.NextHCIState = Bluetooth_Init_SetDeviceClass;
234 Bluetooth_State.CurrentHCIState = Bluetooth_ProcessEvents;
235 break;
236 case Bluetooth_Init_SetDeviceClass:
237 BT_HCI_DEBUG(1, "# Set Device Class");
238
239 HCICommandHeader = (BT_HCICommand_Header_t)
240 {
241 OpCode: (OGF_CTRLR_BASEBAND | OCF_CTRLR_BASEBAND_WRITE_CLASS_OF_DEVICE),
242 ParameterLength: 3,
243 };
244
245 /* Send the command to set the class of the device for other devices to see */
246 Bluetooth_SendHCICommand(&HCICommandHeader, &Bluetooth_DeviceConfiguration.Class, 3);
247
248 Bluetooth_State.NextHCIState = Bluetooth_Init_WriteScanEnable;
249 Bluetooth_State.CurrentHCIState = Bluetooth_ProcessEvents;
250 break;
251 case Bluetooth_Init_WriteScanEnable:
252 BT_HCI_DEBUG(1, "# Write Scan Enable");
253
254 HCICommandHeader = (BT_HCICommand_Header_t)
255 {
256 OpCode: (OGF_CTRLR_BASEBAND | OCF_CTRLR_BASEBAND_WRITE_SCAN_ENABLE),
257 ParameterLength: 1,
258 };
259
260 uint8_t Interval = BT_SCANMODE_InquiryAndPageScans;
261
262 /* Send the command to set the remote device scanning mode */
263 Bluetooth_SendHCICommand(&HCICommandHeader, &Interval, 1);
264
265 Bluetooth_State.NextHCIState = Bluetooth_Init_FinalizeInit;
266 Bluetooth_State.CurrentHCIState = Bluetooth_ProcessEvents;
267 break;
268 case Bluetooth_Init_FinalizeInit:
269 Bluetooth_State.IsInitialized = true;
270
271 /* Fire the user application callback to indicate that the stack is now fully initialized */
272 Bluetooth_StackInitialized();
273
274 Bluetooth_State.NextHCIState = Bluetooth_ProcessEvents;
275 Bluetooth_State.CurrentHCIState = Bluetooth_ProcessEvents;
276 break;
277 case Bluetooth_Conn_AcceptConnection:
278 BT_HCI_DEBUG(1, "# Accept Connection");
279
280 HCICommandHeader = (BT_HCICommand_Header_t)
281 {
282 OpCode: (OGF_LINK_CONTROL | OCF_LINK_CONTROL_ACCEPT_CONNECTION_REQUEST),
283 ParameterLength: sizeof(BT_HCICommand_AcceptConnectionReq_t),
284 };
285
286 /* Copy over the temporary BT device address saved from the Connection Request event, indicate slave
287 connection role */
288 BT_HCICommand_AcceptConnectionReq_t AcceptConnectionParams;
289 memcpy(AcceptConnectionParams.RemoteAddress, Bluetooth_TempDeviceAddress,
290 sizeof(AcceptConnectionParams.RemoteAddress));
291 AcceptConnectionParams.SlaveRole = true;
292
293 /* Send the command to accept the remote connection request */
294 Bluetooth_SendHCICommand(&HCICommandHeader, &AcceptConnectionParams, sizeof(BT_HCICommand_AcceptConnectionReq_t));
295
296 Bluetooth_State.CurrentHCIState = Bluetooth_ProcessEvents;
297 break;
298 case Bluetooth_Conn_RejectConnection:
299 BT_HCI_DEBUG(1, "# Reject Connection");
300
301 HCICommandHeader = (BT_HCICommand_Header_t)
302 {
303 OpCode: (OGF_LINK_CONTROL | OCF_LINK_CONTROL_REJECT_CONNECTION_REQUEST),
304 ParameterLength: sizeof(BT_HCICommand_RejectConnectionReq_t),
305 };
306
307 /* Copy over the temporary BT device address saved from the Connection Request event, indicate failure
308 to accept the connection due to limited device resources or incorrect device address */
309 BT_HCICommand_RejectConnectionReq_t RejectConnectionParams;
310 memcpy(RejectConnectionParams.RemoteAddress, Bluetooth_TempDeviceAddress, sizeof(RejectConnectionParams.RemoteAddress));
311 RejectConnectionParams.Reason = Bluetooth_Connection.IsConnected ? ERROR_LIMITED_RESOURCES : ERROR_UNACCEPTABLE_BDADDR;
312
313 /* Send the command to reject the remote connection request */
314 Bluetooth_SendHCICommand(&HCICommandHeader, &RejectConnectionParams, sizeof(BT_HCICommand_RejectConnectionReq_t));
315
316 Bluetooth_State.CurrentHCIState = Bluetooth_ProcessEvents;
317 break;
318 case Bluetooth_Conn_SendPINCode:
319 BT_HCI_DEBUG(1, "# Send Pin Code");
320
321 HCICommandHeader = (BT_HCICommand_Header_t)
322 {
323 OpCode: (OGF_LINK_CONTROL | OCF_LINK_CONTROL_PIN_CODE_REQUEST_REPLY),
324 ParameterLength: sizeof(BT_HCICommand_PinCodeResp_t),
325 };
326
327 /* Copy over the temporary BT device address saved from the PIN Code Request event, copy over the
328 local PIN authentication code to the response */
329 BT_HCICommand_PinCodeResp_t PINCodeRequestParams;
330 memcpy(PINCodeRequestParams.RemoteAddress, Bluetooth_TempDeviceAddress, sizeof(PINCodeRequestParams.RemoteAddress));
331 PINCodeRequestParams.PINCodeLength = strlen(Bluetooth_DeviceConfiguration.PINCode);
332 memcpy(PINCodeRequestParams.PINCode, Bluetooth_DeviceConfiguration.PINCode, sizeof(PINCodeRequestParams.PINCode));
333
334 /* Send the command to transmit the device's local PIN number for authentication */
335 Bluetooth_SendHCICommand(&HCICommandHeader, &PINCodeRequestParams, sizeof(BT_HCICommand_PinCodeResp_t));
336
337 Bluetooth_State.CurrentHCIState = Bluetooth_ProcessEvents;
338 break;
339 case Bluetooth_Conn_SendLinkKeyNAK:
340 BT_HCI_DEBUG(1, "# Send Link Key NAK");
341
342 HCICommandHeader = (BT_HCICommand_Header_t)
343 {
344 OpCode: (OGF_LINK_CONTROL | OCF_LINK_CONTROL_LINK_KEY_REQUEST_NEG_REPLY),
345 ParameterLength: sizeof(BT_HCICommand_LinkKeyNAKResp_t),
346 };
347
348 /* Copy over the temporary BT device address saved from the Link Key Request event */
349 BT_HCICommand_LinkKeyNAKResp_t LinkKeyNAKParams;
350 memcpy(LinkKeyNAKParams.RemoteAddress, Bluetooth_TempDeviceAddress, sizeof(LinkKeyNAKParams.RemoteAddress));
351
352 /* Send the command to transmit the link key NAK to the receiver */
353 Bluetooth_SendHCICommand(&HCICommandHeader, &LinkKeyNAKParams, sizeof(BT_HCICommand_LinkKeyNAKResp_t));
354
355 Bluetooth_State.CurrentHCIState = Bluetooth_ProcessEvents;
356 break;
357 }
358 }
359
360 /** Sends a Bluetooth HCI control command to the attached Bluetooth device.
361 *
362 * \param[in] HCICommandHeader HCI command header to send to the attached device
363 * \param[in] Parameters Pointer to the source of the control parameters (if any)
364 * \param[in] ParameterLength Length of the parameters to send in bytes
365 *
366 * \return A value from the USB_Host_SendControlErrorCodes_t enum.
367 */
368 static uint8_t Bluetooth_SendHCICommand(const BT_HCICommand_Header_t* const HCICommandHeader, const void* Parameters, const uint16_t ParameterLength)
369 {
370 /* Need to reserve the amount of bytes given in the header for the complete payload */
371 uint8_t CommandBuffer[sizeof(BT_HCICommand_Header_t) + HCICommandHeader->ParameterLength];
372
373 USB_ControlRequest = (USB_Request_Header_t)
374 {
375 .bmRequestType = (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_DEVICE),
376 .bRequest = 0,
377 .wValue = 0,
378 .wIndex = 0,
379 .wLength = sizeof(CommandBuffer)
380 };
381
382 /* Copy over the HCI command header to the allocated buffer */
383 memcpy(CommandBuffer, HCICommandHeader, sizeof(BT_HCICommand_Header_t));
384
385 /* Zero out the parameter section of the response so that all padding bytes are known to be zero */
386 memset(&CommandBuffer[sizeof(BT_HCICommand_Header_t)], 0x00, HCICommandHeader->ParameterLength);
387
388 /* Copy over the command parameters (if any) to the command buffer - note, the number of actual source parameter bytes
389 may differ to those in the header; any difference in length is filled with 0x00 padding bytes */
390 memcpy(&CommandBuffer[sizeof(BT_HCICommand_Header_t)], Parameters, ParameterLength);
391
392 Pipe_SelectPipe(PIPE_CONTROLPIPE);
393 return USB_Host_SendControlRequest(CommandBuffer);
394 }