h_ble 0.2.6 copy "h_ble: ^0.2.6" to clipboard
h_ble: ^0.2.6 copied to clipboard

That can make it easy for you to use Bluetooth.

example/lib/main.dart

import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:h_ble/h_ble.dart';
import 'package:h_ble/h_ble_device.dart';
import 'package:h_ble/h_ble_device_services.dart';
import 'package:h_ble/h_ble_device_services_characteristics.dart';

import 'h_permission.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  final _hBlePlugin = HBle();
  HBleDeviceServicesCharacteristics? sentCharacteristics;

  @override
  void initState() {
    super.initState();

    HPermission.checkBluetooth(context, end: (){});
    _hBlePlugin.addScanListen(scanListen);
    _hBlePlugin.addNotificationListen(notification);
  }


Map<String,HBleDevice> deviceMap = {};

  void scanListen(HBleDevice device){
    // debugPrint("scanListen $device");
    // //_hBlePlugin.connect(device: device);
    // deviceMap[device.identifier] = device;
    // if(mounted){
    //   setState(() {});
    // }

    if(device.name?.contains("YX") == true){
      debugPrint("scanListen $device");
      //_hBlePlugin.connect(device: device);
      deviceMap[device.identifier] = device;
      if(mounted){
        setState(() {});
      }
    }
  }


  void notification(String serviceUuid,String characteristicsUuid,Uint8List bytes){
    debugPrint("notification main : ${bytes.toString()}");

  }




  @override
  Widget build(BuildContext context) {

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Column(
          children: [
            Row(
              children: [
                GestureDetector(
                child: Container(color: Color(0xffff0000),width: 100,height: 100,child: Text("扫描"),),
                onTap: (){
                  deviceMap = {};
                  _hBlePlugin.scan();
                  setState(() {

                  });
                },
              ),
              GestureDetector(
                child: Container(color: Color(0xff00ff00),width: 100,height: 100,child: Text("停止扫描"),),
                onTap: (){
                  _hBlePlugin.stopScan();
                },
              ),
                GestureDetector(
                  child: Container(color: Color(0xff0000ff),width: 60,height: 100,child: Text("发送测试"),),
                  onTap: (){
                   // HPermission.checkBluetooth(context, end: (){});
                    String str = _appToMcuSentBase(
                      dataType: '5',
                      data: "0123456789",
                    );
                    if(sentCharacteristics != null){
                      _hBlePlugin.writeCharacteristics(
                          characteristics: sentCharacteristics!,
                          value:Uint8List.fromList(str.codeUnits),
                          writeResult:(b){
                            debugPrint("发送结果 : $b");
                          }
                      );
                      //_hBlePlugin.disConnectDevice();
                    }
                  },
                ),
                GestureDetector(
                  child: Container(color: Color(0xff44824c),width: 60,height: 100,child: Text("测试"),),
                  onTap: (){
                    //_hBlePlugin.addHistoryScanListen(historyScanListen);
                    //_hBlePlugin.getHistoryScanList(100);
                    // _hBlePlugin.getHBleState((state){
                    //   debugPrint("state ; $state");
                    // });
                    final str = "G08043040030BDFF21C905084330BD084607210905884330BD0000C07FF0B50C46871A9C410D46861A9D4103D2C01BA141D21963410D0D1F0DC94EEC1BAE435CD07F057F0D0026002F51D02D05AC46A943DD020123ED0A1B051D4320231B1B24D41746E740381871412F46E740CC199D402818314661410C0D27D161449A4013D50023401C594152000ED14008400001224B005205D34207D305204007C14201D5B04900E0B0493046F0BD6B00002A00D001229A181F23203C1B1B01D5002302E0E540281871410C0DD7D0012424050919C407CD0740084908E40F28436144002CD5D00024401C61419A40D0D1CDE76A05520DD9D1C90FC907D5E79C4D4E00002801D0012400E0002434195F00002A01D0012600E00026BE19954FAC420CD8AE420AD8B44206D001256D05EC42BCD010461946F0BD9942FCD000203946F0BDF0B51FB40C460F46811A9F412546861A9D4106D20125ED076F40401ABC4152187B41210D1E0D8D1BAC467D4D8D437ED075056D0D7CD00D05AE46AC431B031B0B794D52429D41202366469B1B14D31746F740381800260090744160462F460741E41900989D402818664116D4714671189A4025D5012320E093182A466A415200002B00D0521C1E23203E9B1B002B61DD3541EE1728186641E8D5001876415B1C9A4000D3401C4B05F3181524E34010D3002B52D071467118D30FC01802D3491C05B0F0BD0123DB079A42F9D140084000F6E701225205B21801D1002853D00123CC0ADB029943891E002A08D1020C03D0020C0004103902E00246002020390023550B05D112020823550B01D152010D23550C01D112011B1DD50C01D192009B1C150D01D152005B1C2025EE1A01E02CE022E00546F54015439840CA1AE10769181305C918002ABBDA032040070818C10FC9070FE071466118B2E7F10740080843711071444A000CD001235B059A42A7D2C90FC9070020A3E74905490D26D1002001E00028F4D100219AE7284D6600002801D0012100E0002171185F00002A01D0012600E00026BE19224FA94210D8AE420ED8B14208D001256D05E94206D01946A802414010467BE79C4201D0214677E70020394674E710B50C465C4005D50124E4076340FFF70CFF10BDFFF778FE10BD30B40C465C4004D50124E407634030BC6DE630BCFCE670B50124E40761400D465D4002D4FFF763FE70BD6340FFF7F0FE70BDFF0700000000F0FF0000F07F0000E0FF0000F87F0121C9050123411842001B06D3185B0E0AD0C1100722D206891840075242D14201D5520089187047090208D50146002A03D0C10FC9070020704710467047420202D0002002497047072109050143F4E70000F87FF0B5FF252D04C609C209FF2704462E400137CB093E4348402A402B400746002A6BD0002B69D0AA4267D0AB4265D0002800DA32460125ED0529432C43R";

                    _hBlePlugin.secureWriteCharacteristics(
                      characteristics: HBleDeviceServicesCharacteristics.fromMap({}),
                      value: Uint8List.fromList(str.codeUnits),
                    );

                  },
                ),
              ],),
            Expanded(child: listView()),
          ],
        )
      ),
    );
  }

  void historyScanListen(List<HBleDevice> devices){
    debugPrint("历史记录 ; ${devices.length}");

    // devices.forEach((device) {
    //
    //   if(device.name?.contains("YX-") == true){
    //     debugPrint("scanListen $device");
    //     //_hBlePlugin.connect(device: device);
    //     deviceMap[device.identifier] = device;
    //     if(mounted){
    //       setState(() {});
    //     }
    //   }
    //
    //
    // });





  }

  String _appToMcuSentBase({
    required String dataType,
    String? data,
  }){
    const String headStr = "T";
    String dataTypeLength = intToHexTwoStr(data?.length ?? 0);
    const String tail = "W";
    if(data != null){
      return headStr+dataTypeLength+dataType+data+tail;
    }else{
      return headStr+dataTypeLength+dataType+tail;
    }
  }

  static final List _hexStringList = ["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];
  static String intToHexOneStr(int i){
    if(i<0){i = - i;}
    if(i < _hexStringList.length){
      return _hexStringList[i];
    }else{
      return _hexStringList[15];
    }
  }
  static String intToHexTwoStr(int i){
    return intToHexOneStr((i & 0xf0) >> 4) + intToHexOneStr(i & 0x0f);
  }

  Widget listView(){
    List<HBleDevice> deviceList = [];
    deviceMap.forEach((key, value) {
      deviceList.add(value);
    });

    return
      ListView(
        children:List<Widget>.generate(deviceMap.length, (index) {
          HBleDevice oneDevice = deviceList[index];
          return
            GestureDetector(
              child: Container(
                margin: const EdgeInsets.all(10),
                width: 300,
                height: 60,
                color: const Color(0xffaff36a),
                child: Text("${oneDevice.name}  ${oneDevice.rssi}  ${oneDevice.advertisementData.toString()}"),
              ),
              onTap: (){

                _hBlePlugin.connect(device: oneDevice, deviceStatus: (ConnectionStatus status) {
                  debugPrint("连接状态 : $status");

                  if(status == ConnectionStatus.STATE_CONNECTED){
                    _hBlePlugin.discoverService(device: oneDevice, deviceServices: (HBleDeviceServices services) {
                      debugPrint("发现服务 : $services");

                      if(services.uuid.toLowerCase().contains("ae3a")){
                        _hBlePlugin.getCharacteristics(services:services, deviceServicesCharacteristics: (HBleDeviceServicesCharacteristics characteristics) {
                          debugPrint("发现特征 : $characteristics");

                          if(characteristics.characteristicsUuid.toLowerCase().contains("ae3c")){//读

                            Future.delayed(Duration(milliseconds:300),(){
                              debugPrint("characteristics 读");
                              _hBlePlugin.characteristicsNotification(characteristics: characteristics, enable: true);
                            });
                          }else{
                            debugPrint("${characteristics.characteristicsUuid} 非读");
                          }

                          if(characteristics.characteristicsUuid.toLowerCase().contains("ae3b")){//写

                            Future.delayed(Duration(milliseconds:500),(){
                              debugPrint("characteristics 写1");
                              String str = "T041AABBW";
                              _hBlePlugin.writeCharacteristics(characteristics: characteristics, value:Uint8List.fromList(str.codeUnits));
                            });

                            sentCharacteristics = characteristics;

                            // Future.delayed(Duration(milliseconds:6000),(){
                            //   debugPrint("characteristics 写3");
                            //   String str = "T00EW";
                            //   _hBlePlugin.writeCharacteristics(characteristics: characteristics, value:Uint8List.fromList(str.codeUnits));
                            // });
                          }else{
                            debugPrint("${characteristics.characteristicsUuid.toString()} 非写");
                          }

                        });
                      }

                    },);
                  }

                });
              },
            );
        }),
      );
  }

}


//flutter packages pub publish --server=https://pub.dartlang.org
//flutter packages pub publish --server=https://pub.flutter-io.cn
//https://pub.dartlang.org
//https://pub.flutter-io.cn
2
likes
0
points
32
downloads

Publisher

unverified uploader

Weekly Downloads

That can make it easy for you to use Bluetooth.

Homepage

License

unknown (license)

Dependencies

flutter, plugin_platform_interface

More

Packages that depend on h_ble