spring boot 4 + netty搭建JT808车载终端服务

1、项目结构

bash 复制代码
jt808-server/
├── pom.xml
├── src/main/resources/
│   └── application.yml
└── src/main/java/com/example/jt808/
    ├── Jt808GatewayApplication.java
    ├── config/
    │   ├── Jt808Properties.java
    │   └── Jt808NettyServer.java
    ├── protocol/
    │   ├── Jt808Message.java
    │   ├── Jt808CodecUtil.java
    │   └── Jt808MsgId.java
    ├── codec/
    │   ├── Jt808FrameDecoder.java
    │   └── Jt808Encoder.java
    ├── session/
    │   └── Jt808SessionManager.java
    └── handler/
        ├── Jt808BizHandler.java
        ├── Jt808MessageDispatcher.java
        ├── IBusinessHandler.java
        └── DefaultBusinessHandler.java   ← ★ 你在这写业务逻辑

2、maven及其application.yml配置文件

maven依赖

bash 复制代码
<dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>4.2.21.Final</version>
        </dependency>

        <!-- Source: https://mvnrepository.com/artifact/com.alibaba.fastjson2/fastjson2 -->
        <dependency>
            <groupId>com.alibaba.fastjson2</groupId>
            <artifactId>fastjson2</artifactId>
            <version>2.0.66</version>
        </dependency>

application.yml配置文件

bash 复制代码
server:
  port: 9090                     # HTTP 管理端口(非 JT808 端口)

spring:
  application:
    name: jt808-gateway
  threads:
    virtual:
      enabled: true              # 启用虚拟线程

jt808:
  enabled: true
  host: 0.0.0.0
  port: 7611                     # JT808 监听端口
  boss-threads: 1
  worker-threads: 0              # 0 = 自动 (2*CPU)
  max-frame-length: 8192
  reader-idle-seconds: 600       # 10分钟无数据断开
  so-backlog: 4096
  biz-queue-capacity: 32768      # 背压队列容量

management:
  endpoints:
    web:
      exposure:
        include: health,info

3、各种接口和类

1)Jt808Encoder类

bash 复制代码
package com.example.jt808.codec;


import com.example.jt808.protocol.Jt808CodecUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

public class Jt808Encoder extends ChannelHandlerAdapter {
    public static void write(ChannelHandlerContext ctx, int msgId, int seq,
                             String terminalId, int version, byte[] body) {
        boolean ext = version == 1;
        int phoneLen = ext ? 10 : 6;
        int props = (body.length & 0x03FF) | (version << 11);
        if (ext) {
            props |= 0x4000;
        }

        byte[] head = new byte[2 + 2 + phoneLen + 2];
        int p = 0;
        head[p++] = (byte) (msgId >> 8); head[p++] = (byte) msgId;
        head[p++] = (byte) (props >> 8); head[p++] = (byte) props;
        System.arraycopy(Jt808CodecUtil.phoneToBcd(terminalId, phoneLen), 0, head, p, phoneLen);
        p += phoneLen;
        head[p++] = (byte) (seq >> 8); head[p++] = (byte) seq;

        byte[] unsigned = new byte[head.length + body.length];
        System.arraycopy(head, 0, unsigned, 0, head.length);
        System.arraycopy(body, 0, unsigned, head.length, body.length);

        byte xor = Jt808CodecUtil.xor(unsigned, 0, unsigned.length);
        byte[] withCheck = new byte[unsigned.length + 1];
        System.arraycopy(unsigned, 0, withCheck, 0, unsigned.length);
        withCheck[withCheck.length - 1] = xor;

        byte[] framed = Jt808CodecUtil.escape(withCheck);
        ByteBuf buf = ctx.alloc().buffer(framed.length);
        buf.writeBytes(framed);
        ctx.writeAndFlush(buf);
    }
}

2)解码器Jt808FrameDecoder

bash 复制代码
package com.example.jt808.codec;

import com.example.jt808.protocol.Jt808CodecUtil;
import com.example.jt808.protocol.Jt808Message;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.List;

@Slf4j
public class Jt808FrameDecoder extends ByteToMessageDecoder {

    private final int maxFrameLength;

