BluetoothHCICommands.c 14.6 KB
Newer Older
1
2
/*
             LUFA Library
Dean Camera's avatar
Dean Camera committed
3
     Copyright (C) Dean Camera, 2010.
4
5
6
7
8
9
              
  dean [at] fourwalledcubicle [dot] com
      www.fourwalledcubicle.com
*/

/*
Dean Camera's avatar
Dean Camera committed
10
  Copyright 2010  Dean Camera (dean [at] fourwalledcubicle [dot] com)
11

12
13
14
15
16
17
18
  Permission to use, copy, modify, distribute, and sell this 
  software and its documentation for any purpose is hereby granted
  without fee, provided that the above copyright notice appear in 
  all copies and that both that the copyright notice and this
  permission notice and warranty disclaimer appear in supporting 
  documentation, and that the name of the author not be used in 
  advertising or publicity pertaining to distribution of the 
19
20
21
22
23
24
25
26
27
28
29
30
  software without specific, written prior permission.

  The author disclaim all warranties with regard to this
  software, including all implied warranties of merchantability
  and fitness.  In no event shall the author be liable for any
  special, indirect or consequential damages or any damages
  whatsoever resulting from loss of use, data or profits, whether
  in an action of contract, negligence or other tortious action,
  arising out of or in connection with the use or performance of
  this software.
*/

31
#define  INCLUDE_FROM_BLUETOOTHHCICOMMANDS_C
32
33
#include "BluetoothHCICommands.h"

34
35
/** Current processing state of the HCI portion of the Bluetooth stack. */
uint8_t Bluetooth_HCIProcessingState;
36

37
38
/** Next HCI state to enter once the last issued HCI command has completed. */
static uint8_t Bluetooth_HCINextState;
39

40
41
42
43
44
45
46
/** Temporary Bluetooth Device Address, for HCI responses which much include the detination address */
static uint8_t Bluetooth_TempDeviceAddress[6];


/** Bluetooth HCI processing task. This task should be called repeatedly the main Bluetooth
 *  stack task to manage the HCI processing state.
 */
