无法通过蓝牙将数据从 Flutter 应用程序发送到 Pycom 板为什么?

如何解决无法通过蓝牙将数据从 Flutter 应用程序发送到 Pycom 板为什么?

我想要达到的目标

使用 flutter_blueFlutter 应用程序中的数据发送到使用连接的 Pycom Pytrack 2 boardPycom WiPy

问题

当我将测试数据从 Flutter 应用程序发送到 pycom 开发板时,pycom 代码中的写入回调处理程序方法从未被调用。对我来说,pycom 代码似乎无法识别或收到我从 Flutter 应用程序向其发送和写入数据的通知。我不知道是什么原因造成的,也不知道问题存在于事件链中的哪个位置。可能数据从一开始就没有成功发送,或者数据到达但我的回调方法代码中有问题,它侦听 pycom 板上的传入写入。

Flutter 应用代码(发送方)

我使用 Flutter_blue 库编写的一个简单的蓝牙客户端:

import 'package:Flutter_blue/Flutter_blue.dart';

class BluetoothClient {
  Future<List<ScanResult>> scanForDevices() async {
    FlutterBlue FlutterBlue = FlutterBlue.instance;

    var scanRes = <ScanResult>[];
    FlutterBlue.scanResults.listen((scanResults) {
      for (ScanResult scanResult in scanResults) {
        scanRes.add(scanResult);
      }
    });

    await FlutterBlue.startScan(timeout: Duration(seconds: 4));
    await FlutterBlue.stopScan();

    scanRes = filterDuplicateResults(scanRes);
    sortScanResults(scanRes);

    printScanResults(scanRes);

    return scanRes;
  }

  List<ScanResult> filterDuplicateResults(List<ScanResult> scanResults) {
    var uniques = <ScanResult>[];

    for (var scanResult in scanResults) {
      var uniquesContain = scanResultsHave(uniques,scanResult);
      if (!uniquesContain) uniques.add(scanResult);
    }

    return uniques;
  }

  sortScanResults(List<ScanResult> scanResults) {
    scanResults.sort((a,b) => a.device.name.compareto(b.device.name));
  }

  bool scanResultsHave(List<ScanResult> scanResults,ScanResult scanResult) {
    var index = scanResults
        .indexWhere((ScanResult sr) => sr.device.id == scanResult.device.id);
    return index >= 0;
  }

  Future<List<BluetoothService>> getServices(BluetoothDevice device) async {
    var services = await device.discoverServices();
    return services;
  }

  Future<List<BluetoothCharacteristic>> getcharacteristics(
      BluetoothDevice device) async {
    var services = await getServices(device);

    var characteristics = <BluetoothCharacteristic>[];
    for (var service in services)
      characteristics.addAll(service.characteristics);

    return characteristics;
  }

  List<BluetoothDevice> getDevicesFromresults(List<ScanResult> scanResults) {
    var devices = scanResults.map((scanResult) => scanResult.device).toList();
    return devices;
  }

  Future<BluetoothDeviceState> getDeviceState(BluetoothDevice device) async {
    var stateList = await device.state.toList();
    return stateList.first;
  }

  Future connect(BluetoothDevice device) async {
    var timeout = Duration(seconds: 10);
    var autoConnect = false;
    try {
      await device.connect(timeout: timeout,autoConnect: autoConnect);
    } catch (e) {
      print(e);
    }
  }

  printScanResults(List<ScanResult> scanResults) {
    for (var scanResult in scanResults) printScanResult(scanResult);
  }

  printScanResult(ScanResult scanResult) {
    print("==== BLUetoOTH DEVICE ====");
    print("Name: ${scanResult.device.name}");
    print("Local name: ${scanResult.advertisementData.localName}");
    print("Type: ${scanResult.device.type}");
    print("Id: ${scanResult.device.id}");
    print("Connectable: ${scanResult.advertisementData.connectable}");
    print("Power level: ${scanResult.advertisementData.txPowerLevel}");
    print(
        "Manufacturer data: ${scanResult.advertisementData.manufacturerData}");
    print("Service data: ${scanResult.advertisementData.serviceData}");
    print("==========================");
  }

