我在 dart 中使用 BLE,我需要向特定特性发送 9 个字节,其中第一个字节是 5,其余是纪元

问题描述

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

我试过了,

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

为了在几秒钟内获得纪元,我试过了,

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

将纪元转换为字节我已经试过了,

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

在这里我得到 10 个字节,因为 timestampEpochInSeconds 是 1623331779 // 10 位

 print(bytes); // [49,54,50,51,49,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,Endian.little);
  }
  return sendValueBytes.buffer.asUint8List();
}

void main() {
  print('Epoch Bytes (plus 0x05): ${epoch()}');
}

给出了以下输出:

Epoch Bytes (plus 0x05): [5,167,60,194,96,0]