47
void Bluetooth_HCITask(void)
48
{
49
50
	BT_HCICommand_Header_t HCICommandHeader;

51
52
	switch (Bluetooth_HCIProcessingState)
	{
53
		case Bluetooth_ProcessEvents:
54
			Pipe_SelectPipe(BLUETOOTH_EVENTS_PIPE);
55
56
57
58
			Pipe_Unfreeze();
			
			if (Pipe_IsReadWriteAllowed())
			{
59
				BT_HCIEvent_Header_t HCIEventHeader;
60
61

				/* Read in the event header to fetch the event code and payload length */
62
63
				Pipe_Read_Stream_LE(&HCIEventHeader, sizeof(HCIEventHeader));
				
64
				/* Create a temporary buffer for the event parameters */
65
66
				uint8_t EventParams[HCIEventHeader.ParameterLength];

67
				/* Read in the event parameters into the temporary buffer */
68
69
				Pipe_Read_Stream_LE(&EventParams, HCIEventHeader.ParameterLength);
				Pipe_ClearIN();
70
71
				
				BT_HCI_DEBUG(1, "Event Received (0x%02X)", HCIEventHeader.EventCode);
72
73
74
75

				switch (HCIEventHeader.EventCode)
				{
					case EVENT_COMMAND_COMPLETE:
76
						BT_HCI_DEBUG(1, "<< Command Complete", NULL);
77
78
79
						Bluetooth_HCIProcessingState = Bluetooth_HCINextState;
						break;
					case EVENT_COMMAND_STATUS:
80
81
82
						BT_HCI_DEBUG(1, "<< Command Status", NULL);
						BT_HCI_DEBUG(2, "-- Status Code: 0x%02X", (((BT_HCIEvent_CommandStatus_t*)&EventParams)->Status));

83
						/* If the execution of a command failed, reset the stack */
84
						if (((BT_HCIEvent_CommandStatus_t*)&EventParams)->Status)
85
86
87
						  Bluetooth_HCIProcessingState = Bluetooth_Init;
						break;
					case EVENT_CONNECTION_REQUEST:
88
89
90
						BT_HCI_DEBUG(1, "<< Connection Request", NULL);
						BT_HCI_DEBUG(2, "-- Link Type: 0x%02X", (((BT_HCIEvent_ConnectionRequest_t*)&EventParams)->LinkType));

91
						/* Need to store the remote device's BT address in a temporary buffer for later use */
92
						memcpy(Bluetooth_TempDeviceAddress,
93
						       &((BT_HCIEvent_ConnectionRequest_t*)&EventParams)->RemoteAddress,
94
						       sizeof(Bluetooth_TempDeviceAddress));
95
							   
96
						bool IsACLConnection = (((BT_HCIEvent_ConnectionRequest_t*)&EventParams)->LinkType == 0x01);
97
98
99
100

						/* Only accept the connection if it is a ACL (data) connection, a device is not already connected
						   and the user application has indicated that the connection should be allowed */
						Bluetooth_HCIProcessingState = (Bluetooth_Connection.IsConnected || !(IsACLConnection) ||
101
													    !(Bluetooth_ConnectionRequest(Bluetooth_TempDeviceAddress))) ?
102
													   Bluetooth_Conn_RejectConnection : Bluetooth_Conn_AcceptConnection;
103
104
105
106

						BT_HCI_DEBUG(2, "-- Connection %S", (Bluetooth_HCIProcessingState == Bluetooth_Conn_RejectConnection) ?
						                                     PSTR("REJECTED") : PSTR("ACCEPTED"));

107
108
						break;
					case EVENT_PIN_CODE_REQUEST:
109
110
						BT_HCI_DEBUG(1, "<< Pin Code Request", NULL);

111
						/* Need to store the remote device's BT address in a temporary buffer for later use */
112
						memcpy(Bluetooth_TempDeviceAddress,
113
						       &((BT_HCIEvent_PinCodeReq_t*)&EventParams)->RemoteAddress,
114
115
116
117
						       sizeof(Bluetooth_TempDeviceAddress));

						Bluetooth_HCIProcessingState = Bluetooth_Conn_SendPINCode;
						break;
118
119
120
121
122
123
124
125
126
127
					case EVENT_LINK_KEY_REQUEST:
						BT_HCI_DEBUG(1, "<< Link Key Request", NULL);
						
						/* Need to store the remote device's BT address in a temporary buffer for later use */
						memcpy(Bluetooth_TempDeviceAddress,
						       &((BT_HCIEvent_LinkKeyReq_t*)&EventParams)->RemoteAddress,
						       sizeof(Bluetooth_TempDeviceAddress));						
						
						Bluetooth_HCIProcessingState = Bluetooth_Conn_SendLinkKeyNAK;
						break;
128
					case EVENT_CONNECTION_COMPLETE:
129
130
131
						BT_HCI_DEBUG(1, "<< Connection Complete", NULL);
						BT_HCI_DEBUG(2, "-- Handle: 0x%04X", ((BT_HCIEvent_ConnectionComplete_t*)&EventParams)->ConnectionHandle);

132
						/* Need to store the remote device's BT address in a temporary buffer for later use */
133
						memcpy(Bluetooth_Connection.RemoteAddress,
134
						       &((BT_HCIEvent_ConnectionComplete_t*)&EventParams)->RemoteAddress,
135
136
						       sizeof(Bluetooth_TempDeviceAddress));

137
						/* Store the created connection handle and indicate that the connection has been established */
138
						Bluetooth_Connection.ConnectionHandle = ((BT_HCIEvent_ConnectionComplete_t*)&EventParams)->ConnectionHandle;
139
						Bluetooth_Connection.IsConnected      = true;
140
141
						
						Bluetooth_ConnectionComplete();						
142
						break;
143
					case EVENT_DISCONNECTION_COMPLETE:
144
145
						BT_HCI_DEBUG(1, "<< Disconnection Complete", NULL);

146
147
148
						/* Device disconnected, indicate connection information no longer valid */
						Bluetooth_Connection.IsConnected = false;
						
149
150
						Bluetooth_DisconnectionComplete();
						
151
						Bluetooth_HCIProcessingState = Bluetooth_Init;
152
						break;
153
154
155
156
				}
			}
			
			Pipe_Freeze();
157
			
158
159
			break;
		case Bluetooth_Init:
160
161
			BT_HCI_DEBUG(1, "# Init", NULL);

162
			/* Reset the connection information structure to destroy any previous connection state */
163
			memset(&Bluetooth_Connection, 0x00, sizeof(Bluetooth_Connection));
164

165
166
167
			Bluetooth_HCIProcessingState = Bluetooth_Init_Reset; 
			break;
		case Bluetooth_Init_Reset:
168
169
			BT_HCI_DEBUG(1, "# Reset", NULL);

170
			HCICommandHeader = (BT_HCICommand_Header_t)
171
172
173
174
175
			{
				OpCode: {OGF: OGF_CTRLR_BASEBAND, OCF: OCF_CTRLR_BASEBAND_RESET},
				ParameterLength: 0,
			};

176
			/* Send the command to reset the bluetooth dongle controller */
177
			Bluetooth_SendHCICommand(&HCICommandHeader, NULL, 0);
178
179
180
			
			Bluetooth_HCINextState       = Bluetooth_Init_SetLocalName;
			Bluetooth_HCIProcessingState = Bluetooth_ProcessEvents;
181
182
			break;
		case Bluetooth_Init_SetLocalName:
183
184
			BT_HCI_DEBUG(1, "# Set Local Name", NULL);

185
			HCICommandHeader = (BT_HCICommand_Header_t)
186
187
188
189
190
				{
					OpCode: {OGF: OGF_CTRLR_BASEBAND, OCF: OCF_CTRLR_BASEBAND_WRITE_LOCAL_NAME},
					ParameterLength: 248,
				};

191
			/* Send the command to set the bluetooth dongle's name for other devices to see */
192
			Bluetooth_SendHCICommand(&HCICommandHeader, Bluetooth_DeviceConfiguration.Name, strlen(Bluetooth_DeviceConfiguration.Name));
193

194
195
			Bluetooth_HCINextState       = Bluetooth_Init_SetDeviceClass;
			Bluetooth_HCIProcessingState = Bluetooth_ProcessEvents;
196
197
			break;
		case Bluetooth_Init_SetDeviceClass:
198
199
			BT_HCI_DEBUG(1, "# Set Device Class", NULL);

200
			HCICommandHeader = (BT_HCICommand_Header_t)
201
202
203
204
205
				{
					OpCode: {OGF: OGF_CTRLR_BASEBAND, OCF: OCF_CTRLR_BASEBAND_WRITE_CLASS_OF_DEVICE},
					ParameterLength: 3,
				};

206
			/* Send the command to set the class of the device for other devices to see */
207
			Bluetooth_SendHCICommand(&HCICommandHeader, &Bluetooth_DeviceConfiguration.Class, 3);
208

209
210
			Bluetooth_HCINextState       = Bluetooth_Init_WriteScanEnable;
			Bluetooth_HCIProcessingState = Bluetooth_ProcessEvents;
211
212
			break;
		case Bluetooth_Init_WriteScanEnable:
213
214
			BT_HCI_DEBUG(1, "# Write Scan Enable", NULL);

215
			HCICommandHeader = (BT_HCICommand_Header_t)
216
217
218
219
220
			{
				OpCode: {OGF: OGF_CTRLR_BASEBAND, OCF: OCF_CTRLR_BASEBAND_WRITE_SCAN_ENABLE},
				ParameterLength: 1,
			};

221
222
223
			uint8_t Interval = BT_SCANMODE_InquiryAndPageScans;
			
			/* Send the command to set the remote device scanning mode */
224
			Bluetooth_SendHCICommand(&HCICommandHeader, &Interval, 1);
225
			
226
227
			Bluetooth_HCINextState       = Bluetooth_ProcessEvents;
			Bluetooth_HCIProcessingState = Bluetooth_ProcessEvents;
228
229
			break;
		case Bluetooth_Conn_AcceptConnection:
230
231
			BT_HCI_DEBUG(1, "# Accept Connection", NULL);

232
			HCICommandHeader = (BT_HCICommand_Header_t)
233
234
				{
					OpCode: {OGF: OGF_LINK_CONTROL, OCF: OCF_LINK_CONTROL_ACCEPT_CONNECTION_REQUEST},
235
					ParameterLength: sizeof(BT_HCICommand_AcceptConnectionReq_t),
236
237
				};

238
239
			/* Copy over the temporary BT device address saved from the Connection Request event, indicate slave
			   connection role */
240
			BT_HCICommand_AcceptConnectionReq_t AcceptConnectionParams;
241
242
			memcpy(AcceptConnectionParams.RemoteAddress, Bluetooth_TempDeviceAddress,
			       sizeof(AcceptConnectionParams.RemoteAddress));
243
244
			AcceptConnectionParams.SlaveRole = true;

245
			/* Send the command to accept the remote connection request */
246
			Bluetooth_SendHCICommand(&HCICommandHeader, &AcceptConnectionParams, sizeof(BT_HCICommand_AcceptConnectionReq_t));
247
			
248
			Bluetooth_HCIProcessingState = Bluetooth_ProcessEvents;
249
250
			break;
		case Bluetooth_Conn_RejectConnection:
251
252
			BT_HCI_DEBUG(1, "# Reject Connection", NULL);

253
			HCICommandHeader = (BT_HCICommand_Header_t)
254
				{
255
					OpCode: {OGF: OGF_LINK_CONTROL, OCF: OCF_LINK_CONTROL_REJECT_CONNECTION_REQUEST},
256
					ParameterLength: sizeof(BT_HCICommand_RejectConnectionReq_t),
257
258
				};

259
			/* Copy over the temporary BT device address saved from the Connection Request event, indicate failure
260
			   to accept the connection due to limited device resources or incorrect device address */
261
			BT_HCICommand_RejectConnectionReq_t RejectConnectionParams;
262
			memcpy(RejectConnectionParams.RemoteAddress, Bluetooth_TempDeviceAddress, sizeof(RejectConnectionParams.RemoteAddress));
263
			RejectConnectionParams.Reason = Bluetooth_Connection.IsConnected ? ERROR_LIMITED_RESOURCES : ERROR_UNACCEPTABLE_BDADDR;
264

265
			/* Send the command to reject the remote connection request */
266
			Bluetooth_SendHCICommand(&HCICommandHeader, &RejectConnectionParams, sizeof(BT_HCICommand_RejectConnectionReq_t));
267
		
268
			Bluetooth_HCIProcessingState = Bluetooth_ProcessEvents;
269
270
			break;
		case Bluetooth_Conn_SendPINCode:
271
272
			BT_HCI_DEBUG(1, "# Send Pin Code", NULL);

273
			HCICommandHeader = (BT_HCICommand_Header_t)
274
275
				{
					OpCode: {OGF: OGF_LINK_CONTROL, OCF: OCF_LINK_CONTROL_PIN_CODE_REQUEST_REPLY},
276
					ParameterLength: sizeof(BT_HCICommand_PinCodeResp_t),
277
278
				};

279
280
			/* Copy over the temporary BT device address saved from the PIN Code Request event, copy over the
			   local PIN authentication code to the response */
281
			BT_HCICommand_PinCodeResp_t PINCodeRequestParams;
282
			memcpy(PINCodeRequestParams.RemoteAddress, Bluetooth_TempDeviceAddress, sizeof(PINCodeRequestParams.RemoteAddress));
283
			PINCodeRequestParams.PINCodeLength = strlen(Bluetooth_DeviceConfiguration.PINCode);
284
			memcpy(PINCodeRequestParams.PINCode, Bluetooth_DeviceConfiguration.PINCode, sizeof(PINCodeRequestParams.PINCode));
285
			
286
			/* Send the command to transmit the device's local PIN number for authentication */
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
			Bluetooth_SendHCICommand(&HCICommandHeader, &PINCodeRequestParams, sizeof(BT_HCICommand_PinCodeResp_t));

			Bluetooth_HCIProcessingState = Bluetooth_ProcessEvents;
			break;
		case Bluetooth_Conn_SendLinkKeyNAK:
			BT_HCI_DEBUG(1, "# Send Link Key NAK", NULL);

			HCICommandHeader = (BT_HCICommand_Header_t)
				{
					OpCode: {OGF: OGF_LINK_CONTROL, OCF: OCF_LINK_CONTROL_LINK_KEY_REQUEST_NEG_REPLY},
					ParameterLength: sizeof(BT_HCICommand_LinkKeyNAKResp_t),
				};

			/* Copy over the temporary BT device address saved from the Link Key Request event */
			BT_HCICommand_LinkKeyNAKResp_t LinkKeyNAKParams;
			memcpy(LinkKeyNAKParams.RemoteAddress, Bluetooth_TempDeviceAddress, sizeof(LinkKeyNAKParams.RemoteAddress));

			/* Send the command to transmit the link key NAK to the receiver */
			Bluetooth_SendHCICommand(&HCICommandHeader, &LinkKeyNAKParams, sizeof(BT_HCICommand_LinkKeyNAKResp_t));
306

307
			Bluetooth_HCIProcessingState = Bluetooth_ProcessEvents;
308
309
310
			break;
	}
}
311

