find.dart 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. import 'dart:async';
  2. import 'dart:typed_data';
  3. import 'package:buffer/buffer.dart';
  4. import 'package:flutter/material.dart';
  5. import 'package:flutter_reactive_ble/flutter_reactive_ble.dart';
  6. class Find extends StatefulWidget {
  7. final DiscoveredDevice device;
  8. const Find({Key? key, required this.device}) : super(key: key);
  9. @override
  10. State<StatefulWidget> createState() {
  11. return _State();
  12. }
  13. }
  14. class _State extends State<Find> {
  15. final flutterReactiveBle = FlutterReactiveBle();
  16. final ValueNotifier<String> _infoNotifier = ValueNotifier("正在连接...");
  17. @override
  18. void initState() {
  19. super.initState();
  20. _connect(widget.device).then((value) => Navigator.of(context).pop());
  21. }
  22. Future _write(QualifiedCharacteristic characteristicWrite, Uint8List data) async {
  23. int length = data.length + 4;
  24. ByteDataWriter writer = ByteDataWriter();
  25. writer.writeUint8(0xAA);
  26. writer.writeUint8(length);
  27. writer.writeUint8(0xFF - length);
  28. if (data.isNotEmpty) writer.write(data);
  29. int ver = writer.toBytes().reduce((value, element) => value + element);
  30. writer.writeUint8(ver);
  31. Uint8List out = writer.toBytes();
  32. await flutterReactiveBle.writeCharacteristicWithoutResponse(characteristicWrite, value: out);
  33. }
  34. Future _connect(DiscoveredDevice device) async {
  35. bool _connecting = true;
  36. try {
  37. final stream = flutterReactiveBle.connectToDevice(id: device.id, connectionTimeout: const Duration(seconds: 10));
  38. await for (var state in stream) {
  39. print("device state: $state");
  40. if (state.connectionState == DeviceConnectionState.connected) {
  41. _infoNotifier.value = "连接成功";
  42. var services = await flutterReactiveBle.discoverServices(device.id);
  43. _infoNotifier.value = "连接成功,已发现服务${services.length}";
  44. for (DiscoveredService service in services) {
  45. for (var characteristic in service.characteristics) {
  46. if (characteristic.isWritableWithoutResponse) {
  47. QualifiedCharacteristic characteristicWrite = QualifiedCharacteristic(serviceId: service.serviceId, characteristicId: characteristic.characteristicId, deviceId: device.id);
  48. _infoNotifier.value = "连接成功,正在发送闪灯和震动";
  49. Stream.periodic(const Duration(seconds: 1)).take(5).forEach((element) {
  50. _write(characteristicWrite, Uint8List.fromList([0xB0, 0x01]));
  51. });
  52. for(var i = 0; i < 5; i++){
  53. ByteDataWriter writer = ByteDataWriter();
  54. writer.writeUint8(0xAC);
  55. writer.writeUint16(1000);
  56. _write(characteristicWrite, writer.toBytes());
  57. writer = ByteDataWriter();
  58. writer.writeUint8(0xA4);
  59. writer.writeUint16(1000);
  60. writer.writeUint8(0);
  61. _write(characteristicWrite, writer.toBytes());
  62. await Future.delayed(const Duration(milliseconds: 2000));
  63. }
  64. _connecting = false;
  65. }
  66. }
  67. }
  68. break;
  69. } else if (state.connectionState == DeviceConnectionState.disconnected) {
  70. if (state.failure?.code == ConnectionError.failedToConnect) {
  71. _infoNotifier.value = "${state.failure?.message}";
  72. await Future.delayed(const Duration(seconds: 3));
  73. }
  74. break;
  75. }
  76. if (!_connecting) {
  77. break;
  78. }
  79. }
  80. } catch (e) {
  81. print("bluetooth -- connect error: $e");
  82. }
  83. }
  84. @override
  85. Widget build(BuildContext context) {
  86. return Material(
  87. type: MaterialType.transparency,
  88. child: Scaffold(
  89. backgroundColor: Colors.transparent,
  90. body: Center(
  91. child: Container(
  92. width: 140,
  93. height: 140,
  94. decoration: const BoxDecoration(
  95. borderRadius: BorderRadius.all(Radius.circular(10.0)),
  96. color: Colors.white,
  97. ),
  98. child: Center(
  99. child: Column(
  100. mainAxisSize: MainAxisSize.min,
  101. children: [
  102. const CircularProgressIndicator(),
  103. Padding(
  104. padding: const EdgeInsets.only(top: 16.0),
  105. child: ValueListenableBuilder<String>(
  106. valueListenable: _infoNotifier,
  107. builder: (_, value, __) => Padding(
  108. padding: const EdgeInsets.all(8.0),
  109. child: Text(
  110. value,
  111. style: Theme.of(context).textTheme.bodyText1,
  112. ),
  113. ),
  114. ),
  115. )
  116. ],
  117. ),
  118. ),
  119. ),
  120. ),
  121. ),
  122. );
  123. }
  124. }