bluetooth_socket.dart 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. part of flutter_bluetooth;
  2. class BluetoothSocket {
  3. static const int _MESSAGE_READ = 1;
  4. static const int _MESSAGE_EXCEPTIONS = 2;
  5. static const int _MESSAGE_SUCCESS = 3;
  6. static const int _MESSAGE_CLOSE = 4;
  7. final String _address;
  8. String get address => _address;
  9. final String _uuid;
  10. String get uuid => _uuid;
  11. final StreamController<Uint8List> _readController =
  12. StreamController<Uint8List>();
  13. Stream<Uint8List> get readStream => _readController.stream;
  14. final StreamController _closeController = StreamController();
  15. Stream get closeStream => _closeController.stream;
  16. BluetoothSocketStatusEnum _status = BluetoothSocketStatusEnum.Connected;
  17. BluetoothSocketStatusEnum get status => _status;
  18. BluetoothSocket._(this._address, this._uuid) {
  19. this._handlerEvent();
  20. }
  21. write(Uint8List data) async {
  22. await FlutterBluetooth._channel.invokeMethod(
  23. 'write', {'address': address, 'uuid': uuid, 'data': data});
  24. }
  25. close() async {
  26. await FlutterBluetooth._channel
  27. .invokeMethod('close', {'address': address, 'uuid': uuid});
  28. }
  29. _handlerEvent() {
  30. EventChannel('flutter_bluetooth/connectedEvent$address-$uuid')
  31. .receiveBroadcastStream()
  32. .takeUntil(closeStream)
  33. .listen((event) {
  34. switch (event['type']) {
  35. case _MESSAGE_READ:
  36. this._readController.add(event['data']);
  37. break;
  38. case _MESSAGE_CLOSE:
  39. _status = BluetoothSocketStatusEnum.Disconnect;
  40. _closeController.add(null);
  41. break;
  42. default:
  43. }
  44. });
  45. }
  46. }
  47. enum BluetoothSocketStatusEnum { Connected, Disconnect }