312
313
/** Sends a Bluetooth HCI control command to the attached Bluetooth device.
 *
314
315
316
 *  \param[in] HCICommandHeader  HCI command header to send to the attached device
 *  \param[in] Parameters        Pointer to the source of the control parameters (if any)
 *  \param[in] ParameterLength   Length of the parameters to send in bytes
317
318
319
320
 *
 *  \return A value from the USB_Host_SendControlErrorCodes_t enum.
 */
static uint8_t Bluetooth_SendHCICommand(BT_HCICommand_Header_t* HCICommandHeader, void* Parameters, uint16_t ParameterLength)
321
322
{
	/* Need to reserve the amount of bytes given in the header for the complete payload */
323
	uint8_t CommandBuffer[sizeof(BT_HCICommand_Header_t) + HCICommandHeader->ParameterLength];
324
325
326
327
328
329
330
331
332
333
334

	USB_ControlRequest = (USB_Request_Header_t)
		{
			.bmRequestType = (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_DEVICE),
			.bRequest      = 0,
			.wValue        = 0,
			.wIndex        = 0,
			.wLength       = sizeof(CommandBuffer)
		};

	/* Copy over the HCI command header to the allocated buffer */
335
	memcpy(CommandBuffer, HCICommandHeader, sizeof(BT_HCICommand_Header_t));
336
	
337
338
	/* Zero out the parameter section of the response so that all padding bytes are known to be zero */
	memset(&CommandBuffer[sizeof(BT_HCICommand_Header_t)], 0x00, HCICommandHeader->ParameterLength);
339
340
341

	/* Copy over the command parameters (if any) to the command buffer - note, the number of actual source parameter bytes
	   may differ to those in the header; any difference in length is filled with 0x00 padding bytes */
342
	memcpy(&CommandBuffer[sizeof(BT_HCICommand_Header_t)], Parameters, ParameterLength);
343
344
345
346
	
	Pipe_SelectPipe(PIPE_CONTROLPIPE);
	return USB_Host_SendControlRequest(CommandBuffer);
}