  Future printDeviceInfo(BluetoothDevice device) async {
    try {
      var services = await getServices(device);
      var characteristics = await getcharacteristics(device);
      print("=== DEVICE INFO ===");
      for (var service in services) print(service);
      for (var characteristic in characteristics) print(characteristic);
      print("===================");
    } catch (e) {
      print(e);
    }
  }

  Future<BluetoothService> getWaterSwitchService(BluetoothDevice device) async {
    var services = await getServices(device);
    var service =
        services.firstWhere((serv) => serv.uuid.toString().startsWith("3"));
    return service;
  }

  BluetoothCharacteristic getWaterSwitchCharacteristic(
      BluetoothService service) {
    var characteristics = service.characteristics;
    var characteristic = characteristics
        .firstWhere((char) => char.uuid.toString().startsWith("3"));
    return characteristic;
  }

  bool writeallowed(BluetoothCharacteristic characteristic) {
    var properties = characteristic.properties;
    return properties.write;
  }

  bool writeWithoutResponseAllowed(BluetoothCharacteristic characteristic) {
    var properties = characteristic.properties;
    return properties.writeWithoutResponse;
  }
}

一个测试页面,它创建一些测试数据并在连接到它后将其发送到电路板。它使用上面的蓝牙客户端类与 pycom 板通信:

import 'dart:convert';

import 'package:Flutter/cupertino.dart';
import 'package:Flutter/material.dart';
import 'package:Flutter_blue/Flutter_blue.dart';
import 'package:gustavsberg_waterswitch_mobile/clients/BluetoothClient.dart';
import 'package:gustavsberg_waterswitch_mobile/helpers/DeviceHelper.dart';
import 'package:gustavsberg_waterswitch_mobile/globals.dart' as globals;
import 'package:gustavsberg_waterswitch_mobile/widgets/Buttons/CustomIconButton.dart';
import 'package:gustavsberg_waterswitch_mobile/widgets/Buttons/CustomTextButton.dart';

class BluetoothTestPage extends StatefulWidget {
  @override
  _BluetoothTestPageState createState() => _BluetoothTestPageState();
}

class _BluetoothTestPageState extends State<BluetoothTestPage> {
  BluetoothClient bluetoothClient;
  List<BluetoothDevice> bluetoothDevices;
  ScrollController scrollController;

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

  init() {
    scrollController = new ScrollController();
    bluetoothClient = new BluetoothClient();
    bluetoothDevices = [];
  }

  @override
  Widget build(BuildContext context) {
    DeviceHelper.readdisplayDimensions(context);
    return Scaffold(
      body: buildBody(),);
  }

  buildBody() {
    return Container(
      width: globals.displayWidth,height: globals.displayHeight,child: Stack(
        children: [buildControlsLayer()],),);
  }

  buildControlsLayer() {
    return Container(
        child: Column(
      mainAxisAlignment: MainAxisAlignment.center,mainAxisSize: MainAxisSize.max,crossAxisAlignment: CrossAxisAlignment.stretch,children: [buildScanButton(),buildDeviceList()],));
  }

