h_ble 0.3.6 copy "h_ble: ^0.3.6" to clipboard
h_ble: ^0.3.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_broadcast_base.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()}");

  }


  final List _hexStringList = ["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];
  // static final List<int> _hexIntList = [0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x41,0x42,0x43,0x44,0x45,0x46];
  String intToHexOneStr(int i){
    if(i<0){i = - i;}
    if(i < _hexStringList.length){
      return _hexStringList[i];
    }else{
      return _hexStringList[15];
    }
  }

  String intToHexTwoStr(int i){
    return intToHexOneStr((i & 0xf0) >> 4) + intToHexOneStr(i & 0x0f);
  }
  String appId = "1234";
  int appIdValue = 0x1234;



  String connection(){
    int checksum = 0;
    int appId1 = appIdValue;
    int appId2 = appIdValue >> 8;
    checksum = 0xad + appId1 + appId2+ 0x80+0x80+0x80;
    debugPrint("checksum ${intToHexTwoStr(checksum)}");
    return "AD${appId}808080${intToHexTwoStr(checksum)}52";
  }


  String control(){

String appId = "0102";


    return "7D$appId${distanceToHexStr()}${distanceToHexStr()}${distanceToHexStr()}82";
  }


String distanceToHexStr(){
  return "${distanceToOneHexStr()}${distanceToOneHexStr()}${distanceToOneHexStr()}${distanceToOneHexStr()}";
}

String distanceToOneHexStr(){

  return "7";
}

  @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),
                      // );


                      test1();
                     // debugPrint("testS  $testS");

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

  Future<void> test1() async {
    //String testS = connection();
    debugPrint("----------");
    HBleBroadcastBase.stop();
    await Future.delayed(Duration(milliseconds: 100));
    HBleBroadcastBase.sentHexStr("AD2A55808080AC52");
    await Future.delayed(Duration(milliseconds: 100));
    HBleBroadcastBase.start();
    await Future.delayed(Duration(seconds: 5));

    debugPrint("----------");
    HBleBroadcastBase.stop();
    await Future.delayed(Duration(milliseconds: 100));
    HBleBroadcastBase.sentHexStr("7D2A5588788888888882");
    await Future.delayed(Duration(milliseconds: 100));
    HBleBroadcastBase.start();
    //HBleBroadcastBase.sentHexStr("010203040506070809");


    // flutter: sentHexStr() : 010203040506070809
    // 88
    // 53
    // 238
    // 68
    // 247
    // 207
    // 245
    // 173
    // 39
    // 0
    // 202
    // 246
    // 11
    // 121
    // 219
    // 32
    // 116
    // 138
    // 191
    // 0
    // UUIDs:
    // 3558
    // 44EE
    // CFF7
    // ADF5
    // 0027
    // F6CA
    // 790B
    // 20DB
    // 8A74
    // 00BF
    // 1312
    // 1514
    // 1716




    ////

  }

  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;
    }
  }



  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
115
points
23
downloads

Publisher

unverified uploader

Weekly Downloads

That can make it easy for you to use Bluetooth.

Documentation

API reference

License

BSD-3-Clause (license)

Dependencies

flutter, plugin_platform_interface

More

Packages that depend on h_ble

Packages that implement h_ble