    public Jt808FrameDecoder(int maxFrameLength) {
        this.maxFrameLength = maxFrameLength;
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
        //log.info("收到原始字节数: {}, 可读字节: {}", in.capacity(), in.readableBytes());

        // 1. 查找起始 0x7E(只读不消费)
        int readable = in.readableBytes();
        int startIndex = -1;
        for (int i = 0; i < readable; i++) {
            if ((in.getByte(i) & 0xFF) == 0x7E) {
                startIndex = i;
                break;
            }
        }

        if (startIndex < 0) {
            // 找不到起始符,丢弃脏数据(这里消费是安全的)
            log.warn("未找到起始符 0x7E,丢弃 {} 字节脏数据", readable);
            in.skipBytes(readable);
            return;
        }

        // 跳过起始符之前的脏数据
        if (startIndex > 0) {
            log.warn("丢弃起始符前的 {} 字节脏数据", startIndex);
            in.skipBytes(startIndex);
        }

        // 此时 readerIndex 指向起始 0x7E,但【不要】消费它,等整帧收齐再消费
        readable = in.readableBytes();
        if (readable < 2) {
            // 只有起始符,等更多数据
            return;
        }

        // 2. 从索引 1 开始查找结束 0x7E(索引 0 是起始符)
        int endIndex = -1;
        for (int i = 1; i < readable; i++) {
            if ((in.getByte(i) & 0xFF) == 0x7E) {
                endIndex = i;
                break;
            }
        }

        if (endIndex < 0) {
            // 帧还没收全:一个字节都不能消费,等下次数据进入后整段重新解析
            if (readable > maxFrameLength) {
                log.warn("单帧超过 {} 字节仍无结束符,丢弃整段 {} 字节", maxFrameLength, readable);
                in.skipBytes(readable);
            } else {
                log.debug("未找到结束符 0x7E,等待更多数据,当前 {} 字节", readable);
            }
            return;
        }

        // 3. 完整帧到手,才开始消费
        in.readByte(); // 跳过起始 7E
        byte[] escaped = new byte[endIndex - 1];
        in.readBytes(escaped); // 中间数据(未反转义)
        in.readByte(); // 跳过结束 7E

        // 4. 反转义
        byte[] raw = Jt808CodecUtil.unescape(escaped);
        log.debug("反转义后 raw 长度: {}", raw.length);

        if (raw.length < 13) {
            log.warn("帧太短,丢弃({}+2 字节)", raw.length);
            return;
        }

        // 4. 解析头
        int idx = 0;
        int msgId = ((raw[idx] & 0xFF) << 8) | (raw[idx + 1] & 0xFF); idx += 2;
        int props = ((raw[idx] & 0xFF) << 8) | (raw[idx + 1] & 0xFF); idx += 2;

        int version = (props >> 11) & 0x03;
        boolean encrypted = (props & 0x0400) != 0;
        boolean subPkg   = (props & 0x2000) != 0;
        boolean extPhone = version == Jt808Message.VERSION_2019 && (props & 0x4000) != 0;
        int phoneLen = extPhone ? 10 : 6;

        if (idx + phoneLen + 2 + 1 > raw.length) {
            log.warn("数据长度不足(手机号/流水号),丢弃");
            return;
        }

        String terminalId = Jt808CodecUtil.bcdToPhone(
                Arrays.copyOfRange(raw, idx, idx + phoneLen));
        idx += phoneLen;

        int seq = ((raw[idx] & 0xFF) << 8) | (raw[idx + 1] & 0xFF); idx += 2;
        if (subPkg) {
            idx += 4;
        }

        int bodyLen = props & 0x03FF;
        if (idx + bodyLen + 1 > raw.length) {
            bodyLen = raw.length - idx - 1;
        }

        // 5. 校验码验证
        byte checksum = Jt808CodecUtil.xor(raw, 0, idx + bodyLen);
        byte receivedChecksum = raw[idx + bodyLen];

        log.info("校验码对比: 收到={}, 计算={}",
                String.format("%02X", receivedChecksum),
                String.format("%02X", checksum));

        if (checksum != receivedChecksum) {
            log.warn("校验码错误 terminal={} msgId=0x{}", terminalId, Integer.toHexString(msgId));
            return;
        }

        // 6. 组装对象
        byte[] body = new byte[bodyLen];
        System.arraycopy(raw, idx, body, 0, bodyLen);

        Jt808Message msg = new Jt808Message();
        msg.setMsgId(msgId);
        msg.setBodyProps(props);
        msg.setVersion(version);
        msg.setEncrypted(encrypted);
        msg.setSubPkg(subPkg);
        msg.setTerminalId(terminalId);
        msg.setSeq(seq);
        msg.setBody(body);
        msg.setArriveTimeMillis(System.currentTimeMillis());

        log.info("解码成功!消息ID: 0x{}, 终端: {}", Integer.toHexString(msgId), terminalId);

        // ⚠️ 关键:放入 out 列表,交给下一个 Handler
        out.add(msg);
    }

}

