summaryrefslogtreecommitdiffstats
path: root/device/bluetooth/bluetooth_task_manager_win.cc
blob: 144682f61c66578a91b5c69eb8c841413399cd71 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "device/bluetooth/bluetooth_task_manager_win.h"

#include <string>

#include "base/bind.h"
#include "base/memory/ref_counted.h"
#include "base/message_loop.h"
#include "base/sequenced_task_runner.h"
#include "base/stringprintf.h"
#include "base/sys_string_conversions.h"
#include "base/threading/sequenced_worker_pool.h"
#include "base/threading/thread_restrictions.h"
#include "base/win/scoped_handle.h"
#include "device/bluetooth/bluetooth_includes_win.h"

namespace {

const int kNumThreadsInWorkerPool = 3;
const char kBluetoothThreadName[] = "BluetoothPollingThreadWin";

// A frame-based exception handler filter function for a handler for exceptions
// generated by the Visual C++ delay loader helper function.
int FilterVisualCPPExceptions(DWORD exception_code) {
  return HRESULT_FACILITY(exception_code) == FACILITY_VISUALCPP ?
      EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
}  // namespace

// Populates bluetooth adapter state using adapter_handle.
void GetAdapterState(HANDLE adapter_handle,
                     device::BluetoothTaskManagerWin::AdapterState* state) {
  std::string name;
  std::string address;
  bool powered = false;
  BLUETOOTH_RADIO_INFO adapter_info = { sizeof(BLUETOOTH_RADIO_INFO), 0 };
  if (adapter_handle &&
      ERROR_SUCCESS == BluetoothGetRadioInfo(adapter_handle,
                                             &adapter_info)) {
    name = base::SysWideToUTF8(adapter_info.szName);
    address = base::StringPrintf("%02X:%02X:%02X:%02X:%02X:%02X",
        adapter_info.address.rgBytes[5],
        adapter_info.address.rgBytes[4],
        adapter_info.address.rgBytes[3],
        adapter_info.address.rgBytes[2],
        adapter_info.address.rgBytes[1],
        adapter_info.address.rgBytes[0]);
    powered = !!BluetoothIsConnectable(adapter_handle);
  }
  state->name = name;
  state->address = address;
  state->powered = powered;
}

}

