在 Flutter 中将字节列表转换为整数值
Convert List of Bytes to integer value in Flutter
我无法从 ESP32(即 BLE 设备)获得的值中删除括号。我想在 Heart Rate Widget 中显示不带括号的值,但我很难解决这个问题。请帮助我找到解决方案。来自设备的数据被转换为字符串格式
BLE代码:
class HomeScreen extends StatefulWidget {
const HomeScreen({Key key, this.device}) : super(key: key);
final BluetoothDevice device;
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
// BLE
final String SERVICE_UUID = "4fafc201-1fb5-459e-8fcc-c5c9c331914b";
final String CHARACTERISTIC_UUID = "beb5483e-36e1-4688-b7f5-ea07361b26a8";
bool isReady;
Stream<List<int>> stream;
List<int> lastValue;
List<double> traceDust = List();
connectToDevice() async {
// await widget.device.connect();
print("connected");
discoverServices();
}
discoverServices() async {
List<BluetoothService> services = await widget.device.discoverServices();
services.forEach((service) {
if (service.uuid.toString() == SERVICE_UUID) {
service.characteristics.forEach((characteristic) {
if (characteristic.uuid.toString() == CHARACTERISTIC_UUID) {
characteristic.setNotifyValue(!characteristic.isNotifying);
stream = characteristic.value;
print(stream);
lastValue = characteristic.lastValue;
print(lastValue);
setState(() {
isReady = true;
});
}
});
}
});
}
心率小部件代码:
Container(
padding: EdgeInsets.symmetric(vertical: 20),
alignment: Alignment.center,
//width: double.infinity,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
StreamBuilder<List<int>>(
stream: stream,
initialData: lastValue,
builder: (BuildContext context,
AsyncSnapshot<List<int>> snapshot) {
if (snapshot.hasError)
return Text('Error: ${snapshot.error}',
style: TextStyle(
fontFamily: 'SF Pro Display',
fontSize: 19,
color: const Color(0xffffffff),
fontWeight: FontWeight.w500,
height: 1.4736842105263157,
),
);
if (snapshot.connectionState ==
ConnectionState.active) {
var currentValue = snapshot.data.toString();
//traceDust.add(double.tryParse(currentValue) ?? 0);
return Text('$currentValue',
style: TextStyle(
fontFamily: 'SF Pro Display',
fontSize: 19,
color: const Color(0xffffffff),
fontWeight: FontWeight.w500,
height: 1.4736842105263157,
),
);
} else {
return Text('Check the stream',
style: TextStyle(
fontFamily: 'SF Pro Display',
fontSize: 19,
color: const Color(0xffffffff),
fontWeight: FontWeight.w500,
height: 1.4736842105263157,
),
);
}
},
),
SizedBox(
height: 5,
),
Text(
'Heart Rate',
style: TextStyle(
fontFamily: 'SF Pro Display',
fontSize: 19,
color: Colors.white.withOpacity(0.7),
fontWeight: FontWeight.w500,
height: 1.2777777777777777,
),
textHeightBehavior: TextHeightBehavior(
applyHeightToFirstAscent: false),
textAlign: TextAlign.left,
),
],
),
)
我得到这样的值(如心率上方所示):
如果这确实是您正在接收的数据格式并且只是想以不同的方式格式化它,请尝试一些字符串操作,例如:
final currentValue = '[33]';
print(currentValue.substring(1, currentValue.length-1)); // 33
你没有说你在问题中期望的价值是什么。我假设它是 33
,尽管这对于心率读数来说似乎很低。
我希望数据是字节列表,因此您需要将其转换为整数值。
import 'dart:typed_data';
void main() {
var value = Uint8List.fromList([33]);
print("stream.value: ${value}"); // stream.value: [33]
var hr = ByteData.sublistView(value, 0, 1);
print("Heart rate: ${hr.getUint8(0)}"); // Heart rate: 33
}
BLE 设备似乎未遵循有关如何发送心率测量值的蓝牙标准,详见以下文档:
- 心率服务 (HRS)
- GATT 规范补充 (GSS)
两者都位于:https://www.bluetooth.com/specifications/specs/
如果这样做,那么它可以使用 16-bit UUID Numbers Document and work with code examples that exist such as https://webbluetoothcg.github.io/demos/heart-rate-sensor/
中的 UUID
我无法从 ESP32(即 BLE 设备)获得的值中删除括号。我想在 Heart Rate Widget 中显示不带括号的值,但我很难解决这个问题。请帮助我找到解决方案。来自设备的数据被转换为字符串格式
BLE代码:
class HomeScreen extends StatefulWidget {
const HomeScreen({Key key, this.device}) : super(key: key);
final BluetoothDevice device;
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
// BLE
final String SERVICE_UUID = "4fafc201-1fb5-459e-8fcc-c5c9c331914b";
final String CHARACTERISTIC_UUID = "beb5483e-36e1-4688-b7f5-ea07361b26a8";
bool isReady;
Stream<List<int>> stream;
List<int> lastValue;
List<double> traceDust = List();
connectToDevice() async {
// await widget.device.connect();
print("connected");
discoverServices();
}
discoverServices() async {
List<BluetoothService> services = await widget.device.discoverServices();
services.forEach((service) {
if (service.uuid.toString() == SERVICE_UUID) {
service.characteristics.forEach((characteristic) {
if (characteristic.uuid.toString() == CHARACTERISTIC_UUID) {
characteristic.setNotifyValue(!characteristic.isNotifying);
stream = characteristic.value;
print(stream);
lastValue = characteristic.lastValue;
print(lastValue);
setState(() {
isReady = true;
});
}
});
}
});
}
心率小部件代码:
Container(
padding: EdgeInsets.symmetric(vertical: 20),
alignment: Alignment.center,
//width: double.infinity,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
StreamBuilder<List<int>>(
stream: stream,
initialData: lastValue,
builder: (BuildContext context,
AsyncSnapshot<List<int>> snapshot) {
if (snapshot.hasError)
return Text('Error: ${snapshot.error}',
style: TextStyle(
fontFamily: 'SF Pro Display',
fontSize: 19,
color: const Color(0xffffffff),
fontWeight: FontWeight.w500,
height: 1.4736842105263157,
),
);
if (snapshot.connectionState ==
ConnectionState.active) {
var currentValue = snapshot.data.toString();
//traceDust.add(double.tryParse(currentValue) ?? 0);
return Text('$currentValue',
style: TextStyle(
fontFamily: 'SF Pro Display',
fontSize: 19,
color: const Color(0xffffffff),
fontWeight: FontWeight.w500,
height: 1.4736842105263157,
),
);
} else {
return Text('Check the stream',
style: TextStyle(
fontFamily: 'SF Pro Display',
fontSize: 19,
color: const Color(0xffffffff),
fontWeight: FontWeight.w500,
height: 1.4736842105263157,
),
);
}
},
),
SizedBox(
height: 5,
),
Text(
'Heart Rate',
style: TextStyle(
fontFamily: 'SF Pro Display',
fontSize: 19,
color: Colors.white.withOpacity(0.7),
fontWeight: FontWeight.w500,
height: 1.2777777777777777,
),
textHeightBehavior: TextHeightBehavior(
applyHeightToFirstAscent: false),
textAlign: TextAlign.left,
),
],
),
)
我得到这样的值(如心率上方所示):
如果这确实是您正在接收的数据格式并且只是想以不同的方式格式化它,请尝试一些字符串操作,例如:
final currentValue = '[33]';
print(currentValue.substring(1, currentValue.length-1)); // 33
你没有说你在问题中期望的价值是什么。我假设它是 33
,尽管这对于心率读数来说似乎很低。
我希望数据是字节列表,因此您需要将其转换为整数值。
import 'dart:typed_data';
void main() {
var value = Uint8List.fromList([33]);
print("stream.value: ${value}"); // stream.value: [33]
var hr = ByteData.sublistView(value, 0, 1);
print("Heart rate: ${hr.getUint8(0)}"); // Heart rate: 33
}
BLE 设备似乎未遵循有关如何发送心率测量值的蓝牙标准,详见以下文档:
- 心率服务 (HRS)
- GATT 规范补充 (GSS)
两者都位于:https://www.bluetooth.com/specifications/specs/
如果这样做,那么它可以使用 16-bit UUID Numbers Document and work with code examples that exist such as https://webbluetoothcg.github.io/demos/heart-rate-sensor/
中的 UUID