3)netty服务类Jt808NettyServer

bash 复制代码
package com.example.jt808.config;

import com.example.jt808.codec.Jt808FrameDecoder;
import com.example.jt808.handler.Jt808BizHandler;
import com.example.jt808.handler.Jt808MessageDispatcher;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.SmartLifecycle;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class Jt808NettyServer implements SmartLifecycle {
    @Resource
    @Lazy
    private Jt808Properties properties;

    @Resource
    @Lazy
    private Jt808MessageDispatcher dispatcher;

    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;
    private Channel serverChannel;
    private volatile boolean running;

    @Override
    public void start() {
        if (!properties.isEnabled() || running) {
            return;
        }

        bossGroup = new NioEventLoopGroup(properties.getBossThreads());
        workerGroup = new NioEventLoopGroup(properties.getWorkerThreads());

        Jt808BizHandler bizHandler = new Jt808BizHandler(
                dispatcher, properties.getBizQueueCapacity());

        try {
            serverChannel = new ServerBootstrap()
                    .group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, properties.getSoBacklog())
                    .option(ChannelOption.SO_REUSEADDR, true)
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childOption(ChannelOption.WRITE_BUFFER_WATER_MARK,
                            new WriteBufferWaterMark(32 * 1024, 256 * 1024))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            // 打印终端原始收包字节(十六进制),排查粘包/拆包用,正式环境可移除
                            ch.pipeline().addLast("dump", new LoggingHandler(LogLevel.INFO));
                            ch.pipeline().addLast("frame",
                                    new Jt808FrameDecoder(properties.getMaxFrameLength()));
                            ch.pipeline().addLast("idle",
                                    new IdleStateHandler(properties.getReaderIdleSeconds(), 0, 0, TimeUnit.SECONDS));
                            ch.pipeline().addLast("biz", bizHandler);
                        }
                    })
                    .bind(properties.getHost(), properties.getPort())
                    .sync()
                    .channel();
            running = true;
            log.info("JT808 服务已启动,监听 {}:{}", properties.getHost(), properties.getPort());
        } catch (Exception e) {
            throw new RuntimeException("JT808 启动失败", e);
        }
    }

    @Override
    public void stop() {
        running = false;
        try {
            if (serverChannel != null) {
                serverChannel.close().sync();
            }
        } catch (InterruptedException ignored) {}
        if (bossGroup != null) {
            bossGroup.shutdownGracefully(1, 5, TimeUnit.SECONDS).syncUninterruptibly();
        }
        if (workerGroup != null) {
            workerGroup.shutdownGracefully(1, 5, TimeUnit.SECONDS).syncUninterruptibly();
        }
        log.info("JT808 服务已停止");
    }

    @Override
    public boolean isRunning() { return running; }

    @Override
    public int getPhase() { return Integer.MAX_VALUE - 50; }
}

4)Jt808Properties类

bash 复制代码
package com.example.jt808.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Data
@Component
@ConfigurationProperties(prefix = "jt808")
public class Jt808Properties {
    private boolean enabled;
    private String host;
    private int port;
    private int bossThreads;
    private int workerThreads;
    private int maxFrameLength;
    private int readerIdleSeconds;
    private int soBacklog;
    private int bizQueueCapacity;
}

5)Jt808CodecUtil类

bash 复制代码
package com.example.jt808.protocol;

import java.io.ByteArrayOutputStream;

public final class Jt808CodecUtil {
    public static final byte FLAG = 0x7E;
    public static final byte ESC = 0x7D;

    private static final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray();

    private Jt808CodecUtil() {
    }

