我在dart中使用BLE,我需要向特定特性发送9个字节,其中第一个字节是5,剩下的是epoch



Hi我试图向特定特征发送9个字节,其中第一个字节是0x05,即5,接下来的8个字节是以秒为单位的epoch,

我试过了,

List<int> timeDataForBLEWrite = [0x5, 0, 0, 0, 0, 0, 0, 0, 0 ];  // here 0 will be replaced by 8 bytes of epoch

为了在几秒钟内获得epoch,我尝试了这个,

int timestampEpochInSeconds = DateTime.now().millisecondsSinceEpoch ~/ 1000; // 1623331779

要将epoch转换为字节,我已经尝试过了,

List<int> bytes = utf8.encode(timestampEpochInSeconds.toString());

但这里我得到了10个字节,因为时间戳EpochInSeconds是1623331779//10位

print(bytes); // [49, 54, 50, 51, 51, 51, 49, 55, 55, 57]

如何从秒历元中获得8个整数,以便向特征发送总共9个字节。如下图所示,

characteristic.write(timeDataForBLEWrite);

我假设您不想要以字节为单位的字符串,而是以字节为单元的值。

蓝牙中的大多数数据都在Little Endian中,所以我假设时间戳是字节。

我在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]

最新更新