  buildScanButton() {
    return Expanded(
      flex: 10,child: CustomTextButton(
        onpressed: onScanpressed,text: "Scan",);
  }

  onScanpressed() {
    clearDeviceList();
    scanDevices();
  }

  Future scanDevices() async {
    var scanResults = await bluetoothClient.scanForDevices();
    var devices = bluetoothClient.getDevicesFromresults(scanResults);
    setBluetoothDevices(devices);
  }

  setBluetoothDevices(List<BluetoothDevice> devices) {
    if (mounted)
      setState(() {
        bluetoothDevices = devices;
      });
    else
      bluetoothDevices = devices;
  }

  buildDeviceList() {
    return Expanded(
        flex: 100,child: Container(
          child: Scrollbar(
            controller: scrollController,child: ListView(
              controller: scrollController,children: buildDeviceButtons(),));
  }

  List<Widget> buildDeviceButtons() {
    var deviceButtons = <Widget>[];
    for (var device in bluetoothDevices) {
      var deviceButton = buildDeviceButton(device);
      deviceButtons.add(deviceButton);
    }

    return deviceButtons;
  }

  Widget buildDeviceButton(BluetoothDevice device) {
    return Container(
      child: CustomIconButton(
        text: "${device.name},${device.id}",onTap: () {
          onDeviceButtonTap(device);
        },iconData: Icons.devices,);
  }

  Future onDeviceButtonTap(BluetoothDevice device) async {
    await bluetoothClient.connect(device);
    await runDeviceTests(device);
  }

  Future runDeviceTests(BluetoothDevice device) async {
    // Print device info
    bluetoothClient.printDeviceInfo(device);

    var service = await bluetoothClient.getWaterSwitchService(device);
    var characteristic = bluetoothClient.getWaterSwitchCharacteristic(service);
    print(service);
    print(characteristic);

    var testData = buildTestData();
    await writeDataWithoutResponsetocharacteristic(characteristic,testData);

    // Send test data to device
    // await writetoDevice(device,testData);
  }

  Future writetoDevice(BluetoothDevice device,List<int> data) async {
    var characteristics = await bluetoothClient.getcharacteristics(device);
    await writeDataTocharacteristics(characteristics,data);
  }

  Future writeDataTocharacteristics(
      List<BluetoothCharacteristic> characteristics,List<int> data) async {
    for (var characteristic in characteristics) {
      await writeDataWithoutResponsetocharacteristic(characteristic,data);
    }
  }

  Future writeDatatocharacteristic(
      BluetoothCharacteristic characteristic,List<int> data) async {
    if (!bluetoothClient.writeallowed(characteristic)) return;

    try {
      await characteristic.write(data);
    } catch (e) {
      print(e);
    }
  }

  Future writeDataWithoutResponsetocharacteristic(
      BluetoothCharacteristic characteristic,List<int> data) async {
    if (!bluetoothClient.writeWithoutResponseAllowed(characteristic)) return;

    try {
      await characteristic.write(data,withoutResponse: true);
    } catch (e) {
      print(e);
    }
  }

  List<int> buildTestData() {
    var str = "Hello bluetooth space!";
    var bytes = utf8.encode(str);
    return bytes;
  }

  clearDeviceList() {
    setBluetoothDevices([]);
  }
}

pycom代码(接收器)

main.py:

from network import Bluetooth
import time

bluetooth = Bluetooth()
bluetooth.set_advertisement(name='LoPy',service_uuid=b'1234567890123456')

def char_handler(chr,data):
    print("char_handler called!!!")
    events,value = data
    if events & Bluetooth.CHAR_WRITE_EVENT:
        print("Write request with value = {}".format(value))
    else:
        print('Read request on char 1')

service = bluetooth.service(uuid=b'1234567890123456',isprimary=True)
service.start()

characteristic = service.characteristic(uuid=b'2234567890123456',permissions=14,properties=14,value=64)
characteristic.callback(trigger=Bluetooth.CHAR_WRITE_EVENT | Bluetooth.CHAR_READ_EVENT,handler=char_handler)

bluetooth.advertise(True)

while True:
    print("Listening...")
    time.sleep(3)

尽管从 Flutter 应用程序写入数据,但从未调用写入回调方法 char_handler

目前有效

我已确认设备已连接。我还确认 Flutter 应用程序写入了我在 pycom 代码中创建的服务和特征,用于侦听传入的写入。

问题

为什么 pycom 代码没有得到通知或运行写入回调方法

谢谢!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?