├── .gitignore ├── LICENSE ├── README.md ├── doc ├── JTT808-2011.pdf └── JTT809-2011.pdf ├── pom.xml └── src ├── main ├── java │ └── org │ │ └── tucke │ │ ├── MainApplication.java │ │ ├── config │ │ ├── AppConfig.java │ │ └── LoggerConfig.java │ │ ├── gnsscenter │ │ └── GnssCenterService.java │ │ ├── jtt809 │ │ ├── Jtt809Client.java │ │ ├── Jtt809Server.java │ │ ├── common │ │ │ ├── CRC16CCITT.java │ │ │ ├── Jtt809Constant.java │ │ │ └── Jtt809Util.java │ │ ├── decoder │ │ │ └── Jtt809Decoder.java │ │ ├── encoder │ │ │ └── Jtt809Encoder.java │ │ ├── handler │ │ │ ├── ProtocolHandler.java │ │ │ ├── master │ │ │ │ ├── Jtt809MasterInboundHandler.java │ │ │ │ └── Jtt809MasterOutboundHandler.java │ │ │ ├── protocol │ │ │ │ ├── Protocol.java │ │ │ │ ├── connect │ │ │ │ │ └── ConnectProtocol.java │ │ │ │ └── exg │ │ │ │ │ └── VehicleExgProtocol.java │ │ │ └── slave │ │ │ │ ├── Jtt809SlaveInboundHandler.java │ │ │ │ └── Jtt809SlaveOutBoundHandler.java │ │ └── packet │ │ │ ├── DownTotalReceivePacket.java │ │ │ ├── common │ │ │ └── OuterPacket.java │ │ │ ├── connect │ │ │ ├── DownConnectPacket.java │ │ │ ├── UpConnectPacket.java │ │ │ └── UpDisConnectPacket.java │ │ │ └── upexg │ │ │ ├── UpExgHistoryPacket.java │ │ │ ├── UpExgPacket.java │ │ │ ├── UpExgRealLocationPacket.java │ │ │ └── UpExgRegisterPacket.java │ │ └── net │ │ ├── NettyClient.java │ │ └── NettyServer.java └── resources │ └── application.yml └── test └── java └── org └── tucke ├── inferior ├── client │ ├── InferiorClientInboundHandler.java │ └── InferiorClientTest.java └── server │ ├── InferiorServerInboundHandler.java │ └── InferiorServerTest.java └── packet └── PacketTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | /logs 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | .sts4-cache 12 | 13 | ### IntelliJ IDEA ### 14 | .idea 15 | *.iws 16 | *.iml 17 | *.ipr 18 | 19 | ### NetBeans ### 20 | /nbproject/private/ 21 | /nbbuild/ 22 | /dist/ 23 | /nbdist/ 24 | /.nb-gradle/ 25 | /build/ 26 | 27 | ### System Files ### 28 | .DS_Store 29 | Thumbs.db 30 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 tucke 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # java-jtt809-2011 2 | 3 | #### 介绍 4 | JT / T809-2011 Java版本 5 | 6 | 不依赖spring、不依赖springboot,拒绝万物皆可spring !我不是抵触spring,因为项目引入spring会让项目膨胀很大,spring虽然很方便,但是为了一点点小方便,似乎十分不划算!而且作为一个优秀的CV程序员,要学会自己写代码 7 | 8 | #### 软件架构 9 | 后续补充 10 | 11 | 12 | #### 安装教程 13 | 14 | 没啥特别之处,按照普通项目运行就行 15 | 项目入口可以查看 pom 文件 properties 的 start-class 配置 16 | 17 | #### 使用说明 18 | 19 | 1. GnssCenterService 管理下级平台的一些认证啥的,需要自己实现。甚至你自己去写死都行 20 | 2. 所有关于业务的协议处理都在 org.tucke.jtt809.handler.protocol 包下,只需根据自己使用的数据库实现数据保存即可。尽量避免使用一个文件,也尽量避免文件过多,建议将类型相同的协议放在一起(如连接类的协议都放在 org.tucke.jtt809.handler.protocol.connect.ConnectProtocol ) 21 | 3. 所有的内层包解析建议都放在 org.tucke.jtt809.packet 包下的消息实体类中,将消息实体和消息解码编码放在一起,方便代码管理和阅读,省得来回切换目录,眼花缭乱 22 | 23 | #### 参与贡献 24 | 25 | 1. Fork 本仓库 26 | 2. 新建 Feat_xxx 分支 27 | 3. 提交代码 28 | 4. 新建 Pull Request 29 | -------------------------------------------------------------------------------- /doc/JTT808-2011.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tucke/java-jtt809-2011/416eed913c646f568d7d3613a7ee626ba8ba68e1/doc/JTT808-2011.pdf -------------------------------------------------------------------------------- /doc/JTT809-2011.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tucke/java-jtt809-2011/416eed913c646f568d7d3613a7ee626ba8ba68e1/doc/JTT809-2011.pdf -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | org.tucke 8 | java-jtt809-2011 9 | 1.0-SNAPSHOT 10 | Java - JT/T 809-2011 11 | 12 | 13 | 11 14 | org.tucke.MainApplication 15 | 1.29 16 | 3.12.0 17 | 1.15 18 | 4.1.70.Final 19 | 1.18.22 20 | 1.3.0-alpha10 21 | 2.0.0-alpha5 22 | 5.8.2 23 | 24 | 25 | 26 | 27 | org.yaml 28 | snakeyaml 29 | ${snakeyaml.version} 30 | 31 | 32 | io.netty 33 | netty-all 34 | ${io.netty.version} 35 | 36 | 37 | 38 | org.apache.commons 39 | commons-lang3 40 | ${commons.lang3} 41 | 42 | 43 | commons-codec 44 | commons-codec 45 | 46 | ${commons.codec} 47 | 48 | 49 | 50 | org.projectlombok 51 | lombok 52 | ${org.projectlombok.version} 53 | provided 54 | 55 | 56 | 57 | ch.qos.logback 58 | logback-classic 59 | ${logback.version} 60 | 61 | 62 | org.slf4j 63 | slf4j-api 64 | ${slf4j-api.version} 65 | 66 | 67 | org.junit.jupiter 68 | junit-jupiter-api 69 | ${junit.jupiter.version} 70 | test 71 | 72 | 73 | 74 | 75 | 76 | 77 | src/main/java 78 | 79 | **/*.xml 80 | 81 | 82 | 83 | src/main/resources 84 | 85 | **/*.* 86 | 87 | 88 | 89 | 90 | 91 | org.apache.maven.plugins 92 | maven-compiler-plugin 93 | 3.8.1 94 | 95 | ${java.version} 96 | ${java.version} 97 | UTF-8 98 | 99 | 100 | 101 | org.apache.maven.plugins 102 | maven-resources-plugin 103 | 3.2.0 104 | 105 | UTF-8 106 | 107 | 108 | 109 | org.apache.maven.plugins 110 | maven-clean-plugin 111 | 3.1.0 112 | 113 | 114 | org.apache.maven.plugins 115 | maven-surefire-plugin 116 | 2.22.2 117 | 118 | true 119 | 120 | 121 | 122 | org.apache.maven.plugins 123 | maven-shade-plugin 124 | 3.2.4 125 | 126 | true 127 | true 128 | 129 | 130 | *:* 131 | 132 | META-INF/*.MF 133 | META-INF/*.SF 134 | META-INF/*.DSA 135 | META-INF/*.RSA 136 | META-INF/*.txt 137 | 138 | 139 | 140 | 141 | 142 | 143 | package 144 | 145 | shade 146 | 147 | 148 | false 149 | 150 | 152 | 154 | ${start-class} 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | ${project.artifactId} 163 | 164 | 165 | -------------------------------------------------------------------------------- /src/main/java/org/tucke/MainApplication.java: -------------------------------------------------------------------------------- 1 | package org.tucke; 2 | 3 | import org.tucke.config.AppConfig; 4 | import org.tucke.config.LoggerConfig; 5 | import org.tucke.gnsscenter.GnssCenterService; 6 | import org.tucke.jtt809.Jtt809Server; 7 | 8 | /** 9 | * @author tucke 10 | */ 11 | public class MainApplication { 12 | 13 | private static void loadConfiguration(String[] args) { 14 | AppConfig.load(args); 15 | LoggerConfig.load(); 16 | } 17 | 18 | private static void addHooks() { 19 | Runtime.getRuntime().addShutdownHook(new Thread(MainApplication::exit)); 20 | } 21 | 22 | private static void startService() throws Exception { 23 | GnssCenterService.getInstance().start(); 24 | Jtt809Server.getInstance().start(); 25 | } 26 | 27 | private static void exit() { 28 | Jtt809Server.getInstance().stop(); 29 | GnssCenterService.getInstance().stop(); 30 | } 31 | 32 | public static void main(String[] args) throws Exception { 33 | loadConfiguration(args); 34 | addHooks(); 35 | startService(); 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/org/tucke/config/AppConfig.java: -------------------------------------------------------------------------------- 1 | package org.tucke.config; 2 | 3 | import org.apache.commons.lang3.StringUtils; 4 | import org.yaml.snakeyaml.Yaml; 5 | 6 | import java.io.InputStream; 7 | import java.util.LinkedHashMap; 8 | import java.util.List; 9 | 10 | /** 11 | * @author tucke 12 | */ 13 | public class AppConfig { 14 | 15 | private static LinkedHashMap APPLICATION_CONFIG; 16 | 17 | private AppConfig() { 18 | throw new IllegalStateException(); 19 | } 20 | 21 | public static void load(String[] env) { 22 | StringBuilder fileName = new StringBuilder("application"); 23 | if (env != null) { 24 | for (String s : env) { 25 | String[] opt = s.split("="); 26 | if ("--env".equals(opt[0])) { 27 | fileName.append("-").append(opt[1]); 28 | } 29 | } 30 | } 31 | Yaml yaml = new Yaml(); 32 | InputStream inputStream = AppConfig.class.getClassLoader().getResourceAsStream(fileName.append(".yml").toString()); 33 | APPLICATION_CONFIG = yaml.load(inputStream); 34 | } 35 | 36 | /** 37 | * 获得指定KEY最近一层的数据 38 | * 39 | * @param key 指定的KEY 40 | * @param map 需要查找的MAP 41 | * @return 最近一层的数据 42 | */ 43 | private static LinkedHashMap getNearestLevelMap(String key, LinkedHashMap map) { 44 | if (StringUtils.isNotBlank(key) && map != null) { 45 | String[] keys = key.split("\\."); 46 | if (keys.length > 1) { 47 | String key0 = keys[0]; 48 | Object o = map.get(keys[0]); 49 | if (o instanceof LinkedHashMap) { 50 | return getNearestLevelMap(key.substring(key0.length() + 1), (LinkedHashMap) o); 51 | } else { 52 | return map; 53 | } 54 | } 55 | } 56 | return map; 57 | } 58 | 59 | /** 60 | * 按.分割字符串,并返回最后一层 61 | * 62 | * @param key 需要分割的KEY 63 | * @return 最后一层的KEY 64 | */ 65 | private static String lastIndexKey(String key) { 66 | boolean flag = key.contains("."); 67 | if (flag) { 68 | return key.substring(key.lastIndexOf(".") + 1); 69 | } 70 | return key; 71 | } 72 | 73 | public static Object getObject(String key) { 74 | LinkedHashMap nearestLevelObject = getNearestLevelMap(key, APPLICATION_CONFIG); 75 | return nearestLevelObject.get(lastIndexKey(key)); 76 | } 77 | 78 | public static String getString(String key) { 79 | return getObject(key).toString(); 80 | } 81 | 82 | public static int getIntValue(String key) { 83 | String str = getString(key); 84 | if (str == null) { 85 | return 0; 86 | } 87 | return Integer.parseInt(str); 88 | } 89 | 90 | public static boolean getBoolean(String key) { 91 | String str = getString(key); 92 | if (str == null) { 93 | return false; 94 | } 95 | return Boolean.parseBoolean(str); 96 | } 97 | 98 | public static double getDoubleValue(String key) { 99 | String str = getString(key); 100 | if (str == null) { 101 | return 0.0D; 102 | } 103 | return Double.parseDouble(str); 104 | } 105 | 106 | public static List getList(String key) { 107 | Object obj = getObject(key); 108 | if (obj instanceof List) { 109 | return (List) obj; 110 | } 111 | return null; 112 | } 113 | 114 | public static LinkedHashMap getMap(String key) { 115 | Object obj = getObject(key); 116 | if (obj instanceof LinkedHashMap) { 117 | return (LinkedHashMap) obj; 118 | } 119 | return null; 120 | } 121 | 122 | } 123 | -------------------------------------------------------------------------------- /src/main/java/org/tucke/config/LoggerConfig.java: -------------------------------------------------------------------------------- 1 | package org.tucke.config; 2 | 3 | import ch.qos.logback.classic.Level; 4 | import ch.qos.logback.classic.Logger; 5 | import ch.qos.logback.classic.LoggerContext; 6 | import ch.qos.logback.classic.pattern.ThrowableProxyConverter; 7 | import ch.qos.logback.classic.spi.ILoggingEvent; 8 | import ch.qos.logback.classic.spi.IThrowableProxy; 9 | import ch.qos.logback.core.Appender; 10 | import ch.qos.logback.core.ConsoleAppender; 11 | import ch.qos.logback.core.CoreConstants; 12 | import ch.qos.logback.core.LayoutBase; 13 | import ch.qos.logback.core.encoder.LayoutWrappingEncoder; 14 | import ch.qos.logback.core.util.CachingDateFormatter; 15 | import org.slf4j.LoggerFactory; 16 | 17 | /** 18 | * @author tucke 19 | */ 20 | public class LoggerConfig { 21 | 22 | private static LoggerConfig instance = new LoggerConfig(); 23 | private final LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); 24 | 25 | public static void load() { 26 | if (instance == null) { 27 | synchronized (LoggerConfig.class) { 28 | instance = new LoggerConfig(); 29 | } 30 | } 31 | instance.config(); 32 | } 33 | 34 | private Appender console() { 35 | ConsoleAppender ca = new ConsoleAppender<>(); 36 | ca.setContext(lc); 37 | ca.setName("console"); 38 | LayoutWrappingEncoder encoder = new LayoutWrappingEncoder<>(); 39 | encoder.setContext(lc); 40 | LayoutBase layout = new LayoutBase<>() { 41 | final ThrowableProxyConverter tpc = new ThrowableProxyConverter(); 42 | 43 | @Override 44 | public void start() { 45 | tpc.start(); 46 | super.start(); 47 | } 48 | 49 | @Override 50 | public String doLayout(ILoggingEvent event) { 51 | if (!isStarted()) { 52 | return CoreConstants.EMPTY_STRING; 53 | } 54 | StringBuilder sb = new StringBuilder(); 55 | 56 | long timestamp = event.getTimeStamp(); 57 | 58 | sb.append(new CachingDateFormatter("yyyy-MM-dd HH:mm:ss.SSS").format(timestamp)); 59 | sb.append(" ["); 60 | sb.append(event.getThreadName()); 61 | sb.append("] "); 62 | sb.append(event.getLevel().toString()); 63 | sb.append(" "); 64 | sb.append(event.getLoggerName()); 65 | sb.append(" - "); 66 | sb.append(event.getFormattedMessage()); 67 | sb.append(CoreConstants.LINE_SEPARATOR); 68 | IThrowableProxy tp = event.getThrowableProxy(); 69 | if (tp != null) { 70 | String stackTrace = tpc.convert(event); 71 | sb.append(stackTrace); 72 | } 73 | return sb.toString(); 74 | } 75 | }; 76 | layout.setContext(lc); 77 | layout.start(); 78 | encoder.setLayout(layout); 79 | ca.setEncoder(encoder); 80 | ca.start(); 81 | return ca; 82 | } 83 | 84 | private void config() { 85 | Logger logger = lc.getLogger(Logger.ROOT_LOGGER_NAME); 86 | logger.setLevel(Level.valueOf(AppConfig.getString("logging.level"))); 87 | logger.detachAndStopAllAppenders(); 88 | logger.addAppender(console()); 89 | } 90 | 91 | } 92 | -------------------------------------------------------------------------------- /src/main/java/org/tucke/gnsscenter/GnssCenterService.java: -------------------------------------------------------------------------------- 1 | package org.tucke.gnsscenter; 2 | 3 | import org.tucke.jtt809.packet.connect.UpConnectPacket; 4 | 5 | import java.util.Map; 6 | import java.util.concurrent.ConcurrentHashMap; 7 | 8 | /** 9 | * 下级平台配置服务 10 | * 11 | * @author tucke 12 | */ 13 | @SuppressWarnings("SpellCheckingInspection") 14 | public class GnssCenterService { 15 | 16 | private final Map DOWN_REQUEST = new ConcurrentHashMap<>(); 17 | private volatile static GnssCenterService instance; 18 | 19 | private GnssCenterService() { 20 | } 21 | 22 | public static GnssCenterService getInstance() { 23 | if (instance == null) { 24 | synchronized (GnssCenterService.class) { 25 | if (instance == null) { 26 | instance = new GnssCenterService(); 27 | } 28 | } 29 | } 30 | return instance; 31 | } 32 | 33 | public void start() throws Exception { 34 | // TODO 加载下级平台配置信息 35 | } 36 | 37 | /** 38 | * 获取加密的参数 39 | * 40 | * @param gnsscenterId 下级平台接入码 41 | * @return {M1, IA1, IC1} 42 | */ 43 | public int[] getEncryptParam(int gnsscenterId) { 44 | // TODO 45 | return new int[]{1, 2, 3}; 46 | } 47 | 48 | /** 49 | * 获取解密的参数 50 | * 51 | * @param gnsscenterId 下级平台接入码 52 | * @return {M1, IA1, IC1} 53 | */ 54 | public int[] getDecryptParam(int gnsscenterId) { 55 | return getEncryptParam(gnsscenterId); 56 | } 57 | 58 | /** 59 | * 验证下级平台登录 60 | */ 61 | public byte validateLogin(int gnsscenterId, UpConnectPacket.Request request) { 62 | // TODO 63 | // 首先验证 IP 地址 64 | // 其次验证接入码、用户名以及密码 65 | byte result = 0x00; 66 | if (result == 0x00) { 67 | DOWN_REQUEST.put(gnsscenterId, request); 68 | } 69 | return result; 70 | } 71 | 72 | public UpConnectPacket.Request getDownRequest(int gnsscenterId) { 73 | return DOWN_REQUEST.get(gnsscenterId); 74 | } 75 | 76 | public void stop() { 77 | 78 | } 79 | 80 | } 81 | -------------------------------------------------------------------------------- /src/main/java/org/tucke/jtt809/Jtt809Client.java: -------------------------------------------------------------------------------- 1 | package org.tucke.jtt809; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.buffer.Unpooled; 5 | import io.netty.channel.Channel; 6 | import io.netty.channel.ChannelId; 7 | import io.netty.channel.ChannelInitializer; 8 | import io.netty.channel.group.ChannelGroup; 9 | import io.netty.channel.group.DefaultChannelGroup; 10 | import io.netty.handler.codec.DelimiterBasedFrameDecoder; 11 | import io.netty.handler.timeout.IdleStateHandler; 12 | import io.netty.util.concurrent.GlobalEventExecutor; 13 | import lombok.extern.slf4j.Slf4j; 14 | import org.tucke.gnsscenter.GnssCenterService; 15 | import org.tucke.jtt809.common.Jtt809Constant; 16 | import org.tucke.jtt809.decoder.Jtt809Decoder; 17 | import org.tucke.jtt809.encoder.Jtt809Encoder; 18 | import org.tucke.jtt809.handler.slave.Jtt809SlaveInboundHandler; 19 | import org.tucke.jtt809.handler.slave.Jtt809SlaveOutBoundHandler; 20 | import org.tucke.jtt809.packet.common.OuterPacket; 21 | import org.tucke.jtt809.packet.connect.UpConnectPacket; 22 | import org.tucke.net.NettyClient; 23 | 24 | import java.net.InetSocketAddress; 25 | import java.net.SocketAddress; 26 | import java.util.Map; 27 | import java.util.concurrent.ConcurrentHashMap; 28 | import java.util.concurrent.TimeUnit; 29 | import java.util.concurrent.atomic.AtomicInteger; 30 | import java.util.concurrent.locks.Lock; 31 | import java.util.concurrent.locks.ReentrantLock; 32 | 33 | /** 34 | * 从链接 35 | * 36 | * @author tucke 37 | */ 38 | @SuppressWarnings({"RedundantThrows", "SpellCheckingInspection", "DuplicatedCode"}) 39 | @Slf4j 40 | public class Jtt809Client { 41 | 42 | private static final Lock LOCK = new ReentrantLock(); 43 | private static final ChannelGroup GROUP = new DefaultChannelGroup("Jtt809Client", GlobalEventExecutor.INSTANCE); 44 | private static final Map ID_MAP = new ConcurrentHashMap<>(); 45 | private static final Map RETRY_COUNT = new ConcurrentHashMap<>(); 46 | 47 | public static void newClient(Integer gnsscenterId, SocketAddress address, OuterPacket activePacket) { 48 | ByteBuf packetEndFlag = Unpooled.wrappedBuffer(new byte[]{Jtt809Constant.PACKET_END_FLAG}); 49 | String clientName = "下级平台 " + gnsscenterId + " 服务器"; 50 | NettyClient client = new NettyClient(clientName, address, new ChannelInitializer<>() { 51 | @Override 52 | protected void initChannel(Channel ch) throws Exception { 53 | // 每分钟(这里设置为 55 秒)进行心跳检查 54 | ch.pipeline().addLast(new IdleStateHandler(0, 55, 0, TimeUnit.SECONDS)); 55 | ch.pipeline().addLast(new Jtt809SlaveOutBoundHandler()); 56 | ch.pipeline().addLast(new Jtt809Encoder()); 57 | ch.pipeline().addLast(new DelimiterBasedFrameDecoder(2048, packetEndFlag)); 58 | ch.pipeline().addLast(new Jtt809Decoder()); 59 | ch.pipeline().addLast(new Jtt809SlaveInboundHandler(gnsscenterId, activePacket)); 60 | } 61 | }); 62 | try { 63 | client.connect(); 64 | } catch (Exception e) { 65 | downDisconnectInform(gnsscenterId, (byte) 0x00); 66 | log.error("连接下级平台 {} 失败:{}", gnsscenterId, e); 67 | } 68 | } 69 | 70 | public static void newClient(Integer gnsscenterId, String host, int port, OuterPacket activePacket) { 71 | newClient(gnsscenterId, new InetSocketAddress(host, port), activePacket); 72 | } 73 | 74 | public static void createClient(Integer gnsscenterId, SocketAddress address, OuterPacket activePacket) { 75 | // 如果存在该从链接,则不用创建 76 | Channel channel = find(gnsscenterId); 77 | if (channel != null && channel.isActive()) { 78 | return; 79 | } 80 | newClient(gnsscenterId, address, activePacket); 81 | } 82 | 83 | @SuppressWarnings("AlibabaUndefineMagicConstant") 84 | public static void reconnect(Integer gnsscenterId, OuterPacket activePacket) { 85 | int retry = 0; 86 | LOCK.lock(); 87 | try { 88 | if (RETRY_COUNT.containsKey(gnsscenterId)) { 89 | retry = RETRY_COUNT.get(gnsscenterId).incrementAndGet(); 90 | } else { 91 | RETRY_COUNT.put(gnsscenterId, new AtomicInteger()); 92 | } 93 | } finally { 94 | LOCK.unlock(); 95 | } 96 | if (retry < 3) { 97 | log.warn("第 {} 次尝试重连下级平台 {} 服务器。。。", retry + 1, gnsscenterId); 98 | UpConnectPacket.Request request = GnssCenterService.getInstance().getDownRequest(gnsscenterId); 99 | if (request == null) { 100 | log.warn("无法重连"); 101 | return; 102 | } 103 | newClient(gnsscenterId, request.getDownLinkIp(), request.getDownLinkPort(), activePacket); 104 | } else { 105 | log.warn("从链路下级平台 {} 服务器超过重连次数,不再进行重连,并且通过主链路通知下级平台", gnsscenterId); 106 | downDisconnectInform(gnsscenterId, (byte) 0x01); 107 | RETRY_COUNT.remove(gnsscenterId); 108 | close(gnsscenterId); 109 | // 通过抛出异常的方式关闭重试任务 110 | throw new RuntimeException("超过重试次数"); 111 | } 112 | } 113 | 114 | /** 115 | * 主链路通知下级平台从链路断开 116 | * 117 | * @param reason 0x00:无法连接下级平台指定的服务IP与端口 118 | * 0x01:上级平台客户端与下级平台服务端断开 119 | * 0x02:其他原因 120 | */ 121 | private static void downDisconnectInform(Integer gnsscenterId, byte reason) { 122 | Channel masterChannel = Jtt809Server.find(gnsscenterId); 123 | if (masterChannel != null) { 124 | OuterPacket out = new OuterPacket(Jtt809Constant.DataType.DOWN_DISCONNECT_INFORM, new byte[]{reason}); 125 | masterChannel.writeAndFlush(out); 126 | } 127 | } 128 | 129 | public static void resetRetryCount(Integer gnsscenterId) { 130 | RETRY_COUNT.remove(gnsscenterId); 131 | } 132 | 133 | @SuppressWarnings("DuplicatedCode") 134 | public static Channel find(Integer gnsscenterId) { 135 | ChannelId channelId = ID_MAP.get(gnsscenterId); 136 | if (channelId == null) { 137 | return null; 138 | } 139 | Channel channel = GROUP.find(channelId); 140 | if (channel == null) { 141 | ID_MAP.remove(gnsscenterId); 142 | } 143 | return channel; 144 | } 145 | 146 | public static void add(Integer gnsscenterId, Channel channel) { 147 | resetRetryCount(gnsscenterId); 148 | ChannelId channelId = channel.id(); 149 | ID_MAP.put(gnsscenterId, channelId); 150 | GROUP.add(channel); 151 | } 152 | 153 | public static void close(Integer gnsscenterId) { 154 | Channel channel = find(gnsscenterId); 155 | if (channel != null) { 156 | channel.close(); 157 | } 158 | ID_MAP.remove(gnsscenterId); 159 | } 160 | 161 | public static void write(Integer gnsscenterId, Object message) { 162 | Channel channel = find(gnsscenterId); 163 | if (channel != null) { 164 | channel.write(message); 165 | } 166 | } 167 | 168 | public static void writeAndFlush(Integer gnsscenterId, Object message) { 169 | Channel channel = find(gnsscenterId); 170 | if (channel != null) { 171 | channel.writeAndFlush(message); 172 | } 173 | } 174 | 175 | } 176 | -------------------------------------------------------------------------------- /src/main/java/org/tucke/jtt809/Jtt809Server.java: -------------------------------------------------------------------------------- 1 | package org.tucke.jtt809; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.buffer.Unpooled; 5 | import io.netty.channel.Channel; 6 | import io.netty.channel.ChannelId; 7 | import io.netty.channel.ChannelInitializer; 8 | import io.netty.channel.group.ChannelGroup; 9 | import io.netty.channel.group.DefaultChannelGroup; 10 | import io.netty.handler.codec.DelimiterBasedFrameDecoder; 11 | import io.netty.handler.timeout.ReadTimeoutHandler; 12 | import io.netty.util.concurrent.GlobalEventExecutor; 13 | import org.tucke.config.AppConfig; 14 | import org.tucke.jtt809.common.Jtt809Constant; 15 | import org.tucke.jtt809.decoder.Jtt809Decoder; 16 | import org.tucke.jtt809.encoder.Jtt809Encoder; 17 | import org.tucke.jtt809.handler.master.Jtt809MasterInboundHandler; 18 | import org.tucke.jtt809.handler.master.Jtt809MasterOutboundHandler; 19 | import org.tucke.net.NettyServer; 20 | 21 | import java.util.Map; 22 | import java.util.concurrent.ConcurrentHashMap; 23 | 24 | /** 25 | * 主链接 26 | * 27 | * @author tucke 28 | */ 29 | @SuppressWarnings({"SpellCheckingInspection", "DuplicatedCode"}) 30 | public class Jtt809Server { 31 | 32 | private static final ChannelGroup GROUP = new DefaultChannelGroup("Jtt809Server", GlobalEventExecutor.INSTANCE); 33 | private static final Map ID_MAP = new ConcurrentHashMap<>(); 34 | 35 | private volatile static Jtt809Server instance; 36 | private NettyServer nettyServer; 37 | 38 | private Jtt809Server() { 39 | } 40 | 41 | public static Jtt809Server getInstance() { 42 | if (instance == null) { 43 | synchronized (Jtt809Server.class) { 44 | if (instance == null) { 45 | instance = new Jtt809Server(); 46 | } 47 | } 48 | } 49 | return instance; 50 | } 51 | 52 | public void start() throws Exception { 53 | // 数据包结束标识 54 | ByteBuf packetEndFlag = Unpooled.wrappedBuffer(new byte[]{Jtt809Constant.PACKET_END_FLAG}); 55 | nettyServer = new NettyServer(Jtt809Constant.SERVER_NAME, new ChannelInitializer<>() { 56 | @Override 57 | protected void initChannel(Channel ch) throws Exception { 58 | // 连续 3min 未收到下级平台发送的从链路保持应答数据包,则认为下级平台已经失去连接,将主动断开数据传输从链路。 59 | // 考虑网络问题,这里设置为 5 分钟 60 | ch.pipeline().addLast(new ReadTimeoutHandler(300)); 61 | ch.pipeline().addLast(new Jtt809MasterOutboundHandler()); 62 | ch.pipeline().addLast(new Jtt809Encoder()); 63 | ch.pipeline().addLast(new DelimiterBasedFrameDecoder(2048, packetEndFlag)); 64 | ch.pipeline().addLast(new Jtt809Decoder()); 65 | ch.pipeline().addLast(new Jtt809MasterInboundHandler()); 66 | } 67 | }); 68 | nettyServer.bind(AppConfig.getIntValue("jtt809.port")); 69 | } 70 | 71 | public void stop() { 72 | nettyServer.shutdown(); 73 | } 74 | 75 | public static void add(Integer gnsscenterId, Channel channel) { 76 | ChannelId channelId = channel.id(); 77 | ID_MAP.put(gnsscenterId, channelId); 78 | GROUP.add(channel); 79 | } 80 | 81 | public static Channel find(Integer gnsscenterId) { 82 | ChannelId channelId = ID_MAP.get(gnsscenterId); 83 | if (channelId == null) { 84 | return null; 85 | } 86 | Channel channel = GROUP.find(channelId); 87 | if (channel == null) { 88 | ID_MAP.remove(gnsscenterId); 89 | } 90 | return channel; 91 | } 92 | 93 | public static void write(Integer gnsscenterId, Object message) { 94 | Channel channel = find(gnsscenterId); 95 | if (channel != null) { 96 | channel.write(message); 97 | } 98 | } 99 | 100 | public static void writeAndFlush(Integer gnsscenterId, Object message) { 101 | Channel channel = find(gnsscenterId); 102 | if (channel != null) { 103 | channel.writeAndFlush(message); 104 | } 105 | } 106 | 107 | } 108 | -------------------------------------------------------------------------------- /src/main/java/org/tucke/jtt809/common/CRC16CCITT.java: -------------------------------------------------------------------------------- 1 | package org.tucke.jtt809.common; 2 | 3 | /** 4 | * @author tucke 5 | */ 6 | @SuppressWarnings("AlibabaClassNamingShouldBeCamel") 7 | public class CRC16CCITT { 8 | 9 | public static int crc16(byte[] bytes){ 10 | int crc = 0xFFFF; 11 | for (byte aByte : bytes) { 12 | crc = ((crc >>> 8) | (crc << 8)) & 0xFFFF; 13 | // byte to int, trunc sign 14 | crc ^= (aByte & 0xFF); 15 | crc ^= ((crc & 0xFF) >> 4); 16 | crc ^= (crc << 12) & 0xFFFF; 17 | crc ^= ((crc & 0xFF) << 5) & 0xFFFF; 18 | } 19 | crc &= 0xFFFF; 20 | return crc; 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/org/tucke/jtt809/common/Jtt809Constant.java: -------------------------------------------------------------------------------- 1 | package org.tucke.jtt809.common; 2 | 3 | import io.netty.util.AttributeKey; 4 | 5 | import java.util.concurrent.atomic.AtomicInteger; 6 | 7 | /** 8 | * @author tucke 9 | */ 10 | public class Jtt809Constant { 11 | 12 | public static final String SERVER_NAME = "JT/T 809"; 13 | 14 | public static final byte PACKET_HEAD_FLAG = 0x5B; 15 | public static final byte PACKET_END_FLAG = 0x5D; 16 | 17 | public static final class NettyAttribute { 18 | public static final AttributeKey GNSS_CENTER_ID = AttributeKey.valueOf("GNSS_CENTER_ID"); 19 | public static final AttributeKey PLATFORM_ACK_SERIAL_NO = AttributeKey.valueOf("PLATFORM_ACK_SERIAL_NO"); 20 | } 21 | 22 | /** 23 | * 业务数据类型标识 24 | *