    /**
     * 字节数组 -> 十六进制字符串(不截断),字节间以单个空格分隔,例如 "04 18 47 00"。
     * 空数组返回空串,可直接用于日志/JSON。
     */
    public static String toHex(byte[] data) {
        if (data == null || data.length == 0) {
            return "";
        }
        StringBuilder sb = new StringBuilder(data.length * 3);
        for (int i = 0; i < data.length; i++) {
            if (i > 0) {
                sb.append(' ');
            }
            sb.append(HEX_DIGITS[(data[i] >> 4) & 0x0F])
              .append(HEX_DIGITS[data[i] & 0x0F]);
        }
        return sb.toString();
    }

    public static byte[] unescape(byte[] in) {
        ByteArrayOutputStream out = new ByteArrayOutputStream(in.length);
        for (int i = 0; i < in.length; i++) {
            byte b = in[i];
            if (b == ESC && i + 1 < in.length) {
                byte next = in[++i];
                if (next == 0x02) {
                    out.write(FLAG);
                } else if (next == 0x01) {
                    out.write(ESC);
                } else {
                    out.write(next);
                }
            } else {
                out.write(b);
            }
        }
        return out.toByteArray();
    }

    public static byte[] escape(byte[] data) {
        ByteArrayOutputStream out = new ByteArrayOutputStream(data.length + 64);
        out.write(FLAG);
        for (byte b : data) {
            if (b == FLAG) {
                out.write(ESC);
                out.write(0x02);
            } else if (b == ESC) {
                out.write(ESC);
                out.write(0x01);
            } else {
                out.write(b);
            }
        }
        out.write(FLAG);
        return out.toByteArray();
    }

    public static byte xor(byte[] data, int offset, int length) {
        byte crc = 0;
        for (int i = offset; i < offset + length; i++) {
            crc ^= data[i];
        }
        return crc;
    }

    public static byte[] phoneToBcd(String phone, int byteLen) {
        String padded = phone.length() % 2 == 0 ? phone : "0" + phone;
        byte[] bcd = new byte[byteLen];
        for (int i = 0; i < byteLen && i * 2 + 1 < padded.length(); i++) {
            int high = Character.digit(padded.charAt(padded.length() - 2 - i * 2), 16);
            int low = Character.digit(padded.charAt(padded.length() - 1 - i * 2), 16);
            bcd[i] = (byte) ((high << 4) | low);
        }
        return bcd;
    }

    public static String bcdToPhone(byte[] bcd) {
        StringBuilder sb = new StringBuilder(bcd.length * 2);
        for (byte b : bcd) {
            sb.append(String.format("%02x", b & 0xFF));
        }
        return sb.toString();
    }
}

6)Jt808Message类

bash 复制代码
package com.example.jt808.protocol;

import lombok.Data;

@Data
public class Jt808Message {
    public static final int VERSION_2013 = 0;
    public static final int VERSION_2019 = 1;

    private int msgId;
    private int bodyProps;
    private int version;
    private boolean encrypted;
    private boolean subPkg;
    private String terminalId;
    private int seq;
    private byte[] body;
    private long arriveTimeMillis;
}

7)Jt808SessionManager类

bash 复制代码
package com.example.jt808.session;

import io.netty.channel.Channel;
import io.netty.util.AttributeKey;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

public final class Jt808SessionManager {
    public static final AttributeKey<String> TERMINAL_ID = AttributeKey.valueOf("terminalId");
    public static final AttributeKey<Integer> SEQ_GEN = AttributeKey.valueOf("seqGen");
    public static final AttributeKey<Long> LAST_TIME = AttributeKey.valueOf("lastTime");

    private static final ConcurrentHashMap<String, Channel> channels = new ConcurrentHashMap<>();
    private static final AtomicInteger seqCounter = new AtomicInteger(0);

    private Jt808SessionManager() {
    }

    public static void bindIfAbsent(Channel ch, String terminalId) {
        if (ch.attr(TERMINAL_ID).get() == null) {
            ch.attr(TERMINAL_ID).set(terminalId);
            ch.attr(SEQ_GEN).set(seqCounter.getAndIncrement() & 0xFFFF);
            channels.put(terminalId, ch);
        }
        touch(ch);
    }

    public static void touch(Channel ch) {
        ch.attr(LAST_TIME).set(System.currentTimeMillis());
    }

    public static int nextSeq(Channel ch) {
        int old = ch.attr(SEQ_GEN).get() == null ? 0 : ch.attr(SEQ_GEN).get();
        int next = (old + 1) & 0xFFFF;
        ch.attr(SEQ_GEN).set(next);
        return next;
    }

