h_ble 0.3.3 copy "h_ble: ^0.3.3" to clipboard
h_ble: ^0.3.3 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: (){
                    debugPrint("发送测试");
                   // HPermission.checkBluetooth(context, end: (){});
                    String str = _appToMcuSentBase(
                      dataType: '5',
                      data: "0123456789",
                    );
                    if(sentCharacteristics != null){
                      _hBlePlugin.writeCharacteristics(
                          characteristics: sentCharacteristics!,
                          value:Uint8List.fromList(str.codeUnits),
                          withResponse:true,
                          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 = "1234";

                    _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("af80")){
                        _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("af83")){//写

                            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
120
points
146
downloads

Publisher

unverified uploader

Weekly Downloads

That can make it easy for you to use Bluetooth.

Homepage

Documentation

API reference

License

BSD-3-Clause (license)

Dependencies

flutter, plugin_platform_interface

More

Packages that depend on h_ble