25 | * a) 上级平台向下级平台发送的请求消息,一般以 DOWN_ 开头,以后缀 _REQ 结尾;而下级平台向上级平台发送的请求消息一般以 UP_ 开头,以后缀 _REQ 结尾; 26 | * b) 当上下级平台之间有应答消息情况下,应答消息可继续沿用对应的请求消息开头标识符,而通过后缀 RSP 来标识结尾。 27 | */ 28 | @SuppressWarnings({"SpellCheckingInspection", "unused"}) 29 | public static class DataType { 30 | 31 | /** 32 | * 主链路登录请求消息 33 | */ 34 | public final static int UP_CONNECT_REQ = 0x1001; 35 | /** 36 | * 主链路登录应答消息 37 | */ 38 | public final static int UP_CONNECT_RSP = 0x1002; 39 | /** 40 | * 主链路注销请求消息 41 | */ 42 | public final static int UP_DICONNECE_REQ = 0x1003; 43 | /** 44 | * 主链路注销应答消息 45 | */ 46 | public final static int UP_DISCONNECT_RSP = 0x1004; 47 | /** 48 | * 主链路连接保持请求消息 49 | */ 50 | public final static int UP_LINKTEST_REQ = 0x1005; 51 | /** 52 | * 主链路连接保持应答消息 53 | */ 54 | public final static int UP_LINKTEST_RSP = 0x1006; 55 | /** 56 | * 主链路断开通知 57 | */ 58 | public final static int UP_DISCONNECT_INFORM = 0x1007; 59 | /** 60 | * 下级平台主动关闭从链路通知 61 | */ 62 | public final static int UP_CLOSELINK_INFORM = 0x1008; 63 | /** 64 | * 主链路登录请求消息 65 | */ 66 | public final static int DOWN_CONNECT_REQ = 0x9001; 67 | /** 68 | * 从链路登录应答消息 69 | */ 70 | public final static int DOWN_CONNECT_RSP = 0x9002; 71 | /** 72 | * 从链路注销请求消息 73 | */ 74 | public final static int DOWN_DISCONNECT_REQ = 0x9003; 75 | /** 76 | * 从链路注销应答消息 77 | */ 78 | public final static int DOWN_DISCONNECT_RSP = 0x9004; 79 | /** 80 | * 从链路连接保持请求消息 81 | */ 82 | public final static int DOWN_LINKTEST_REQ = 0x9005; 83 | /** 84 | * 从链路连接保持应答消息 85 | */ 86 | public final static int DOWN_LINKTEST_RSP = 0x9006; 87 | /** 88 | * 从链路链路断开通知 89 | */ 90 | public final static int DOWN_DISCONNECT_INFORM = 0x9007; 91 | /** 92 | * 上级平台主动关闭从链路通知 93 | */ 94 | public final static int DOWN_CLOSELINK_INFORM = 0x9008; 95 | 96 | 97 | /** 98 | * 接受定位信息数量通知 99 | */ 100 | public final static int DOWN_TOTAL_RECV_BACK_MSG = 0x9101; 101 | 102 | 103 | /** 104 | * 主链路动态信息交换消息 105 | */ 106 | public final static int UP_EXG_MSG = 0x1200; 107 | /** 108 | * 从链路动态信息交换 109 | */ 110 | public final static int DOWN_EXG_MSG = 0x9200; 111 | 112 | 113 | /** 114 | * 主链路平台间信息交互 115 | */ 116 | public final static int UP_PLATFORM_MSG = 0x1300; 117 | /** 118 | * 从链路平台间信息交互 119 | */ 120 | public final static int DOWN_PLATFORM_MSG = 0x9300; 121 | 122 | 123 | /** 124 | * 主链路报警信息交互 125 | */ 126 | public final static int UP_WARN_MSG = 0x1400; 127 | /** 128 | * 从链路报警信息交互 129 | */ 130 | public final static int DOWN_WARN_MSG = 0x9400; 131 | 132 | 133 | /** 134 | * 主链路车辆监管消息 135 | */ 136 | public final static int UP_CTRL_MSG = 0x1500; 137 | /** 138 | * 从链路车辆监管消息 139 | */ 140 | public final static int DOWN_CTRL_MSG = 0x9500; 141 | 142 | 143 | /** 144 | * 主链路静态信息交换 145 | */ 146 | public final static int UP_BASE_MSG = 0x1600; 147 | /** 148 | * 从链路静态信息交换 149 | */ 150 | public final static int DOWN_BASE_MSG = 0x9600; 151 | 152 | } 153 | 154 | /** 155 | * 子业务类型标识 156 | *

157 | * a) 对应于业务数据类型下的子业务标识头继续遵循原有归属业务数据类型的标识头,例如业务数据类型 UP_EXG_MSG 下的子业务类型标识头均以 UP_EXG_MSG 开始; 158 | * b) 子业务类型名称标识的主从链路方向遵循原有归属业务数据类型的主从链路方向。 159 | */ 160 | @SuppressWarnings({"SpellCheckingInspection", "unused"}) 161 | public static class SubDataType { 162 | 163 | /** 164 | * 上传车辆注册信息 165 | */ 166 | public final static int UP_EXG_MSG_REGISTER = 0x1201; 167 | /** 168 | * 实时上传车辆定位信息 169 | */ 170 | public final static int UP_EXG_MSG_REAL_LOCATION = 0x1202; 171 | /** 172 | * 车辆定位信息自动补报 173 | */ 174 | public final static int UP_EXG_MSG_HISTORY_LOCATION = 0x1203; 175 | /** 176 | * 启动车辆定位信息交换应答 177 | */ 178 | public final static int UP_EXG_MSG_RETURE_STARTUP_ACK = 0x1205; 179 | /** 180 | * 结束车辆定位信息交换应答 181 | */ 182 | public final static int UP_EXG_MSG_RETURE_END_ACK = 0x1206; 183 | /** 184 | * 申请交换指定车辆定位信息请求 185 | */ 186 | public final static int UP_EXG_MSG_APPLE_FOR_MONITOR_STAR_TUP = 0x1207; 187 | /** 188 | * 取消交换制定车辆定位信息请求 189 | */ 190 | public final static int UP_EXG_MSG_APPLE_FOR_MONITOR_END = 0x1208; 191 | /** 192 | * 补发车辆定位信息请求 193 | */ 194 | public final static int UP_EXG_MSG_APPLE_HISGNSSDATA_REQ = 0x1209; 195 | /** 196 | * 上报车辆驾驶员身份识别信息应答 197 | */ 198 | public final static int UP_EXG_MSG_REPORT_DRIVER_INFO_ACK = 0x120A; 199 | /** 200 | * 上报车辆电子运单应答 201 | */ 202 | public final static int UP_EXG_MSG_TAKE_EWAYBILL_ACK = 0x120B; 203 | 204 | 205 | /** 206 | * 车辆定位信息交换 207 | */ 208 | public final static int DOWN_EXG_MSG_CAR_LOCATION = 0x9202; 209 | /** 210 | * 车辆定位信息交换补发 211 | */ 212 | public final static int DOWN_EXG_MSG_HISTORY_ARCOSSAREL = 0x9203; 213 | /** 214 | * 车辆静态信息交换 215 | */ 216 | public final static int DOWN_EXG_MSG_CAR_INFO = 0x9204; 217 | /** 218 | * 启动车辆定位信息交换请求 219 | */ 220 | public final static int DOWN_EXG_MSG_RETURN_STARTUP = 0x9205; 221 | /** 222 | * 关闭车辆定位信息交换请求 223 | */ 224 | public final static int DOWN_EXG_MSG_RETURN_END = 0x9206; 225 | /** 226 | * 申请交换制定车辆定位信息 227 | */ 228 | public final static int DOWN_EXG_MSG_APPLY_FOR_MONITOR_STARTUP_ACK = 0x9207; 229 | /** 230 | * 取消交换制定车辆定位信息 231 | */ 232 | public final static int DOWN_EXG_MSG_APPLY_FOR_MONITOR_END_ACK = 0x9208; 233 | /** 234 | * 补发车辆定位信息应答 235 | */ 236 | public final static int DOWN_EXG_MSG_APPLY_HISGNSSDATA_ACK = 0x9209; 237 | /** 238 | * 上报车辆驾驶员身份识别信息请求 239 | */ 240 | public final static int DOWN_EXG_MSG_REPORT_DRIVER_INFO = 0x920A; 241 | /** 242 | * 上报车辆电子运单请求 243 | */ 244 | public final static int DOWN_EXG_MSG_TAKE_EWAYBILL_REQ = 0x920B; 245 | 246 | 247 | /** 248 | * 平台查岗应答 249 | */ 250 | public final static int UP_PLATFORM_MSG_POST_QUERY_ACK = 0x1301; 251 | /** 252 | * 下发平台间报文应答 253 | */ 254 | public final static int UP_PLATFORM_MSG_INFO_ACK = 0x1302; 255 | 256 | 257 | /** 258 | * 平台查岗应答 259 | */ 260 | public final static int DOWN_PLATFORM_MSG_POST_QUERY_REQ = 0x9301; 261 | /** 262 | * 下发平台间报文应答 263 | */ 264 | public final static int DOWN_PLATFORM_MSG_INFO_REQ = 0x9302; 265 | 266 | 267 | /** 268 | * 报警督办应答 269 | */ 270 | public final static int UP_WARN_MSG_URGE_TODO_ACK = 0x1401; 271 | /** 272 | * 上报报警信息 273 | */ 274 | public final static int UP_WARN_MSG_ADPT_INFO = 0x1402; 275 | 276 | 277 | /** 278 | * 报警督办请求 279 | */ 280 | public final static int DOWN_WARN_MSG_URGE_TODO_REQ = 0x9401; 281 | /** 282 | * 报警预警 283 | */ 284 | public final static int DOWN_WARN_MSG_INFORM_TIPS = 0x9402; 285 | /** 286 | * 实时交换报警信息 287 | */ 288 | public final static int DOWN_WARN_MSG_EXG_INFORM = 0x9403; 289 | 290 | 291 | /** 292 | * 车辆单向监听应答 293 | */ 294 | public final static int UP_CTRL_MSG_MONITOR_VEHICLE_ACK = 0x1501; 295 | /** 296 | * 车辆牌照应答 297 | */ 298 | public final static int UP_CTRL_MSG_TAKE_PHOTO_ACK = 0x1502; 299 | /** 300 | * 下发车辆报文应答 301 | */ 302 | public final static int UP_CTRL_MSG_TEXT_INFO_ACK = 0x1503; 303 | /** 304 | * 上报车辆形式记录应答 305 | */ 306 | public final static int UP_CTRL_MSG_TAKE_TRAVEL_ACK = 0x1504; 307 | /** 308 | * 车辆应急接入监管平台应答 309 | */ 310 | public final static int UP_CTRL_MSG_EMERGENCY_MONITORING_ACK = 0x1505; 311 | 312 | 313 | /** 314 | * 车辆单向监听请求 315 | */ 316 | public final static int DOWN_CTRL_MSG_MONITOR_VEHICLE_REQ = 0x9501; 317 | /** 318 | * 车辆牌照请求 319 | */ 320 | public final static int DOWN_CTRL_MSG_TAKE_PHOTO_REQ = 0x9502; 321 | /** 322 | * 下发车辆报文请求 323 | */ 324 | public final static int DOWN_CTRL_MSG_TEXT_INFO_REQ = 0x9503; 325 | /** 326 | * 上报车辆形式记录请求 327 | */ 328 | public final static int DOWN_CTRL_MSG_TAKE_TRAVEL_REQ = 0x9504; 329 | /** 330 | * 车辆应急接入监管平台请求 331 | */ 332 | public final static int UP_CTRL_MSG_EMERGENCY_MONITORING_REQ = 0x9505; 333 | 334 | 335 | /** 336 | * 补报车辆静态信息应答 337 | */ 338 | public final static int UP_BASE_MSG_VEHICLE_ADDED_ACK = 0x1601; 339 | /** 340 | * 补报车辆静态信息请求 341 | */ 342 | public final static int DOWN_BASE_MSG_VEHICLE_ADDED = 0x9601; 343 | 344 | } 345 | 346 | } 347 | -------------------------------------------------------------------------------- /src/main/java/org/tucke/jtt809/common/Jtt809Util.java: -------------------------------------------------------------------------------- 1 | package org.tucke.jtt809.common; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import lombok.extern.slf4j.Slf4j; 5 | import org.apache.commons.lang3.time.DateUtils; 6 | import org.apache.commons.lang3.time.FastDateFormat; 7 | 8 | import java.nio.charset.Charset; 9 | import java.text.ParseException; 10 | import java.util.Arrays; 11 | import java.util.TimeZone; 12 | 13 | /** 14 | * @author tucke 15 | */ 16 | @SuppressWarnings({"AlibabaUndefineMagicConstant", "UnusedReturnValue", "AlibabaLowerCamelCaseVariableNaming", "unused", "BooleanMethodIsAlwaysInverted"}) 17 | @Slf4j 18 | public class Jtt809Util { 19 | 20 | /** 21 | * 0x5B, 0x5A, 0x5D, 0x5E 转义处理 22 | */ 23 | public static byte[] escape(byte[] bytes) { 24 | // 最极端情况,每个byte都需要转义,所以使用2倍长度 25 | byte[] result = new byte[bytes.length * 2]; 26 | int i = 0; 27 | for (byte b : bytes) { 28 | switch (b) { 29 | case 0x5B: 30 | result[i++] = 0x5A; 31 | result[i++] = 0x01; 32 | break; 33 | case 0x5A: 34 | result[i++] = 0x5A; 35 | result[i++] = 0x02; 36 | break; 37 | case 0x5D: 38 | result[i++] = 0x5E; 39 | result[i++] = 0x01; 40 | break; 41 | case 0x5E: 42 | result[i++] = 0x5E; 43 | result[i++] = 0x02; 44 | break; 45 | default: 46 | result[i++] = b; 47 | } 48 | } 49 | // 截取转义后的数据并返回 50 | return Arrays.copyOf(result, i); 51 | } 52 | 53 | /** 54 | * 0x5B, 0x5A, 0x5D, 0x5E 反转义处理 55 | */ 56 | public static byte[] unescape(byte[] bytes) { 57 | if (bytes == null || bytes.length <= 1) { 58 | return bytes; 59 | } 60 | // 最极端情况,每个byte都不需要反转义,所以使用1倍长度 61 | byte[] result = new byte[bytes.length]; 62 | int ii = 0; 63 | for (int i = 0; i < bytes.length; i++) { 64 | // 当前循环的 byte 数据 65 | byte curr = bytes[i]; 66 | // 若最后一条 byte 数据还能进入循环,则它必定不满足反转义 67 | if (i == bytes.length - 1) { 68 | result[ii++] = curr; 69 | break; 70 | } 71 | // 下一条 byte 数据 72 | byte next = bytes[i + 1]; 73 | if (curr == 0x5A) { 74 | // 将 0x5A 0x01 反转义为 0x5B,且下一条数据 0x01 不需要参与循环 75 | if (next == 0x01) { 76 | result[ii++] = 0x5B; 77 | i++; 78 | continue; 79 | } 80 | // 0x5A 0x02 反转义结果就是 0x5A,且下一条数据 0x02 不需要参与循环 81 | if (next == 0x02) { 82 | i++; 83 | } 84 | } 85 | if (curr == 0x5E) { 86 | // 将 0x5E 0x01 反转义为 0x5D,且下一条数据 0x01 不需要参与循环 87 | if (next == 0x01) { 88 | result[ii++] = 0x5D; 89 | i++; 90 | continue; 91 | } 92 | // 0x5E 0x02 反转义结果就是 0x5E,且下一条数据 0x02 不需要参与循环 93 | if (next == 0x02) { 94 | i++; 95 | } 96 | } 97 | result[ii++] = curr; 98 | } 99 | // 截取反转义后的数据并返回 100 | return Arrays.copyOf(result, ii); 101 | } 102 | 103 | /** 104 | * 消息校验 105 | */ 106 | public static boolean validate(ByteBuf byteBuf) { 107 | int len = byteBuf.readableBytes(); 108 | byte[] bytes = new byte[len - 2]; 109 | byteBuf.getBytes(0, bytes); 110 | int calc = CRC16CCITT.crc16(bytes); 111 | int code = byteBuf.getUnsignedShort(len - 2); 112 | boolean result = calc == code; 113 | if (!result) { 114 | log.warn("CRC校验失败!计算结果为:{}, 传入值为:{}", calc, code); 115 | } 116 | return result; 117 | } 118 | 119 | /** 120 | * 加密 121 | */ 122 | public static byte[] encrypt(int m1, int ia1, int ic1, long key, byte[] bytes) { 123 | if (bytes == null) { 124 | return null; 125 | } 126 | if (key == 0) { 127 | key = 1; 128 | } 129 | for (int i = 0; i < bytes.length; i++) { 130 | key = ia1 * (key % m1) + ic1; 131 | bytes[i] ^= ((key >> 20) & 0xFF); 132 | } 133 | return bytes; 134 | } 135 | 136 | /** 137 | * 解密 138 | */ 139 | public static byte[] decrypt(int m1, int ia1, int ic1, long key, byte[] bytes) { 140 | return encrypt(m1, ia1, ic1, key, bytes); 141 | } 142 | 143 | /** 144 | * 解析字符串 145 | * 146 | * @param complement 是否考虑右边补零的情况 147 | */ 148 | public static String readString(ByteBuf byteBuf, int length, Charset charset, boolean complement) { 149 | // 是否考虑右补十六进制 0x00 150 | if (complement) { 151 | byte[] bytes = new byte[length]; 152 | byteBuf.readBytes(bytes); 153 | int len = 0; 154 | for (int i = bytes.length; i > 0; i--) { 155 | if (bytes[i - 1] != 0x00) { 156 | len = i; 157 | break; 158 | } 159 | } 160 | return new String(Arrays.copyOf(bytes, len), charset); 161 | } else { 162 | return byteBuf.readBytes(length).toString(charset); 163 | } 164 | } 165 | 166 | /** 167 | * 解析GBK字符串 168 | * 169 | * @param complement 是否考虑右边补零的情况 170 | */ 171 | public static String readGBKString(ByteBuf byteBuf, int length, boolean complement) { 172 | return readString(byteBuf, length, Charset.forName("GBK"), complement); 173 | } 174 | 175 | /** 176 | * 解析GBK字符串 177 | */ 178 | public static String readGBKString(ByteBuf byteBuf, int length) { 179 | return readGBKString(byteBuf, length, true); 180 | } 181 | 182 | /** 183 | * 解析时间 184 | */ 185 | public static long parseDateTime(ByteBuf byteBuf) { 186 | String date = byteBuf.readByte() + "-" + byteBuf.readByte() + "-" + byteBuf.readShort() + " " + 187 | byteBuf.readByte() + ":" + byteBuf.readByte() + ":" + byteBuf.readByte(); 188 | long time = 0L; 189 | try { 190 | FastDateFormat format = FastDateFormat.getInstance("dd-MM-yyyy HH:mm:ss", TimeZone.getTimeZone("GMT+8:00")); 191 | time = format.parse(date).getTime(); 192 | } catch (ParseException e) { 193 | log.warn("日期 [{}] 解析错误", date); 194 | } 195 | return time; 196 | } 197 | 198 | } 199 | -------------------------------------------------------------------------------- /src/main/java/org/tucke/jtt809/decoder/Jtt809Decoder.java: -------------------------------------------------------------------------------- 1 | package org.tucke.jtt809.decoder; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.buffer.ByteBufUtil; 5 | import io.netty.buffer.Unpooled; 6 | import io.netty.channel.ChannelHandlerContext; 7 | import io.netty.handler.codec.MessageToMessageDecoder; 8 | import io.netty.util.ReferenceCountUtil; 9 | import lombok.extern.slf4j.Slf4j; 10 | import org.tucke.gnsscenter.GnssCenterService; 11 | import org.tucke.jtt809.common.Jtt809Constant; 12 | import org.tucke.jtt809.common.Jtt809Util; 13 | import org.tucke.jtt809.packet.common.OuterPacket; 14 | 15 | import java.util.List; 16 | 17 | /** 18 | * @author tucke 19 | */ 20 | @Slf4j 21 | public class Jtt809Decoder extends MessageToMessageDecoder { 22 | 23 | @SuppressWarnings({"AlibabaUndefineMagicConstant", "SpellCheckingInspection"}) 24 | @Override 25 | protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List out) throws Exception { 26 | // 写个判断,线上环境就不需要执行 ByteBufUtil.hexDump 27 | if (log.isDebugEnabled()) { 28 | log.debug("收到一条消息:{}5d", ByteBufUtil.hexDump(msg)); 29 | } 30 | // 判断包头 31 | if (msg.readByte() != Jtt809Constant.PACKET_HEAD_FLAG) { 32 | msg.resetReaderIndex(); 33 | log.warn("消息包头错误: {}5d", ByteBufUtil.hexDump(msg)); 34 | return; 35 | } 36 | byte[] readableBytes = new byte[msg.readableBytes()]; 37 | msg.readBytes(readableBytes); 38 | // 反转义处理 39 | byte[] bytes = Jtt809Util.unescape(readableBytes); 40 | ByteBuf byteBuf = Unpooled.wrappedBuffer(bytes); 41 | // crc校验 42 | if (!Jtt809Util.validate(byteBuf)) { 43 | ReferenceCountUtil.release(byteBuf); 44 | return; 45 | } 46 | 47 | /* 解析外层包 */ 48 | // 长度 49 | long length = byteBuf.readUnsignedInt(); 50 | // 长度校验, 反转义之后数组加上包头和包尾长度与解析出来的长度对比; 51 | // 因为数据长度不包含校验码,而此时解析出来的数据不包含头尾标识,刚好都是2个字节,所以两个长度应该相等 52 | if (length != bytes.length) { 53 | log.warn("消息长度校验错误,报文解析出来长度为 {}, 实际可解析的长度为 {}", length, bytes.length); 54 | ReferenceCountUtil.release(byteBuf); 55 | return; 56 | } 57 | // 报文序列号 58 | long sn = byteBuf.readUnsignedInt(); 59 | // 业务数据类型 60 | int id = byteBuf.readUnsignedShort(); 61 | // 下级平台接入码 62 | int gnsscenterId = byteBuf.readInt(); 63 | ctx.channel().attr(Jtt809Constant.NettyAttribute.GNSS_CENTER_ID).setIfAbsent(String.valueOf(gnsscenterId)); 64 | // 协议版本号标识 65 | String version = "v" + byteBuf.readByte() + "." + byteBuf.readByte() + "." + byteBuf.readByte(); 66 | // 报文加密标识位 67 | byte encryptFlag = byteBuf.readByte(); 68 | // 数据加密解密的密匙 69 | long encryptKey = byteBuf.readUnsignedInt(); 70 | // 消息体 71 | byte[] body; 72 | if (encryptFlag == 1) { 73 | byte[] encryptedBytes = new byte[byteBuf.readableBytes() - 2]; 74 | byteBuf.readBytes(encryptedBytes); 75 | // 解密 76 | int[] param = GnssCenterService.getInstance().getDecryptParam(gnsscenterId); 77 | Jtt809Util.decrypt(param[0], param[1], param[2], encryptKey, encryptedBytes); 78 | body = encryptedBytes; 79 | } else { 80 | body = new byte[byteBuf.readableBytes() - 2]; 81 | byteBuf.readBytes(body); 82 | } 83 | // 校验码 84 | int crcCode = byteBuf.readUnsignedShort(); 85 | ReferenceCountUtil.release(byteBuf); 86 | out.add(new OuterPacket(length, sn, id, gnsscenterId, version, encryptFlag, encryptKey, body, crcCode)); 87 | } 88 | 89 | } 90 | -------------------------------------------------------------------------------- /src/main/java/org/tucke/jtt809/encoder/Jtt809Encoder.java: -------------------------------------------------------------------------------- 1 | package org.tucke.jtt809.encoder; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.channel.ChannelHandlerContext; 5 | import io.netty.handler.codec.MessageToByteEncoder; 6 | import io.netty.util.Attribute; 7 | import org.tucke.jtt809.common.CRC16CCITT; 8 | import org.tucke.jtt809.common.Jtt809Constant; 9 | import org.tucke.jtt809.common.Jtt809Util; 10 | import org.tucke.jtt809.packet.common.OuterPacket; 11 | 12 | import java.util.concurrent.atomic.AtomicInteger; 13 | 14 | /** 15 | * @author tucke 16 | */ 17 | public class Jtt809Encoder extends MessageToByteEncoder { 18 | 19 | 20 | @SuppressWarnings("SpellCheckingInspection") 21 | @Override 22 | protected void encode(ChannelHandlerContext ctx, OuterPacket packet, ByteBuf out) throws Exception { 23 | if (packet == null) { 24 | return; 25 | } 26 | int gnsscenterId; 27 | if (ctx.channel().hasAttr(Jtt809Constant.NettyAttribute.GNSS_CENTER_ID)) { 28 | gnsscenterId = Integer.parseInt(ctx.channel().attr(Jtt809Constant.NettyAttribute.GNSS_CENTER_ID).get()); 29 | } else { 30 | gnsscenterId = packet.getGnsscenterId(); 31 | } 32 | byte[] body = packet.getBody(); 33 | if (body == null) { 34 | body = new byte[0]; 35 | } 36 | // 24 = 头标识[1] + 数据头[22 = 长度[4] + 序列号[4] + 数据类型[2] + 接入码[4] + 版本号[3] + 加密标识[1] + 密钥[4]] + 尾标识[1] 37 | int len = body.length + 24; 38 | out.markReaderIndex(); 39 | // 数据长度 40 | out.writeInt(len); 41 | // 序列号 42 | out.writeInt(ackSerialNo(ctx)); 43 | // 业务数据类型 44 | out.writeShort(packet.getId()); 45 | // 下级平台接入码 46 | out.writeInt(gnsscenterId); 47 | // 版本号 48 | out.writeByte(1); 49 | out.writeByte(0); 50 | out.writeByte(0); 51 | // 报文加密标识位 52 | out.writeByte(0); 53 | // 数据加密的密钥 54 | out.writeInt(0); 55 | // 数据体 56 | out.writeBytes(body); 57 | // 校验码 58 | byte[] crcBytes = new byte[out.readableBytes()]; 59 | out.readBytes(crcBytes); 60 | out.writeShort(CRC16CCITT.crc16(crcBytes)); 61 | 62 | // 转义 63 | out.resetReaderIndex(); 64 | byte[] escapeBytes = new byte[out.readableBytes()]; 65 | out.readBytes(escapeBytes); 66 | 67 | // 重置下标 68 | out.setIndex(0, 0); 69 | // 包头标识 70 | out.writeByte(Jtt809Constant.PACKET_HEAD_FLAG); 71 | // 数据内容 72 | out.writeBytes(Jtt809Util.escape(escapeBytes)); 73 | // 包尾标识 74 | out.writeByte(Jtt809Constant.PACKET_END_FLAG); 75 | } 76 | 77 | private int ackSerialNo(ChannelHandlerContext ctx) { 78 | Attribute serialNoAttribute = ctx.channel().attr(Jtt809Constant.NettyAttribute.PLATFORM_ACK_SERIAL_NO); 79 | AtomicInteger serialNo = serialNoAttribute.get(); 80 | if (serialNo == null) { 81 | serialNo = new AtomicInteger(); 82 | serialNoAttribute.set(serialNo); 83 | } 84 | int result = serialNo.getAndIncrement(); 85 | if (result >= Integer.MAX_VALUE) { 86 | serialNo.set(0); 87 | } 88 | return result; 89 | } 90 | 91 | } 92 | -------------------------------------------------------------------------------- /src/main/java/org/tucke/jtt809/handler/ProtocolHandler.java: -------------------------------------------------------------------------------- 1 | package org.tucke.jtt809.handler; 2 | 3 | import io.netty.channel.ChannelHandlerContext; 4 | import lombok.extern.slf4j.Slf4j; 5 | import org.tucke.jtt809.handler.protocol.Protocol; 6 | import org.tucke.jtt809.packet.common.OuterPacket; 7 | 8 | import java.util.HashSet; 9 | import java.util.Set; 10 | 11 | /** 12 | * @author tucke 13 | */ 14 | @Slf4j 15 | public class ProtocolHandler { 16 | 17 | private final Set protocols = new HashSet<>(); 18 | 19 | public void addProtocol(Protocol protocol) { 20 | protocols.add(protocol); 21 | } 22 | 23 | public void handle(ChannelHandlerContext ctx, OuterPacket packet) throws Exception { 24 | for (Protocol protocol : protocols) { 25 | if (protocol.support(packet.getId())) { 26 | protocol.handle(ctx, packet); 27 | return; 28 | } 29 | } 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/org/tucke/jtt809/handler/master/Jtt809MasterInboundHandler.java: -------------------------------------------------------------------------------- 1 | package org.tucke.jtt809.handler.master; 2 | 3 | import io.netty.channel.ChannelHandlerContext; 4 | import io.netty.channel.SimpleChannelInboundHandler; 5 | import lombok.extern.slf4j.Slf4j; 6 | import org.tucke.jtt809.handler.ProtocolHandler; 7 | import org.tucke.jtt809.handler.protocol.connect.ConnectProtocol; 8 | import org.tucke.jtt809.handler.protocol.exg.VehicleExgProtocol; 9 | import org.tucke.jtt809.packet.common.OuterPacket; 10 | 11 | /** 12 | * @author tucke 13 | */ 14 | @Slf4j 15 | public class Jtt809MasterInboundHandler extends SimpleChannelInboundHandler { 16 | 17 | private final ProtocolHandler protocolHandler; 18 | 19 | public Jtt809MasterInboundHandler() { 20 | super(true); 21 | protocolHandler = new ProtocolHandler(); 22 | protocolHandler.addProtocol(new ConnectProtocol()); 23 | protocolHandler.addProtocol(new VehicleExgProtocol()); 24 | } 25 | 26 | @Override 27 | protected void channelRead0(ChannelHandlerContext ctx, OuterPacket msg) throws Exception { 28 | protocolHandler.handle(ctx, msg); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/org/tucke/jtt809/handler/master/Jtt809MasterOutboundHandler.java: -------------------------------------------------------------------------------- 1 | package org.tucke.jtt809.handler.master; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.buffer.ByteBufUtil; 5 | import io.netty.channel.ChannelHandlerContext; 6 | import io.netty.channel.ChannelOutboundHandlerAdapter; 7 | import io.netty.channel.ChannelPromise; 8 | import lombok.extern.slf4j.Slf4j; 9 | 10 | /** 11 | * @author tucke 12 | */ 13 | @Slf4j 14 | public class Jtt809MasterOutboundHandler extends ChannelOutboundHandlerAdapter { 15 | 16 | @Override 17 | public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { 18 | if (log.isDebugEnabled()) { 19 | log.debug("主链路发送的消息:{}", ByteBufUtil.hexDump((ByteBuf) msg)); 20 | } 21 | super.write(ctx, msg, promise); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/org/tucke/jtt809/handler/protocol/Protocol.java: -------------------------------------------------------------------------------- 1 | package org.tucke.jtt809.handler.protocol; 2 | 3 | import io.netty.channel.ChannelHandlerContext; 4 | import org.tucke.jtt809.packet.common.OuterPacket; 5 | 6 | /** 7 | * 协议处理接口类 8 | * 9 | * @author tucke 10 | */ 11 | public interface Protocol { 12 | 13 | /** 14 | * 判断当前处理器是否能处理该数据类型 15 | * 16 | * @param id 数据类型 17 | * @return ture or false 18 | */ 19 | boolean support(int id); 20 | 21 | /** 22 | * 协议处理逻辑 23 | * 24 | * @param ctx netty 上下文 25 | * @param packet 外层包 26 | */ 27 | void handle(ChannelHandlerContext ctx, OuterPacket packet); 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/org/tucke/jtt809/handler/protocol/connect/ConnectProtocol.java: -------------------------------------------------------------------------------- 1 | package org.tucke.jtt809.handler.protocol.connect; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.buffer.Unpooled; 5 | import io.netty.channel.ChannelHandlerContext; 6 | import io.netty.util.ReferenceCountUtil; 7 | import lombok.extern.slf4j.Slf4j; 8 | import org.tucke.gnsscenter.GnssCenterService; 9 | import org.tucke.jtt809.Jtt809Client; 10 | import org.tucke.jtt809.Jtt809Server; 11 | import org.tucke.jtt809.common.Jtt809Constant; 12 | import org.tucke.jtt809.handler.protocol.Protocol; 13 | import org.tucke.jtt809.packet.common.OuterPacket; 14 | import org.tucke.jtt809.packet.connect.UpConnectPacket; 15 | import org.tucke.jtt809.packet.connect.UpDisConnectPacket; 16 | 17 | import java.net.InetSocketAddress; 18 | import java.util.Set; 19 | import java.util.concurrent.ThreadLocalRandom; 20 | 21 | /** 22 | * @author tucke 23 | */ 24 | @SuppressWarnings("AlibabaUndefineMagicConstant") 25 | @Slf4j 26 | public class ConnectProtocol implements Protocol { 27 | 28 | private static final Set DATA_TYPE = Set.of( 29 | Jtt809Constant.DataType.UP_CONNECT_REQ, 30 | Jtt809Constant.DataType.UP_DICONNECE_REQ, 31 | Jtt809Constant.DataType.UP_LINKTEST_REQ, 32 | Jtt809Constant.DataType.UP_DISCONNECT_INFORM, 33 | Jtt809Constant.DataType.UP_CLOSELINK_INFORM, 34 | Jtt809Constant.DataType.DOWN_CONNECT_RSP, 35 | Jtt809Constant.DataType.DOWN_DISCONNECT_RSP, 36 | Jtt809Constant.DataType.DOWN_LINKTEST_RSP 37 | ); 38 | 39 | @Override 40 | public boolean support(int id) { 41 | return DATA_TYPE.contains(id); 42 | } 43 | 44 | @Override 45 | public void handle(ChannelHandlerContext ctx, OuterPacket packet) { 46 | ByteBuf subBody; 47 | if (packet.getBody() == null) { 48 | subBody = Unpooled.buffer(); 49 | } else { 50 | subBody = Unpooled.wrappedBuffer(packet.getBody()); 51 | } 52 | switch (packet.getId()) { 53 | case Jtt809Constant.DataType.UP_CONNECT_REQ: 54 | login(ctx, packet, subBody); 55 | break; 56 | case Jtt809Constant.DataType.UP_DICONNECE_REQ: 57 | logout(ctx, packet, subBody); 58 | break; 59 | case Jtt809Constant.DataType.UP_LINKTEST_REQ: 60 | keepLink(ctx, packet, subBody); 61 | break; 62 | case Jtt809Constant.DataType.UP_DISCONNECT_INFORM: 63 | disConnectInform(ctx, packet, subBody); 64 | break; 65 | case Jtt809Constant.DataType.UP_CLOSELINK_INFORM: 66 | closeLinkInform(ctx, packet, subBody); 67 | break; 68 | case Jtt809Constant.DataType.DOWN_CONNECT_RSP: 69 | downConnectRsp(ctx, packet, subBody); 70 | break; 71 | case Jtt809Constant.DataType.DOWN_DISCONNECT_RSP: 72 | downDisConnectRsp(ctx, packet, subBody); 73 | break; 74 | case Jtt809Constant.DataType.DOWN_LINKTEST_RSP: 75 | downLinkTestRsp(ctx, packet, subBody); 76 | break; 77 | default: 78 | } 79 | ReferenceCountUtil.release(subBody); 80 | } 81 | 82 | /** 83 | * 处理下级平台登录请求 84 | * 链路类型:主链路 85 | */ 86 | private void login(ChannelHandlerContext ctx, OuterPacket packet, ByteBuf subBody) { 87 | UpConnectPacket.Request request = UpConnectPacket.decode(subBody); 88 | byte result = GnssCenterService.getInstance().validateLogin(packet.getGnsscenterId(), request); 89 | log.info("接入码:{},用户:{},密码:{},结果:{}。", packet.getGnsscenterId(), request.getUserId(), request.getPassword(), result); 90 | // 随机一个校验码 91 | int verifyCode = ThreadLocalRandom.current().nextInt(); 92 | byte[] body = UpConnectPacket.encode(new UpConnectPacket.Response(result, verifyCode)); 93 | // 应答 94 | OuterPacket out = new OuterPacket(Jtt809Constant.DataType.UP_CONNECT_RSP, body); 95 | ctx.writeAndFlush(out); 96 | // 接入成功就建立从链接,否则关闭链接 97 | if (result == 0x00) { 98 | Jtt809Server.add(packet.getGnsscenterId(), ctx.channel()); 99 | InetSocketAddress address = new InetSocketAddress(request.getDownLinkIp(), request.getDownLinkPort()); 100 | Jtt809Client.createClient(packet.getGnsscenterId(), address, new OuterPacket(Jtt809Constant.DataType.DOWN_CONNECT_REQ, body)); 101 | } else { 102 | Jtt809Client.close(packet.getGnsscenterId()); 103 | ctx.close(); 104 | } 105 | } 106 | 107 | /** 108 | * 处理下级平台注销请求 109 | * 链路类型:主链路 110 | */ 111 | private void logout(ChannelHandlerContext ctx, OuterPacket packet, ByteBuf subBody) { 112 | UpDisConnectPacket.Request request = UpDisConnectPacket.decode(subBody); 113 | log.warn("用户:{} 请求注销!", request.getUserId()); 114 | // 应答 115 | OuterPacket out = new OuterPacket(Jtt809Constant.DataType.UP_DISCONNECT_RSP, null); 116 | ctx.writeAndFlush(out); 117 | Jtt809Client.close(packet.getGnsscenterId()); 118 | ctx.close(); 119 | } 120 | 121 | /** 122 | * 保持连接 123 | * 链路类型:主链路 124 | */ 125 | private void keepLink(ChannelHandlerContext ctx, OuterPacket packet, ByteBuf subBody) { 126 | log.info("下级平台 {} 的保持连接消息", packet.getGnsscenterId()); 127 | // 应答 128 | OuterPacket out = new OuterPacket(Jtt809Constant.DataType.UP_LINKTEST_RSP, null); 129 | ctx.writeAndFlush(out); 130 | } 131 | 132 | /** 133 | * 下级平台往上级平台发送的中断通知 134 | * 链路类型:从链路 135 | */ 136 | private void disConnectInform(ChannelHandlerContext ctx, OuterPacket packet, ByteBuf subBody) { 137 | byte errorCode = subBody.readByte(); 138 | // 0x00:主链路断开,0x01:其他原因 139 | // 无需应答 140 | log.warn("主链路断开通知消息,通知发送方:{},原因是:{}", packet.getGnsscenterId(), errorCode == 0 ? "主链路断开" : "其他原因"); 141 | } 142 | 143 | /** 144 | * 下级平台主动关闭主从链路通知消息 145 | * 链路类型:从链路 146 | */ 147 | private void closeLinkInform(ChannelHandlerContext ctx, OuterPacket packet, ByteBuf subBody) { 148 | byte errorCode = subBody.readByte(); 149 | // 0x00:网关重启,0x01:其他原因 150 | // 无需应答 151 | log.warn("下级平台 {} 即将关闭主从链路,原因是:{}", packet.getGnsscenterId(), errorCode == 0 ? "网关重启" : "其他原因"); 152 | } 153 | 154 | /** 155 | * 从链路连接应答消息 156 | * 链路类型:从链路 157 | */ 158 | private void downConnectRsp(ChannelHandlerContext ctx, OuterPacket packet, ByteBuf subBody) { 159 | byte code = subBody.readByte(); 160 | String result = "未知"; 161 | if (code == 0x00) { 162 | Jtt809Client.add(packet.getGnsscenterId(), ctx.channel()); 163 | return; 164 | } else if (code == 0x01) { 165 | result = "校验码错误"; 166 | } else if (code == 0x02) { 167 | result = "资源紧张,稍后再连接(已经占用)"; 168 | } else if (code == 0x03) { 169 | result = "其他"; 170 | } 171 | log.info("下级平台 {} 连接结果:{}", packet.getGnsscenterId(), result); 172 | } 173 | 174 | /** 175 | * 从链路注销应答消息 176 | * 链路类型:从链路 177 | */ 178 | private void downDisConnectRsp(ChannelHandlerContext ctx, OuterPacket packet, ByteBuf subBody) { 179 | // 这是一条空消息 180 | log.warn("下级平台 {} 响应了从链路的注销请求消息", packet.getGnsscenterId()); 181 | } 182 | 183 | /** 184 | * 从链路连接保持应答消息 185 | * 链路类型:从链路 186 | */ 187 | private void downLinkTestRsp(ChannelHandlerContext ctx, OuterPacket packet, ByteBuf subBody) { 188 | // 这是一条空消息 189 | log.warn("下级平台 {} 响应了从链路的连接保持请求消息", packet.getGnsscenterId()); 190 | } 191 | 192 | } 193 | -------------------------------------------------------------------------------- /src/main/java/org/tucke/jtt809/handler/protocol/exg/VehicleExgProtocol.java: -------------------------------------------------------------------------------- 1 | package org.tucke.jtt809.handler.protocol.exg; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.buffer.Unpooled; 5 | import io.netty.channel.ChannelHandlerContext; 6 | import io.netty.util.ReferenceCountUtil; 7 | import lombok.extern.slf4j.Slf4j; 8 | import org.tucke.jtt809.common.Jtt809Constant; 9 | import org.tucke.jtt809.common.Jtt809Util; 10 | import org.tucke.jtt809.handler.protocol.Protocol; 11 | import org.tucke.jtt809.packet.common.OuterPacket; 12 | import org.tucke.jtt809.packet.upexg.UpExgHistoryPacket; 13 | import org.tucke.jtt809.packet.upexg.UpExgRealLocationPacket; 14 | import org.tucke.jtt809.packet.upexg.UpExgRegisterPacket; 15 | 16 | /** 17 | * @author tucke 18 | */ 19 | @Slf4j 20 | public class VehicleExgProtocol implements Protocol { 21 | 22 | @Override 23 | public boolean support(int id) { 24 | return id == Jtt809Constant.DataType.UP_EXG_MSG; 25 | } 26 | 27 | @Override 28 | public void handle(ChannelHandlerContext ctx, OuterPacket outerPacket) { 29 | ByteBuf subBody; 30 | if (outerPacket.getBody() == null) { 31 | subBody = Unpooled.buffer(); 32 | } else { 33 | subBody = Unpooled.wrappedBuffer(outerPacket.getBody()); 34 | } 35 | String vehicleNo = Jtt809Util.readGBKString(subBody, 21); 36 | Byte vehicleColor = subBody.readByte(); 37 | int dataType = subBody.readUnsignedShort(); 38 | int dataLength = subBody.readInt(); 39 | switch (dataType) { 40 | case Jtt809Constant.SubDataType.UP_EXG_MSG_REGISTER: 41 | UpExgRegisterPacket uep = UpExgRegisterPacket.decode(subBody); 42 | uep.complete(vehicleNo, vehicleColor); 43 | registerHandle(ctx, uep); 44 | break; 45 | case Jtt809Constant.SubDataType.UP_EXG_MSG_REAL_LOCATION: 46 | UpExgRealLocationPacket uerlp = UpExgRealLocationPacket.decode(subBody); 47 | uerlp.complete(vehicleNo, vehicleColor); 48 | realLocationHandle(ctx, uerlp); 49 | break; 50 | case Jtt809Constant.SubDataType.UP_EXG_MSG_HISTORY_LOCATION: 51 | UpExgHistoryPacket uehp = UpExgHistoryPacket.decode(subBody); 52 | uehp.complete(vehicleNo, vehicleColor); 53 | historyHandle(ctx, uehp); 54 | break; 55 | default: 56 | } 57 | ReferenceCountUtil.release(subBody); 58 | } 59 | 60 | private void registerHandle(ChannelHandlerContext ctx, UpExgRegisterPacket packet) { 61 | log.info("上传车辆注册信息:{}", packet.toString()); 62 | } 63 | 64 | private void realLocationHandle(ChannelHandlerContext ctx, UpExgRealLocationPacket packet) { 65 | log.info("实时上传车辆定位信息:{}", packet.toString()); 66 | } 67 | 68 | private void historyHandle(ChannelHandlerContext ctx, UpExgHistoryPacket packet) { 69 | log.info("补报上传车辆定位信息:{}", packet.toString()); 70 | } 71 | 72 | } 73 | -------------------------------------------------------------------------------- /src/main/java/org/tucke/jtt809/handler/slave/Jtt809SlaveInboundHandler.java: -------------------------------------------------------------------------------- 1 | package org.tucke.jtt809.handler.slave; 2 | 3 | import io.netty.channel.ChannelHandlerContext; 4 | import io.netty.channel.EventLoop; 5 | import io.netty.channel.SimpleChannelInboundHandler; 6 | import io.netty.handler.timeout.IdleState; 7 | import io.netty.handler.timeout.IdleStateEvent; 8 | import lombok.extern.slf4j.Slf4j; 9 | import org.tucke.jtt809.Jtt809Client; 10 | import org.tucke.jtt809.common.Jtt809Constant; 11 | import org.tucke.jtt809.handler.ProtocolHandler; 12 | import org.tucke.jtt809.handler.protocol.connect.ConnectProtocol; 13 | import org.tucke.jtt809.handler.protocol.exg.VehicleExgProtocol; 14 | import org.tucke.jtt809.packet.common.OuterPacket; 15 | 16 | import java.util.concurrent.TimeUnit; 17 | 18 | /** 19 | * @author tucke 20 | */ 21 | @SuppressWarnings("SpellCheckingInspection") 22 | @Slf4j 23 | public class Jtt809SlaveInboundHandler extends SimpleChannelInboundHandler { 24 | 25 | private Integer gnsscenterId; 26 | private OuterPacket activePacket; 27 | 28 | private final ProtocolHandler protocolHandler; 29 | 30 | public Jtt809SlaveInboundHandler() { 31 | super(true); 32 | protocolHandler = new ProtocolHandler(); 33 | protocolHandler.addProtocol(new ConnectProtocol()); 34 | protocolHandler.addProtocol(new VehicleExgProtocol()); 35 | } 36 | 37 | public Jtt809SlaveInboundHandler(Integer gnsscenterId, OuterPacket activePacket) { 38 | this(); 39 | this.gnsscenterId = gnsscenterId; 40 | this.activePacket = activePacket; 41 | } 42 | 43 | @Override 44 | protected void channelRead0(ChannelHandlerContext ctx, OuterPacket msg) throws Exception { 45 | log.debug("收到从链路一条消息:{}5d", msg); 46 | protocolHandler.handle(ctx, msg); 47 | } 48 | 49 | @Override 50 | public void channelRegistered(ChannelHandlerContext ctx) throws Exception { 51 | super.channelRegistered(ctx); 52 | } 53 | 54 | @Override 55 | public void channelUnregistered(ChannelHandlerContext ctx) throws Exception { 56 | super.channelUnregistered(ctx); 57 | } 58 | 59 | @Override 60 | public void channelActive(ChannelHandlerContext ctx) throws Exception { 61 | log.debug("从链路下级平台 {} 通道激活", gnsscenterId); 62 | if (activePacket != null) { 63 | ctx.writeAndFlush(activePacket); 64 | } 65 | super.channelActive(ctx); 66 | } 67 | 68 | @Override 69 | public void channelInactive(ChannelHandlerContext ctx) throws Exception { 70 | log.debug("从链路下级平台 {} 通道断开, 准备重连。。。", gnsscenterId); 71 | EventLoop eventLoop = ctx.channel().eventLoop(); 72 | // 每 5 秒进行一次重连 73 | eventLoop.schedule(() -> Jtt809Client.reconnect(gnsscenterId, activePacket), 5, TimeUnit.SECONDS); 74 | super.channelInactive(ctx); 75 | } 76 | 77 | @Override 78 | public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { 79 | if (evt instanceof IdleStateEvent) { 80 | IdleStateEvent event = (IdleStateEvent) evt; 81 | if (event.state() == IdleState.WRITER_IDLE) { 82 | // 从链路连接保持请求 83 | OuterPacket packet = new OuterPacket(); 84 | packet.setId(Jtt809Constant.DataType.DOWN_LINKTEST_REQ); 85 | ctx.writeAndFlush(packet); 86 | } 87 | } 88 | super.userEventTriggered(ctx, evt); 89 | } 90 | 91 | @Override 92 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { 93 | log.error("从链路下级平台 {} 异常:{}", gnsscenterId, cause); 94 | super.exceptionCaught(ctx, cause); 95 | } 96 | 97 | } 98 | -------------------------------------------------------------------------------- /src/main/java/org/tucke/jtt809/handler/slave/Jtt809SlaveOutBoundHandler.java: -------------------------------------------------------------------------------- 1 | package org.tucke.jtt809.handler.slave; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.buffer.ByteBufUtil; 5 | import io.netty.channel.ChannelHandlerContext; 6 | import io.netty.channel.ChannelOutboundHandlerAdapter; 7 | import io.netty.channel.ChannelPromise; 8 | import lombok.extern.slf4j.Slf4j; 9 | 10 | /** 11 | * @author tucke 12 | */ 13 | @Slf4j 14 | public class Jtt809SlaveOutBoundHandler extends ChannelOutboundHandlerAdapter { 15 | 16 | @Override 17 | public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { 18 | if (log.isDebugEnabled()) { 19 | log.debug("从链路发送的消息:{}", ByteBufUtil.hexDump((ByteBuf) msg)); 20 | } 21 | super.write(ctx, msg, promise); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/org/tucke/jtt809/packet/DownTotalReceivePacket.java: -------------------------------------------------------------------------------- 1 | package org.tucke.jtt809.packet; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.buffer.ByteBufUtil; 5 | import io.netty.buffer.Unpooled; 6 | import lombok.Data; 7 | 8 | /** 9 | * @author tucke 10 | */ 11 | @Data 12 | public class DownTotalReceivePacket { 13 | 14 | private Integer dynamicInfoTotal; 15 | private Long startTime; 16 | private Long endTime; 17 | 18 | /** 19 | * 编码登录回复报文 20 | */ 21 | public static byte[] encode(DownTotalReceivePacket packet) { 22 | ByteBuf byteBuf = Unpooled.buffer(5); 23 | byteBuf.writeInt(packet.getDynamicInfoTotal()); 24 | byteBuf.writeLong(packet.getStartTime()); 25 | byteBuf.writeLong(packet.getEndTime()); 26 | byte[] bytes = ByteBufUtil.getBytes(byteBuf); 27 | byteBuf.release(); 28 | return bytes; 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/org/tucke/jtt809/packet/common/OuterPacket.java: -------------------------------------------------------------------------------- 1 | package org.tucke.jtt809.packet.common; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Data; 5 | import lombok.NoArgsConstructor; 6 | 7 | import java.io.Serializable; 8 | 9 | /** 10 | * @author tucke 11 | */ 12 | @SuppressWarnings("SpellCheckingInspection") 13 | @AllArgsConstructor 14 | @NoArgsConstructor 15 | @Data 16 | public class OuterPacket implements Serializable { 17 | 18 | private static final long serialVersionUID = 1L; 19 | 20 | /** 21 | * 数据长度(包括头标识、数据头、数据体和尾标识) 22 | */ 23 | private long length; 24 | /** 25 | * 报文序列号 26 | * 占用四个字节,为发送信息的序列号,用于接收方检测是否有信息的丢失,上级平台和下级平台接自己发送数据包的个数计数,互不影响。 27 | * 程序开始运行时等于零,发送第一帧数据时开始计数,到最大数后自动归零 28 | */ 29 | private long sn; 30 | /** 31 | * 业务数据类型 32 | */ 33 | private int id; 34 | /** 35 | * 下级平台接入码,上级平台给下级平台分配唯一标识码 36 | */ 37 | private int gnsscenterId; 38 | /** 39 | * 协议版本号标识,上下级平台之间采用的标准协议版编号 40 | * 长度为 3 个字节来表示,0x01 0x02 0x0F 表示的版本号是 v1.2.15,以此类推 41 | */ 42 | private String version; 43 | /** 44 | * 报文加密标识位 45 | * 0 - 报文不加密 46 | * 1 - 报文加密, 后继相应业务的数据体采用 ENCRYPT_KEY 对应的密钥进行加密处理 47 | */ 48 | private byte encryptFlag; 49 | /** 50 | * 数据加密解密的密匙,长度为 4 个字节 51 | */ 52 | private long encryptKey; 53 | /** 54 | * 消息体 55 | */ 56 | private byte[] body; 57 | /** 58 | * 数据 CRC 校验码 59 | */ 60 | private int crcCode; 61 | 62 | public OuterPacket(int id, byte[] body) { 63 | this.id = id; 64 | this.body = body; 65 | } 66 | 67 | public OuterPacket(int id, int gnsscenterId, byte[] body) { 68 | this.id = id; 69 | this.gnsscenterId = gnsscenterId; 70 | this.body = body; 71 | } 72 | 73 | } 74 | -------------------------------------------------------------------------------- /src/main/java/org/tucke/jtt809/packet/connect/DownConnectPacket.java: -------------------------------------------------------------------------------- 1 | package org.tucke.jtt809.packet.connect; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.buffer.ByteBufUtil; 5 | import io.netty.buffer.Unpooled; 6 | 7 | /** 8 | * @author tucke 9 | */ 10 | public class DownConnectPacket { 11 | 12 | public static byte[] encode(int verifyCode) { 13 | ByteBuf byteBuf = Unpooled.buffer(4); 14 | byteBuf.writeInt(verifyCode); 15 | byte[] bytes = ByteBufUtil.getBytes(byteBuf); 16 | byteBuf.release(); 17 | return bytes; 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/org/tucke/jtt809/packet/connect/UpConnectPacket.java: -------------------------------------------------------------------------------- 1 | package org.tucke.jtt809.packet.connect; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.buffer.ByteBufUtil; 5 | import io.netty.buffer.Unpooled; 6 | import lombok.AllArgsConstructor; 7 | import lombok.Data; 8 | import lombok.NoArgsConstructor; 9 | import org.tucke.jtt809.common.Jtt809Util; 10 | 11 | /** 12 | * @author tucke 13 | */ 14 | public class UpConnectPacket { 15 | 16 | @AllArgsConstructor 17 | @NoArgsConstructor 18 | @Data 19 | public static class Request { 20 | /** 21 | * 用户名 22 | */ 23 | private int userId; 24 | /** 25 | * 密码 26 | */ 27 | private String password; 28 | /** 29 | * 下级平台提供对应的从链路服务端 IP 地址 30 | */ 31 | private String downLinkIp; 32 | /** 33 | * 下级平台提供对应的从链路服务器端口号 34 | */ 35 | private short downLinkPort; 36 | } 37 | 38 | @AllArgsConstructor 39 | @NoArgsConstructor 40 | @Data 41 | public static class Response { 42 | /** 43 | * 验证结果 44 | *

45 | * 0x00 - 成功 46 | * 0x01 - IP 地址不正确 47 | * 0x02 - 接入码不正确 48 | * 0x03 - 用户没用注册 49 | * 0x04 - 密码错误 50 | * 0x05 - 资源紧张,稍后再连接(已经占用) 51 | * 0x06 - 其他 52 | */ 53 | private byte result; 54 | /** 55 | * 校验码 56 | */ 57 | private int verifyCode; 58 | } 59 | 60 | /** 61 | * 解析登录报文 62 | */ 63 | public static Request decode(ByteBuf byteBuf) { 64 | int userId = byteBuf.readInt(); 65 | String password = Jtt809Util.readGBKString(byteBuf, 8); 66 | String ip = Jtt809Util.readGBKString(byteBuf, 32); 67 | short port = byteBuf.readShort(); 68 | return new Request(userId, password, ip, port); 69 | } 70 | 71 | /** 72 | * 编码登录回复报文 73 | */ 74 | public static byte[] encode(Response response) { 75 | ByteBuf byteBuf = Unpooled.buffer(5); 76 | byteBuf.writeByte(response.getResult()); 77 | byteBuf.writeInt(response.getVerifyCode()); 78 | byte[] bytes = ByteBufUtil.getBytes(byteBuf); 79 | byteBuf.release(); 80 | return bytes; 81 | } 82 | 83 | } 84 | -------------------------------------------------------------------------------- /src/main/java/org/tucke/jtt809/packet/connect/UpDisConnectPacket.java: -------------------------------------------------------------------------------- 1 | package org.tucke.jtt809.packet.connect; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Data; 6 | import lombok.NoArgsConstructor; 7 | import org.tucke.jtt809.common.Jtt809Util; 8 | 9 | /** 10 | * @author tucke 11 | */ 12 | public class UpDisConnectPacket { 13 | 14 | @AllArgsConstructor 15 | @NoArgsConstructor 16 | @Data 17 | public static class Request { 18 | /** 19 | * 用户名 20 | */ 21 | private int userId; 22 | /** 23 | * 密码 24 | */ 25 | private String password; 26 | } 27 | 28 | /** 29 | * 解析注销报文 30 | */ 31 | public static Request decode(ByteBuf byteBuf) { 32 | int userId = byteBuf.readInt(); 33 | String password = Jtt809Util.readGBKString(byteBuf, 8); 34 | return new Request(userId, password); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/org/tucke/jtt809/packet/upexg/UpExgHistoryPacket.java: -------------------------------------------------------------------------------- 1 | package org.tucke.jtt809.packet.upexg; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import lombok.Data; 5 | import lombok.EqualsAndHashCode; 6 | import lombok.ToString; 7 | 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | 11 | /** 12 | * @author tucke 13 | */ 14 | @ToString(callSuper = true) 15 | @EqualsAndHashCode(callSuper = true) 16 | @Data 17 | public class UpExgHistoryPacket extends UpExgPacket { 18 | 19 | private byte cnt; 20 | private List locations; 21 | 22 | public static UpExgHistoryPacket decode(ByteBuf byteBuf) { 23 | UpExgHistoryPacket packet = new UpExgHistoryPacket(); 24 | byte cnt = byteBuf.readByte(); 25 | packet.setCnt(byteBuf.readByte()); 26 | List locations = new ArrayList<>(); 27 | for (int i = cnt; i > 0; i--) { 28 | locations.add(UpExgRealLocationPacket.decode(byteBuf)); 29 | } 30 | packet.setLocations(locations); 31 | return packet; 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/org/tucke/jtt809/packet/upexg/UpExgPacket.java: -------------------------------------------------------------------------------- 1 | package org.tucke.jtt809.packet.upexg; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import lombok.Data; 5 | 6 | /** 7 | * @author tucke 8 | */ 9 | @Data 10 | public class UpExgPacket { 11 | 12 | private String vehicleNo; 13 | private byte vehicleColor; 14 | private short dataType; 15 | private int dataLength; 16 | private ByteBuf data; 17 | 18 | public void complete(String vehicleNo, Byte vehicleColor) { 19 | this.setVehicleNo(vehicleNo); 20 | this.setVehicleColor(vehicleColor); 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/org/tucke/jtt809/packet/upexg/UpExgRealLocationPacket.java: -------------------------------------------------------------------------------- 1 | package org.tucke.jtt809.packet.upexg; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import lombok.Data; 5 | import lombok.EqualsAndHashCode; 6 | import lombok.ToString; 7 | import lombok.extern.slf4j.Slf4j; 8 | import org.apache.commons.lang3.time.DateUtils; 9 | import org.tucke.jtt809.common.Jtt809Util; 10 | 11 | import java.math.BigDecimal; 12 | import java.math.RoundingMode; 13 | import java.text.ParseException; 14 | 15 | /** 16 | * @author tucke 17 | */ 18 | @Slf4j 19 | @ToString(callSuper = true) 20 | @EqualsAndHashCode(callSuper = true) 21 | @Data 22 | public class UpExgRealLocationPacket extends UpExgPacket { 23 | 24 | private static final BigDecimal LAT_LON_DIVISOR = new BigDecimal(1000000); 25 | 26 | private byte encrypt; 27 | private long timestamp; 28 | private double lon; 29 | private double lat; 30 | private short vec1; 31 | private short vec2; 32 | private int vec3; 33 | private short direction; 34 | private short altitude; 35 | private int state; 36 | private int alarm; 37 | 38 | public static UpExgRealLocationPacket decode(ByteBuf byteBuf) { 39 | UpExgRealLocationPacket packet = new UpExgRealLocationPacket(); 40 | packet.setEncrypt(byteBuf.readByte()); 41 | long time = Jtt809Util.parseDateTime(byteBuf); 42 | packet.setTimestamp(time); 43 | BigDecimal lon = new BigDecimal(String.valueOf(byteBuf.readInt())); 44 | BigDecimal lat = new BigDecimal(String.valueOf(byteBuf.readInt())); 45 | try { 46 | packet.setLon(lon.divide(LAT_LON_DIVISOR, 6, RoundingMode.UNNECESSARY).doubleValue()); 47 | packet.setLat(lat.divide(LAT_LON_DIVISOR, 6, RoundingMode.UNNECESSARY).doubleValue()); 48 | } catch (ArithmeticException e) { 49 | log.warn("经纬度 [{}, {}] 解析错误", lon, lat); 50 | } 51 | packet.setVec1(byteBuf.readShort()); 52 | packet.setVec2(byteBuf.readShort()); 53 | packet.setVec3(byteBuf.readInt()); 54 | packet.setDirection(byteBuf.readShort()); 55 | packet.setAltitude(byteBuf.readShort()); 56 | packet.setState(byteBuf.readInt()); 57 | packet.setAlarm(byteBuf.readInt()); 58 | return packet; 59 | } 60 | 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/org/tucke/jtt809/packet/upexg/UpExgRegisterPacket.java: -------------------------------------------------------------------------------- 1 | package org.tucke.jtt809.packet.upexg; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import lombok.Data; 5 | import lombok.EqualsAndHashCode; 6 | import lombok.ToString; 7 | import org.tucke.jtt809.common.Jtt809Util; 8 | 9 | /** 10 | * @author tucke 11 | */ 12 | @ToString(callSuper = true) 13 | @EqualsAndHashCode(callSuper = true) 14 | @Data 15 | public class UpExgRegisterPacket extends UpExgPacket { 16 | 17 | private String platformId; 18 | private String producerId; 19 | private String terminalModelType; 20 | private String terminalId; 21 | private String terminalSimCode; 22 | 23 | public static UpExgRegisterPacket decode(ByteBuf byteBuf) { 24 | UpExgRegisterPacket packet = new UpExgRegisterPacket(); 25 | packet.setPlatformId(Jtt809Util.readGBKString(byteBuf, 11)); 26 | packet.setProducerId(Jtt809Util.readGBKString(byteBuf, 11)); 27 | packet.setTerminalModelType(Jtt809Util.readGBKString(byteBuf, 8)); 28 | packet.setTerminalId(Jtt809Util.readGBKString(byteBuf, 7)); 29 | packet.setTerminalSimCode(Jtt809Util.readGBKString(byteBuf, 12)); 30 | return packet; 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/org/tucke/net/NettyClient.java: -------------------------------------------------------------------------------- 1 | package org.tucke.net; 2 | 3 | import io.netty.bootstrap.Bootstrap; 4 | import io.netty.channel.ChannelFuture; 5 | import io.netty.channel.ChannelHandler; 6 | import io.netty.channel.ChannelOption; 7 | import io.netty.channel.EventLoopGroup; 8 | import io.netty.channel.nio.NioEventLoopGroup; 9 | import io.netty.channel.socket.nio.NioSocketChannel; 10 | import lombok.Data; 11 | import lombok.extern.slf4j.Slf4j; 12 | 13 | import java.net.InetSocketAddress; 14 | import java.net.SocketAddress; 15 | 16 | /** 17 | * @author tucke 18 | */ 19 | @Slf4j 20 | @Data 21 | public class NettyClient { 22 | 23 | private final String name; 24 | private final SocketAddress address; 25 | private final ChannelHandler handler; 26 | 27 | private EventLoopGroup group; 28 | 29 | public NettyClient(String name, SocketAddress address, ChannelHandler handler) { 30 | this.name = name; 31 | this.address = address; 32 | this.handler = handler; 33 | } 34 | 35 | public NettyClient(String name, String host, int port, ChannelHandler handler) { 36 | this.name = name; 37 | this.address = new InetSocketAddress(host, port); 38 | this.handler = handler; 39 | } 40 | 41 | public void connect() throws Exception { 42 | // 配置客户端NIO线程组 43 | group = new NioEventLoopGroup(); 44 | Bootstrap bootstrap = new Bootstrap(); 45 | bootstrap.group(group) 46 | .channel(NioSocketChannel.class) 47 | .remoteAddress(address) 48 | .option(ChannelOption.TCP_NODELAY, true) 49 | .option(ChannelOption.SO_KEEPALIVE, true) 50 | .handler(handler); 51 | ChannelFuture channelFuture = bootstrap.connect(); 52 | channelFuture.addListener(future -> { 53 | if (future.isSuccess()) { 54 | log.info("{}连接成功,远端地址为:{}", name, address.toString()); 55 | } 56 | }); 57 | } 58 | 59 | public void shutdown() { 60 | // 优雅退出,释放线程池资源 61 | if (group != null) { 62 | group.shutdownGracefully(); 63 | } 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/org/tucke/net/NettyServer.java: -------------------------------------------------------------------------------- 1 | package org.tucke.net; 2 | 3 | import io.netty.bootstrap.ServerBootstrap; 4 | import io.netty.buffer.UnpooledByteBufAllocator; 5 | import io.netty.channel.ChannelFuture; 6 | import io.netty.channel.ChannelHandler; 7 | import io.netty.channel.ChannelOption; 8 | import io.netty.channel.EventLoopGroup; 9 | import io.netty.channel.nio.NioEventLoopGroup; 10 | import io.netty.channel.socket.nio.NioServerSocketChannel; 11 | import lombok.extern.slf4j.Slf4j; 12 | 13 | /** 14 | * @author tucke 15 | */ 16 | @Slf4j 17 | public class NettyServer { 18 | 19 | private final String name; 20 | private final ChannelHandler handler; 21 | 22 | private EventLoopGroup bossGroup; 23 | private EventLoopGroup workerGroup; 24 | 25 | public NettyServer(String name, ChannelHandler handler) { 26 | this.name = name; 27 | this.handler = handler; 28 | } 29 | 30 | public void bind(int port) throws InterruptedException { 31 | ServerBootstrap bootstrap = new ServerBootstrap(); 32 | // 配置NIO线程组 33 | bossGroup = new NioEventLoopGroup(); 34 | workerGroup = new NioEventLoopGroup(); 35 | bootstrap.group(bossGroup, workerGroup) 36 | .channel(NioServerSocketChannel.class) 37 | // BACKLOG用于构造服务端套接字ServerSocket对象,标识当服务器请求处理线程全满时,用于临时存放已完成三次握手的请求的队列的最大长度。 38 | .option(ChannelOption.SO_BACKLOG, 128) 39 | // Socket参数,连接保活,默认值为False。启用该功能时,TCP会主动探测空闲连接的有效性。 40 | // 可以将此功能视为TCP的心跳机制,需要注意的是:默认的心跳间隔是7200s即2小时。Netty默认关闭该功能。 41 | .childOption(ChannelOption.SO_KEEPALIVE, true) 42 | // 在TCP/IP协议中,无论发送多少数据,总是要在数据前面加上协议头,同时,对方接收到数据,也需要发送ACK表示确认。 43 | // 为了尽可能的利用网络带宽,TCP总是希望尽可能的发送足够大的数据。这里就涉及到一个名为Nagle的算法,该算法的目的就是为了尽可能发送大块数据,避免网络中充斥着许多小数据块。 44 | // TCP_NODELAY就是用于启用或关于Nagle算法。如果要求高实时性,有数据发送时就马上发送,就将该选项设置为true关闭Nagle算法;如果要减少发送次数减少网络交互,就设置为false等累积一定大小后再发送。默认为false。 45 | .childOption(ChannelOption.TCP_NODELAY, true) 46 | // Netty参数,ByteBuf的分配器(重用缓冲区) 47 | .childOption(ChannelOption.ALLOCATOR, UnpooledByteBufAllocator.DEFAULT) 48 | .childHandler(handler); 49 | // 绑定端口同步等待 50 | ChannelFuture future = bootstrap.bind(port).sync(); 51 | log.debug("{} server start listen at {}", name, port); 52 | // 等待监听端口关闭 53 | future.channel().closeFuture().addListener(f -> shutdown()); 54 | } 55 | 56 | public void shutdown() { 57 | // 优雅退出,释放线程池资源 58 | if (bossGroup != null) { 59 | bossGroup.shutdownGracefully(); 60 | } 61 | if (workerGroup != null) { 62 | workerGroup.shutdownGracefully(); 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | logging: 2 | level: debug 3 | 4 | jtt809: 5 | port: 5200 6 | -------------------------------------------------------------------------------- /src/test/java/org/tucke/inferior/client/InferiorClientInboundHandler.java: -------------------------------------------------------------------------------- 1 | package org.tucke.inferior.client; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.buffer.ByteBufUtil; 5 | import io.netty.buffer.Unpooled; 6 | import io.netty.channel.ChannelHandlerContext; 7 | import io.netty.channel.SimpleChannelInboundHandler; 8 | import io.netty.handler.timeout.IdleState; 9 | import io.netty.handler.timeout.IdleStateEvent; 10 | import org.tucke.jtt809.common.Jtt809Constant; 11 | import org.tucke.jtt809.packet.common.OuterPacket; 12 | 13 | import java.nio.charset.Charset; 14 | 15 | public class InferiorClientInboundHandler extends SimpleChannelInboundHandler { 16 | 17 | @Override 18 | protected void channelRead0(ChannelHandlerContext ctx, OuterPacket msg) throws Exception { 19 | System.out.println(msg.toString()); 20 | } 21 | 22 | @Override 23 | public void channelRegistered(ChannelHandlerContext ctx) throws Exception { 24 | System.out.println("channelRegistered"); 25 | super.channelRegistered(ctx); 26 | } 27 | 28 | @Override 29 | public void channelUnregistered(ChannelHandlerContext ctx) throws Exception { 30 | System.out.println("channelUnregistered"); 31 | super.channelUnregistered(ctx); 32 | } 33 | 34 | @Override 35 | public void channelActive(ChannelHandlerContext ctx) throws Exception { 36 | System.out.println("channelActive"); 37 | ctx.channel().attr(Jtt809Constant.NettyAttribute.GNSS_CENTER_ID).setIfAbsent("95277"); 38 | 39 | ByteBuf byteBuf = Unpooled.buffer(); 40 | byteBuf.writeInt(2021); 41 | byte[] pwd = new byte[8]; 42 | byte[] pwdBytes = "1234560".getBytes(Charset.forName("GBK")); 43 | System.arraycopy(pwdBytes, 0, pwd, 0, pwdBytes.length); 44 | byteBuf.writeBytes(pwd); 45 | byte[] ip = new byte[32]; 46 | byte[] ipBytes = "192.168.12.6".getBytes(Charset.forName("GBK")); 47 | System.arraycopy(ipBytes, 0, ip, 0, ipBytes.length); 48 | byteBuf.writeBytes(ip); 49 | byteBuf.writeShort(5300); 50 | 51 | OuterPacket packet = new OuterPacket(); 52 | packet.setId(Jtt809Constant.DataType.UP_CONNECT_REQ); 53 | packet.setBody(ByteBufUtil.getBytes(byteBuf)); 54 | byteBuf.release(); 55 | 56 | ctx.writeAndFlush(packet); 57 | super.channelActive(ctx); 58 | } 59 | 60 | @Override 61 | public void channelInactive(ChannelHandlerContext ctx) throws Exception { 62 | System.out.println("channelInactive"); 63 | super.channelInactive(ctx); 64 | } 65 | 66 | @Override 67 | public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { 68 | if (evt instanceof IdleStateEvent) { 69 | IdleStateEvent event = (IdleStateEvent) evt; 70 | if (event.state() == IdleState.WRITER_IDLE) { 71 | OuterPacket packet = new OuterPacket(); 72 | packet.setId(Jtt809Constant.DataType.UP_LINKTEST_REQ); 73 | ctx.writeAndFlush(packet); 74 | } 75 | } 76 | super.userEventTriggered(ctx, evt); 77 | } 78 | 79 | @Override 80 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { 81 | System.out.println("exceptionCaught"); 82 | super.exceptionCaught(ctx, cause); 83 | } 84 | 85 | } 86 | -------------------------------------------------------------------------------- /src/test/java/org/tucke/inferior/client/InferiorClientTest.java: -------------------------------------------------------------------------------- 1 | package org.tucke.inferior.client; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.buffer.Unpooled; 5 | import io.netty.channel.Channel; 6 | import io.netty.channel.ChannelInitializer; 7 | import io.netty.handler.codec.DelimiterBasedFrameDecoder; 8 | import io.netty.handler.timeout.IdleStateHandler; 9 | import org.tucke.jtt809.common.Jtt809Constant; 10 | import org.tucke.jtt809.decoder.Jtt809Decoder; 11 | import org.tucke.jtt809.encoder.Jtt809Encoder; 12 | import org.tucke.net.NettyClient; 13 | 14 | import java.util.concurrent.TimeUnit; 15 | 16 | public class InferiorClientTest { 17 | 18 | public static void main(String[] args) throws Exception { 19 | ByteBuf packetEndFlag = Unpooled.wrappedBuffer(new byte[]{Jtt809Constant.PACKET_END_FLAG}); 20 | 21 | NettyClient client = new NettyClient("InferiorClientTest", "localhost", 5200, new ChannelInitializer<>() { 22 | @Override 23 | protected void initChannel(Channel ch) throws Exception { 24 | ch.pipeline().addLast(new IdleStateHandler(0, 55, 0, TimeUnit.SECONDS)); 25 | ch.pipeline().addLast(new Jtt809Encoder()); 26 | ch.pipeline().addLast(new DelimiterBasedFrameDecoder(2048, packetEndFlag)); 27 | ch.pipeline().addLast(new Jtt809Decoder()); 28 | ch.pipeline().addLast(new InferiorClientInboundHandler()); 29 | } 30 | }); 31 | client.connect(); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/test/java/org/tucke/inferior/server/InferiorServerInboundHandler.java: -------------------------------------------------------------------------------- 1 | package org.tucke.inferior.server; 2 | 3 | import io.netty.channel.ChannelHandlerContext; 4 | import io.netty.channel.SimpleChannelInboundHandler; 5 | import org.tucke.jtt809.packet.common.OuterPacket; 6 | 7 | public class InferiorServerInboundHandler extends SimpleChannelInboundHandler { 8 | 9 | @Override 10 | protected void channelRead0(ChannelHandlerContext ctx, OuterPacket msg) throws Exception { 11 | System.out.println(msg); 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /src/test/java/org/tucke/inferior/server/InferiorServerTest.java: -------------------------------------------------------------------------------- 1 | package org.tucke.inferior.server; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.buffer.Unpooled; 5 | import io.netty.channel.Channel; 6 | import io.netty.channel.ChannelInitializer; 7 | import io.netty.handler.codec.DelimiterBasedFrameDecoder; 8 | import io.netty.handler.timeout.ReadTimeoutHandler; 9 | import org.tucke.jtt809.common.Jtt809Constant; 10 | import org.tucke.jtt809.decoder.Jtt809Decoder; 11 | import org.tucke.jtt809.encoder.Jtt809Encoder; 12 | import org.tucke.jtt809.handler.master.Jtt809MasterOutboundHandler; 13 | import org.tucke.net.NettyServer; 14 | 15 | public class InferiorServerTest { 16 | 17 | public static void main(String[] args) throws InterruptedException { 18 | ByteBuf packetEndFlag = Unpooled.wrappedBuffer(new byte[]{Jtt809Constant.PACKET_END_FLAG}); 19 | NettyServer nettyServer = new NettyServer(Jtt809Constant.SERVER_NAME, new ChannelInitializer<>() { 20 | @Override 21 | protected void initChannel(Channel ch) throws Exception { 22 | // 连续 3min 未收到下级平台发送的从链路保持应答数据包,则认为下级平台已经失去连接,将主动断开数据传输从链路。 23 | // 考虑网络问题,这里设置为 5 分钟 24 | ch.pipeline().addLast(new ReadTimeoutHandler(300)); 25 | ch.pipeline().addLast(new Jtt809MasterOutboundHandler()); 26 | ch.pipeline().addLast(new Jtt809Encoder()); 27 | ch.pipeline().addLast(new DelimiterBasedFrameDecoder(2048, packetEndFlag)); 28 | ch.pipeline().addLast(new Jtt809Decoder()); 29 | ch.pipeline().addLast(new InferiorServerInboundHandler()); 30 | } 31 | }); 32 | nettyServer.bind(5300); 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/test/java/org/tucke/packet/PacketTest.java: -------------------------------------------------------------------------------- 1 | package org.tucke.packet; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.buffer.ByteBufUtil; 5 | import io.netty.buffer.Unpooled; 6 | import io.netty.util.ReferenceCountUtil; 7 | import org.tucke.gnsscenter.GnssCenterService; 8 | import org.tucke.jtt809.common.CRC16CCITT; 9 | import org.tucke.jtt809.common.Jtt809Constant; 10 | import org.tucke.jtt809.common.Jtt809Util; 11 | import org.tucke.jtt809.packet.common.OuterPacket; 12 | 13 | import java.nio.charset.StandardCharsets; 14 | 15 | public class PacketTest { 16 | 17 | public static void main(String[] args) { 18 | byte[] body = "这是测试的数据啊啊啊啊啊啊".getBytes(StandardCharsets.UTF_8); 19 | ByteBuf buf = encode(body); 20 | String dump = ByteBufUtil.hexDump(buf); 21 | // 5b0000003c000000011001000025370102050000000000e8bf99e698afe6b58be8af95e79a84e695b0e68daee5958ae5958ae5958ae5958ae5958ae5958ab8535d 22 | System.out.println(dump); 23 | System.out.println(); 24 | 25 | ByteBuf msg = Unpooled.wrappedBuffer(ByteBufUtil.decodeHexDump(dump, 0, dump.length() - 2)); 26 | OuterPacket packet = decode(msg); 27 | System.out.println(packet); 28 | } 29 | 30 | public static ByteBuf encode(byte[] body) { 31 | ByteBuf out = Unpooled.buffer(); 32 | 33 | // 24 = 头标识[1] + 数据头[22 = 长度[4] + 序列号[4] + 数据类型[2] + 接入码[4] + 版本号[3] + 加密标识[1] + 密钥[4]] + 尾标识[1] 34 | int len = body.length + 24; 35 | out.markReaderIndex(); 36 | // 数据长度 37 | out.writeInt(len); 38 | // 序列号 39 | out.writeInt(2); 40 | // 业务数据类型 41 | out.writeShort(0x1001); 42 | // 下级平台接入码 43 | out.writeInt(9526); 44 | // 版本号 45 | String[] version = "v1.2.8".replace("v", "").split("\\."); 46 | for (String s : version) { 47 | out.writeByte(Byte.parseByte(s)); 48 | } 49 | // 报文加密标识位 50 | out.writeByte(0); 51 | // 数据加密的密钥 52 | out.writeInt(0); 53 | // 数据体 54 | out.writeBytes(body); 55 | // 校验码 56 | byte[] crcBytes = new byte[out.readableBytes()]; 57 | out.readBytes(crcBytes); 58 | out.writeShort(CRC16CCITT.crc16(crcBytes)); 59 | 60 | // 转义 61 | out.resetReaderIndex(); 62 | byte[] escapeBytes = new byte[out.readableBytes()]; 63 | out.readBytes(escapeBytes); 64 | 65 | // 重置下标 66 | out.setIndex(0, 0); 67 | // 包头标识 68 | out.writeByte(Jtt809Constant.PACKET_HEAD_FLAG); 69 | // 数据内容 70 | out.writeBytes(Jtt809Util.escape(escapeBytes)); 71 | // 包尾标识 72 | out.writeByte(Jtt809Constant.PACKET_END_FLAG); 73 | return out; 74 | } 75 | 76 | 77 | public static OuterPacket decode(ByteBuf msg) { 78 | if (msg.readByte() != Jtt809Constant.PACKET_HEAD_FLAG) { 79 | return null; 80 | } 81 | byte[] readableBytes = new byte[msg.readableBytes()]; 82 | msg.readBytes(readableBytes); 83 | // 反转义处理 84 | byte[] bytes = Jtt809Util.unescape(readableBytes); 85 | ByteBuf byteBuf = Unpooled.wrappedBuffer(bytes); 86 | // crc校验 87 | if (!Jtt809Util.validate(byteBuf)) { 88 | return null; 89 | } 90 | 91 | /* 解析外层包 */ 92 | // 长度 93 | long length = byteBuf.readUnsignedInt(); 94 | // 长度校验, 反转义之后数组加上包头和包尾长度与解析出来的长度对比; 95 | // 因为数据长度不包含校验码,而此时解析出来的数据不包含头尾标识,刚好都是2个字节,所以两个长度应该相等 96 | if (length != bytes.length) { 97 | return null; 98 | } 99 | // 报文序列号 100 | long sn = byteBuf.readUnsignedInt(); 101 | // 业务数据类型 102 | int id = byteBuf.readUnsignedShort(); 103 | // 下级平台接入码 104 | int gnsscenterId = byteBuf.readInt(); 105 | // 协议版本号标识 106 | String version = "v" + byteBuf.readByte() + "." + byteBuf.readByte() + "." + byteBuf.readByte(); 107 | // 报文加密标识位 108 | byte encryptFlag = byteBuf.readByte(); 109 | // 数据加密解密的密匙 110 | long encryptKey = byteBuf.readUnsignedInt(); 111 | // 消息体 112 | byte[] body; 113 | if (encryptFlag == 1) { 114 | byte[] encryptedBytes = new byte[byteBuf.readableBytes() - 2]; 115 | byteBuf.readBytes(encryptedBytes); 116 | // 解密 117 | int[] param = GnssCenterService.getInstance().getDecryptParam(gnsscenterId); 118 | Jtt809Util.decrypt(param[0], param[1], param[2], encryptKey, encryptedBytes); 119 | body = encryptedBytes; 120 | } else { 121 | body = new byte[byteBuf.readableBytes() - 2]; 122 | byteBuf.readBytes(body); 123 | } 124 | // 校验码 125 | int crcCode = byteBuf.readUnsignedShort(); 126 | ReferenceCountUtil.release(byteBuf); 127 | return new OuterPacket(length, sn, id, gnsscenterId, version, encryptFlag, encryptKey, body, crcCode); 128 | } 129 | 130 | } 131 | --------------------------------------------------------------------------------