    public static void remove(Channel ch) {
        String tid = ch.attr(TERMINAL_ID).get();
        if (tid != null) {
            channels.remove(tid, ch);
        }
    }

    public static Channel getChannel(String terminalId) {
        return channels.get(terminalId);
    }

    public static int onlineCount() {
        return channels.size();
    }
}

8)Jt808BizHandler类

bash 复制代码
package com.example.jt808.handler;

import com.example.jt808.protocol.Jt808Message;
import com.example.jt808.session.Jt808SessionManager;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

@Slf4j
@ChannelHandler.Sharable
public class Jt808BizHandler extends ChannelInboundHandlerAdapter {
    private final ExecutorService virtualPool = Executors.newVirtualThreadPerTaskExecutor();
    private final Semaphore inflight;
    private final Jt808MessageDispatcher dispatcher;

    public Jt808BizHandler(Jt808MessageDispatcher dispatcher, int maxInflight) {
        this.dispatcher = dispatcher;
        this.inflight = new Semaphore(maxInflight);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        Jt808Message m = (Jt808Message) msg;
        Jt808SessionManager.bindIfAbsent(ctx.channel(), m.getTerminalId());
        Jt808SessionManager.touch(ctx.channel());

        if (!inflight.tryAcquire()) {
            log.warn("业务过载,丢弃消息: terminal={}, msgId=0x{}", m.getTerminalId(),
                    Integer.toHexString(m.getMsgId()));
            return;
        }

        virtualPool.submit(() -> {
            try {
                dispatcher.dispatch(ctx, m);
            } catch (Exception e) {
                log.error("业务处理异常: terminal={}, msgId=0x{}",
                        m.getTerminalId(), Integer.toHexString(m.getMsgId()), e);
            } finally {
                inflight.release();
            }
        });
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
        if (evt instanceof IdleStateEvent) {
            log.info("读空闲超时,断开连接: {}", ctx.channel().remoteAddress());
            ctx.close();
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        Jt808SessionManager.remove(ctx.channel());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error("管道异常: {}", ctx.channel().remoteAddress(), cause);
        ctx.close();
    }
}

9)Jt808MessageDispatcher类

bash 复制代码
package com.example.jt808.handler;

import com.example.jt808.codec.Jt808Encoder;
import com.example.jt808.protocol.Jt808Message;
import com.example.jt808.session.Jt808SessionManager;

import io.netty.channel.ChannelHandlerContext;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class Jt808MessageDispatcher {

    @Resource
    @Lazy
    private IBusinessHandler businessHandler;

    public void dispatch(ChannelHandlerContext ctx, Jt808Message msg) {
        // 所有消息都交给业务处理器的同一个方法
        byte[] replyBody = businessHandler.handleMessage(ctx, msg);

        // 如果有应答内容,发送通用应答(0x8001)
        if (replyBody != null) {
            Jt808Encoder.write(ctx, 0x8001,
                    Jt808SessionManager.nextSeq(ctx.channel()),
                    msg.getTerminalId(), msg.getVersion(), replyBody);
        }
    }
}

10)IBusinessHandler

bash 复制代码
package com.example.jt808.handler;

import com.example.jt808.protocol.Jt808Message;
import io.netty.channel.ChannelHandlerContext;


public interface IBusinessHandler {
    /**
     * 处理所有接收到的 JT808 消息。
     *
     * @param ctx Netty 上下文,可用于回复消息
     * @param msg 解码后的消息对象(包含 msgId、terminalId、body 等)
     * @return 应答消息体(字节数组),如果不需要回复则返回 null
     */
    byte[] handleMessage(ChannelHandlerContext ctx, Jt808Message msg);
}

11)DefaultBusinessHandler(也就是你写业务的地方)

bash 复制代码
package com.example.jt808.handler;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.example.jt808.protocol.Jt808Message;