namespace device {

// static
const int BluetoothTaskManagerWin::kPollIntervalMs = 500;

// static
bool BluetoothTaskManagerWin::HasBluetoothStack() {
  static enum {
    HBS_UNKNOWN,
    HBS_YES,
    HBS_NO,
  } has_bluetooth_stack = HBS_UNKNOWN;

  if (has_bluetooth_stack == HBS_UNKNOWN) {
    base::ThreadRestrictions::AssertIOAllowed();
    HRESULT hr = E_FAIL;
    __try {
      hr = __HrLoadAllImportsForDll("bthprops.cpl");
    } __except(FilterVisualCPPExceptions(::GetExceptionCode())) {
      hr = E_FAIL;
    }
    has_bluetooth_stack = SUCCEEDED(hr) ? HBS_YES : HBS_NO;
  }

  return has_bluetooth_stack == HBS_YES;
}

BluetoothTaskManagerWin::BluetoothTaskManagerWin(
    scoped_refptr<base::SequencedTaskRunner> ui_task_runner)
    : ui_task_runner_(ui_task_runner),
      worker_pool_(new base::SequencedWorkerPool(kNumThreadsInWorkerPool,
                                                 kBluetoothThreadName)),
      bluetooth_task_runner_(
          worker_pool_->GetSequencedTaskRunnerWithShutdownBehavior(
              worker_pool_->GetSequenceToken(),
              base::SequencedWorkerPool::CONTINUE_ON_SHUTDOWN)) {
}

BluetoothTaskManagerWin::BluetoothTaskManagerWin(
      scoped_refptr<base::SequencedTaskRunner> ui_task_runner,
      scoped_refptr<base::SequencedTaskRunner> bluetooth_task_runner)
    : ui_task_runner_(ui_task_runner),
      bluetooth_task_runner_(bluetooth_task_runner) {
}

BluetoothTaskManagerWin::~BluetoothTaskManagerWin() {
}

void BluetoothTaskManagerWin::AddObserver(Observer* observer) {
  DCHECK(observer);
  DCHECK(ui_task_runner_->RunsTasksOnCurrentThread());
  observers_.AddObserver(observer);
}

void BluetoothTaskManagerWin::RemoveObserver(Observer* observer) {
  DCHECK(observer);
  DCHECK(ui_task_runner_->RunsTasksOnCurrentThread());
  observers_.RemoveObserver(observer);
}

void BluetoothTaskManagerWin::Initialize() {
  DCHECK(ui_task_runner_->RunsTasksOnCurrentThread());
  bluetooth_task_runner_->PostTask(
      FROM_HERE,
      base::Bind(&BluetoothTaskManagerWin::StartPolling,
                 this));
}

void BluetoothTaskManagerWin::StartPolling() {
  DCHECK(bluetooth_task_runner_->RunsTasksOnCurrentThread());

  // TODO(youngki): Handle this check where BluetoothAdapter is initialized.
  if (HasBluetoothStack()) {
    PollAdapter();
  }
}

void BluetoothTaskManagerWin::Shutdown() {
  DCHECK(ui_task_runner_->RunsTasksOnCurrentThread());
  worker_pool_->Shutdown();
}

void BluetoothTaskManagerWin::PostSetPoweredBluetoothTask(
    bool powered,
    const base::Closure& callback,
    const BluetoothAdapter::ErrorCallback& error_callback) {
  DCHECK(ui_task_runner_->RunsTasksOnCurrentThread());
  bluetooth_task_runner_->PostTask(
      FROM_HERE,
      base::Bind(&BluetoothTaskManagerWin::SetPowered,
                 this,
                 powered,
                 callback,
                 error_callback));
}

void BluetoothTaskManagerWin::OnAdapterStateChanged(const AdapterState* state) {
  DCHECK(ui_task_runner_->RunsTasksOnCurrentThread());
  FOR_EACH_OBSERVER(BluetoothTaskManagerWin::Observer, observers_,
                    AdapterStateChanged(*state));
}

void BluetoothTaskManagerWin::PollAdapter() {
  DCHECK(bluetooth_task_runner_->RunsTasksOnCurrentThread());

  const BLUETOOTH_FIND_RADIO_PARAMS adapter_param =
      { sizeof(BLUETOOTH_FIND_RADIO_PARAMS) };
  if (adapter_handle_)
    adapter_handle_.Close();
  HBLUETOOTH_RADIO_FIND handle = BluetoothFindFirstRadio(
      &adapter_param, adapter_handle_.Receive());

  if (handle)
    BluetoothFindRadioClose(handle);

  AdapterState* state = new AdapterState();
  GetAdapterState(adapter_handle_, state);

  // Notify the UI thread of the Bluetooth Adapter state.
  ui_task_runner_->PostTask(
      FROM_HERE,
      base::Bind(&BluetoothTaskManagerWin::OnAdapterStateChanged,
                 this,
                 base::Owned(state)));

  // Re-poll.
  bluetooth_task_runner_->PostDelayedTask(
      FROM_HERE,
      base::Bind(&BluetoothTaskManagerWin::PollAdapter,
                 this),
      base::TimeDelta::FromMilliseconds(kPollIntervalMs));
}

void BluetoothTaskManagerWin::SetPowered(
    bool powered,
    const base::Closure& callback,
    const BluetoothAdapter::ErrorCallback& error_callback) {
  DCHECK(bluetooth_task_runner_->RunsTasksOnCurrentThread());
  bool success = false;
  if (adapter_handle_) {
    if (!powered)
      BluetoothEnableDiscovery(adapter_handle_, false);
    success = !!BluetoothEnableIncomingConnections(adapter_handle_, powered);
  }

  if (success) {
    AdapterState* state = new AdapterState();
    GetAdapterState(adapter_handle_, state);
    ui_task_runner_->PostTask(
        FROM_HERE,
        base::Bind(&BluetoothTaskManagerWin::OnAdapterStateChanged,
                   this,
                   base::Owned(state)));
    ui_task_runner_->PostTask(FROM_HERE, callback);
  } else {
    ui_task_runner_->PostTask(FROM_HERE, error_callback);
  }
}

}  // namespace device