问题描述
限时送ChatGPT账号..我尝试向特定特征发送 9 个字节,其中第一个字节是 0x05 ,即 5 ,接下来的 8 个字节作为以秒为单位的纪元,
Hi I trying to send 9 bytes to specific characteristic, where first byte is 0x05 , i.e 5 ,and next 8 bytes as epoch in seconds,
我试过了,
List<int> timeDataForBLEWrite = [0x5, 0, 0, 0, 0, 0, 0, 0, 0 ]; // here 0 will be replaced by 8 bytes of epoch
为了在几秒钟内获得纪元,我试过这个,
to get epoch in seconds, I tried this,
int timestampEpochInSeconds = DateTime.now().millisecondsSinceEpoch ~/ 1000; // 1623331779
将纪元转换为字节我已经试过了,
to convert epoch into bytes I have tried this,
List<int> bytes = utf8.encode(timestampEpochInSeconds.toString());
但在这里我得到 10 个字节,因为 timestampEpochInSeconds 是 1623331779//10 位
but here I am getting 10 bytes because timestampEpochInSeconds is 1623331779 // 10 digits
print(bytes); // [49, 54, 50, 51, 51, 51, 49, 55, 55, 57]
如何从秒纪元中获取 8 个整数,以便可以向特征发送总共 9 个字节.如下图,
how can I get 8 integers from the seconds epoch so that I can send total 9 bytes to the characteristic. like below,
characteristic.write(timeDataForBLEWrite);
推荐答案
我假设您不想要以字节为单位的字符串,而是以字节为单位的值.
I am assuming that you don't want the string in bytes but the values in bytes.
蓝牙中的大多数数据都在 Little Endian 中,因此我假设时间戳为字节.
Most data in Bluetooth is in Little Endian so I have made that assumption about the timestamp as bytes.
我在 DartPad 上做了以下示例:
I did the following as an example on DartPad:
import 'dart:typed_data';
List<int> epoch() {
var timestamp = DateTime.now().millisecondsSinceEpoch ~/ 1000;
var sendValueBytes = ByteData(9);
sendValueBytes.setUint8(0, 5);
// setUint64 not implemented on some systems so use setUint32 in
// those cases. Leading zeros to pad to equal 64 bit.
// Epoch as 32-bit good until 2038 Jan 19 @ 03:14:07
try {
sendValueBytes.setUint64(1, timestamp.toInt(), Endian.little);
} on UnsupportedError {
sendValueBytes.setUint32(1, timestamp.toInt(), Endian.little);
}
return sendValueBytes.buffer.asUint8List();
}
void main() {
print('Epoch Bytes (plus 0x05): ${epoch()}');
}
给出了以下输出:
Epoch Bytes (plus 0x05): [5, 167, 60, 194, 96, 0, 0, 0, 0]
这篇关于我在 dart 中使用 BLE,我需要向特定特性发送 9 个字节,其中第一个字节是 5,其余是纪元的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论