import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class DefaultBusinessHandler implements IBusinessHandler {

    private static final int MSG_LOCATION_0205 = 0x0205;

    /** 位置字段起始偏移(报警4 + 状态4 之后):国标报文为 8,实测 0x0205 报文为 32 */
    private static final int POS_BASE_DEFAULT = 8;
    private static final int POS_BASE_0205 = 32;

    /** 位置块长度:纬度4 + 经度4 + 高程2 + 速度2 + 方向2 + 时间6 = 20 */
    private static final int POS_BLOCK_LEN = 20;

    /** 报警标志位定义(国标 0x0200,bit0 起) */
    private static final String[] ALARM_LABELS = {
            "紧急报警", "超速报警", "疲劳驾驶", "危险预警", "危险驾驶行为",
            "模块故障", "电池电量低", "车辆非法点火", "车辆非法位移"
    };

    @Override
    public byte[] handleMessage(ChannelHandlerContext ctx, Jt808Message msg) {
        // 整条消息转 JSON,body 由 byte[] 解析成可读字段
        JSONObject json = (JSONObject) JSON.toJSON(msg);
        json.put("body", parseBody(msg));
        log.info("收到消息(json): {}", json.toJSONString());

        // 回复通用应答(0x8001),不回复终端会超时重发
        byte[] reply = new byte[5];
        reply[0] = (byte) (msg.getSeq() >> 8);
        reply[1] = (byte) msg.getSeq();
        reply[2] = (byte) (msg.getMsgId() >> 8);
        reply[3] = (byte) msg.getMsgId();
        reply[4] = 0; // 0 = 成功
        return reply;
    }

    // ------------------------------------------------------------------ 消息体解析

    /**
     * 消息体 -> JSON:固定输出 11 个字段,顺序与前端约定一致;解析不到的值给空串。
     */
    private static JSONObject parseBody(Jt808Message msg) {
        JSONObject body = new JSONObject();
        body.put("alarmLabel", "");
        body.put("status", "");
        body.put("longitude", "");
        body.put("latitude", "");
        body.put("elevation", "");
        body.put("speed", "");
        body.put("direction", "");
        body.put("time", "");
        body.put("mileage", "");
        body.put("fuelQuantity", "");
        body.put("signalStrength", "");

        byte[] b = msg.getBody();
        if (b == null) {
            return body;
        }

        // 位置字段起始偏移:国标 0x0200 从 8 开始;0x0205 按实测报文从 32 开始
        int base = msg.getMsgId() == MSG_LOCATION_0205 ? POS_BASE_0205 : POS_BASE_DEFAULT;
        if (b.length < base + POS_BLOCK_LEN) {
            return body; // 长度不够,字段保持空串
        }

        long alarm = u32(b, 0);
        long status = u32(b, 4);
        body.put("alarmLabel", alarmLabel(alarm));
        body.put("status", statusLabel(status));

        boolean south = (status & 0x04) != 0;
        boolean west = (status & 0x08) != 0;
        body.put("longitude", round6((west ? -1 : 1) * (u32(b, base + 4) / 1e6)));
        body.put("latitude", round6((south ? -1 : 1) * (u32(b, base) / 1e6)));
        body.put("elevation", u16(b, base + 8));
        body.put("speed", round1(u16(b, base + 10) / 10.0));
        body.put("direction", u16(b, base + 12));

        String time = bcdTime(b, base + 14);
        if (time != null) {
            body.put("time", time);
        }

        parseExtras(b, base + 20, body);
        return body;
    }

    /** 附加信息:ID(1) + 长度(1) + 内容(n),只取里程 / 油量 / 信号强度 */
    private static void parseExtras(byte[] b, int start, JSONObject body) {
        int i = start;
        while (i + 2 <= b.length) {
            int id = b[i] & 0xFF;
            int len = b[i + 1] & 0xFF;
            if (i + 2 + len > b.length) {
                return;
            }
            switch (id) {
                case 0x01 -> {
                    if (len == 4) {
                        body.put("mileage", round1(u32(b, i + 2) / 10.0)); // 单位 km
                    }
                }
                case 0x02 -> {
                    if (len == 2) {
                        body.put("fuelQuantity", round1(u16(b, i + 2) / 10.0)); // 单位 L
                    }
                }
                case 0x30 -> {
                    if (len == 1) {
                        body.put("signalStrength", b[i + 2] & 0xFF);
                    }
                }
                default -> {
                    // 其它附加项忽略
                }
            }
            i += 2 + len;
        }
    }

    private static String alarmLabel(long alarm) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < ALARM_LABELS.length; i++) {
            if ((alarm & (1L << i)) != 0) {
                if (sb.length() > 0) {
                    sb.append(',');
                }
                sb.append(ALARM_LABELS[i]);
            }
        }
        return sb.toString();
    }

    private static String statusLabel(long status) {
        StringBuilder sb = new StringBuilder();
        sb.append((status & 0x01) != 0 ? "ACC开" : "ACC关");
        sb.append(',').append((status & 0x02) != 0 ? "已定位" : "未定位");
        int op = (int) ((status >> 4) & 0x03);
        if (op == 1) {
            sb.append(",运营");
        } else if (op == 2) {
            sb.append(",空车");
        } else if (op == 3) {
            sb.append(",停运");
        }
        return sb.toString();
    }

    // ------------------------------------------------------------------ 基础工具

    private static int u16(byte[] b, int i) {
        return ((b[i] & 0xFF) << 8) | (b[i + 1] & 0xFF);
    }

    private static long u32(byte[] b, int i) {
        return ((long) (b[i] & 0xFF) << 24)
                | ((b[i + 1] & 0xFF) << 16)
                | ((b[i + 2] & 0xFF) << 8)
                | (b[i + 3] & 0xFF);
    }

    /** BCD 时间 yyMMddHHmmss,非法返回 null */
    private static String bcdTime(byte[] b, int offset) {
        if (offset + 6 > b.length) {
            return null;
        }
        int yy = bcd(b[offset]);
        int mo = bcd(b[offset + 1]);
        int dd = bcd(b[offset + 2]);
        int hh = bcd(b[offset + 3]);
        int mi = bcd(b[offset + 4]);
        int ss = bcd(b[offset + 5]);
        if (yy < 0 || mo < 1 || mo > 12 || dd < 1 || dd > 31
                || hh < 0 || hh > 23 || mi < 0 || mi > 59 || ss < 0 || ss > 59) {
            return null;
        }
        return String.format("20%02d-%02d-%02d %02d:%02d:%02d", yy, mo, dd, hh, mi, ss);
    }

    private static int bcd(byte v) {
        int hi = (v >> 4) & 0x0F;
        int lo = v & 0x0F;
        return (hi > 9 || lo > 9) ? -1 : hi * 10 + lo;
    }

    private static double round6(double v) {
        return Math.round(v * 1_000_000d) / 1_000_000d;
    }

    private static double round1(double v) {
        return Math.round(v * 10d) / 10d;
    }
}

