gpt4 book ai didi

Flutter蓝牙串口通信

转载 作者:行者123 更新时间:2023-12-05 05:40:32 25 4
gpt4 key购买 nike

我有一个连接了 HC-06 蓝牙模块的微 Controller 。我想构建一个 flutter 应用程序,它可以与微 Controller 通信以通过蓝牙发送整数值,然后也从微 Controller 接收整数值。另一端的代码是用C编程写的。在我这边,我开始用 flutter 构建应用程序。我正在使用 flutter_bluetooth_serial 包。对于蓝牙连接,我使用了官方包github上示例中的一些代码。 https://github.com/edufolly/flutter_bluetooth_serial . (我将名为:BluetoothDeviceListEntry 的文件复制到我的项目中)。

接下来,我创建了应用程序的主页和蓝牙连接编码。这是我的 main.dart 文件:

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

}

class MyApp extends StatelessWidget {

@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage() ,
debugShowCheckedModeBanner: false,
);
}
}


class HomePage extends StatefulWidget{
@override
State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with WidgetsBindingObserver {

BluetoothState _bluetoothState = BluetoothState.UNKNOWN;

List<BluetoothDevice> devices = <BluetoothDevice>[];


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

_getBTState();
_stateChangeListener();
_listBondedDevices();
_stateChangeListener();
}

@override
void dispose(){
WidgetsBinding.instance!.removeObserver(this);
super.dispose();

@override
void disChangeAppLifeCycleState(AppLifecycleState state){
if(state.index == 0){
//resume
if(_bluetoothState.isEnabled){
_listBondedDevices();
}
}
}

}
_getBTState(){
FlutterBluetoothSerial.instance.state.then((state){
_bluetoothState = state;
if(_bluetoothState.isEnabled){
_listBondedDevices();
}
setState(() {});

});
}
_stateChangeListener(){
FlutterBluetoothSerial.instance.onStateChanged().listen((BluetoothState state) {
_bluetoothState = state;
if(_bluetoothState.isEnabled){
_listBondedDevices();
}else{
devices.clear();
}
print("State isEnabled: ${state.isEnabled}");
setState(() {});
});

}

_listBondedDevices(){
FlutterBluetoothSerial.instance.getBondedDevices().then((List<BluetoothDevice> bondedDevices){
devices = bondedDevices;
setState(() {});
});


}



@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Bluetooth Scanner"),),
body: Container(
child: Column(children: <Widget>[
SwitchListTile(
title: Text('Enable Bluetooth'),
value: _bluetoothState.isEnabled,
onChanged: (bool value){
future() async{
if(value){
await FlutterBluetoothSerial.instance.requestEnable();
}else{
await FlutterBluetoothSerial.instance.requestDisable();
}
future().then((_){
setState(() {});
});
}
},
),
ListTile(
title: Text("Bluetooth Status"),
subtitle: Text(_bluetoothState.toString()),
trailing: RaisedButton(child: Text("Settings"), onPressed: (){
FlutterBluetoothSerial.instance.openSettings();
},
),
),

// adaptor code


Expanded(
child: ListView(
children: devices
.map((_device)=> BluetoothDeviceListEntry(
device: _device,
enabled: true,
onTap: (){
print("item");
_startDataCollection(context, _device);
},
))
.toList(),
),
),

// discovery code

],
),
),
);
}
void _startDataCollection(BuildContext context, BluetoothDevice server){
Navigator.of(context).push(MaterialPageRoute(builder: (context){
return DetailPage(server: server);
}));
}
}

当我按下配对设备时,函数 _startDataCollection 被触发,我转到另一个文件 (detailpage.dart),这就是我开始痛苦的地方......

这里是详细页面的编码:


class DetailPage extends StatefulWidget {

final BluetoothDevice server;

DetailPage({required this.server});


@override
State<DetailPage> createState() => _DetailPageState();
}

class _DetailPageState extends State<DetailPage> {
late BluetoothConnection connection;
bool isConnecting = true;
bool get isConnected => connection.isConnected;
bool isDisconnecting = false;

int _selectedvalue =0;

int chunks = 0;
int rcvdData = 0;
int contentLength =0;
late Uint8List _bytes;



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

}

@override
void dispose() {
if(isConnected){
isDisconnecting = true;
connection.dispose();
}
super.dispose();

}

_getBTConnection(){
BluetoothConnection.toAddress(widget.server.address).then((_connection){
connection = _connection;
isConnecting = false;
isDisconnecting = false;
setState(() {});

connection.input?.listen(_onDataReceived).onDone(() {
if(isDisconnecting){
print("Disconnecting locally");


}else{
print("Disconnecting remotely");

}
if(mounted){
setState(() {});
}
Navigator.of(context).pop();

});

}).catchError((error){
Navigator.of(context).pop();

});
}


_onDataReceived(int data){
if(data != null && data.bitLength > 0){
chunks.add(data);



}

}


Future<void> _sendMessageString() async {
connection.output.add(ascii.encode('Hello!'));
await connection.output.allSent;
print('ok send message');
}


@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey,
appBar: AppBar(title: (isConnecting ? Text('Connecting to ${widget.server.name} ...')
: isConnected ? Text ('Connected with ${widget.server.name}') : Text(
'Disconnected with ${widget.server.name}')),),
body: SafeArea(child: isConnected

? Column(
children: <Widget>[
submitButton()
],
)
: const Center(
child: Text(
"Connecting ...",
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
color: Colors.white),

),
),

));
}
Widget submitButton(){
return Container(
padding: const EdgeInsets.all(16),
child: ElevatedButton(

onPressed: () {
print (chunks);
},
child: const Padding(
padding: EdgeInsets.all(8),
child: Text("show value", style: TextStyle(fontSize: 24),
),

),
),
);
}

}

我想做的是,当我按下按钮(显示值)时,我想在编译器中打印接收到的数据,但出现 2 个错误。第一个是关于 _getBTConnection 函数:

"connection.input?.listen(_onDataReceived).onDone(()"

The argument type 'dynamic Function(int)' can't be assigned to the parameter type 'void Function(Uint8List)?'.

另一个是关于 (_onDataReceived) 函数:

The method 'add' isn't defined for the type 'int'.

我也尝试制作一些函数来发送整数,但似乎没有一个也能正常工作。如果有人可以帮我解决这个问题,因为我是 flutter 的新手

非常感谢

最佳答案

查看您提供的链接中的示例。传入数据的类型是 Uint8List 而不是 int

try {
BluetoothConnection connection = await BluetoothConnection.toAddress(address);
print('Connected to the device');

connection.input.listen((Uint8List data) {
print('Data incoming: ${ascii.decode(data)}');
...
}).onDone(() {
print('Disconnected by remote request');
});
}
catch (exception) {
print('Cannot connect, exception occured');
}

使用ByteDatadata 中读取值。

final byteData = ByteData.sublistView(data);
final value = byteData.getFloat32(0);

关于Flutter蓝牙串口通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72388235/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com