Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(184)

Side by Side Diff: trunk/src/chrome/browser/extensions/api/bluetooth/bluetooth_api.cc

Issue 227493006: Revert 262175 "* Replace "read" method with onReceiveXxx events." (Closed) Base URL: svn://svn.chromium.org/chrome/
Patch Set: Created 6 years, 8 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "chrome/browser/extensions/api/bluetooth/bluetooth_api.h" 5 #include "chrome/browser/extensions/api/bluetooth/bluetooth_api.h"
6 6
7 #include <string> 7 #include <string>
8 8
9 #include "base/lazy_instance.h" 9 #include "base/lazy_instance.h"
10 #include "base/memory/ref_counted.h" 10 #include "base/memory/ref_counted.h"
11 #include "chrome/browser/extensions/api/bluetooth/bluetooth_api_utils.h" 11 #include "chrome/browser/extensions/api/bluetooth/bluetooth_api_utils.h"
12 #include "chrome/browser/extensions/api/bluetooth/bluetooth_event_router.h" 12 #include "chrome/browser/extensions/api/bluetooth/bluetooth_event_router.h"
13 #include "chrome/browser/extensions/api/bluetooth/bluetooth_socket_event_dispatc her.h"
14 #include "chrome/browser/profiles/profile_manager.h"
15 #include "chrome/common/extensions/api/bluetooth.h" 13 #include "chrome/common/extensions/api/bluetooth.h"
16 #include "chrome/common/extensions/api/bluetooth/bluetooth_manifest_data.h" 14 #include "chrome/common/extensions/api/bluetooth/bluetooth_manifest_data.h"
17 #include "content/public/browser/browser_thread.h" 15 #include "content/public/browser/browser_thread.h"
18 #include "device/bluetooth/bluetooth_adapter.h" 16 #include "device/bluetooth/bluetooth_adapter.h"
19 #include "device/bluetooth/bluetooth_device.h" 17 #include "device/bluetooth/bluetooth_device.h"
20 #include "device/bluetooth/bluetooth_out_of_band_pairing_data.h" 18 #include "device/bluetooth/bluetooth_out_of_band_pairing_data.h"
21 #include "device/bluetooth/bluetooth_profile.h" 19 #include "device/bluetooth/bluetooth_profile.h"
22 #include "device/bluetooth/bluetooth_service_record.h" 20 #include "device/bluetooth/bluetooth_service_record.h"
23 #include "device/bluetooth/bluetooth_socket.h" 21 #include "device/bluetooth/bluetooth_socket.h"
24 #include "extensions/browser/event_router.h" 22 #include "extensions/browser/event_router.h"
25 #include "extensions/browser/extension_system.h" 23 #include "extensions/browser/extension_system.h"
26 #include "extensions/common/permissions/permissions_data.h" 24 #include "extensions/common/permissions/permissions_data.h"
27 #include "net/base/io_buffer.h" 25 #include "net/base/io_buffer.h"
28 26
29 using content::BrowserContext; 27 using content::BrowserContext;
30 using content::BrowserThread;
31
32 using device::BluetoothAdapter; 28 using device::BluetoothAdapter;
33 using device::BluetoothDevice; 29 using device::BluetoothDevice;
34 using device::BluetoothProfile; 30 using device::BluetoothProfile;
35 using device::BluetoothServiceRecord; 31 using device::BluetoothServiceRecord;
36 using device::BluetoothSocket; 32 using device::BluetoothSocket;
37 33
38 using extensions::BluetoothApiSocket; 34 namespace {
39 35
40 namespace AddProfile = extensions::api::bluetooth::AddProfile; 36 extensions::BluetoothEventRouter* GetEventRouter(BrowserContext* context) {
41 namespace bluetooth = extensions::api::bluetooth; 37 return extensions::BluetoothAPI::Get(context)->bluetooth_event_router();
42 namespace Connect = extensions::api::bluetooth::Connect; 38 }
43 namespace Disconnect = extensions::api::bluetooth::Disconnect; 39
44 namespace GetDevice = extensions::api::bluetooth::GetDevice; 40 } // namespace
45 namespace GetDevices = extensions::api::bluetooth::GetDevices;
46 namespace RemoveProfile = extensions::api::bluetooth::RemoveProfile;
47 namespace SetOutOfBandPairingData =
48 extensions::api::bluetooth::SetOutOfBandPairingData;
49 namespace Send = extensions::api::bluetooth::Send;
50 41
51 namespace { 42 namespace {
52 43
53 const char kCouldNotGetLocalOutOfBandPairingData[] = 44 const char kCouldNotGetLocalOutOfBandPairingData[] =
54 "Could not get local Out Of Band Pairing Data"; 45 "Could not get local Out Of Band Pairing Data";
55 const char kCouldNotSetOutOfBandPairingData[] = 46 const char kCouldNotSetOutOfBandPairingData[] =
56 "Could not set Out Of Band Pairing Data"; 47 "Could not set Out Of Band Pairing Data";
48 const char kFailedToConnect[] = "Connection failed";
57 const char kInvalidDevice[] = "Invalid device"; 49 const char kInvalidDevice[] = "Invalid device";
58 const char kInvalidUuid[] = "Invalid UUID"; 50 const char kInvalidUuid[] = "Invalid UUID";
59 const char kPermissionDenied[] = "Permission to add profile denied."; 51 const char kPermissionDenied[] = "Permission to add profile denied.";
60 const char kProfileAlreadyRegistered[] = 52 const char kProfileAlreadyRegistered[] =
61 "This profile has already been registered"; 53 "This profile has already been registered";
62 const char kProfileNotFound[] = "Profile not found: invalid uuid"; 54 const char kProfileNotFound[] = "Profile not found: invalid uuid";
63 const char kProfileRegistrationFailed[] = "Profile registration failed"; 55 const char kProfileRegistrationFailed[] = "Profile registration failed";
64 const char kSocketNotFoundError[] = "Socket not found: invalid socket id"; 56 const char kSocketNotFoundError[] = "Socket not found: invalid socket id";
65 const char kStartDiscoveryFailed[] = "Starting discovery failed"; 57 const char kStartDiscoveryFailed[] = "Starting discovery failed";
66 const char kStopDiscoveryFailed[] = "Failed to stop discovery"; 58 const char kStopDiscoveryFailed[] = "Failed to stop discovery";
67 59
68 extensions::BluetoothEventRouter* GetEventRouter(BrowserContext* context) { 60 } // namespace
69 // Note: |context| is valid on UI thread only.
70 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
71 return extensions::BluetoothAPI::Get(context)->event_router();
72 }
73 61
74 linked_ptr<bluetooth::Socket> CreateSocketInfo(int socket_id, 62 namespace AddProfile = extensions::api::bluetooth::AddProfile;
75 BluetoothApiSocket* socket) { 63 namespace bluetooth = extensions::api::bluetooth;
76 DCHECK(BrowserThread::CurrentlyOn(BluetoothApiSocket::kThreadId)); 64 namespace Connect = extensions::api::bluetooth::Connect;
77 linked_ptr<bluetooth::Socket> socket_info(new bluetooth::Socket()); 65 namespace Disconnect = extensions::api::bluetooth::Disconnect;
78 // This represents what we know about the socket, and does not call through 66 namespace GetDevice = extensions::api::bluetooth::GetDevice;
79 // to the system. 67 namespace GetDevices = extensions::api::bluetooth::GetDevices;
80 socket_info->id = socket_id; 68 namespace Read = extensions::api::bluetooth::Read;
81 if (!socket->name().empty()) { 69 namespace RemoveProfile = extensions::api::bluetooth::RemoveProfile;
82 socket_info->name.reset(new std::string(socket->name())); 70 namespace SetOutOfBandPairingData =
83 } 71 extensions::api::bluetooth::SetOutOfBandPairingData;
84 socket_info->persistent = socket->persistent(); 72 namespace Write = extensions::api::bluetooth::Write;
85 if (socket->buffer_size() > 0) {
86 socket_info->buffer_size.reset(new int(socket->buffer_size()));
87 }
88 socket_info->paused = socket->paused();
89 socket_info->device.address = socket->device_address();
90 socket_info->uuid = socket->uuid().canonical_value();
91
92 return socket_info;
93 }
94
95 void SetSocketProperties(extensions::BluetoothApiSocket* socket,
96 bluetooth::SocketProperties* properties) {
97 if (properties->name.get()) {
98 socket->set_name(*properties->name.get());
99 }
100 if (properties->persistent.get()) {
101 socket->set_persistent(*properties->persistent.get());
102 }
103 if (properties->buffer_size.get()) {
104 // buffer size is validated when issuing the actual Recv operation
105 // on the socket.
106 socket->set_buffer_size(*properties->buffer_size.get());
107 }
108 }
109
110 static void DispatchConnectionEventWorker(
111 void* browser_context_id,
112 const std::string& extension_id,
113 const device::BluetoothUUID& profile_uuid,
114 const device::BluetoothDevice* device,
115 scoped_refptr<device::BluetoothSocket> socket) {
116 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
117
118 content::BrowserContext* context =
119 reinterpret_cast<content::BrowserContext*>(browser_context_id);
120 if (!extensions::ExtensionsBrowserClient::Get()->IsValidContext(context))
121 return;
122
123 extensions::BluetoothAPI* bluetooth_api =
124 extensions::BluetoothAPI::Get(context);
125 if (!bluetooth_api)
126 return;
127
128 bluetooth_api->DispatchConnectionEvent(
129 extension_id, profile_uuid, device, socket);
130 }
131
132 } // namespace
133 73
134 namespace extensions { 74 namespace extensions {
135 75
136 static base::LazyInstance<BrowserContextKeyedAPIFactory<BluetoothAPI> > 76 static base::LazyInstance<BrowserContextKeyedAPIFactory<BluetoothAPI> >
137 g_factory = LAZY_INSTANCE_INITIALIZER; 77 g_factory = LAZY_INSTANCE_INITIALIZER;
138 78
139 // static 79 // static
140 BrowserContextKeyedAPIFactory<BluetoothAPI>* 80 BrowserContextKeyedAPIFactory<BluetoothAPI>*
141 BluetoothAPI::GetFactoryInstance() { 81 BluetoothAPI::GetFactoryInstance() {
142 return g_factory.Pointer(); 82 return g_factory.Pointer();
143 } 83 }
144 84
145 // static 85 // static
146 BluetoothAPI* BluetoothAPI::Get(BrowserContext* context) { 86 BluetoothAPI* BluetoothAPI::Get(BrowserContext* context) {
147 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
148 return GetFactoryInstance()->Get(context); 87 return GetFactoryInstance()->Get(context);
149 } 88 }
150 89
151 BluetoothAPI::ConnectionParams::ConnectionParams() {} 90 BluetoothAPI::BluetoothAPI(BrowserContext* context)
152
153 BluetoothAPI::ConnectionParams::~ConnectionParams() {}
154
155 BluetoothAPI::BluetoothAPI(content::BrowserContext* context)
156 : browser_context_(context) { 91 : browser_context_(context) {
157 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
158 ExtensionSystem::Get(browser_context_)->event_router()->RegisterObserver( 92 ExtensionSystem::Get(browser_context_)->event_router()->RegisterObserver(
159 this, bluetooth::OnAdapterStateChanged::kEventName); 93 this, bluetooth::OnAdapterStateChanged::kEventName);
160 ExtensionSystem::Get(browser_context_)->event_router()->RegisterObserver( 94 ExtensionSystem::Get(browser_context_)->event_router()->RegisterObserver(
161 this, bluetooth::OnDeviceAdded::kEventName); 95 this, bluetooth::OnDeviceAdded::kEventName);
162 ExtensionSystem::Get(browser_context_)->event_router()->RegisterObserver( 96 ExtensionSystem::Get(browser_context_)->event_router()->RegisterObserver(
163 this, bluetooth::OnDeviceChanged::kEventName); 97 this, bluetooth::OnDeviceChanged::kEventName);
164 ExtensionSystem::Get(browser_context_)->event_router()->RegisterObserver( 98 ExtensionSystem::Get(browser_context_)->event_router()->RegisterObserver(
165 this, bluetooth::OnDeviceRemoved::kEventName); 99 this, bluetooth::OnDeviceRemoved::kEventName);
166 } 100 }
167 101
168 BluetoothAPI::~BluetoothAPI() {} 102 BluetoothAPI::~BluetoothAPI() {
169
170 BluetoothEventRouter* BluetoothAPI::event_router() {
171 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
172 if (!event_router_) {
173 event_router_.reset(new BluetoothEventRouter(browser_context_));
174 }
175 return event_router_.get();
176 } 103 }
177 104
178 scoped_refptr<BluetoothAPI::SocketData> BluetoothAPI::socket_data() { 105 BluetoothEventRouter* BluetoothAPI::bluetooth_event_router() {
179 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); 106 if (!bluetooth_event_router_)
180 if (!socket_data_) { 107 bluetooth_event_router_.reset(new BluetoothEventRouter(browser_context_));
181 ApiResourceManager<BluetoothApiSocket>* socket_manager =
182 ApiResourceManager<BluetoothApiSocket>::Get(browser_context_);
183 DCHECK(socket_manager)
184 << "There is no socket manager. "
185 "If this assertion is failing during a test, then it is likely that "
186 "TestExtensionSystem is failing to provide an instance of "
187 "ApiResourceManager<BluetoothApiSocket>.";
188 108
189 socket_data_ = socket_manager->data_; 109 return bluetooth_event_router_.get();
190 }
191 return socket_data_;
192 }
193
194 scoped_refptr<api::BluetoothSocketEventDispatcher>
195 BluetoothAPI::socket_event_dispatcher() {
196 if (!socket_event_dispatcher_) {
197 socket_event_dispatcher_ = new api::BluetoothSocketEventDispatcher(
198 browser_context_, socket_data());
199 }
200 return socket_event_dispatcher_;
201 } 110 }
202 111
203 void BluetoothAPI::Shutdown() { 112 void BluetoothAPI::Shutdown() {
204 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
205 ExtensionSystem::Get(browser_context_)->event_router()->UnregisterObserver( 113 ExtensionSystem::Get(browser_context_)->event_router()->UnregisterObserver(
206 this); 114 this);
207 } 115 }
208 116
209 void BluetoothAPI::OnListenerAdded(const EventListenerInfo& details) { 117 void BluetoothAPI::OnListenerAdded(const EventListenerInfo& details) {
210 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); 118 if (bluetooth_event_router()->IsBluetoothSupported())
211 if (event_router()->IsBluetoothSupported()) 119 bluetooth_event_router()->OnListenerAdded();
212 event_router()->OnListenerAdded();
213 } 120 }
214 121
215 void BluetoothAPI::OnListenerRemoved(const EventListenerInfo& details) { 122 void BluetoothAPI::OnListenerRemoved(const EventListenerInfo& details) {
216 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); 123 if (bluetooth_event_router()->IsBluetoothSupported())
217 if (event_router()->IsBluetoothSupported()) 124 bluetooth_event_router()->OnListenerRemoved();
218 event_router()->OnListenerRemoved();
219 }
220
221 void BluetoothAPI::DispatchConnectionEvent(
222 const std::string& extension_id,
223 const device::BluetoothUUID& uuid,
224 const device::BluetoothDevice* device,
225 scoped_refptr<device::BluetoothSocket> socket) {
226 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
227
228 if (!event_router()->HasProfile(uuid))
229 return;
230
231 extensions::BluetoothAPI::ConnectionParams params;
232 params.browser_context_id = browser_context_;
233 params.thread_id = BluetoothApiSocket::kThreadId;
234 params.extension_id = extension_id;
235 params.uuid = uuid;
236 params.device_address = device->GetAddress();
237 params.socket = socket;
238 params.socket_data = socket_data();
239 BrowserThread::PostTask(
240 params.thread_id, FROM_HERE, base::Bind(&RegisterSocket, params));
241 }
242
243 // static
244 void BluetoothAPI::RegisterSocket(
245 const BluetoothAPI::ConnectionParams& params) {
246 DCHECK(BrowserThread::CurrentlyOn(params.thread_id));
247
248 BluetoothApiSocket* api_socket = new BluetoothApiSocket(
249 params.extension_id, params.socket, params.device_address, params.uuid);
250 int socket_id = params.socket_data->Add(api_socket);
251
252 BrowserThread::PostTask(BrowserThread::UI,
253 FROM_HERE,
254 base::Bind(&RegisterSocketUI, params, socket_id));
255 }
256
257 // static
258 void BluetoothAPI::RegisterSocketUI(const ConnectionParams& params,
259 int socket_id) {
260 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
261
262 content::BrowserContext* context =
263 reinterpret_cast<content::BrowserContext*>(params.browser_context_id);
264 if (!extensions::ExtensionsBrowserClient::Get()->IsValidContext(context))
265 return;
266
267 BluetoothAPI::Get(context)->event_router()->GetAdapter(
268 base::Bind(&RegisterSocketWithAdapterUI, params, socket_id));
269 }
270
271 void BluetoothAPI::RegisterSocketWithAdapterUI(
272 const ConnectionParams& params,
273 int socket_id,
274 scoped_refptr<device::BluetoothAdapter> adapter) {
275 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
276
277 content::BrowserContext* context =
278 reinterpret_cast<content::BrowserContext*>(params.browser_context_id);
279 if (!extensions::ExtensionsBrowserClient::Get()->IsValidContext(context))
280 return;
281
282 BluetoothDevice* device = adapter->GetDevice(params.device_address);
283 if (!device)
284 return;
285
286 api::bluetooth::Socket result_socket;
287 bluetooth::BluetoothDeviceToApiDevice(*device, &result_socket.device);
288 result_socket.uuid = params.uuid.canonical_value();
289 result_socket.id = socket_id;
290
291 scoped_ptr<base::ListValue> args =
292 bluetooth::OnConnection::Create(result_socket);
293 scoped_ptr<Event> event(
294 new Event(bluetooth::OnConnection::kEventName, args.Pass()));
295
296 EventRouter* router = ExtensionSystem::Get(context)->event_router();
297 if (router)
298 router->DispatchEventToExtension(params.extension_id, event.Pass());
299 } 125 }
300 126
301 namespace api { 127 namespace api {
302 128
303 BluetoothSocketApiFunction::BluetoothSocketApiFunction() {} 129 BluetoothAddProfileFunction::BluetoothAddProfileFunction() {
304
305 BluetoothSocketApiFunction::~BluetoothSocketApiFunction() {}
306
307 bool BluetoothSocketApiFunction::RunImpl() {
308 if (!PrePrepare() || !Prepare()) {
309 return false;
310 }
311 AsyncWorkStart();
312 return true;
313 } 130 }
314 131
315 bool BluetoothSocketApiFunction::PrePrepare() {
316 socket_data_ = BluetoothAPI::Get(browser_context())->socket_data();
317 socket_event_dispatcher_ =
318 BluetoothAPI::Get(browser_context())->socket_event_dispatcher();
319 return socket_data_ && socket_event_dispatcher_;
320 }
321
322 void BluetoothSocketApiFunction::AsyncWorkStart() {
323 Work();
324 AsyncWorkCompleted();
325 }
326
327 void BluetoothSocketApiFunction::Work() {}
328
329 void BluetoothSocketApiFunction::AsyncWorkCompleted() {
330 SendResponse(Respond());
331 }
332
333 bool BluetoothSocketApiFunction::Respond() { return error_.empty(); }
334
335 BluetoothGetAdapterStateFunction::~BluetoothGetAdapterStateFunction() {}
336
337 bool BluetoothGetAdapterStateFunction::DoWork(
338 scoped_refptr<BluetoothAdapter> adapter) {
339 bluetooth::AdapterState state;
340 PopulateAdapterState(*adapter.get(), &state);
341 results_ = bluetooth::GetAdapterState::Results::Create(state);
342 SendResponse(true);
343 return true;
344 }
345
346 BluetoothGetDevicesFunction::~BluetoothGetDevicesFunction() {}
347
348 bool BluetoothGetDevicesFunction::DoWork(
349 scoped_refptr<BluetoothAdapter> adapter) {
350 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
351
352 base::ListValue* device_list = new base::ListValue;
353 SetResult(device_list);
354
355 BluetoothAdapter::DeviceList devices = adapter->GetDevices();
356 for (BluetoothAdapter::DeviceList::const_iterator iter = devices.begin();
357 iter != devices.end();
358 ++iter) {
359 const BluetoothDevice* device = *iter;
360 DCHECK(device);
361
362 bluetooth::Device extension_device;
363 bluetooth::BluetoothDeviceToApiDevice(*device, &extension_device);
364
365 device_list->Append(extension_device.ToValue().release());
366 }
367
368 SendResponse(true);
369
370 return true;
371 }
372
373 BluetoothGetDeviceFunction::~BluetoothGetDeviceFunction() {}
374
375 bool BluetoothGetDeviceFunction::DoWork(
376 scoped_refptr<BluetoothAdapter> adapter) {
377 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
378
379 scoped_ptr<GetDevice::Params> params(GetDevice::Params::Create(*args_));
380 EXTENSION_FUNCTION_VALIDATE(params.get() != NULL);
381 const std::string& device_address = params->device_address;
382
383 BluetoothDevice* device = adapter->GetDevice(device_address);
384 if (device) {
385 bluetooth::Device extension_device;
386 bluetooth::BluetoothDeviceToApiDevice(*device, &extension_device);
387 SetResult(extension_device.ToValue().release());
388 SendResponse(true);
389 } else {
390 SetError(kInvalidDevice);
391 SendResponse(false);
392 }
393
394 return false;
395 }
396
397 BluetoothAddProfileFunction::BluetoothAddProfileFunction() {}
398
399 BluetoothAddProfileFunction::~BluetoothAddProfileFunction() {}
400
401 bool BluetoothAddProfileFunction::RunImpl() { 132 bool BluetoothAddProfileFunction::RunImpl() {
402 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
403 scoped_ptr<AddProfile::Params> params(AddProfile::Params::Create(*args_)); 133 scoped_ptr<AddProfile::Params> params(AddProfile::Params::Create(*args_));
404 EXTENSION_FUNCTION_VALIDATE(params.get() != NULL); 134 EXTENSION_FUNCTION_VALIDATE(params.get() != NULL);
405 135
406 device::BluetoothUUID uuid(params->profile.uuid); 136 device::BluetoothUUID uuid(params->profile.uuid);
407 137
408 if (!uuid.IsValid()) { 138 if (!uuid.IsValid()) {
409 SetError(kInvalidUuid); 139 SetError(kInvalidUuid);
410 return false; 140 return false;
411 } 141 }
412 142
(...skipping 35 matching lines...) Expand 10 before | Expand all | Expand 10 after
448 RegisterProfile( 178 RegisterProfile(
449 options, 179 options,
450 base::Bind(&BluetoothAddProfileFunction::OnProfileRegistered, this)); 180 base::Bind(&BluetoothAddProfileFunction::OnProfileRegistered, this));
451 181
452 return true; 182 return true;
453 } 183 }
454 184
455 void BluetoothAddProfileFunction::RegisterProfile( 185 void BluetoothAddProfileFunction::RegisterProfile(
456 const BluetoothProfile::Options& options, 186 const BluetoothProfile::Options& options,
457 const BluetoothProfile::ProfileCallback& callback) { 187 const BluetoothProfile::ProfileCallback& callback) {
458 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
459 BluetoothProfile::Register(uuid_, options, callback); 188 BluetoothProfile::Register(uuid_, options, callback);
460 } 189 }
461 190
462 void BluetoothAddProfileFunction::OnProfileRegistered( 191 void BluetoothAddProfileFunction::OnProfileRegistered(
463 BluetoothProfile* bluetooth_profile) { 192 BluetoothProfile* bluetooth_profile) {
464 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
465 if (!bluetooth_profile) { 193 if (!bluetooth_profile) {
466 SetError(kProfileRegistrationFailed); 194 SetError(kProfileRegistrationFailed);
467 SendResponse(false); 195 SendResponse(false);
468 return; 196 return;
469 } 197 }
470 198
471 if (GetEventRouter(browser_context())->HasProfile(uuid_)) { 199 if (GetEventRouter(browser_context())->HasProfile(uuid_)) {
472 bluetooth_profile->Unregister(); 200 bluetooth_profile->Unregister();
473 SetError(kProfileAlreadyRegistered); 201 SetError(kProfileAlreadyRegistered);
474 SendResponse(false); 202 SendResponse(false);
475 return; 203 return;
476 } 204 }
477 205
478 bluetooth_profile->SetConnectionCallback( 206 bluetooth_profile->SetConnectionCallback(
479 base::Bind(&DispatchConnectionEventWorker, 207 base::Bind(&BluetoothEventRouter::DispatchConnectionEvent,
480 browser_context(), 208 base::Unretained(GetEventRouter(browser_context())),
481 extension_id(), 209 extension_id(),
482 uuid_)); 210 uuid_));
483 GetEventRouter(browser_context()) 211 GetEventRouter(browser_context())
484 ->AddProfile(uuid_, extension_id(), bluetooth_profile); 212 ->AddProfile(uuid_, extension_id(), bluetooth_profile);
485 SendResponse(true); 213 SendResponse(true);
486 } 214 }
487 215
488 BluetoothRemoveProfileFunction::~BluetoothRemoveProfileFunction() {}
489
490 bool BluetoothRemoveProfileFunction::RunImpl() { 216 bool BluetoothRemoveProfileFunction::RunImpl() {
491 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
492 scoped_ptr<RemoveProfile::Params> params( 217 scoped_ptr<RemoveProfile::Params> params(
493 RemoveProfile::Params::Create(*args_)); 218 RemoveProfile::Params::Create(*args_));
494 219
495 device::BluetoothUUID uuid(params->profile.uuid); 220 device::BluetoothUUID uuid(params->profile.uuid);
496 221
497 if (!uuid.IsValid()) { 222 if (!uuid.IsValid()) {
498 SetError(kInvalidUuid); 223 SetError(kInvalidUuid);
499 return false; 224 return false;
500 } 225 }
501 226
502 if (!GetEventRouter(browser_context())->HasProfile(uuid)) { 227 if (!GetEventRouter(browser_context())->HasProfile(uuid)) {
503 SetError(kProfileNotFound); 228 SetError(kProfileNotFound);
504 return false; 229 return false;
505 } 230 }
506 231
507 GetEventRouter(browser_context())->RemoveProfile(uuid); 232 GetEventRouter(browser_context())->RemoveProfile(uuid);
508 return true; 233 return true;
509 } 234 }
510 235
511 BluetoothConnectFunction::~BluetoothConnectFunction() {} 236 bool BluetoothGetAdapterStateFunction::DoWork(
237 scoped_refptr<BluetoothAdapter> adapter) {
238 bluetooth::AdapterState state;
239 PopulateAdapterState(*adapter.get(), &state);
240 SetResult(state.ToValue().release());
241 SendResponse(true);
242 return true;
243 }
244
245 bool BluetoothGetDevicesFunction::DoWork(
246 scoped_refptr<BluetoothAdapter> adapter) {
247 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
248
249 base::ListValue* device_list = new base::ListValue;
250 SetResult(device_list);
251
252 BluetoothAdapter::DeviceList devices = adapter->GetDevices();
253 for (BluetoothAdapter::DeviceList::const_iterator iter = devices.begin();
254 iter != devices.end();
255 ++iter) {
256 const BluetoothDevice* device = *iter;
257 DCHECK(device);
258
259 bluetooth::Device extension_device;
260 bluetooth::BluetoothDeviceToApiDevice(*device, &extension_device);
261
262 device_list->Append(extension_device.ToValue().release());
263 }
264
265 SendResponse(true);
266
267 return true;
268 }
269
270 bool BluetoothGetDeviceFunction::DoWork(
271 scoped_refptr<BluetoothAdapter> adapter) {
272 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
273
274 scoped_ptr<GetDevice::Params> params(GetDevice::Params::Create(*args_));
275 EXTENSION_FUNCTION_VALIDATE(params.get() != NULL);
276 const std::string& device_address = params->device_address;
277
278 BluetoothDevice* device = adapter->GetDevice(device_address);
279 if (device) {
280 bluetooth::Device extension_device;
281 bluetooth::BluetoothDeviceToApiDevice(*device, &extension_device);
282 SetResult(extension_device.ToValue().release());
283 SendResponse(true);
284 } else {
285 SetError(kInvalidDevice);
286 SendResponse(false);
287 }
288
289 return false;
290 }
291
292 void BluetoothConnectFunction::OnSuccessCallback() {
293 SendResponse(true);
294 }
295
296 void BluetoothConnectFunction::OnErrorCallback() {
297 SetError(kFailedToConnect);
298 SendResponse(false);
299 }
512 300
513 bool BluetoothConnectFunction::DoWork(scoped_refptr<BluetoothAdapter> adapter) { 301 bool BluetoothConnectFunction::DoWork(scoped_refptr<BluetoothAdapter> adapter) {
514 scoped_ptr<Connect::Params> params(Connect::Params::Create(*args_)); 302 scoped_ptr<Connect::Params> params(Connect::Params::Create(*args_));
515 EXTENSION_FUNCTION_VALIDATE(params.get() != NULL); 303 EXTENSION_FUNCTION_VALIDATE(params.get() != NULL);
516 const bluetooth::ConnectOptions& options = params->options; 304 const bluetooth::ConnectOptions& options = params->options;
517 305
518 device::BluetoothUUID uuid(options.profile.uuid); 306 device::BluetoothUUID uuid(options.profile.uuid);
519 307
520 if (!uuid.IsValid()) { 308 if (!uuid.IsValid()) {
521 SetError(kInvalidUuid); 309 SetError(kInvalidUuid);
(...skipping 17 matching lines...) Expand all
539 } 327 }
540 328
541 device->ConnectToProfile( 329 device->ConnectToProfile(
542 bluetooth_profile, 330 bluetooth_profile,
543 base::Bind(&BluetoothConnectFunction::OnSuccessCallback, this), 331 base::Bind(&BluetoothConnectFunction::OnSuccessCallback, this),
544 base::Bind(&BluetoothConnectFunction::OnErrorCallback, this)); 332 base::Bind(&BluetoothConnectFunction::OnErrorCallback, this));
545 333
546 return true; 334 return true;
547 } 335 }
548 336
549 void BluetoothConnectFunction::OnSuccessCallback() { 337 bool BluetoothDisconnectFunction::RunImpl() {
550 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); 338 scoped_ptr<Disconnect::Params> params(Disconnect::Params::Create(*args_));
551 SendResponse(true); 339 EXTENSION_FUNCTION_VALIDATE(params.get() != NULL);
340 const bluetooth::DisconnectOptions& options = params->options;
341 return GetEventRouter(browser_context())->ReleaseSocket(options.socket.id);
552 } 342 }
553 343
554 void BluetoothConnectFunction::OnErrorCallback(const std::string& error) { 344 BluetoothReadFunction::BluetoothReadFunction() : success_(false) {}
555 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); 345 BluetoothReadFunction::~BluetoothReadFunction() {}
556 SetError(error);
557 SendResponse(false);
558 }
559 346
560 BluetoothDisconnectFunction::BluetoothDisconnectFunction() {} 347 bool BluetoothReadFunction::Prepare() {
348 scoped_ptr<Read::Params> params(Read::Params::Create(*args_));
349 EXTENSION_FUNCTION_VALIDATE(params.get() != NULL);
350 const bluetooth::ReadOptions& options = params->options;
561 351
562 BluetoothDisconnectFunction::~BluetoothDisconnectFunction() {} 352 socket_ = GetEventRouter(browser_context())->GetSocket(options.socket.id);
353 if (socket_.get() == NULL) {
354 SetError(kSocketNotFoundError);
355 return false;
356 }
563 357
564 bool BluetoothDisconnectFunction::Prepare() { 358 success_ = false;
565 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
566 params_ = Disconnect::Params::Create(*args_);
567 EXTENSION_FUNCTION_VALIDATE(params_.get() != NULL);
568 return true; 359 return true;
569 } 360 }
570 361
571 void BluetoothDisconnectFunction::AsyncWorkStart() { 362 void BluetoothReadFunction::Work() {
572 DCHECK(BrowserThread::CurrentlyOn(work_thread_id())); 363 DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
573 BluetoothApiSocket* socket = 364
574 socket_data_->Get(extension_id(), params_->options.socket_id); 365 if (!socket_.get())
575 if (!socket) {
576 error_ = kSocketNotFoundError;
577 return; 366 return;
578 } 367
579 socket->Disconnect(base::Bind(&BluetoothDisconnectFunction::OnSuccess, this)); 368 scoped_refptr<net::GrowableIOBuffer> buffer(new net::GrowableIOBuffer);
369 success_ = socket_->Receive(buffer.get());
370 if (success_)
371 SetResult(base::BinaryValue::CreateWithCopiedBuffer(buffer->StartOfBuffer(),
372 buffer->offset()));
373 else
374 SetError(socket_->GetLastErrorMessage());
580 } 375 }
581 376
582 void BluetoothDisconnectFunction::OnSuccess() { 377 bool BluetoothReadFunction::Respond() {
583 DCHECK(BrowserThread::CurrentlyOn(work_thread_id())); 378 return success_;
584 socket_data_->Remove(extension_id(), params_->options.socket_id);
585 results_ = bluetooth::Disconnect::Results::Create();
586 AsyncWorkCompleted();
587 } 379 }
588 380
589 BluetoothSendFunction::BluetoothSendFunction() : io_buffer_size_(0) {} 381 BluetoothWriteFunction::BluetoothWriteFunction()
590 382 : success_(false),
591 BluetoothSendFunction::~BluetoothSendFunction() {} 383 data_to_write_(NULL) {
592
593 bool BluetoothSendFunction::Prepare() {
594 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
595 params_ = Send::Params::Create(*args_);
596 EXTENSION_FUNCTION_VALIDATE(params_.get() != NULL);
597 io_buffer_size_ = params_->data.size();
598 io_buffer_ = new net::WrappedIOBuffer(params_->data.data());
599 return true;
600 } 384 }
601 385
602 void BluetoothSendFunction::AsyncWorkStart() { 386 BluetoothWriteFunction::~BluetoothWriteFunction() {}
603 DCHECK(BrowserThread::CurrentlyOn(work_thread_id())); 387
604 BluetoothApiSocket* socket = 388 bool BluetoothWriteFunction::Prepare() {
605 socket_data_->Get(extension_id(), params_->socket_id); 389 // TODO(bryeung): update to new-style parameter passing when ArrayBuffer
606 if (!socket) { 390 // support is added
607 error_ = kSocketNotFoundError; 391 base::DictionaryValue* options;
608 return; 392 EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(0, &options));
393
394 base::DictionaryValue* socket;
395 EXTENSION_FUNCTION_VALIDATE(options->GetDictionary("socket", &socket));
396
397 int socket_id;
398 EXTENSION_FUNCTION_VALIDATE(socket->GetInteger("id", &socket_id));
399
400 socket_ = GetEventRouter(browser_context())->GetSocket(socket_id);
401 if (socket_.get() == NULL) {
402 SetError(kSocketNotFoundError);
403 return false;
609 } 404 }
610 socket->Send(io_buffer_, 405
611 io_buffer_size_, 406 base::BinaryValue* tmp_data;
612 base::Bind(&BluetoothSendFunction::OnSendSuccess, this), 407 EXTENSION_FUNCTION_VALIDATE(options->GetBinary("data", &tmp_data));
613 base::Bind(&BluetoothSendFunction::OnSendError, this)); 408 data_to_write_ = tmp_data;
409
410 success_ = false;
411 return socket_.get() != NULL;
614 } 412 }
615 413
616 void BluetoothSendFunction::OnSendSuccess(int bytes_sent) { 414 void BluetoothWriteFunction::Work() {
617 DCHECK(BrowserThread::CurrentlyOn(work_thread_id())); 415 DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
618 results_ = Send::Results::Create(bytes_sent); 416
619 AsyncWorkCompleted(); 417 if (socket_.get() == NULL)
418 return;
419
420 scoped_refptr<net::WrappedIOBuffer> wrapped_io_buffer(
421 new net::WrappedIOBuffer(data_to_write_->GetBuffer()));
422 scoped_refptr<net::DrainableIOBuffer> drainable_io_buffer(
423 new net::DrainableIOBuffer(wrapped_io_buffer.get(),
424 data_to_write_->GetSize()));
425 success_ = socket_->Send(drainable_io_buffer.get());
426 if (success_) {
427 if (drainable_io_buffer->BytesConsumed() > 0)
428 SetResult(new base::FundamentalValue(
429 drainable_io_buffer->BytesConsumed()));
430 else
431 results_.reset();
432 } else {
433 SetError(socket_->GetLastErrorMessage());
434 }
620 } 435 }
621 436
622 void BluetoothSendFunction::OnSendError(const std::string& message) { 437 bool BluetoothWriteFunction::Respond() {
623 DCHECK(BrowserThread::CurrentlyOn(work_thread_id())); 438 return success_;
624 error_ = message;
625 AsyncWorkCompleted();
626 }
627
628 BluetoothUpdateSocketFunction::BluetoothUpdateSocketFunction() {}
629
630 BluetoothUpdateSocketFunction::~BluetoothUpdateSocketFunction() {}
631
632 bool BluetoothUpdateSocketFunction::Prepare() {
633 params_ = bluetooth::UpdateSocket::Params::Create(*args_);
634 EXTENSION_FUNCTION_VALIDATE(params_.get());
635 return true;
636 }
637
638 void BluetoothUpdateSocketFunction::Work() {
639 BluetoothApiSocket* socket =
640 socket_data_->Get(extension_id(), params_->socket_id);
641 if (!socket) {
642 error_ = kSocketNotFoundError;
643 return;
644 }
645
646 SetSocketProperties(socket, &params_.get()->properties);
647 results_ = bluetooth::UpdateSocket::Results::Create();
648 }
649
650 BluetoothSetSocketPausedFunction::BluetoothSetSocketPausedFunction() {}
651
652 BluetoothSetSocketPausedFunction::~BluetoothSetSocketPausedFunction() {}
653
654 bool BluetoothSetSocketPausedFunction::Prepare() {
655 params_ = bluetooth::SetSocketPaused::Params::Create(*args_);
656 EXTENSION_FUNCTION_VALIDATE(params_.get());
657 return true;
658 }
659
660 void BluetoothSetSocketPausedFunction::Work() {
661 BluetoothApiSocket* socket =
662 socket_data_->Get(extension_id(), params_->socket_id);
663 if (!socket) {
664 error_ = kSocketNotFoundError;
665 return;
666 }
667
668 if (socket->paused() != params_->paused) {
669 socket->set_paused(params_->paused);
670 if (!params_->paused) {
671 socket_event_dispatcher_->OnSocketResume(extension_->id(),
672 params_->socket_id);
673 }
674 }
675
676 results_ = bluetooth::SetSocketPaused::Results::Create();
677 }
678
679 BluetoothGetSocketFunction::BluetoothGetSocketFunction() {}
680
681 BluetoothGetSocketFunction::~BluetoothGetSocketFunction() {}
682
683 bool BluetoothGetSocketFunction::Prepare() {
684 params_ = bluetooth::GetSocket::Params::Create(*args_);
685 EXTENSION_FUNCTION_VALIDATE(params_.get());
686 return true;
687 }
688
689 void BluetoothGetSocketFunction::Work() {
690 BluetoothApiSocket* socket =
691 socket_data_->Get(extension_id(), params_->socket_id);
692 if (!socket) {
693 error_ = kSocketNotFoundError;
694 return;
695 }
696
697 linked_ptr<bluetooth::Socket> socket_info =
698 CreateSocketInfo(params_->socket_id, socket);
699 results_ = bluetooth::GetSocket::Results::Create(*socket_info);
700 }
701
702 BluetoothGetSocketsFunction::BluetoothGetSocketsFunction() {}
703
704 BluetoothGetSocketsFunction::~BluetoothGetSocketsFunction() {}
705
706 bool BluetoothGetSocketsFunction::Prepare() { return true; }
707
708 void BluetoothGetSocketsFunction::Work() {
709 std::vector<linked_ptr<bluetooth::Socket> > socket_infos;
710 base::hash_set<int>* resource_ids =
711 socket_data_->GetResourceIds(extension_id());
712 if (resource_ids != NULL) {
713 for (base::hash_set<int>::iterator it = resource_ids->begin();
714 it != resource_ids->end();
715 ++it) {
716 int socket_id = *it;
717 BluetoothApiSocket* socket = socket_data_->Get(extension_id(), socket_id);
718 if (socket) {
719 socket_infos.push_back(CreateSocketInfo(socket_id, socket));
720 }
721 }
722 }
723 results_ = bluetooth::GetSockets::Results::Create(socket_infos);
724 } 439 }
725 440
726 void BluetoothSetOutOfBandPairingDataFunction::OnSuccessCallback() { 441 void BluetoothSetOutOfBandPairingDataFunction::OnSuccessCallback() {
727 SendResponse(true); 442 SendResponse(true);
728 } 443 }
729 444
730 void BluetoothSetOutOfBandPairingDataFunction::OnErrorCallback() { 445 void BluetoothSetOutOfBandPairingDataFunction::OnErrorCallback() {
731 SetError(kCouldNotSetOutOfBandPairingData); 446 SetError(kCouldNotSetOutOfBandPairingData);
732 SendResponse(false); 447 SendResponse(false);
733 } 448 }
(...skipping 123 matching lines...) Expand 10 before | Expand all | Expand 10 after
857 adapter, 572 adapter,
858 extension_id(), 573 extension_id(),
859 base::Bind(&BluetoothStopDiscoveryFunction::OnSuccessCallback, this), 574 base::Bind(&BluetoothStopDiscoveryFunction::OnSuccessCallback, this),
860 base::Bind(&BluetoothStopDiscoveryFunction::OnErrorCallback, this)); 575 base::Bind(&BluetoothStopDiscoveryFunction::OnErrorCallback, this));
861 576
862 return true; 577 return true;
863 } 578 }
864 579
865 } // namespace api 580 } // namespace api
866 } // namespace extensions 581 } // namespace extensions
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698