bluetooth_socket.dart 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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 _statusController = StreamController();
  15. final StreamController _closeController = StreamController();
  16. Stream get closeStream => _closeController.stream;
  17. BluetoothSocketStatusEnum _status = BluetoothSocketStatusEnum.Connected;
  18. BluetoothSocketStatusEnum get status => _status;
  19. BluetoothSocket._(this._address, this._uuid) {
  20. this._handlerEvent();
  21. }
  22. write(Uint8List data) async {
  23. await FlutterBluetooth.instance._channel.invokeMethod(
  24. 'write', {'address': address, 'uuid': uuid, 'data': data});
  25. }
  26. close() async {
  27. await FlutterBluetooth.instance._channel
  28. .invokeMethod('close', {'address': address, 'uuid': uuid});
  29. }
  30. _handlerEvent() {
  31. EventChannel('flutter_bluetooth/connectedEvent$address-$uuid')
  32. .receiveBroadcastStream()
  33. .takeUntil(_statusController.stream)
  34. .listen((event) {
  35. switch (event['type']) {
  36. case _MESSAGE_READ:
  37. this._readController.add(event['data']);
  38. break;
  39. case _MESSAGE_CLOSE:
  40. _status = BluetoothSocketStatusEnum.Disconnect;
  41. _closeController.add(null);
  42. _statusController.add(null);
  43. break;
  44. default:
  45. }
  46. });
  47. }
  48. }
  49. enum BluetoothSocketStatusEnum { Connected, Disconnect }