BatteryStatus
数据结构
| 字节索引 | 类型 | 字段含义 |
|---|---|---|
| 0-3 | uint32 | 故障码 |
| 4-7 | float32 | 电池总电压 [V] |
| 8-11 | float32 | 回路电流 [A],充电为正,放电为负 |
| 12-15 | float32 | 剩余电量百分比 0-100 [%] |
| 16-17 | uint16 | 温度传感器数量 |
| 18-19 | uint16 | 保留字段,必须为 0 |
| 20- | float32[] | 温度传感器数组 [℃],T 为温度数量 |
固定头部为 20 字节,因此总长度为 字节
示例
C++ 示例
struct BatteryStatusHeader {
uint32_t fault_code;
float voltage;
float current;
float soc;
uint16_t temp_count;
uint16_t reserved;
};
// payload = BatteryStatusHeader + temp_count * float
Rust 示例
#[repr(C)]
#[derive(Clone, Copy, Debug, Default)]
pub struct BatteryStatusHeader {
pub fault_code: u32,
pub voltage: f32,
pub current: f32,
pub soc: f32,
pub temp_count: u16,
pub reserved: u16,
}
const _: () = {
assert!(core::mem::size_of::<BatteryStatusHeader>() == 20);
assert!(core::mem::align_of::<BatteryStatusHeader>() == 4);
};
Dart 示例
import 'dart:typed_data';
final class BatteryStatusView {
static const int headerLength = 20;
static const int tempLength = Float32List.bytesPerElement;
final ByteBuffer buffer;
final ByteData header;
final int offsetInBytes;
BatteryStatusView(this.buffer, [this.offsetInBytes = 0])
: header = ByteData.view(buffer, offsetInBytes, headerLength);
int get faultCode => header.getUint32(0, Endian.little);
double get voltage => header.getFloat32(4, Endian.little);
double get current => header.getFloat32(8, Endian.little);
double get soc => header.getFloat32(12, Endian.little);
int get tempCount => header.getUint16(16, Endian.little);
int get byteLength => headerLength + tempCount * tempLength;
Float32List get temps => Float32List.view(
buffer,
offsetInBytes + headerLength,
tempCount,
);
}
Java 示例
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
public final class BatteryStatusView {
public static final int HEADER_LENGTH = 20;
public static final int TEMP_LENGTH = Float.BYTES;
private final ByteBuffer buffer;
private final int offset;
public BatteryStatusView(ByteBuffer buffer, int offset) {
this.buffer = buffer.order(ByteOrder.LITTLE_ENDIAN);
this.offset = offset;
}
public int faultCode() { return buffer.getInt(offset); }
public float voltage() { return buffer.getFloat(offset + 4); }
public float current() { return buffer.getFloat(offset + 8); }
public float soc() { return buffer.getFloat(offset + 12); }
public int tempCount() { return Short.toUnsignedInt(buffer.getShort(offset + 16)); }
public int byteLength() { return HEADER_LENGTH + tempCount() * TEMP_LENGTH; }
public FloatBuffer temps() {
return buffer.slice(offset + HEADER_LENGTH, tempCount() * TEMP_LENGTH)
.order(ByteOrder.LITTLE_ENDIAN)
.asFloatBuffer();
}
}