OSDN Git Service

6d0381a0f8b6b53b9dd267d5fce27d514945ae66
[android-x86/system-bt.git] / service / client / main.cpp
1 //
2 //  Copyright (C) 2015 Google, Inc.
3 //
4 //  Licensed under the Apache License, Version 2.0 (the "License");
5 //  you may not use this file except in compliance with the License.
6 //  You may obtain a copy of the License at:
7 //
8 //  http://www.apache.org/licenses/LICENSE-2.0
9 //
10 //  Unless required by applicable law or agreed to in writing, software
11 //  distributed under the License is distributed on an "AS IS" BASIS,
12 //  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 //  See the License for the specific language governing permissions and
14 //  limitations under the License.
15 //
16
17 #include <iostream>
18 #include <string>
19
20 #include <base/at_exit.h>
21 #include <base/command_line.h>
22 #include <base/logging.h>
23 #include <base/macros.h>
24 #include <base/strings/string_number_conversions.h>
25 #include <base/strings/string_split.h>
26 #include <base/strings/string_util.h>
27 #include <binder/IPCThreadState.h>
28 #include <binder/ProcessState.h>
29
30 #include <bluetooth/adapter_state.h>
31 #include <bluetooth/binder/IBluetooth.h>
32 #include <bluetooth/binder/IBluetoothCallback.h>
33 #include <bluetooth/binder/IBluetoothGattClient.h>
34 #include <bluetooth/binder/IBluetoothGattClientCallback.h>
35 #include <bluetooth/binder/IBluetoothLowEnergy.h>
36 #include <bluetooth/binder/IBluetoothLowEnergyCallback.h>
37 #include <bluetooth/low_energy_constants.h>
38 #include <bluetooth/scan_filter.h>
39 #include <bluetooth/scan_settings.h>
40 #include <bluetooth/uuid.h>
41
42 using namespace std;
43
44 using android::sp;
45
46 using ipc::binder::IBluetooth;
47 using ipc::binder::IBluetoothGattClient;
48 using ipc::binder::IBluetoothLowEnergy;
49
50 namespace {
51
52 #define COLOR_OFF         "\x1B[0m"
53 #define COLOR_RED         "\x1B[0;91m"
54 #define COLOR_GREEN       "\x1B[0;92m"
55 #define COLOR_YELLOW      "\x1B[0;93m"
56 #define COLOR_BLUE        "\x1B[0;94m"
57 #define COLOR_MAGENTA     "\x1B[0;95m"
58 #define COLOR_BOLDGRAY    "\x1B[1;30m"
59 #define COLOR_BOLDWHITE   "\x1B[1;37m"
60 #define COLOR_BOLDYELLOW  "\x1B[1;93m"
61
62 const char kCommandDisable[] = "disable";
63 const char kCommandEnable[] = "enable";
64 const char kCommandGetState[] = "get-state";
65 const char kCommandIsEnabled[] = "is-enabled";
66
67 #define CHECK_ARGS_COUNT(args, op, num, msg) \
68   if (!(args.size() op num)) { \
69     PrintError(msg); \
70     return; \
71   }
72 #define CHECK_NO_ARGS(args) \
73   CHECK_ARGS_COUNT(args, ==, 0, "Expected no arguments")
74
75 // TODO(armansito): Clean up this code. Right now everything is in this
76 // monolithic file. We should organize this into different classes for command
77 // handling, console output/printing, callback handling, etc.
78 // (See http://b/23387611)
79
80 // Used to synchronize the printing of the command-line prompt and incoming
81 // Binder callbacks.
82 std::atomic_bool showing_prompt(false);
83
84 // The registered IBluetoothLowEnergy client handle. If |ble_registering| is
85 // true then an operation to register the client is in progress.
86 std::atomic_bool ble_registering(false);
87 std::atomic_int ble_client_id(0);
88
89 // The registered IBluetoothGattClient client handle. If |gatt_registering| is
90 // true then an operation to register the client is in progress.
91 std::atomic_bool gatt_registering(false);
92 std::atomic_int gatt_client_id(0);
93
94 // True if we should dump the scan record bytes for incoming scan results.
95 std::atomic_bool dump_scan_record(false);
96
97 // True if the remote process has died and we should exit.
98 std::atomic_bool should_exit(false);
99
100 void PrintPrompt() {
101   cout << COLOR_BLUE "[FCLI] " COLOR_OFF << flush;
102 }
103
104 void PrintError(const string& message) {
105   cout << COLOR_RED << message << COLOR_OFF << endl;
106 }
107
108 void PrintOpStatus(const std::string& op, bool status) {
109   cout << COLOR_BOLDWHITE << op << " status: " COLOR_OFF
110        << (status ? (COLOR_GREEN "success") : (COLOR_RED "failure"))
111        << COLOR_OFF << endl << endl;
112 }
113
114 class CLIBluetoothCallback : public ipc::binder::BnBluetoothCallback {
115  public:
116   CLIBluetoothCallback() = default;
117   ~CLIBluetoothCallback() override = default;
118
119   // IBluetoothCallback overrides:
120   void OnBluetoothStateChange(
121       bluetooth::AdapterState prev_state,
122       bluetooth::AdapterState new_state) override {
123     if (showing_prompt.load())
124       cout << endl;
125     cout << COLOR_BOLDWHITE "Adapter state changed: " COLOR_OFF
126          << COLOR_MAGENTA << AdapterStateToString(prev_state) << COLOR_OFF
127          << COLOR_BOLDWHITE " -> " COLOR_OFF
128          << COLOR_BOLDYELLOW << AdapterStateToString(new_state) << COLOR_OFF
129          << endl << endl;
130     if (showing_prompt.load())
131       PrintPrompt();
132   }
133
134  private:
135   DISALLOW_COPY_AND_ASSIGN(CLIBluetoothCallback);
136 };
137
138 class CLIBluetoothLowEnergyCallback
139     : public ipc::binder::BnBluetoothLowEnergyCallback {
140  public:
141   CLIBluetoothLowEnergyCallback() = default;
142   ~CLIBluetoothLowEnergyCallback() override = default;
143
144   // IBluetoothLowEnergyCallback overrides:
145   void OnClientRegistered(int status, int client_id) override {
146     if (showing_prompt.load())
147       cout << endl;
148     if (status != bluetooth::BLE_STATUS_SUCCESS) {
149       PrintError("Failed to register BLE client");
150     } else {
151       ble_client_id = client_id;
152       cout << COLOR_BOLDWHITE "Registered BLE client with ID: " COLOR_OFF
153            << COLOR_GREEN << client_id << COLOR_OFF << endl << endl;
154     }
155     if (showing_prompt.load())
156       PrintPrompt();
157
158     ble_registering = false;
159   }
160
161   void OnConnectionState(int status, int client_id, const char* address,
162                          bool connected) override {
163     if (showing_prompt.load())
164       cout << endl;
165
166     cout << COLOR_BOLDWHITE "Connection state: "
167          << COLOR_BOLDYELLOW "[" << address
168          << " connected: " << (connected ? "true" : "false") << " ] "
169          << COLOR_BOLDWHITE "- status: " << status
170          << COLOR_BOLDWHITE " - client_id: " << client_id << COLOR_OFF;
171
172     cout  << endl << endl;
173
174     if (showing_prompt.load())
175       PrintPrompt();
176   }
177
178   void OnScanResult(const bluetooth::ScanResult& scan_result) override {
179     if (showing_prompt.load())
180       cout << endl;
181
182     cout << COLOR_BOLDWHITE "Scan result: "
183          << COLOR_BOLDYELLOW "[" << scan_result.device_address() << "] "
184          << COLOR_BOLDWHITE "- RSSI: " << scan_result.rssi() << COLOR_OFF;
185
186     if (dump_scan_record) {
187       cout << " - Record: "
188            << base::HexEncode(scan_result.scan_record().data(),
189                               scan_result.scan_record().size());
190     }
191
192     cout  << endl << endl;
193
194     if (showing_prompt.load())
195       PrintPrompt();
196   }
197
198   void OnMultiAdvertiseCallback(
199       int status, bool is_start,
200       const bluetooth::AdvertiseSettings& /* settings */) {
201     if (showing_prompt.load())
202       cout << endl;
203
204     std::string op = is_start ? "start" : "stop";
205
206     PrintOpStatus("Advertising " + op, status == bluetooth::BLE_STATUS_SUCCESS);
207
208     if (showing_prompt.load())
209       PrintPrompt();
210   }
211
212  private:
213   DISALLOW_COPY_AND_ASSIGN(CLIBluetoothLowEnergyCallback);
214 };
215
216 class CLIGattClientCallback
217     : public ipc::binder::BnBluetoothGattClientCallback {
218  public:
219   CLIGattClientCallback() = default;
220   ~CLIGattClientCallback() override = default;
221
222   // IBluetoothGattClientCallback overrides:
223   void OnClientRegistered(int status, int client_id) override {
224     if (showing_prompt.load())
225       cout << endl;
226     if (status != bluetooth::BLE_STATUS_SUCCESS) {
227       PrintError("Failed to register GATT client");
228     } else {
229       gatt_client_id = client_id;
230       cout << COLOR_BOLDWHITE "Registered GATT client with ID: " COLOR_OFF
231            << COLOR_GREEN << client_id << COLOR_OFF << endl << endl;
232     }
233     if (showing_prompt.load())
234       PrintPrompt();
235
236     gatt_registering = false;
237   }
238
239  private:
240   DISALLOW_COPY_AND_ASSIGN(CLIGattClientCallback);
241 };
242
243 void PrintCommandStatus(bool status) {
244   PrintOpStatus("Command", status);
245 }
246
247 void PrintFieldAndValue(const string& field, const string& value) {
248   cout << COLOR_BOLDWHITE << field << ": " << COLOR_BOLDYELLOW << value
249        << COLOR_OFF << endl;
250 }
251
252 void PrintFieldAndBoolValue(const string& field, bool value) {
253   PrintFieldAndValue(field, (value ? "true" : "false"));
254 }
255
256 void HandleDisable(IBluetooth* bt_iface, const vector<string>& args) {
257   CHECK_NO_ARGS(args);
258   PrintCommandStatus(bt_iface->Disable());
259 }
260
261 void HandleEnable(IBluetooth* bt_iface, const vector<string>& args) {
262   CHECK_NO_ARGS(args);
263   PrintCommandStatus(bt_iface->Enable());
264 }
265
266 void HandleGetState(IBluetooth* bt_iface, const vector<string>& args) {
267   CHECK_NO_ARGS(args);
268   bluetooth::AdapterState state = static_cast<bluetooth::AdapterState>(
269       bt_iface->GetState());
270   PrintFieldAndValue("Adapter state", bluetooth::AdapterStateToString(state));
271 }
272
273 void HandleIsEnabled(IBluetooth* bt_iface, const vector<string>& args) {
274   CHECK_NO_ARGS(args);
275   bool enabled = bt_iface->IsEnabled();
276   PrintFieldAndBoolValue("Adapter enabled", enabled);
277 }
278
279 void HandleGetLocalAddress(IBluetooth* bt_iface, const vector<string>& args) {
280   CHECK_NO_ARGS(args);
281   string address = bt_iface->GetAddress();
282   PrintFieldAndValue("Adapter address", address);
283 }
284
285 void HandleSetLocalName(IBluetooth* bt_iface, const vector<string>& args) {
286   CHECK_ARGS_COUNT(args, >=, 1, "No name was given");
287
288   std::string name;
289   for (const auto& arg : args)
290     name += arg + " ";
291
292   base::TrimWhitespaceASCII(name, base::TRIM_TRAILING, &name);
293
294   PrintCommandStatus(bt_iface->SetName(name));
295 }
296
297 void HandleGetLocalName(IBluetooth* bt_iface, const vector<string>& args) {
298   CHECK_NO_ARGS(args);
299   string name = bt_iface->GetName();
300   PrintFieldAndValue("Adapter name", name);
301 }
302
303 void HandleAdapterInfo(IBluetooth* bt_iface, const vector<string>& args) {
304   CHECK_NO_ARGS(args);
305
306   cout << COLOR_BOLDWHITE "Adapter Properties: " COLOR_OFF << endl;
307
308   PrintFieldAndValue("\tAddress", bt_iface->GetAddress());
309   PrintFieldAndValue("\tState", bluetooth::AdapterStateToString(
310       static_cast<bluetooth::AdapterState>(bt_iface->GetState())));
311   PrintFieldAndValue("\tName", bt_iface->GetName());
312   PrintFieldAndBoolValue("\tMulti-Adv. supported",
313                          bt_iface->IsMultiAdvertisementSupported());
314 }
315
316 void HandleSupportsMultiAdv(IBluetooth* bt_iface, const vector<string>& args) {
317   CHECK_NO_ARGS(args);
318
319   bool status = bt_iface->IsMultiAdvertisementSupported();
320   PrintFieldAndBoolValue("Multi-advertisement support", status);
321 }
322
323 void HandleRegisterBLE(IBluetooth* bt_iface, const vector<string>& args) {
324   CHECK_NO_ARGS(args);
325
326   if (ble_registering.load()) {
327     PrintError("In progress");
328     return;
329   }
330
331   if (ble_client_id.load()) {
332     PrintError("Already registered");
333     return;
334   }
335
336   sp<IBluetoothLowEnergy> ble_iface = bt_iface->GetLowEnergyInterface();
337   if (!ble_iface.get()) {
338     PrintError("Failed to obtain handle to Bluetooth Low Energy interface");
339     return;
340   }
341
342   bool status = ble_iface->RegisterClient(new CLIBluetoothLowEnergyCallback());
343   ble_registering = status;
344   PrintCommandStatus(status);
345 }
346
347 void HandleUnregisterBLE(IBluetooth* bt_iface, const vector<string>& args) {
348   CHECK_NO_ARGS(args);
349
350   if (!ble_client_id.load()) {
351     PrintError("Not registered");
352     return;
353   }
354
355   sp<IBluetoothLowEnergy> ble_iface = bt_iface->GetLowEnergyInterface();
356   if (!ble_iface.get()) {
357     PrintError("Failed to obtain handle to Bluetooth Low Energy interface");
358     return;
359   }
360
361   ble_iface->UnregisterClient(ble_client_id.load());
362   ble_client_id = 0;
363   PrintCommandStatus(true);
364 }
365
366 void HandleUnregisterAllBLE(IBluetooth* bt_iface, const vector<string>& args) {
367   CHECK_NO_ARGS(args);
368
369   sp<IBluetoothLowEnergy> ble_iface = bt_iface->GetLowEnergyInterface();
370   if (!ble_iface.get()) {
371     PrintError("Failed to obtain handle to Bluetooth Low Energy interface");
372     return;
373   }
374
375   ble_iface->UnregisterAll();
376   PrintCommandStatus(true);
377 }
378
379 void HandleRegisterGATT(IBluetooth* bt_iface, const vector<string>& args) {
380   CHECK_NO_ARGS(args);
381
382   if (gatt_registering.load()) {
383     PrintError("In progress");
384     return;
385   }
386
387   if (gatt_client_id.load()) {
388     PrintError("Already registered");
389     return;
390   }
391
392   sp<IBluetoothGattClient> gatt_iface = bt_iface->GetGattClientInterface();
393   if (!gatt_iface.get()) {
394     PrintError("Failed to obtain handle to Bluetooth GATT Client interface");
395     return;
396   }
397
398   bool status = gatt_iface->RegisterClient(new CLIGattClientCallback());
399   gatt_registering = status;
400   PrintCommandStatus(status);
401 }
402
403 void HandleUnregisterGATT(IBluetooth* bt_iface, const vector<string>& args) {
404   CHECK_NO_ARGS(args);
405
406   if (!gatt_client_id.load()) {
407     PrintError("Not registered");
408     return;
409   }
410
411   sp<IBluetoothGattClient> gatt_iface = bt_iface->GetGattClientInterface();
412   if (!gatt_iface.get()) {
413     PrintError("Failed to obtain handle to Bluetooth GATT Client interface");
414     return;
415   }
416
417   gatt_iface->UnregisterClient(gatt_client_id.load());
418   gatt_client_id = 0;
419   PrintCommandStatus(true);
420 }
421
422 void HandleStartAdv(IBluetooth* bt_iface, const vector<string>& args) {
423   bool include_name = false;
424   bool include_tx_power = false;
425   bool connectable = false;
426   bool set_manufacturer_data = false;
427   bool set_uuid = false;
428   bluetooth::UUID uuid;
429
430   for (auto iter = args.begin(); iter != args.end(); ++iter) {
431     const std::string& arg = *iter;
432     if (arg == "-n")
433       include_name = true;
434     else if (arg == "-t")
435       include_tx_power = true;
436     else if (arg == "-c")
437       connectable = true;
438     else if (arg == "-m")
439       set_manufacturer_data = true;
440     else if (arg == "-u") {
441       // This flag has a single argument.
442       ++iter;
443       if (iter == args.end()) {
444         PrintError("Expected a UUID after -u");
445         return;
446       }
447
448       std::string uuid_str = *iter;
449       uuid = bluetooth::UUID(uuid_str);
450       if (!uuid.is_valid()) {
451         PrintError("Invalid UUID: " + uuid_str);
452         return;
453       }
454
455       set_uuid = true;
456     }
457     else if (arg == "-h") {
458       static const char kUsage[] =
459           "Usage: start-adv [flags]\n"
460           "\n"
461           "Flags:\n"
462           "\t-n\tInclude device name\n"
463           "\t-t\tInclude TX power\n"
464           "\t-c\tSend connectable adv. packets (default is non-connectable)\n"
465           "\t-m\tInclude random manufacturer data\n"
466           "\t-h\tShow this help message\n";
467       cout << kUsage << endl;
468       return;
469     }
470     else {
471       PrintError("Unrecognized option: " + arg);
472       return;
473     }
474   }
475
476   if (!ble_client_id.load()) {
477     PrintError("BLE not registered");
478     return;
479   }
480
481   sp<IBluetoothLowEnergy> ble_iface = bt_iface->GetLowEnergyInterface();
482   if (!ble_iface.get()) {
483     PrintError("Failed to obtain handle to Bluetooth Low Energy interface");
484     return;
485   }
486
487   std::vector<uint8_t> data;
488   if (set_manufacturer_data) {
489     data = {{
490       0x07, bluetooth::kEIRTypeManufacturerSpecificData,
491       0xe0, 0x00,
492       'T', 'e', 's', 't'
493     }};
494   }
495
496   if (set_uuid) {
497     // Determine the type and length bytes.
498     int uuid_size = uuid.GetShortestRepresentationSize();
499     uint8_t type;
500     if (uuid_size == bluetooth::UUID::kNumBytes128)
501       type = bluetooth::kEIRTypeComplete128BitUUIDs;
502     else if (uuid_size == bluetooth::UUID::kNumBytes32)
503       type = bluetooth::kEIRTypeComplete32BitUUIDs;
504     else if (uuid_size == bluetooth::UUID::kNumBytes16)
505       type = bluetooth::kEIRTypeComplete16BitUUIDs;
506     else
507       NOTREACHED() << "Unexpected size: " << uuid_size;
508
509     data.push_back(uuid_size + 1);
510     data.push_back(type);
511
512     auto uuid_bytes = uuid.GetFullLittleEndian();
513     int index = (uuid_size == 16) ? 0 : 12;
514     data.insert(data.end(), uuid_bytes.data() + index,
515                 uuid_bytes.data() + index + uuid_size);
516   }
517
518   base::TimeDelta timeout;
519
520   bluetooth::AdvertiseSettings settings(
521       bluetooth::AdvertiseSettings::MODE_LOW_POWER,
522       timeout,
523       bluetooth::AdvertiseSettings::TX_POWER_LEVEL_MEDIUM,
524       connectable);
525
526   bluetooth::AdvertiseData adv_data(data);
527   adv_data.set_include_device_name(include_name);
528   adv_data.set_include_tx_power_level(include_tx_power);
529
530   bluetooth::AdvertiseData scan_rsp;
531
532   bool status = ble_iface->StartMultiAdvertising(ble_client_id.load(),
533                                                  adv_data, scan_rsp, settings);
534   PrintCommandStatus(status);
535 }
536
537 void HandleStopAdv(IBluetooth* bt_iface, const vector<string>& args) {
538   if (!ble_client_id.load()) {
539     PrintError("BLE not registered");
540     return;
541   }
542
543   sp<IBluetoothLowEnergy> ble_iface = bt_iface->GetLowEnergyInterface();
544   if (!ble_iface.get()) {
545     PrintError("Failed to obtain handle to Bluetooth Low Energy interface");
546     return;
547   }
548
549   bool status = ble_iface->StopMultiAdvertising(ble_client_id.load());
550   PrintCommandStatus(status);
551 }
552
553 void HandleConnect(IBluetooth* bt_iface, const vector<string>& args) {
554   string address;
555
556   if (args.size() != 1) {
557     PrintError("Expected MAC address as only argument");
558     return;
559   }
560
561   address = args[0];
562
563   if (!ble_client_id.load()) {
564     PrintError("BLE not registered");
565     return;
566   }
567
568   sp<IBluetoothLowEnergy> ble_iface = bt_iface->GetLowEnergyInterface();
569   if (!ble_iface.get()) {
570     PrintError("Failed to obtain handle to Bluetooth Low Energy interface");
571     return;
572   }
573
574   bool status = ble_iface->Connect(ble_client_id.load(), address.c_str(),
575                                    false /*  is_direct */);
576
577   PrintCommandStatus(status);
578 }
579
580 void HandleDisconnect(IBluetooth* bt_iface, const vector<string>& args) {
581   string address;
582
583   if (args.size() != 1) {
584     PrintError("Expected MAC address as only argument");
585     return;
586   }
587
588   address = args[0];
589
590   if (!ble_client_id.load()) {
591     PrintError("BLE not registered");
592     return;
593   }
594
595   sp<IBluetoothLowEnergy> ble_iface = bt_iface->GetLowEnergyInterface();
596   if (!ble_iface.get()) {
597     PrintError("Failed to obtain handle to Bluetooth Low Energy interface");
598     return;
599   }
600
601   bool status = ble_iface->Disconnect(ble_client_id.load(), address.c_str());
602
603   PrintCommandStatus(status);
604 }
605
606 void HandleStartLeScan(IBluetooth* bt_iface, const vector<string>& args) {
607   if (!ble_client_id.load()) {
608     PrintError("BLE not registered");
609     return;
610   }
611
612   for (auto arg : args) {
613     if (arg == "-d") {
614       dump_scan_record = true;
615     } else if (arg == "-h") {
616       static const char kUsage[] =
617           "Usage: start-le-scan [flags]\n"
618           "\n"
619           "Flags:\n"
620           "\t-d\tDump scan record\n"
621           "\t-h\tShow this help message\n";
622       cout << kUsage << endl;
623       return;
624     }
625   }
626
627   sp<IBluetoothLowEnergy> ble_iface = bt_iface->GetLowEnergyInterface();
628   if (!ble_iface.get()) {
629     PrintError("Failed to obtain handle to Bluetooth Low Energy interface");
630     return;
631   }
632
633   bluetooth::ScanSettings settings;
634   std::vector<bluetooth::ScanFilter> filters;
635
636   bool status = ble_iface->StartScan(ble_client_id.load(), settings, filters);
637   PrintCommandStatus(status);
638 }
639
640 void HandleStopLeScan(IBluetooth* bt_iface, const vector<string>& args) {
641   if (!ble_client_id.load()) {
642     PrintError("BLE not registered");
643     return;
644   }
645
646   sp<IBluetoothLowEnergy> ble_iface = bt_iface->GetLowEnergyInterface();
647   if (!ble_iface.get()) {
648     PrintError("Failed to obtain handle to Bluetooth Low Energy interface");
649     return;
650   }
651
652   bluetooth::ScanSettings settings;
653   std::vector<bluetooth::ScanFilter> filters;
654
655   bool status = ble_iface->StopScan(ble_client_id.load());
656   PrintCommandStatus(status);
657 }
658
659 void HandleHelp(IBluetooth* bt_iface, const vector<string>& args);
660
661 struct {
662   string command;
663   void (*func)(IBluetooth*, const vector<string>& args);
664   string help;
665 } kCommandMap[] = {
666   { "help", HandleHelp, "\t\t\tDisplay this message" },
667   { "disable", HandleDisable, "\t\t\tDisable Bluetooth" },
668   { "enable", HandleEnable, "\t\t\tEnable Bluetooth" },
669   { "get-state", HandleGetState, "\t\tGet the current adapter state" },
670   { "is-enabled", HandleIsEnabled, "\t\tReturn if Bluetooth is enabled" },
671   { "get-local-address", HandleGetLocalAddress,
672     "\tGet the local adapter address" },
673   { "set-local-name", HandleSetLocalName, "\t\tSet the local adapter name" },
674   { "get-local-name", HandleGetLocalName, "\t\tGet the local adapter name" },
675   { "adapter-info", HandleAdapterInfo, "\t\tPrint adapter properties" },
676   { "supports-multi-adv", HandleSupportsMultiAdv,
677     "\tWhether multi-advertisement is currently supported" },
678   { "register-ble", HandleRegisterBLE,
679     "\t\tRegister with the Bluetooth Low Energy interface" },
680   { "unregister-ble", HandleUnregisterBLE,
681     "\t\tUnregister from the Bluetooth Low Energy interface" },
682   { "unregister-all-ble", HandleUnregisterAllBLE,
683     "\tUnregister all clients from the Bluetooth Low Energy interface" },
684   { "register-gatt", HandleRegisterGATT,
685     "\t\tRegister with the Bluetooth GATT Client interface" },
686   { "unregister-gatt", HandleUnregisterGATT,
687     "\t\tUnregister from the Bluetooth GATT Client interface" },
688   { "connect-le", HandleConnect, "\t\tConnect to LE device (-h for options)"},
689   { "disconnect-le", HandleDisconnect,
690     "\t\tDisconnect LE device (-h for options)"},
691   { "start-adv", HandleStartAdv, "\t\tStart advertising (-h for options)" },
692   { "stop-adv", HandleStopAdv, "\t\tStop advertising" },
693   { "start-le-scan", HandleStartLeScan,
694     "\t\tStart LE device scan (-h for options)" },
695   { "stop-le-scan", HandleStopLeScan, "\t\tStop LE device scan" },
696   {},
697 };
698
699 void HandleHelp(IBluetooth* /* bt_iface */, const vector<string>& /* args */) {
700   cout << endl;
701   for (int i = 0; kCommandMap[i].func; i++)
702     cout << "\t" << kCommandMap[i].command << kCommandMap[i].help << endl;
703   cout << endl;
704 }
705
706 }  // namespace
707
708 class BluetoothDeathRecipient : public android::IBinder::DeathRecipient {
709  public:
710   BluetoothDeathRecipient() = default;
711   ~BluetoothDeathRecipient() override = default;
712
713   // android::IBinder::DeathRecipient override:
714   void binderDied(const android::wp<android::IBinder>& /* who */) override {
715     if (showing_prompt.load())
716       cout << endl;
717     cout << COLOR_BOLDWHITE "The Bluetooth daemon has died" COLOR_OFF << endl;
718     cout << "\nPress 'ENTER' to exit." << endl;
719     if (showing_prompt.load())
720       PrintPrompt();
721
722     android::IPCThreadState::self()->stopProcess();
723     should_exit = true;
724   }
725
726  private:
727   DISALLOW_COPY_AND_ASSIGN(BluetoothDeathRecipient);
728 };
729
730 int main(int argc, char* argv[]) {
731   base::AtExitManager exit_manager;
732   base::CommandLine::Init(argc, argv);
733   logging::LoggingSettings log_settings;
734
735   if (!logging::InitLogging(log_settings)) {
736     LOG(ERROR) << "Failed to set up logging";
737     return EXIT_FAILURE;
738   }
739
740   sp<IBluetooth> bt_iface = IBluetooth::getClientInterface();
741   if (!bt_iface.get()) {
742     LOG(ERROR) << "Failed to obtain handle on IBluetooth";
743     return EXIT_FAILURE;
744   }
745
746   sp<BluetoothDeathRecipient> dr(new BluetoothDeathRecipient());
747   if (android::IInterface::asBinder(bt_iface.get())->linkToDeath(dr) !=
748       android::NO_ERROR) {
749     LOG(ERROR) << "Failed to register DeathRecipient for IBluetooth";
750     return EXIT_FAILURE;
751   }
752
753   // Initialize the Binder process thread pool. We have to set this up,
754   // otherwise, incoming callbacks from IBluetoothCallback will block the main
755   // thread (in other words, we have to do this as we are a "Binder server").
756   android::ProcessState::self()->startThreadPool();
757
758   // Register Adapter state-change callback
759   sp<CLIBluetoothCallback> callback = new CLIBluetoothCallback();
760   bt_iface->RegisterCallback(callback);
761
762   cout << COLOR_BOLDWHITE << "Fluoride Command-Line Interface\n" << COLOR_OFF
763        << endl
764        << "Type \"help\" to see possible commands.\n"
765        << endl;
766
767   while (true) {
768     string command;
769
770     PrintPrompt();
771
772     showing_prompt = true;
773     auto& istream = getline(cin, command);
774     showing_prompt = false;
775
776     if (istream.eof() || should_exit.load()) {
777       cout << "\nExiting" << endl;
778       return EXIT_SUCCESS;
779     }
780
781     if (!istream.good()) {
782       LOG(ERROR) << "An error occured while reading input";
783       return EXIT_FAILURE;
784     }
785
786     vector<string> args =
787         base::SplitString(command, " ", base::TRIM_WHITESPACE,
788                           base::SPLIT_WANT_ALL);
789
790     if (args.empty())
791       continue;
792
793     // The first argument is the command while the remaning are what we pass to
794     // the handler functions.
795     command = args[0];
796     args.erase(args.begin());
797
798     bool command_handled = false;
799     for (int i = 0; kCommandMap[i].func && !command_handled; i++) {
800       if (command == kCommandMap[i].command) {
801         kCommandMap[i].func(bt_iface.get(), args);
802         command_handled = true;
803       }
804     }
805
806     if (!command_handled)
807       cout << "Unrecognized command: " << command << endl;
808   }
809
810   return EXIT_SUCCESS;
811 }