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