gpt4 book ai didi

Java 使用 ByteBuffer 解码来自 GPS 设备的字节

转载 作者:行者123 更新时间:2023-11-30 05:49:09 25 4
gpt4 key购买 nike

我在解码从 GPS 设备发送到我的 java UDP 监听器程序的字节时遇到问题。我可以提取一些信息,但对于其他信息,我无法理解如何执行此操作。设备手册中的数据格式如下:

Name       | Type          | Length
length: | short | 2
cmd: | short | 2
enabled: | unsigned char | 1
alarm: | unsigned char | 1
speed: | char | 1
direction: | short | 2
longitude: | double | 4
latitude: | double | 4
datetime: | long | 4
userid: | char | 11
iostate: | char | 1
oilstate: | char | 1

在我的程序中,我可以解码长度、命令、警报、速度、方向和设备。我陷入了纬度、经度和日期时间的困境,需要一些帮助。我得到的值与正确的值完全相去甚远。使用 struct.unpack 函数在 python 上运行没有任何问题。

函数中代码如下:

private void SetupUDP() throws IOException {
String message;
// Setup UDP Stuff and listen on all interfaces
DatagramSocket serverSocket = new DatagramSocket(9876, InetAddress.getByName("0.0.0.0"));
byte[] receiveData = new byte[1024];
while(true) {
// Start receiving UDP packets from devices
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);

ByteBuffer data = ByteBuffer.wrap(receivePacket.getData());
data.order(ByteOrder.LITTLE_ENDIAN);
if (receivePacket.getLength() == 15) {
short len = data.getShort(0);
short cmd = data.getShort(2);
String device = "";
for (int x=4; x < 14; x++) {
byte b = data.get(x);
device += (char) b;
}
System.out.println(len + " " + cmd + " -- " + device);
}
if (receivePacket.getLength() == 34) {
short len = data.getShort(0);
short cmd = data.getShort(2);
byte benabled = data.get(4);
int enabled = (int) benabled;
byte balarm = data.get(5);
// Alarm (OK)
int alarm = Math.abs((int) balarm);
// Speed (OK)
byte bspeed = data.get(6);
int speed = (int) bspeed;
// Direction (OK)
short direction = data.getShort(7);
// Coordinates
double longitude = data.getDouble(9);
double latitude = data.getDouble(13);
// Device ID (OK)
String device = "";
for (int x=21; x < 31; x++) {
byte bdevice = data.get(x);
device += (char) bdevice;
}

// Datetime (testing)
int ddatetime = data.get(17);
Date datetime = new Date(ddatetime * 1000);
//System.out.println("-->" + datetime + ", " + longitude);
System.out.println(len + " " + cmd + " " + enabled + " " + alarm + " " + speed + " " + direction + " " + longitude + " " + latitude + " " + datetime + " " + device);
}
}
}

最佳答案

您正在读取的纬度和经度各为 8 个字节,您的规范显示为 4。java中的doubleByteBuffer中的getDouble都是8个字节,你需要getFloat

当您读得太远时,这也会损坏数据。

关于Java 使用 ByteBuffer 解码来自 GPS 设备的字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54271953/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com