bluetooth_device.dart 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. part of flutter_bluetooth;
  2. class BluetoothDevice {
  3. final String name;
  4. final String address;
  5. final int deviceClass;
  6. BluetoothDevice({this.name, this.address, this.deviceClass});
  7. static BluetoothDevice fromJson(data) {
  8. String name = data['name'];
  9. String address = data['address'];
  10. int deviceClass = data['deviceClass'];
  11. return BluetoothDevice(name: name, address: address, deviceClass: deviceClass);
  12. }
  13. static Future<BluetoothDevice> fromAddress(String address) async {
  14. String name =
  15. await FlutterBluetooth._channel.invokeMethod('getName', address);
  16. int deviceClass =
  17. await FlutterBluetooth._channel.invokeMethod('getDeviceClass', address);
  18. return BluetoothDevice(
  19. address: address,
  20. name: name,
  21. deviceClass: deviceClass);
  22. }
  23. Future<bool> isBond() async {
  24. return FlutterBluetooth._channel.invokeMethod('isBond', address);
  25. }
  26. Future<bool> createBond() async {
  27. return FlutterBluetooth._channel.invokeMethod('createBond', address);
  28. }
  29. Future<BluetoothSocket> createSocket(String uuid) async {
  30. await FlutterBluetooth._channel.invokeMethod('createSocket', {
  31. 'address': address,
  32. 'uuid': uuid
  33. });
  34. return BluetoothSocket._(address, uuid);
  35. }
  36. Future<List<String>> getUUIDs() async{
  37. var isBond = await this.isBond();
  38. if(isBond){
  39. List uuids = await FlutterBluetooth._channel.invokeMethod('getUUIDs', address);
  40. return uuids.map((item)=>item as String).toList();
  41. }else{
  42. throw ErrorDescription("只有配对蓝牙后才可以获取UUID");
  43. }
  44. }
  45. bool operator ==(target){
  46. if(target is BluetoothDevice){
  47. return this.address == target.address;
  48. }else{
  49. return false;
  50. }
  51. }
  52. @override
  53. // TODO: implement hashCode
  54. int get hashCode => this.address.hashCode;
  55. }