这里面假定消息格式为,主要解析的是Jt808Message的body字段

bash 复制代码
{
    "alarmLabel": "", //报警标志
    "status": "", //状态
    "longitude": "", //经度
    "latitude": "", //纬度
    "elevation": "", //高程
    "speed": "", //速度
    "direction": "", //方向
    "time": "", //时间
    "mileage": "", //里程
    "fuelQuantity": "", //油量
    "signalStrength": "", //信号强度
}

12、客户端工具可采用NetAssist.exe

相关推荐
AI开源软件41 分钟前
SpringBoot多系统同步:别让“同名数据”变成“同一条数据”
vue.js·spring boot·企业管理·mdm
软件技术NINI1 小时前
基于 SpringBoot 的共享植物管理系统
java·spring boot·后端
IT研究室1 小时前
最新计算机毕业设计选题推荐-基于spring boot的家政保洁预约系统-网站-文档指导-Java-springboot
java·spring boot·课程设计
FYKJ_20101 小时前
springboot网上汽车租赁系统93523-计算机毕业设计、课程设计
java·vue.js·spring boot·后端·python·汽车·课程设计
计算机毕业编程指导师1 小时前
计算机毕设选题:马术俱乐部管理系统 SpringBoot 全解析(功能模块 + 数据表设计 + 核心代码)
java·spring boot·后端·mysql·elementui·毕业设计·马术俱乐部
码事漫谈10 小时前
WorkBuddy 固然很香,但豆姐她免费呀
后端
金銀銅鐵10 小时前
带您看懂字节码指令(八):数组里有什么
java·jvm·后端
zark_chuan10 小时前
怎么让 AI 写十万行代码不腐化:我的 AGENTS.md、Pre-Push 门禁与活体 Wiki
后端
Rain的Java大神之路12 小时前
Spring Boot 3 升级实战:真正吃掉工期的,是 MyBatis-Plus 坐标和 Security 6 重写
java·后端·面试