ble_plugin 1.3.4 copy "ble_plugin: ^1.3.4" to clipboard
ble_plugin: ^1.3.4 copied to clipboard

A simple and easy-to-use ble plugin.

example/lib/main.dart

import 'dart:io';

import 'package:ble_plugin/ble_device.dart';
import 'package:ble_plugin/event_channel_constant.dart';
import 'package:ble_plugin_example/data.dart';
import 'package:ble_plugin_example/data_provider.dart';
import 'package:flutter/material.dart';

import 'package:flutter/services.dart';
import 'package:ble_plugin/ble_plugin.dart';

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

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

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

class _MyAppState extends State<MyApp> implements DeviceListener, DataListener {
  final _blePlugin = BlePlugin.getInstance();
  List<BleDevice> deviceList = [];
  BleDevice? connectedDevice;
  int copies = 5;

  @override
  void initState() {
    super.initState();
    _blePlugin.setDeviceListener(this);
    _blePlugin.setDataListener(this);
  }

  @override
  void dispose() {
    super.dispose();
    _blePlugin.stopListener();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Ble Plugin example'),
        ),
        body: Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                ElevatedButton(
                    onPressed: () async {
                      deviceList = [];
                      await _blePlugin.startScanBluetooth();
                    },
                    child: const Text("扫描")),
                ElevatedButton(
                    onPressed: () async {
                      await _blePlugin.stopScanBluetooth();
                    },
                    child: const Text("停止扫描")),
              ],
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                ElevatedButton(
                    onPressed: printImage, child: const Text("发数据文本")),
                ElevatedButton(
                    onPressed: () async {
                      await _blePlugin.sendUint8Command(
                          Uint8List.fromList([16, 255, 48, 17]));
                    },
                    child: const Text("发原始数据")),
                ElevatedButton(
                    onPressed: () async {
                      bool isAvailable = await _blePlugin.isAvailable();
                      bool isConnected = await _blePlugin.isConnected();
                      bool isScanning = await _blePlugin.isScanning();
                      bool isEnable = await _blePlugin.isEnable();
                      BleDevice? connectedDevice =
                          await _blePlugin.getConnectedDevice();
                      print("isAvailable: ${isAvailable}");
                      print("isConnected: ${isConnected}");
                      print("isScanning: ${isScanning}");
                      print("isEnable: ${isEnable}");
                      print("connectedDevice: ${connectedDevice}");
                    },
                    child: const Text("获取状态")),
              ],
            ),
            const Divider(height: 1.0, endIndent: 20.0),
            if (connectedDevice != null)
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 10),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      "已连接:${connectedDevice?.name}",
                      style: const TextStyle(color: Colors.red, fontSize: 18),
                    ),
                    ElevatedButton(
                        onPressed: () async {
                          await _blePlugin.disconnect();
                        },
                        child: const Text("断开")),
                  ],
                ),
              ),
            if (connectedDevice != null)
              const Divider(height: 1.0, endIndent: 20.0),
            Expanded(
              child: ListView(
                shrinkWrap: true,
                children: List.generate(deviceList.length, (index) {
                  BleDevice device = deviceList[index];
                  return Container(
                    padding: const EdgeInsets.symmetric(horizontal: 10),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Expanded(
                            child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(device.name),
                            Text(
                              "mac: ${device.mac ?? 'null'}",
                              style: const TextStyle(
                                  fontSize: 12, color: Colors.grey),
                            ),
                          ],
                        )),
                        const SizedBox(
                          width: 10,
                        ),
                        ElevatedButton(
                            onPressed: () async {
                              // await _blePlugin.stopScanBluetooth();
                              _blePlugin.connect(device);
                            },
                            child: const Text("连接"))
                      ],
                    ),
                  );
                }),
              ),
            )
          ],
        ),
      ),
    );
  }

  Future<void> printImage() async {
    if (copies < 1) return;

    await _blePlugin.sendUint8TextCommand(DataProvider.colorImage());

    // 连续纸  - 小图压缩
    // await _blePlugin.sendUint8TextCommand(DataProvider.tsplImage());
    // 连续纸  - 大图压缩
    // await _blePlugin.sendUint8TextCommand(DataProvider.smallPicLabel());
    // await _blePlugin.sendUint8TextCommand("10ff04");
    setState(() {
      copies--;
    });
  }

  @override
  void onFoundDevice(BleDevice device) {
    print("发现设备 : ${device.toString()}");
    setState(() {
      deviceList.add(device);
    });
  }

  @override
  void onReceivedData(Uint8List data) {
    print("收到打印机回传数据 : ${data}");
  }

  @override
  void onConnectionStateChange(int state, BleDevice deviceBle) {
    switch (state) {
      case EventChannelConstant.STATE_CONNECTED:
        print("连接成功 : $deviceBle");
        // _blePlugin.sendUint8Command(Uint8List.fromList([16, 255, 48, 17]));
        break;
      case EventChannelConstant.STATE_DISCONNECTED:
        print("连接断开 : $deviceBle");
        break;
      case EventChannelConstant.STATE_FAILCONNECT:
        print("连接失败 : $deviceBle");
        break;
    }
    setState(() {
      connectedDevice =
          state == EventChannelConstant.STATE_CONNECTED ? deviceBle : null;
    });
  }

  @override
  void onBluetoothStateChange(int state) {
    switch (state) {
      case EventChannelConstant.BLUETOOTHON:
        {
          print("蓝牙开启 ...");
        }
        break;
      case EventChannelConstant.BLUETOOTHOFF:
        {
          print("蓝牙关闭 ...");
        }
        break;
    }
    print("onBluetoothStateChange ... $state");
  }

  @override
  void onWriteEnd(int state) {
    // TODO: implement onWriteEnd
    print("数据写入完成 ...");
  }
}
0
likes
55
points
104
downloads

Publisher

unverified uploader

Weekly Downloads

A simple and easy-to-use ble plugin.

Documentation

API reference

License

MIT (license)

Dependencies

flutter, flutter_web_plugins, plugin_platform_interface

More

Packages that depend on ble_plugin

Packages that implement ble_plugin