├── .gitignore ├── README.md ├── .settings ├── org.eclipse.m2e.core.prefs ├── org.eclipse.core.resources.prefs └── org.eclipse.jdt.core.prefs ├── src └── main │ ├── java │ └── com │ │ └── zhtkj │ │ └── jt808 │ │ ├── mapper │ │ ├── CarHistoryMapper.java │ │ ├── CarEventMapper.java │ │ ├── ConfigMapper.java │ │ ├── DataParamMapper.java │ │ ├── DataActionMapper.java │ │ ├── CarRuntimeMapper.java │ │ ├── CarHistoryMapper.xml │ │ ├── DataActionMapper.xml │ │ ├── CarEventMapper.xml │ │ ├── DataParamMapper.xml │ │ ├── ConfigMapper.xml │ │ └── CarRuntimeMapper.xml │ │ ├── vo │ │ ├── resp │ │ │ └── RespMsgBody.java │ │ ├── Session.java │ │ ├── req │ │ │ ├── EventMsg.java │ │ │ ├── VersionMsg.java │ │ │ └── LocationMsg.java │ │ └── PackageData.java │ │ ├── util │ │ ├── ArrayUtil.java │ │ ├── CarEventUtil.java │ │ ├── CarHistoryUtil.java │ │ └── DigitUtil.java │ │ ├── scheduler │ │ ├── SendDataScheduler.java │ │ └── TerminalScheduler.java │ │ ├── service │ │ ├── BaseMsgProcessService.java │ │ ├── ServerMsgProcessService.java │ │ ├── TerminalMsgProcessService.java │ │ └── codec │ │ │ ├── MsgEncoder.java │ │ │ └── MsgDecoder.java │ │ ├── entity │ │ ├── Config.java │ │ ├── DataAction.java │ │ ├── DataParam.java │ │ └── CarRuntime.java │ │ ├── server │ │ ├── SessionManager.java │ │ ├── ServerApplication.java │ │ └── ServerHandler.java │ │ └── common │ │ └── JT808Const.java │ └── resources │ ├── DBConfig.properties │ ├── logback.xml │ └── applicationContext.xml ├── .project ├── .classpath ├── pom.xml └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # jt808 2 | 根据交通部jt808规范编写的一个已经用于实际生产的tcp通讯服务端 3 | -------------------------------------------------------------------------------- /.settings/org.eclipse.m2e.core.prefs: -------------------------------------------------------------------------------- 1 | activeProfiles= 2 | eclipse.preferences.version=1 3 | resolveWorkspaceProjects=true 4 | version=1 5 | -------------------------------------------------------------------------------- /.settings/org.eclipse.core.resources.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | encoding//src/main/java=UTF-8 3 | encoding//src/main/resources=UTF-8 4 | encoding//src/main/resources/DBConfig.properties=UTF-8 5 | encoding/=UTF-8 6 | -------------------------------------------------------------------------------- /src/main/java/com/zhtkj/jt808/mapper/CarHistoryMapper.java: -------------------------------------------------------------------------------- 1 | package com.zhtkj.jt808.mapper; 2 | 3 | import org.apache.ibatis.annotations.Param; 4 | 5 | import com.zhtkj.jt808.vo.req.LocationMsg.LocationInfo; 6 | 7 | public interface CarHistoryMapper { 8 | 9 | int insertCarHistory(@Param(value = "month") String month, 10 | @Param(value = "locationInfo") LocationInfo locationInfo); 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/zhtkj/jt808/mapper/CarEventMapper.java: -------------------------------------------------------------------------------- 1 | package com.zhtkj.jt808.mapper; 2 | 3 | import org.apache.ibatis.annotations.Param; 4 | 5 | import com.zhtkj.jt808.vo.req.EventMsg.EventInfo; 6 | import com.zhtkj.jt808.vo.req.LocationMsg.LocationInfo; 7 | 8 | public interface CarEventMapper { 9 | 10 | int insertCarEvent(@Param(value = "month") String month, 11 | @Param(value = "eventInfo") EventInfo eventInfo, 12 | @Param(value = "locationInfo") LocationInfo locationInfo); 13 | 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/zhtkj/jt808/mapper/ConfigMapper.java: -------------------------------------------------------------------------------- 1 | package com.zhtkj.jt808.mapper; 2 | 3 | import java.util.List; 4 | 5 | import org.apache.ibatis.annotations.Param; 6 | 7 | import com.zhtkj.jt808.entity.Config; 8 | import com.zhtkj.jt808.vo.req.VersionMsg.VersionInfo; 9 | 10 | public interface ConfigMapper { 11 | 12 | int insertConfig(@Param(value = "configInfo") VersionInfo configInfo); 13 | 14 | int updateConfig(@Param(value = "configInfo") VersionInfo configInfo); 15 | 16 | List selectConfigByKey(@Param(value = "mac") String mac); 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/zhtkj/jt808/mapper/DataParamMapper.java: -------------------------------------------------------------------------------- 1 | package com.zhtkj.jt808.mapper; 2 | 3 | import java.util.List; 4 | 5 | import org.apache.ibatis.annotations.Param; 6 | 7 | import com.zhtkj.jt808.entity.DataParam; 8 | import com.zhtkj.jt808.vo.PackageData.MsgBody; 9 | 10 | public interface DataParamMapper { 11 | 12 | int updateParamResult(@Param(value = "msgBody") MsgBody msgBody); 13 | 14 | int updateParamReceiveResult(@Param(value = "paramId") Integer paramId, 15 | @Param(value = "receiveResult") Integer receiveResult); 16 | 17 | List findSendParamData(); 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/zhtkj/jt808/vo/resp/RespMsgBody.java: -------------------------------------------------------------------------------- 1 | package com.zhtkj.jt808.vo.resp; 2 | 3 | /** 4 | * ClassName: RespMsgBody 5 | * @Description: 通用响应 6 | */ 7 | public class RespMsgBody { 8 | 9 | //响应结果 10 | protected byte replyResult; 11 | 12 | public RespMsgBody() { 13 | 14 | } 15 | 16 | public RespMsgBody(byte replyResult) { 17 | this.replyResult = replyResult; 18 | } 19 | 20 | public byte getReplyResult() { 21 | return replyResult; 22 | } 23 | 24 | 25 | public void setReplyResult(byte replyResult) { 26 | this.replyResult = replyResult; 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/zhtkj/jt808/mapper/DataActionMapper.java: -------------------------------------------------------------------------------- 1 | package com.zhtkj.jt808.mapper; 2 | 3 | import java.util.List; 4 | 5 | import org.apache.ibatis.annotations.Param; 6 | 7 | import com.zhtkj.jt808.entity.DataAction; 8 | import com.zhtkj.jt808.vo.PackageData.MsgBody; 9 | 10 | public interface DataActionMapper { 11 | 12 | int updateActionDealResult(@Param(value = "msgBody") MsgBody msgBody); 13 | 14 | int updateActionReceiveResult(@Param(value = "actionId") Integer actionId, 15 | @Param(value = "receiveResult") Integer receiveResult); 16 | 17 | List findSendActionData(); 18 | } 19 | -------------------------------------------------------------------------------- /src/main/resources/DBConfig.properties: -------------------------------------------------------------------------------- 1 | #渣土平台数据库配置 2 | #正式环境 172.1.0.13 3 | jdbc.zhatu.driver=com.mysql.cj.jdbc.Driver 4 | jdbc.zhatu.url=jdbc:mysql://localhost:3306/zhatu?characterEncoding=utf8&serverTimezone=UTC 5 | jdbc.zhatu.username=root 6 | jdbc.zhatu.password=zt123456 7 | 8 | #网关数据库配置 9 | #正式环境 172.1.0.13 10 | jdbc.gateway.driver=com.mysql.cj.jdbc.Driver 11 | jdbc.gateway.url=jdbc:mysql://localhost:3306/zt_gate_808?characterEncoding=utf8&serverTimezone=UTC 12 | jdbc.gateway.username=root 13 | jdbc.gateway.password=zt123456 14 | 15 | #mongodb数据库配置 16 | #正式环境 127.0.0.1 17 | jdbc.mongo.url=127.0.0.1:27017 18 | jdbc.mongo.dbname=zt_gate_808 -------------------------------------------------------------------------------- /src/main/java/com/zhtkj/jt808/util/ArrayUtil.java: -------------------------------------------------------------------------------- 1 | package com.zhtkj.jt808.util; 2 | 3 | import java.util.Arrays; 4 | 5 | public class ArrayUtil { 6 | 7 | public static byte[] concatAll(byte[] first, byte[]... rest) { 8 | int totalLength = first.length; 9 | for (byte[] array : rest) { 10 | totalLength += array.length; 11 | } 12 | byte[] result = Arrays.copyOf(first, totalLength); 13 | int offset = first.length; 14 | for (byte[] array : rest) { 15 | System.arraycopy(array, 0, result, offset, array.length); 16 | offset += array.length; 17 | } 18 | return result; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/zhtkj/jt808/mapper/CarRuntimeMapper.java: -------------------------------------------------------------------------------- 1 | package com.zhtkj.jt808.mapper; 2 | 3 | import java.util.List; 4 | 5 | import org.apache.ibatis.annotations.Param; 6 | 7 | import com.zhtkj.jt808.entity.CarRuntime; 8 | import com.zhtkj.jt808.vo.req.LocationMsg.LocationInfo; 9 | 10 | public interface CarRuntimeMapper { 11 | 12 | int insertCarRuntime(@Param(value = "locationInfo") LocationInfo locationInfo); 13 | 14 | int updateCarRuntime(@Param(value = "locationInfo") LocationInfo locationInfo); 15 | 16 | int setCarOnlineState(@Param(value = "devPhone") String devPhone); 17 | 18 | int setCarOfflineState(@Param(value = "idleTime") String idleTime); 19 | 20 | List findCarPassword(@Param(value = "terminalPhone") String terminalPhone); 21 | } 22 | -------------------------------------------------------------------------------- /.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 3 | org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate 4 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 5 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve 6 | org.eclipse.jdt.core.compiler.compliance=1.8 7 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate 8 | org.eclipse.jdt.core.compiler.debug.localVariable=generate 9 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate 10 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 11 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 12 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning 13 | org.eclipse.jdt.core.compiler.source=1.8 14 | -------------------------------------------------------------------------------- /.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | jt808-server 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | org.springframework.ide.eclipse.core.springbuilder 15 | 16 | 17 | 18 | 19 | org.springframework.ide.eclipse.boot.validation.springbootbuilder 20 | 21 | 22 | 23 | 24 | org.eclipse.m2e.core.maven2Builder 25 | 26 | 27 | 28 | 29 | 30 | org.springframework.ide.eclipse.core.springnature 31 | org.eclipse.jdt.core.javanature 32 | org.eclipse.m2e.core.maven2Nature 33 | 34 | 35 | -------------------------------------------------------------------------------- /src/main/java/com/zhtkj/jt808/vo/Session.java: -------------------------------------------------------------------------------- 1 | package com.zhtkj.jt808.vo; 2 | 3 | import org.joda.time.DateTime; 4 | 5 | import io.netty.channel.Channel; 6 | 7 | public class Session { 8 | 9 | private String id; 10 | private Channel channel; 11 | private DateTime lastCommunicateTime; 12 | 13 | public Session(String terminalPhone, Channel channel) { 14 | this.id = channel.id().asLongText(); 15 | this.channel = channel; 16 | } 17 | 18 | @Override 19 | public String toString() { 20 | return "Session [id=" + id + ", channel=" + channel + "]"; 21 | } 22 | 23 | 24 | public String getId() { 25 | return id; 26 | } 27 | 28 | public void setId(String id) { 29 | this.id = id; 30 | } 31 | 32 | public Channel getChannel() { 33 | return channel; 34 | } 35 | 36 | public void setChannel(Channel channel) { 37 | this.channel = channel; 38 | } 39 | 40 | 41 | public DateTime getLastCommunicateTime() { 42 | return lastCommunicateTime; 43 | } 44 | 45 | public void setLastCommunicateTime(DateTime lastCommunicateTime) { 46 | this.lastCommunicateTime = lastCommunicateTime; 47 | } 48 | 49 | } -------------------------------------------------------------------------------- /.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /src/main/java/com/zhtkj/jt808/scheduler/SendDataScheduler.java: -------------------------------------------------------------------------------- 1 | package com.zhtkj.jt808.scheduler; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.scheduling.annotation.Scheduled; 7 | import org.springframework.stereotype.Component; 8 | 9 | import com.zhtkj.jt808.service.ServerMsgProcessService; 10 | 11 | @Component 12 | public class SendDataScheduler { 13 | 14 | private static final Logger logger = LoggerFactory.getLogger(SendDataScheduler.class); 15 | 16 | @Autowired 17 | private ServerMsgProcessService serverMsgProcessService; 18 | 19 | /** 20 | * @Description: 定时下发指令 21 | * @return void 22 | */ 23 | @Scheduled(cron = "10/15 * * * * ?") 24 | public void sendActionData() { 25 | try { 26 | serverMsgProcessService.processSendActionMsg(); 27 | } catch (Exception e) { 28 | logger.error(e.getMessage()); 29 | e.printStackTrace(); 30 | } 31 | } 32 | 33 | /** 34 | * @Description: 定时下发参数 35 | * @return void 36 | */ 37 | @Scheduled(cron = "12/15 * * * * ?") 38 | public void sendParamData() { 39 | try { 40 | serverMsgProcessService.processSendParamMsg(); 41 | } catch (Exception e) { 42 | logger.error(e.getMessage()); 43 | e.printStackTrace(); 44 | } 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/zhtkj/jt808/mapper/CarHistoryMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | insert into zt_car_history_${month} ( 7 | dev_phone, 8 | car_number, 9 | gps_pos_x, 10 | gps_pos_y, 11 | gps_speed, 12 | gps_height, 13 | gps_direct, 14 | gps_valid, 15 | box_up, 16 | box_empty, 17 | box_close, 18 | car_state, 19 | car_weigui, 20 | driver_id, 21 | send_datetime, 22 | revice_datetime 23 | ) 24 | values 25 | ( 26 | '${locationInfo.devPhone}', 27 | '${locationInfo.carNumber}', 28 | ${locationInfo.gpsPosX}, 29 | ${locationInfo.gpsPosY}, 30 | ${locationInfo.gpsSpeed}, 31 | ${locationInfo.gpsHeight}, 32 | ${locationInfo.gpsDirect}, 33 | 1, 34 | ${locationInfo.boxUp}, 35 | ${locationInfo.boxEmpty}, 36 | ${locationInfo.boxClose}, 37 | '${locationInfo.carState}', 38 | ${locationInfo.carWeigui}, 39 | '${locationInfo.driverId}', 40 | '${locationInfo.sendDatetime}', 41 | now() 42 | ) 43 | 44 | 45 | -------------------------------------------------------------------------------- /src/main/java/com/zhtkj/jt808/mapper/DataActionMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | update 7 | zt_data_action 8 | set 9 | deal_result = '${msgBody.result}', 10 | deal_time = now() 11 | where 12 | action_id = '${msgBody.serialId}' 13 | 14 | 15 | 16 | update 17 | zt_data_action 18 | set 19 | receive_result = '${receiveResult}' 20 | where 21 | action_id = '${actionId}' 22 | 23 | 24 | 44 | 45 | -------------------------------------------------------------------------------- /src/main/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | [%-5level] %d{yyyy-MM-dd HH:mm:ss} [%thread] %logger{36} - %m%n 13 | 14 | 15 | 16 | 17 | 18 | 19 | ${LOG_HOME}/netty-server.log 20 | 21 | ${LOG_HOME}/netty-server-%d{yyyy-MM-dd}.log 22 | 30 23 | 24 | 25 | %-4relative [%thread] %-5level %logger{35} - %msg%n 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /src/main/java/com/zhtkj/jt808/mapper/CarEventMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | insert into zt_car_event_${month} ( 7 | event_type, 8 | event_serialid, 9 | dev_phone, 10 | gps_pos_x, 11 | gps_pos_y, 12 | gps_speed, 13 | gps_height, 14 | gps_direct, 15 | gps_valid, 16 | box_up, 17 | box_empty, 18 | box_close, 19 | car_number, 20 | car_passport, 21 | car_state, 22 | car_weigui, 23 | driver_id, 24 | send_datetime, 25 | revice_datetime, 26 | online_state 27 | ) 28 | values 29 | ( 30 | '${eventInfo.eventType}', 31 | '${eventInfo.eventSerialId}', 32 | '${locationInfo.devPhone}', 33 | '${locationInfo.gpsPosX}', 34 | '${locationInfo.gpsPosY}', 35 | '${locationInfo.gpsSpeed}', 36 | '${locationInfo.gpsHeight}', 37 | '${locationInfo.gpsDirect}', 38 | '1', 39 | '${locationInfo.boxUp}', 40 | '${locationInfo.boxEmpty}', 41 | '${locationInfo.boxClose}', 42 | '${locationInfo.carNumber}', 43 | '${locationInfo.workPassport}', 44 | '${locationInfo.carState}', 45 | '${locationInfo.carWeigui}', 46 | '${locationInfo.driverId}', 47 | '${locationInfo.sendDatetime}', 48 | now(), 49 | '1' 50 | ) 51 | 52 | 53 | -------------------------------------------------------------------------------- /src/main/java/com/zhtkj/jt808/vo/req/EventMsg.java: -------------------------------------------------------------------------------- 1 | package com.zhtkj.jt808.vo.req; 2 | 3 | import com.zhtkj.jt808.vo.PackageData; 4 | import com.zhtkj.jt808.vo.req.LocationMsg.LocationInfo; 5 | 6 | public class EventMsg extends PackageData { 7 | 8 | private EventInfo eventInfo; 9 | 10 | public EventMsg() { 11 | 12 | } 13 | 14 | public EventMsg(PackageData packageData) { 15 | this(); 16 | this.channel = packageData.getChannel(); 17 | this.msgHead = packageData.getMsgHead(); 18 | this.msgBody = packageData.getMsgBody(); 19 | } 20 | 21 | public EventInfo getEventInfo() { 22 | return eventInfo; 23 | } 24 | 25 | public void setEventInfo(EventInfo eventInfo) { 26 | this.eventInfo = eventInfo; 27 | } 28 | 29 | public static class EventInfo { 30 | 31 | private int eventType; 32 | 33 | private long eventSerialId; 34 | 35 | private LocationInfo locationInfo; 36 | 37 | 38 | public int getEventType() { 39 | return eventType; 40 | } 41 | 42 | 43 | public void setEventType(int eventType) { 44 | this.eventType = eventType; 45 | } 46 | 47 | 48 | public long getEventSerialId() { 49 | return eventSerialId; 50 | } 51 | 52 | 53 | public void setEventSerialId(long eventSerialId) { 54 | this.eventSerialId = eventSerialId; 55 | } 56 | 57 | 58 | public LocationInfo getLocationInfo() { 59 | return locationInfo; 60 | } 61 | 62 | 63 | public void setLocationInfo(LocationInfo locationInfo) { 64 | this.locationInfo = locationInfo; 65 | } 66 | 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/com/zhtkj/jt808/scheduler/TerminalScheduler.java: -------------------------------------------------------------------------------- 1 | package com.zhtkj.jt808.scheduler; 2 | 3 | import java.util.Iterator; 4 | import java.util.Map.Entry; 5 | 6 | import org.joda.time.DateTime; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.scheduling.annotation.Scheduled; 9 | import org.springframework.stereotype.Component; 10 | 11 | import com.zhtkj.jt808.mapper.CarRuntimeMapper; 12 | import com.zhtkj.jt808.server.SessionManager; 13 | import com.zhtkj.jt808.vo.Session; 14 | 15 | import io.netty.channel.Channel; 16 | 17 | @Component 18 | public class TerminalScheduler { 19 | 20 | @Autowired 21 | private CarRuntimeMapper carRuntimeMapper; 22 | 23 | /** 24 | * @Description: 移除没有持续上报数据的终端session, 并更改车辆实时表的车辆状态为离线状态 25 | * @return void 26 | */ 27 | @Scheduled(cron = "0 6/6 * * * ?") 28 | public void removeIdleSession() { 29 | Iterator> iterator = 30 | SessionManager.getInstance().getSessionMap().entrySet().iterator(); 31 | DateTime idleTime = DateTime.now().minusMinutes(6); 32 | while (iterator.hasNext()) { 33 | Session session = iterator.next().getValue(); 34 | DateTime lastCommunicateTime = session.getLastCommunicateTime(); 35 | if (lastCommunicateTime == null || lastCommunicateTime.isBefore(idleTime)) { 36 | Channel channel = session.getChannel(); 37 | if (channel.isOpen()) { 38 | channel.close(); 39 | } 40 | iterator.remove(); 41 | } 42 | } 43 | carRuntimeMapper.setCarOfflineState(idleTime.toString("yyyy-MM-dd HH:mm:ss")); 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/zhtkj/jt808/mapper/DataParamMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | update 7 | zt_data_param 8 | set 9 | deal_result = '${msgBody.result}', 10 | deal_time = now() 11 | where 12 | param_id = '${msgBody.serialId}' 13 | 14 | 15 | 16 | update 17 | zt_data_param 18 | set 19 | receive_result = '${receiveResult}' 20 | where 21 | param_id = '${paramId}' 22 | 23 | 24 | 51 | 52 | -------------------------------------------------------------------------------- /src/main/java/com/zhtkj/jt808/service/BaseMsgProcessService.java: -------------------------------------------------------------------------------- 1 | package com.zhtkj.jt808.service; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | 9 | import com.zhtkj.jt808.common.JT808Const; 10 | import com.zhtkj.jt808.server.SessionManager; 11 | 12 | import io.netty.buffer.Unpooled; 13 | import io.netty.channel.Channel; 14 | 15 | public class BaseMsgProcessService { 16 | 17 | protected final Logger logger = LoggerFactory.getLogger(getClass()); 18 | 19 | protected SessionManager sessionManager; 20 | 21 | public BaseMsgProcessService() { 22 | this.sessionManager = SessionManager.getInstance(); 23 | } 24 | 25 | public void send2Terminal(Channel channel, byte[] array) throws InterruptedException { 26 | //按照808协议转义数据包 27 | List list = new ArrayList(); 28 | list.add((byte)JT808Const.MSG_DELIMITER); 29 | for (int i = 1; i < array.length - 1; i++){ 30 | if (array[i] == (byte)JT808Const.MSG_DELIMITER) { 31 | list.add((byte) 0x7d); 32 | list.add((byte) 0x02); 33 | } else if (array[i] == (byte)0x7d) { 34 | list.add((byte) 0x7d); 35 | list.add((byte) 0x01); 36 | } else { 37 | list.add(array[i]); 38 | } 39 | } 40 | list.add((byte)JT808Const.MSG_DELIMITER); 41 | byte[] bs = new byte[list.size()]; 42 | for (int i = 0; i < list.size(); i++) { 43 | bs[i] = list.get(i); 44 | } 45 | //将转义后的byte[]发送给终端 46 | if (channel.isOpen()) { 47 | channel.writeAndFlush(Unpooled.copiedBuffer(bs)).sync(); 48 | } 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/com/zhtkj/jt808/mapper/ConfigMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | insert into zt_config ( 7 | mac, 8 | car_number, 9 | dev_phone, 10 | version, 11 | version_sys, 12 | ecu_type, 13 | car_type, 14 | update_tag, 15 | update_cfg_tag, 16 | report_time 17 | ) 18 | values 19 | ( 20 | '${configInfo.mac}', 21 | '${configInfo.carNumber}', 22 | '${configInfo.devPhone}', 23 | '${configInfo.version}', 24 | '${configInfo.version}', 25 | '${configInfo.ecuType}', 26 | '${configInfo.carType}', 27 | 0, 28 | 0, 29 | now() 30 | ) 31 | 32 | 33 | 34 | update 35 | zt_config 36 | set 37 | car_number = '${configInfo.carNumber}', 38 | dev_phone = '${configInfo.devPhone}', 39 | version = '${configInfo.version}', 40 | ecu_type = '${configInfo.ecuType}', 41 | car_type = '${configInfo.carType}', 42 | report_time = now() 43 | where 44 | mac = '${configInfo.mac}' 45 | 46 | 47 | 65 | 66 | -------------------------------------------------------------------------------- /src/main/java/com/zhtkj/jt808/vo/req/VersionMsg.java: -------------------------------------------------------------------------------- 1 | package com.zhtkj.jt808.vo.req; 2 | 3 | import com.zhtkj.jt808.vo.PackageData; 4 | 5 | public class VersionMsg extends PackageData { 6 | 7 | /** 8 | * @Fields versionInfo : 终端版本信息 9 | */ 10 | private VersionInfo versionInfo; 11 | 12 | public VersionMsg() { 13 | 14 | } 15 | 16 | public VersionMsg(PackageData packageData) { 17 | this(); 18 | this.channel = packageData.getChannel(); 19 | this.msgHead = packageData.getMsgHead(); 20 | this.msgBody = packageData.getMsgBody(); 21 | } 22 | 23 | public VersionInfo getVersionInfo() { 24 | return versionInfo; 25 | } 26 | 27 | public void setVersionInfo(VersionInfo versionInfo) { 28 | this.versionInfo = versionInfo; 29 | } 30 | 31 | public static class VersionInfo { 32 | 33 | private String mac; 34 | private String carNumber; 35 | private String devPhone; 36 | private String ecuType; 37 | private String carType; 38 | private String version; 39 | 40 | public String getMac() { 41 | return mac; 42 | } 43 | 44 | public void setMac(String mac) { 45 | this.mac = mac; 46 | } 47 | 48 | public String getCarNumber() { 49 | return carNumber; 50 | } 51 | 52 | public void setCarNumber(String carNumber) { 53 | this.carNumber = carNumber; 54 | } 55 | 56 | public String getDevPhone() { 57 | return devPhone; 58 | } 59 | 60 | public void setDevPhone(String devPhone) { 61 | this.devPhone = devPhone; 62 | } 63 | 64 | public String getEcuType() { 65 | return ecuType; 66 | } 67 | 68 | public void setEcuType(String ecuType) { 69 | this.ecuType = ecuType; 70 | } 71 | 72 | public String getCarType() { 73 | return carType; 74 | } 75 | 76 | public void setCarType(String carType) { 77 | this.carType = carType; 78 | } 79 | 80 | public String getVersion() { 81 | return version; 82 | } 83 | 84 | public void setVersion(String version) { 85 | this.version = version; 86 | } 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/main/java/com/zhtkj/jt808/entity/Config.java: -------------------------------------------------------------------------------- 1 | package com.zhtkj.jt808.entity; 2 | 3 | import java.util.Date; 4 | 5 | public class Config { 6 | 7 | private String mac; 8 | private String carNumber; 9 | private String devPhone; 10 | private String ecuType; 11 | private String carType; 12 | private String version; 13 | private String versionSys; 14 | private Integer updateTag; 15 | private Integer updateCfgTag; 16 | private Date reportTime; 17 | 18 | public String getMac() { 19 | return mac; 20 | } 21 | 22 | public void setMac(String mac) { 23 | this.mac = mac; 24 | } 25 | 26 | public String getCarNumber() { 27 | return carNumber; 28 | } 29 | 30 | public void setCarNumber(String carNumber) { 31 | this.carNumber = carNumber; 32 | } 33 | 34 | public String getDevPhone() { 35 | return devPhone; 36 | } 37 | 38 | public void setDevPhone(String devPhone) { 39 | this.devPhone = devPhone; 40 | } 41 | 42 | public String getEcuType() { 43 | return ecuType; 44 | } 45 | 46 | public void setEcuType(String ecuType) { 47 | this.ecuType = ecuType; 48 | } 49 | 50 | public String getCarType() { 51 | return carType; 52 | } 53 | 54 | public void setCarType(String carType) { 55 | this.carType = carType; 56 | } 57 | 58 | public String getVersion() { 59 | return version; 60 | } 61 | 62 | public void setVersion(String version) { 63 | this.version = version; 64 | } 65 | 66 | public String getVersionSys() { 67 | return versionSys; 68 | } 69 | 70 | public void setVersionSys(String versionSys) { 71 | this.versionSys = versionSys; 72 | } 73 | 74 | public Integer getUpdateTag() { 75 | return updateTag; 76 | } 77 | 78 | public void setUpdateTag(Integer updateTag) { 79 | this.updateTag = updateTag; 80 | } 81 | 82 | public Integer getUpdateCfgTag() { 83 | return updateCfgTag; 84 | } 85 | 86 | public void setUpdateCfgTag(Integer updateCfgTag) { 87 | this.updateCfgTag = updateCfgTag; 88 | } 89 | 90 | public Date getReportTime() { 91 | return reportTime; 92 | } 93 | 94 | public void setReportTime(Date reportTime) { 95 | this.reportTime = reportTime; 96 | } 97 | 98 | } 99 | -------------------------------------------------------------------------------- /src/main/java/com/zhtkj/jt808/server/SessionManager.java: -------------------------------------------------------------------------------- 1 | package com.zhtkj.jt808.server; 2 | 3 | import java.util.Iterator; 4 | import java.util.Map; 5 | import java.util.Map.Entry; 6 | import java.util.concurrent.ConcurrentHashMap; 7 | 8 | import com.zhtkj.jt808.vo.Session; 9 | 10 | import io.netty.channel.Channel; 11 | 12 | /** 13 | * ClassName: SessionManager 14 | * @Description: 终端与服务端会话管理 15 | */ 16 | public class SessionManager { 17 | 18 | private static volatile SessionManager instance = null; 19 | 20 | //键:终端手机号, 值:session 21 | private static Map sessionMap; 22 | 23 | private SessionManager() { 24 | sessionMap = new ConcurrentHashMap<>(); 25 | } 26 | 27 | public static SessionManager getInstance() { 28 | if (instance == null) { 29 | synchronized (SessionManager.class) { 30 | if (instance == null) { 31 | instance = new SessionManager(); 32 | } 33 | } 34 | } 35 | return instance; 36 | } 37 | 38 | public Map getSessionMap() { 39 | return sessionMap; 40 | } 41 | 42 | public synchronized boolean containsKey(String terminalPhone) { 43 | return sessionMap.containsKey(terminalPhone); 44 | } 45 | 46 | public synchronized Channel getChannelByKey(String terminalPhone) { 47 | if (sessionMap.get(terminalPhone) == null) { 48 | return null; 49 | } else { 50 | return sessionMap.get(terminalPhone).getChannel(); 51 | } 52 | } 53 | 54 | public synchronized Session addSession(String terminalPhone, Session session) { 55 | return sessionMap.put(terminalPhone, session); 56 | } 57 | 58 | public synchronized Session findSessionByKey(String terminalPhone) { 59 | return sessionMap.get(terminalPhone); 60 | } 61 | 62 | public synchronized void removeSessionByKey(String terminalPhone) { 63 | sessionMap.remove(terminalPhone); 64 | } 65 | 66 | public synchronized void removeSessionByChannelId(String channelId) { 67 | Iterator> iterator = 68 | SessionManager.getInstance().getSessionMap().entrySet().iterator(); 69 | while (iterator.hasNext()) { 70 | Channel channel = iterator.next().getValue().getChannel(); 71 | if (channel.id().asLongText().equals(channelId)) { 72 | channel.close(); 73 | iterator.remove(); 74 | } 75 | } 76 | } 77 | } -------------------------------------------------------------------------------- /src/main/java/com/zhtkj/jt808/entity/DataAction.java: -------------------------------------------------------------------------------- 1 | package com.zhtkj.jt808.entity; 2 | 3 | import java.util.Date; 4 | 5 | public class DataAction { 6 | 7 | private int actionId; 8 | private int actionType; 9 | private int actionValue; 10 | private String carPass; 11 | private Date storeTime; 12 | private byte dealResult; 13 | private Date dealTime; 14 | private String phoneNumber; 15 | private byte receiveResult; 16 | private int resendCount; 17 | private String sendPerson; 18 | private String sendRemark; 19 | private String imgPath; 20 | 21 | public int getActionId() { 22 | return actionId; 23 | } 24 | 25 | public void setActionId(int actionId) { 26 | this.actionId = actionId; 27 | } 28 | 29 | public int getActionType() { 30 | return actionType; 31 | } 32 | 33 | public void setActionType(int actionType) { 34 | this.actionType = actionType; 35 | } 36 | 37 | public int getActionValue() { 38 | return actionValue; 39 | } 40 | 41 | public void setActionValue(int actionValue) { 42 | this.actionValue = actionValue; 43 | } 44 | 45 | public String getCarPass() { 46 | return carPass; 47 | } 48 | 49 | public void setCarPass(String carPass) { 50 | this.carPass = carPass; 51 | } 52 | 53 | public Date getStoreTime() { 54 | return storeTime; 55 | } 56 | 57 | public void setStoreTime(Date storeTime) { 58 | this.storeTime = storeTime; 59 | } 60 | 61 | public byte getDealResult() { 62 | return dealResult; 63 | } 64 | 65 | public void setDealResult(byte dealResult) { 66 | this.dealResult = dealResult; 67 | } 68 | 69 | public Date getDealTime() { 70 | return dealTime; 71 | } 72 | 73 | public void setDealTime(Date dealTime) { 74 | this.dealTime = dealTime; 75 | } 76 | 77 | public String getPhoneNumber() { 78 | return phoneNumber; 79 | } 80 | 81 | public void setPhoneNumber(String phoneNumber) { 82 | this.phoneNumber = phoneNumber; 83 | } 84 | 85 | public byte getReceiveResult() { 86 | return receiveResult; 87 | } 88 | 89 | public void setReceiveResult(byte receiveResult) { 90 | this.receiveResult = receiveResult; 91 | } 92 | 93 | public int getResendCount() { 94 | return resendCount; 95 | } 96 | 97 | public void setResendCount(int resendCount) { 98 | this.resendCount = resendCount; 99 | } 100 | 101 | public String getSendPerson() { 102 | return sendPerson; 103 | } 104 | 105 | public void setSendPerson(String sendPerson) { 106 | this.sendPerson = sendPerson; 107 | } 108 | 109 | public String getSendRemark() { 110 | return sendRemark; 111 | } 112 | 113 | public void setSendRemark(String sendRemark) { 114 | this.sendRemark = sendRemark; 115 | } 116 | 117 | public String getImgPath() { 118 | return imgPath; 119 | } 120 | 121 | public void setImgPath(String imgPath) { 122 | this.imgPath = imgPath; 123 | } 124 | 125 | } 126 | -------------------------------------------------------------------------------- /src/main/java/com/zhtkj/jt808/common/JT808Const.java: -------------------------------------------------------------------------------- 1 | package com.zhtkj.jt808.common; 2 | 3 | /** 4 | * ClassName: JT808Const 5 | * @Description: 消息id、分隔符、抓拍图片保存路径等等配置 6 | */ 7 | public class JT808Const { 8 | 9 | //抓拍图片保存路径 10 | public static final String IMAGE_SAVE_PATH = "D:\\catimg\\"; 11 | 12 | //消息分隔符 13 | public static final int MSG_DELIMITER = 0x7e; 14 | 15 | //任务类 16 | public static final int TASK_HEAD_ID = 0x0F01; //任务类 17 | 18 | public static final int TASK_BODY_ID_LOGIN = 0x0101; //任务类 - 登录ID 19 | 20 | public static final int TASK_BODY_ID_GPS = 0x0102; //任务类 - GPSID 21 | 22 | public static final int TASK_BODY_ID_EVENT = 0x0103; //任务类 - 事件ID 23 | 24 | public static final int TASK_BODY_ID_SELFCHECK = 0x0104; //任务类 - 终端自检ID 25 | 26 | public static final int TASK_BODY_ID_VERSION = 0x0180; //任务类 - 终端程序版本信息上报ID 27 | 28 | public static final int TASK_BODY_ID_CONFIG = 0x0181; //任务类 - 网关下发终端配置文件信息ID 29 | 30 | //命令类 31 | public static final int ACTION_HEAD_ID = 0x0F02; //命令类 32 | 33 | public static final int ACTION_BODY_ID_LOCKCAR = 0x0201; //命令类 - 锁车命令ID 34 | 35 | public static final int ACTION_BODY_ID_LIMITSPEED = 0x0202; //命令类 - 限速命令ID 36 | 37 | public static final int ACTION_BODY_ID_LIMITUP = 0x0203; //命令类 - 限举命令ID 38 | 39 | public static final int ACTION_BODY_ID_IMGACT = 0x0204; //命令类 - 抓拍命令ID 40 | 41 | public static final int ACTION_BODY_ID_PASSWORD = 0x0205; //命令类 - 密码命令ID 42 | 43 | public static final int ACTION_BODY_ID_CONTROL = 0x0206; //命令类 - 管控命令ID 44 | 45 | public static final int ACTION_BODY_ID_LOCKCARCOMPANY = 0x0207; //命令类 - 运输公司锁车命令ID 46 | 47 | //参数类 48 | public static final int PARAM_HEAD_ID = 0x0F03; //参数类 49 | 50 | public static final int PARAM_BODY_ID_LINE = 0x0301; //参数类 - 路线ID 51 | 52 | public static final int PARAM_BODY_ID_GONG = 0x0302; //参数类 - 工地ID 53 | 54 | public static final int PARAM_BODY_ID_XIAO = 0x0303; //参数类 - 消纳场ID 55 | 56 | public static final int PARAM_BODY_ID_LIMSPCIRCLE = 0x0304; //参数类 - 限速圈ID 57 | 58 | public static final int PARAM_BODY_ID_PARKING = 0x0305; //参数类 - 停车场ID 59 | 60 | public static final int PARAM_BODY_ID_BAN = 0x0306; //参数类 - 禁区ID 61 | 62 | public static final int PARAM_BODY_ID_WORKPASSPORT = 0x0307; //参数类 - 核准证ID 63 | 64 | public static final int PARAM_BODY_ID_INFO = 0x0308; //参数类 - 提示信息ID 65 | 66 | public static final int PARAM_BODY_ID_FINGER = 0x0309; //参数类 - 指纹ID 67 | 68 | public static final int PARAM_BODY_ID_REDLIGHT = 0x030A; //参数类 - 红灯电子围栏ID 69 | 70 | public static final int PARAM_BODY_ID_DEVICECONFIG = 0x030B; //参数类 - 终端配置ID 71 | 72 | public static final int PARAM_BODY_ID_LOCKCAREXT = 0x030C; //参数类 - 扩展锁车命令信息ID 73 | 74 | public static final int PARAM_BODY_ID_NOTIFY = 0x030D; //参数类 - 资讯提示信息ID 75 | 76 | public static final int PARAM_BODY_ID_CONTROLSWITCH = 0x0380; //参数类 - 管控处理开关ID 77 | 78 | public static final int PARAM_BODY_ID_THRESHOLDVALUE = 0x0381; //参数类 - 业务阙值ID 79 | } 80 | -------------------------------------------------------------------------------- /src/main/java/com/zhtkj/jt808/vo/PackageData.java: -------------------------------------------------------------------------------- 1 | package com.zhtkj.jt808.vo; 2 | 3 | import io.netty.channel.Channel; 4 | 5 | public class PackageData { 6 | 7 | protected MsgHead msgHead; 8 | protected MsgBody msgBody; 9 | protected Channel channel; 10 | 11 | 12 | public MsgHead getMsgHead() { 13 | return msgHead; 14 | } 15 | 16 | public void setMsgHead(MsgHead msgHead) { 17 | this.msgHead = msgHead; 18 | } 19 | 20 | public MsgBody getMsgBody() { 21 | return msgBody; 22 | } 23 | 24 | public void setMsgBody(MsgBody msgBody) { 25 | this.msgBody = msgBody; 26 | } 27 | 28 | public Channel getChannel() { 29 | return channel; 30 | } 31 | 32 | public void setChannel(Channel channel) { 33 | this.channel = channel; 34 | } 35 | 36 | public static class MsgHead { 37 | 38 | protected int headId; 39 | protected int headSerial; 40 | protected int bodyLength; 41 | protected int encryptType; 42 | protected boolean hasSubPack; 43 | protected String terminalPhone; 44 | 45 | public int getHeadId() { 46 | return headId; 47 | } 48 | 49 | public void setHeadId(int headId) { 50 | this.headId = headId; 51 | } 52 | 53 | public int getHeadSerial() { 54 | return headSerial; 55 | } 56 | 57 | public void setHeadSerial(int headSerial) { 58 | this.headSerial = headSerial; 59 | } 60 | 61 | public int getBodyLength() { 62 | return bodyLength; 63 | } 64 | 65 | public void setBodyLength(int bodyLength) { 66 | this.bodyLength = bodyLength; 67 | } 68 | 69 | public int getEncryptType() { 70 | return encryptType; 71 | } 72 | 73 | public void setEncryptType(int encryptType) { 74 | this.encryptType = encryptType; 75 | } 76 | 77 | public boolean isHasSubPack() { 78 | return hasSubPack; 79 | } 80 | 81 | public void setHasSubPack(boolean hasSubPack) { 82 | this.hasSubPack = hasSubPack; 83 | } 84 | 85 | public String getTerminalPhone() { 86 | return terminalPhone; 87 | } 88 | 89 | public void setTerminalPhone(String terminalPhone) { 90 | this.terminalPhone = terminalPhone; 91 | } 92 | 93 | } 94 | 95 | public static class MsgBody { 96 | 97 | private int bodyId; 98 | private int bodySerial; 99 | private int result; 100 | private byte[] bodyBytes; 101 | 102 | public int getBodyId() { 103 | return bodyId; 104 | } 105 | 106 | public void setBodyId(int bodyId) { 107 | this.bodyId = bodyId; 108 | } 109 | 110 | public int getBodySerial() { 111 | return bodySerial; 112 | } 113 | 114 | public void setBodySerial(int bodySerial) { 115 | this.bodySerial = bodySerial; 116 | } 117 | 118 | public int getResult() { 119 | return result; 120 | } 121 | 122 | public void setResult(int result) { 123 | this.result = result; 124 | } 125 | 126 | public byte[] getBodyBytes() { 127 | return bodyBytes; 128 | } 129 | 130 | public void setBodyBytes(byte[] bodyBytes) { 131 | this.bodyBytes = bodyBytes; 132 | } 133 | 134 | } 135 | 136 | } 137 | -------------------------------------------------------------------------------- /src/main/resources/applicationContext.xml: -------------------------------------------------------------------------------- 1 | 2 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | classpath:DBConfig.properties 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | -------------------------------------------------------------------------------- /src/main/java/com/zhtkj/jt808/mapper/CarRuntimeMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | insert into zt_car_runtime ( 7 | dev_phone, 8 | car_number, 9 | ip_address, 10 | gps_pos_x, 11 | gps_pos_y, 12 | gps_speed, 13 | gps_height, 14 | gps_direct, 15 | gps_valid, 16 | box_up, 17 | box_empty, 18 | box_close, 19 | car_passport, 20 | car_state, 21 | car_weigui, 22 | car_password, 23 | send_datetime, 24 | driver_id, 25 | revice_datetime, 26 | online_state 27 | ) 28 | values 29 | ( 30 | '${locationInfo.devPhone}', 31 | '${locationInfo.carNumber}', 32 | '${locationInfo.terminalIp}', 33 | ${locationInfo.gpsPosX}, 34 | ${locationInfo.gpsPosY}, 35 | ${locationInfo.gpsSpeed}, 36 | ${locationInfo.gpsHeight}, 37 | ${locationInfo.gpsDirect}, 38 | 1, 39 | ${locationInfo.boxUp}, 40 | ${locationInfo.boxEmpty}, 41 | ${locationInfo.boxClose}, 42 | '${locationInfo.workPassport}', 43 | '${locationInfo.carState}', 44 | ${locationInfo.carWeigui}, 45 | 'zt12345678', 46 | '${locationInfo.sendDatetime}', 47 | '${locationInfo.driverId}', 48 | now(), 49 | 1 50 | ) 51 | 52 | 53 | 54 | update 55 | zt_car_runtime 56 | set 57 | car_number = '${locationInfo.carNumber}', 58 | ip_address = '${locationInfo.terminalIp}', 59 | gps_pos_x = '${locationInfo.gpsPosX}', 60 | gps_pos_y = '${locationInfo.gpsPosY}', 61 | gps_speed = '${locationInfo.gpsSpeed}', 62 | gps_height = '${locationInfo.gpsHeight}', 63 | gps_direct = '${locationInfo.gpsDirect}', 64 | gps_valid = 1, 65 | box_up = '${locationInfo.boxUp}', 66 | box_empty = '${locationInfo.boxEmpty}', 67 | box_close = '${locationInfo.boxClose}', 68 | car_passport = '${locationInfo.workPassport}', 69 | car_state = '${locationInfo.carState}', 70 | car_weigui = '${locationInfo.carWeigui}', 71 | send_datetime = '${locationInfo.sendDatetime}', 72 | driver_id = '${locationInfo.driverId}', 73 | revice_datetime = now(), 74 | online_state = 1 75 | where 76 | dev_phone = '${locationInfo.devPhone}' 77 | 78 | 79 | 80 | update 81 | zt_car_runtime 82 | set 83 | online_datetime = now(), 84 | online_state = 1 85 | where 86 | dev_phone = '${devPhone}' 87 | 88 | 89 | 90 | update 91 | zt_car_runtime 92 | set 93 | offline_datetime = now(), 94 | online_state = 0 95 | where 96 | revice_datetime <= '${idleTime}' 97 | and online_state = 1 98 | 99 | 100 | 109 | -------------------------------------------------------------------------------- /src/main/java/com/zhtkj/jt808/util/CarEventUtil.java: -------------------------------------------------------------------------------- 1 | package com.zhtkj.jt808.util; 2 | 3 | import java.util.Hashtable; 4 | 5 | import org.joda.time.DateTime; 6 | 7 | import com.zhtkj.jt808.vo.req.EventMsg.EventInfo; 8 | 9 | /**  10 | * @ClassName: CarEventUtil  11 | * @Description: 每种类型的事件只能在相隔一定的时间后才能上报 12 | */ 13 | public class CarEventUtil { 14 | 15 | private static Hashtable > carEventMap = new Hashtable >(); 16 | 17 | //判断是否需要写入车辆事件数据到数据库 18 | public static boolean isPersistent(EventInfo eventInfo) { 19 | String carNumber = eventInfo.getLocationInfo().getCarNumber(); 20 | int eventType = eventInfo.getEventType(); 21 | if (carEventMap.get(carNumber) == null) { 22 | Hashtable innerMap = new Hashtable (); 23 | innerMap.put(eventType, new DateTime()); 24 | carEventMap.put(carNumber, innerMap); 25 | return true; 26 | } else { 27 | Hashtable innerMap = carEventMap.get(carNumber); 28 | if(!innerMap.containsKey(eventType)) { 29 | innerMap.put(eventType, new DateTime()); 30 | return true; 31 | }else{ 32 | DateTime dateTime = (DateTime) innerMap.get(eventType); 33 | int intervalSec = getIntervalSec(eventType); 34 | if (intervalSec == 0 || dateTime.plusSeconds(intervalSec).isBeforeNow()) { 35 | innerMap.put(eventType, new DateTime()); 36 | return true; 37 | } else { 38 | return false; 39 | } 40 | } 41 | } 42 | } 43 | 44 | private static int getIntervalSec(int eventType) { 45 | switch(eventType){ 46 | case 1: //进入路线 47 | return 180; 48 | case 2: //离开路线(越界) 49 | return 180; 50 | case 3: //进入工地 51 | return 180; 52 | case 4: //离开工地 53 | return 180; 54 | case 5: //进入消纳场 55 | return 180; 56 | case 6: //离开消纳场 57 | return 180; 58 | case 7: //进入限速圈 59 | return 180; 60 | case 8: //离开限速圈 61 | return 180; 62 | case 9: //进入停车场 63 | return 180; 64 | case 10: //离开停车场 65 | return 180; 66 | case 11: //进入禁区 67 | return 180; 68 | case 12: //离开禁区 69 | return 180; 70 | case 13: //举斗 71 | return 180; 72 | case 14: //闯红灯区 73 | return 180; 74 | 75 | case 30: //开箱重车 76 | return 600; 77 | case 31: //GPS无信号 78 | return 600; 79 | case 32: //重车越界 80 | return 600; 81 | case 33: //重车闯禁 82 | return 600; 83 | case 34: //举斗状态监视器失联 84 | return 600; 85 | case 35: //开关箱状态监视器失联 86 | return 600; 87 | case 36: //空重车状态监视器失联 88 | return 600; 89 | case 37: //ECU失联 90 | return 600; 91 | case 38: //网关失联 92 | return 600; 93 | 94 | case 130: //开箱重车恢复 95 | return 180; 96 | case 131: //GPS无信号恢复 97 | return 180; 98 | case 132: //重车越界恢复 99 | return 180; 100 | case 133: //重车闯禁恢复 101 | return 180; 102 | case 134: //举斗状态监视器失联 103 | return 600; 104 | case 135: //开关箱状态监视器失联 105 | return 600; 106 | case 136: //空重车状态监视器失联 107 | return 600; 108 | case 137: //ECU失联恢复 109 | return 180; 110 | case 138: //网关失联恢复 111 | return 180; 112 | 113 | case 60: //非法举斗 114 | return 120; 115 | case 61: //ECU作弊 116 | return 600; 117 | case 62: //举升作弊 118 | return 600; 119 | case 63: //开关箱作弊 120 | return 600; 121 | case 64: //空重车作弊 122 | return 600; 123 | case 65: //重车核准证无效 124 | return 600; 125 | default : 126 | return 600; 127 | } 128 | } 129 | 130 | } -------------------------------------------------------------------------------- /src/main/java/com/zhtkj/jt808/util/CarHistoryUtil.java: -------------------------------------------------------------------------------- 1 | package com.zhtkj.jt808.util; 2 | 3 | import java.util.Date; 4 | import java.util.Hashtable; 5 | import java.util.Map; 6 | 7 | import org.joda.time.DateTime; 8 | 9 | import com.zhtkj.jt808.vo.req.LocationMsg.LocationInfo; 10 | 11 | /**  12 | * @ClassName: CarHistoryUtil  13 | * @Description: 过滤历史数据,主要是过滤白天的历史数据  14 | */ 15 | public class CarHistoryUtil { 16 | 17 | private static Map carState = new Hashtable(); 18 | 19 | //gps坐标连续相同次数 20 | private static Long GPS_SAME_TOTAL = 10L; 21 | 22 | //判断是否需要写入车辆历史数据到数据库 23 | public static boolean isPersistent(LocationInfo locationInfo) { 24 | CarState lastCarState = carState.get(locationInfo.getCarNumber()); 25 | CarState newCarState = new CarState(); 26 | newCarState.setLongitude(locationInfo.getGpsPosX() + ""); 27 | newCarState.setLatitude(locationInfo.getGpsPosY() + ""); 28 | newCarState.setBoxUp(locationInfo.getBoxUp() + ""); 29 | newCarState.setBoxEmpty(locationInfo.getBoxEmpty() + ""); 30 | boolean result = true; 31 | if (lastCarState == null) { 32 | newCarState.setGpsSameTotal(0L); 33 | newCarState.setUpdateTime(new Date()); 34 | result = true; 35 | } else if (newCarState.getLongitude().equals(lastCarState.getLongitude()) && 36 | newCarState.getLatitude().equals(lastCarState.getLatitude()) && 37 | newCarState.getBoxUp().equals(lastCarState.getBoxUp()) && 38 | newCarState.getBoxEmpty().equals(lastCarState.getBoxEmpty())) { 39 | newCarState.setGpsSameTotal(lastCarState.getGpsSameTotal() + 1); 40 | if (new DateTime(lastCarState.getUpdateTime()).plusMinutes(15).isBeforeNow()) { 41 | newCarState.setUpdateTime(new Date()); 42 | result = true; 43 | } else if (newCarState.getGpsSameTotal() >= GPS_SAME_TOTAL) { 44 | newCarState.setUpdateTime(lastCarState.getUpdateTime()); 45 | result = false; 46 | } else { 47 | newCarState.setUpdateTime(new Date()); 48 | result = true; 49 | } 50 | } else { 51 | newCarState.setGpsSameTotal(0L); 52 | newCarState.setUpdateTime(new Date()); 53 | result = true; 54 | } 55 | carState.put(locationInfo.getCarNumber(), newCarState); 56 | return result; 57 | } 58 | 59 | } 60 | 61 | class CarState { 62 | 63 | public String longitude; 64 | public String latitude; 65 | public String boxUp; 66 | public String boxEmpty; 67 | public Long gpsSameTotal; 68 | public Date updateTime; 69 | 70 | public String getLongitude() { 71 | return longitude; 72 | } 73 | 74 | public void setLongitude(String longitude) { 75 | this.longitude = longitude; 76 | } 77 | 78 | public String getLatitude() { 79 | return latitude; 80 | } 81 | 82 | public void setLatitude(String latitude) { 83 | this.latitude = latitude; 84 | } 85 | 86 | public String getBoxUp() { 87 | return boxUp; 88 | } 89 | 90 | public void setBoxUp(String boxUp) { 91 | this.boxUp = boxUp; 92 | } 93 | 94 | public String getBoxEmpty() { 95 | return boxEmpty; 96 | } 97 | 98 | public void setBoxEmpty(String boxEmpty) { 99 | this.boxEmpty = boxEmpty; 100 | } 101 | 102 | public Date getUpdateTime() { 103 | return updateTime; 104 | } 105 | 106 | public void setUpdateTime(Date updateTime) { 107 | this.updateTime = updateTime; 108 | } 109 | 110 | public Long getGpsSameTotal() { 111 | return gpsSameTotal; 112 | } 113 | 114 | public void setGpsSameTotal(Long gpsSameTotal) { 115 | this.gpsSameTotal = gpsSameTotal; 116 | } 117 | 118 | } 119 | -------------------------------------------------------------------------------- /src/main/java/com/zhtkj/jt808/entity/DataParam.java: -------------------------------------------------------------------------------- 1 | package com.zhtkj.jt808.entity; 2 | 3 | import java.util.Date; 4 | 5 | public class DataParam { 6 | 7 | private int paramId; 8 | private String carPass; 9 | private byte dealResult; 10 | private Date dealTime; 11 | private String endHourtime; 12 | private String endTime; 13 | private byte limitValue; 14 | private byte paramDeal; 15 | private byte paramType; 16 | private String phoneNumber; 17 | private Date storeTime; 18 | private byte receiveResult; 19 | private int resendCount; 20 | private String sendPerson; 21 | private String sendRemark; 22 | private String startHourtime; 23 | private String startTime; 24 | private Integer typeId; 25 | private String typeName; 26 | private String typeValue; 27 | 28 | public int getParamId() { 29 | return paramId; 30 | } 31 | 32 | public void setParamId(int paramId) { 33 | this.paramId = paramId; 34 | } 35 | 36 | public String getCarPass() { 37 | return carPass; 38 | } 39 | 40 | public void setCarPass(String carPass) { 41 | this.carPass = carPass; 42 | } 43 | 44 | public byte getDealResult() { 45 | return dealResult; 46 | } 47 | 48 | public void setDealResult(byte dealResult) { 49 | this.dealResult = dealResult; 50 | } 51 | 52 | public Date getDealTime() { 53 | return dealTime; 54 | } 55 | 56 | public void setDealTime(Date dealTime) { 57 | this.dealTime = dealTime; 58 | } 59 | 60 | public String getEndHourtime() { 61 | return endHourtime; 62 | } 63 | 64 | public void setEndHourtime(String endHourtime) { 65 | this.endHourtime = endHourtime; 66 | } 67 | 68 | public String getEndTime() { 69 | return endTime; 70 | } 71 | 72 | public void setEndTime(String endTime) { 73 | this.endTime = endTime; 74 | } 75 | 76 | public byte getLimitValue() { 77 | return limitValue; 78 | } 79 | 80 | public void setLimitValue(byte limitValue) { 81 | this.limitValue = limitValue; 82 | } 83 | 84 | public byte getParamDeal() { 85 | return paramDeal; 86 | } 87 | 88 | public void setParamDeal(byte paramDeal) { 89 | this.paramDeal = paramDeal; 90 | } 91 | 92 | public byte getParamType() { 93 | return paramType; 94 | } 95 | 96 | public void setParamType(byte paramType) { 97 | this.paramType = paramType; 98 | } 99 | 100 | public String getPhoneNumber() { 101 | return phoneNumber; 102 | } 103 | 104 | public void setPhoneNumber(String phoneNumber) { 105 | this.phoneNumber = phoneNumber; 106 | } 107 | 108 | public byte getReceiveResult() { 109 | return receiveResult; 110 | } 111 | 112 | public void setReceiveResult(byte receiveResult) { 113 | this.receiveResult = receiveResult; 114 | } 115 | 116 | public int getResendCount() { 117 | return resendCount; 118 | } 119 | 120 | public void setResendCount(int resendCount) { 121 | this.resendCount = resendCount; 122 | } 123 | 124 | public String getSendPerson() { 125 | return sendPerson; 126 | } 127 | 128 | public void setSendPerson(String sendPerson) { 129 | this.sendPerson = sendPerson; 130 | } 131 | 132 | public String getSendRemark() { 133 | return sendRemark; 134 | } 135 | 136 | public void setSendRemark(String sendRemark) { 137 | this.sendRemark = sendRemark; 138 | } 139 | 140 | public String getStartHourtime() { 141 | return startHourtime; 142 | } 143 | 144 | public void setStartHourtime(String startHourtime) { 145 | this.startHourtime = startHourtime; 146 | } 147 | 148 | public String getStartTime() { 149 | return startTime; 150 | } 151 | 152 | public void setStartTime(String startTime) { 153 | this.startTime = startTime; 154 | } 155 | 156 | public Date getStoreTime() { 157 | return storeTime; 158 | } 159 | 160 | public void setStoreTime(Date storeTime) { 161 | this.storeTime = storeTime; 162 | } 163 | 164 | public Integer getTypeId() { 165 | return typeId; 166 | } 167 | 168 | public void setTypeId(Integer typeId) { 169 | this.typeId = typeId; 170 | } 171 | 172 | public String getTypeName() { 173 | return typeName; 174 | } 175 | 176 | public void setTypeName(String typeName) { 177 | this.typeName = typeName; 178 | } 179 | 180 | public String getTypeValue() { 181 | return typeValue; 182 | } 183 | 184 | public void setTypeValue(String typeValue) { 185 | this.typeValue = typeValue; 186 | } 187 | 188 | } 189 | -------------------------------------------------------------------------------- /src/main/java/com/zhtkj/jt808/server/ServerApplication.java: -------------------------------------------------------------------------------- 1 | package com.zhtkj.jt808.server; 2 | 3 | import java.util.concurrent.TimeUnit; 4 | 5 | import javax.swing.JFrame; 6 | 7 | import org.slf4j.Logger; 8 | import org.slf4j.LoggerFactory; 9 | import org.springframework.context.support.AbstractApplicationContext; 10 | import org.springframework.context.support.ClassPathXmlApplicationContext; 11 | 12 | import io.netty.bootstrap.ServerBootstrap; 13 | import io.netty.buffer.Unpooled; 14 | import io.netty.channel.ChannelFuture; 15 | import io.netty.channel.ChannelInitializer; 16 | import io.netty.channel.ChannelOption; 17 | import io.netty.channel.EventLoopGroup; 18 | import io.netty.channel.nio.NioEventLoopGroup; 19 | import io.netty.channel.socket.SocketChannel; 20 | import io.netty.channel.socket.nio.NioServerSocketChannel; 21 | import io.netty.handler.codec.DelimiterBasedFrameDecoder; 22 | import io.netty.handler.timeout.IdleStateHandler; 23 | import io.netty.util.concurrent.Future; 24 | 25 | /** 26 | * ClassName: ServerApplication 27 | * @Description: 主程序及引导程序 28 | */ 29 | public class ServerApplication { 30 | 31 | private static final Logger LOGGER = LoggerFactory.getLogger(ServerApplication.class); 32 | 33 | public static AbstractApplicationContext appCtx; 34 | 35 | private volatile boolean isRunning = false; 36 | 37 | private int port; 38 | private EventLoopGroup bossGroup = null; 39 | private EventLoopGroup workerGroup = null; 40 | 41 | 42 | public ServerApplication(int port) { 43 | this.port = port; 44 | } 45 | 46 | private void bind() throws Exception { 47 | this.bossGroup = new NioEventLoopGroup(); 48 | this.workerGroup = new NioEventLoopGroup(); 49 | try { 50 | ServerBootstrap serverBootstrap = new ServerBootstrap(); 51 | serverBootstrap.group(bossGroup, workerGroup) 52 | .channel(NioServerSocketChannel.class) 53 | .childHandler(new ChannelInitializer() { 54 | @Override 55 | public void initChannel(SocketChannel ch) throws Exception { 56 | ch.pipeline().addLast("idleStateHandler", new IdleStateHandler(15, 0, 0, TimeUnit.MINUTES)); 57 | //1024表示单条消息的最大长度,解码器在查找分隔符的时候,达到该长度还没找到的话会抛异常 58 | ch.pipeline().addLast(new DelimiterBasedFrameDecoder(2048, true, Unpooled.copiedBuffer(new byte[] { 0x7e }), 59 | Unpooled.copiedBuffer(new byte[] { 0x7e, 0x7e }))); 60 | //添加业务处理handler 61 | ch.pipeline().addLast(new ServerHandler()); 62 | } 63 | }).option(ChannelOption.SO_BACKLOG, 128) 64 | .childOption(ChannelOption.SO_KEEPALIVE, true); 65 | LOGGER.info(this.getName() + "启动完毕, 端口={}", this.port); 66 | ChannelFuture channelFuture = serverBootstrap.bind(port).sync(); 67 | channelFuture.channel().closeFuture().sync(); 68 | } catch (Exception e) { 69 | e.printStackTrace(); 70 | } finally { 71 | this.workerGroup.shutdownGracefully(); 72 | this.bossGroup.shutdownGracefully(); 73 | } 74 | } 75 | 76 | public synchronized void startServer() { 77 | if (this.isRunning) { 78 | throw new IllegalStateException(this.getName() + "已启动,不能重复启动"); 79 | } 80 | this.isRunning = true; 81 | 82 | new Thread(() -> { 83 | try { 84 | this.bind(); 85 | } catch (Exception e) { 86 | e.printStackTrace(); 87 | } 88 | }, this.getName()).start(); 89 | } 90 | 91 | public synchronized void stopServer() { 92 | if (!this.isRunning) { 93 | throw new IllegalStateException(this.getName() + "未启动"); 94 | } 95 | this.isRunning = false; 96 | 97 | try { 98 | Future future = this.workerGroup.shutdownGracefully().await(); 99 | if (!future.isSuccess()) { 100 | } 101 | future = this.bossGroup.shutdownGracefully().await(); 102 | if (!future.isSuccess()) { 103 | } 104 | } catch (InterruptedException e) { 105 | e.printStackTrace(); 106 | } 107 | } 108 | 109 | private String getName() { 110 | return "终端通讯服务端"; 111 | } 112 | 113 | public static void main(String[] args) throws Exception { 114 | //初始化spring容器 115 | appCtx = new ClassPathXmlApplicationContext("applicationContext.xml"); 116 | 117 | //初始化netty 118 | new ServerApplication(6666).startServer(); 119 | 120 | //初始化窗口,这个窗口只是用来展示服务端是否启动 121 | JFrame frame = new JFrame(); 122 | frame.setTitle("终端通讯服务端(这个窗口只是用来展示服务端是否启动)"); 123 | frame.setSize(618, 381); 124 | frame.setVisible(true); 125 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 126 | } 127 | 128 | } -------------------------------------------------------------------------------- /src/main/java/com/zhtkj/jt808/vo/req/LocationMsg.java: -------------------------------------------------------------------------------- 1 | package com.zhtkj.jt808.vo.req; 2 | 3 | import com.zhtkj.jt808.vo.PackageData; 4 | 5 | /** 6 | * ClassName: LocationMsg 7 | * @Description: 基本位置信息消息 8 | */ 9 | public class LocationMsg extends PackageData { 10 | 11 | /** 12 | * @Fields locationInfo : 基本位置信息 13 | */ 14 | private LocationInfo locationInfo; 15 | 16 | public LocationMsg() { 17 | 18 | } 19 | 20 | public LocationMsg(PackageData packageData) { 21 | this(); 22 | this.channel = packageData.getChannel(); 23 | this.msgHead = packageData.getMsgHead(); 24 | this.msgBody = packageData.getMsgBody(); 25 | } 26 | 27 | public LocationInfo getLocationInfo() { 28 | return locationInfo; 29 | } 30 | 31 | public void setLocationInfo(LocationInfo locationInfo) { 32 | this.locationInfo = locationInfo; 33 | } 34 | 35 | public static class LocationInfo { 36 | 37 | private String carNumber; //车牌号码 38 | private String devPhone; //终端sim 39 | private String terminalIp; //终端ip地址 40 | private String carState; //车辆状态 41 | private float gpsPosX; //经度 42 | private float gpsPosY; //纬度 43 | private float gpsHeight; //高程 44 | private float gpsSpeed; //速度 45 | private float gpsDirect; //方向 46 | private String sendDatetime; //时间(设备时间) 47 | private String driverId; //司机ID 48 | private String workPassport; //核准证 49 | private byte boxClose; //车厢状态,1:关闭;2:打开 50 | private byte boxUp; //举升状态,1:平放;2:举升;3:完全举升 51 | private byte boxEmpty; //空重状态,1:空车;2:重车 52 | private byte carWeigui; //违规情况,1:违规;0:未违规 53 | 54 | 55 | public String getDevPhone() { 56 | return devPhone; 57 | } 58 | 59 | public void setDevPhone(String devPhone) { 60 | this.devPhone = devPhone; 61 | } 62 | 63 | public String getTerminalIp() { 64 | return terminalIp; 65 | } 66 | 67 | public void setTerminalIp(String terminalIp) { 68 | this.terminalIp = terminalIp; 69 | } 70 | 71 | public String getCarState() { 72 | return carState; 73 | } 74 | 75 | public void setCarState(String carState) { 76 | this.carState = carState; 77 | } 78 | 79 | public float getGpsPosX() { 80 | return gpsPosX; 81 | } 82 | 83 | public void setGpsPosX(float gpsPosX) { 84 | this.gpsPosX = gpsPosX; 85 | } 86 | 87 | public float getGpsPosY() { 88 | return gpsPosY; 89 | } 90 | 91 | public void setGpsPosY(float gpsPosY) { 92 | this.gpsPosY = gpsPosY; 93 | } 94 | 95 | public float getGpsHeight() { 96 | return gpsHeight; 97 | } 98 | 99 | public void setGpsHeight(float gpsHeight) { 100 | this.gpsHeight = gpsHeight; 101 | } 102 | 103 | public float getGpsSpeed() { 104 | return gpsSpeed; 105 | } 106 | 107 | public void setGpsSpeed(float gpsSpeed) { 108 | this.gpsSpeed = gpsSpeed; 109 | } 110 | 111 | public float getGpsDirect() { 112 | return gpsDirect; 113 | } 114 | 115 | public void setGpsDirect(float gpsDirect) { 116 | this.gpsDirect = gpsDirect; 117 | } 118 | 119 | public String getSendDatetime() { 120 | return sendDatetime; 121 | } 122 | 123 | public void setSendDatetime(String sendDatetime) { 124 | this.sendDatetime = sendDatetime; 125 | } 126 | 127 | public String getCarNumber() { 128 | return carNumber; 129 | } 130 | 131 | public void setCarNumber(String carNumber) { 132 | this.carNumber = carNumber; 133 | } 134 | 135 | public String getDriverId() { 136 | return driverId; 137 | } 138 | 139 | public void setDriverId(String driverId) { 140 | this.driverId = driverId; 141 | } 142 | 143 | public String getWorkPassport() { 144 | return workPassport; 145 | } 146 | 147 | public void setWorkPassport(String workPassport) { 148 | this.workPassport = workPassport; 149 | } 150 | 151 | public byte getBoxClose() { 152 | return boxClose; 153 | } 154 | 155 | public void setBoxClose(byte boxClose) { 156 | this.boxClose = boxClose; 157 | } 158 | 159 | public byte getBoxUp() { 160 | return boxUp; 161 | } 162 | 163 | public void setBoxUp(byte boxUp) { 164 | this.boxUp = boxUp; 165 | } 166 | 167 | public byte getBoxEmpty() { 168 | return boxEmpty; 169 | } 170 | 171 | public void setBoxEmpty(byte boxEmpty) { 172 | this.boxEmpty = boxEmpty; 173 | } 174 | 175 | public byte getCarWeigui() { 176 | return carWeigui; 177 | } 178 | 179 | public void setCarWeigui(byte carWeigui) { 180 | this.carWeigui = carWeigui; 181 | } 182 | 183 | } 184 | 185 | } 186 | -------------------------------------------------------------------------------- /src/main/java/com/zhtkj/jt808/entity/CarRuntime.java: -------------------------------------------------------------------------------- 1 | package com.zhtkj.jt808.entity; 2 | 3 | import java.math.BigDecimal; 4 | import java.util.Date; 5 | 6 | public class CarRuntime { 7 | 8 | private String carNumber; 9 | private String devPhone; 10 | private byte boxClose; 11 | private byte boxEmpty; 12 | private byte boxUp; 13 | private String driverId; 14 | private String carPassport; 15 | private String carPassword; 16 | private String carState; 17 | private byte carWeigui; 18 | private float gpsDirect; 19 | private float gpsHeight; 20 | private BigDecimal gpsPosX; 21 | private BigDecimal gpsPosY; 22 | private float gpsSpeed; 23 | private byte gpsValid; 24 | private Date offlineDatetime; 25 | private Date onlineDatetime; 26 | private Date reviceDatetime; 27 | private Date sendDatetime; 28 | private byte onlineState; 29 | 30 | public String getCarNumber() { 31 | return carNumber; 32 | } 33 | 34 | public void setCarNumber(String carNumber) { 35 | this.carNumber = carNumber; 36 | } 37 | 38 | public String getDevPhone() { 39 | return devPhone; 40 | } 41 | 42 | public void setDevPhone(String devPhone) { 43 | this.devPhone = devPhone; 44 | } 45 | 46 | public byte getBoxClose() { 47 | return boxClose; 48 | } 49 | 50 | public void setBoxClose(byte boxClose) { 51 | this.boxClose = boxClose; 52 | } 53 | 54 | public byte getBoxEmpty() { 55 | return boxEmpty; 56 | } 57 | 58 | public void setBoxEmpty(byte boxEmpty) { 59 | this.boxEmpty = boxEmpty; 60 | } 61 | 62 | public byte getBoxUp() { 63 | return boxUp; 64 | } 65 | 66 | public void setBoxUp(byte boxUp) { 67 | this.boxUp = boxUp; 68 | } 69 | 70 | public String getDriverId() { 71 | return driverId; 72 | } 73 | 74 | public void setDriverId(String driverId) { 75 | this.driverId = driverId; 76 | } 77 | 78 | public String getCarPassport() { 79 | return carPassport; 80 | } 81 | 82 | public void setCarPassport(String carPassport) { 83 | this.carPassport = carPassport; 84 | } 85 | 86 | public String getCarPassword() { 87 | return carPassword; 88 | } 89 | 90 | public void setCarPassword(String carPassword) { 91 | this.carPassword = carPassword; 92 | } 93 | 94 | public String getCarState() { 95 | return carState; 96 | } 97 | 98 | public void setCarState(String carState) { 99 | this.carState = carState; 100 | } 101 | 102 | public byte getCarWeigui() { 103 | return carWeigui; 104 | } 105 | 106 | public void setCarWeigui(byte carWeigui) { 107 | this.carWeigui = carWeigui; 108 | } 109 | 110 | public float getGpsDirect() { 111 | return gpsDirect; 112 | } 113 | 114 | public void setGpsDirect(float gpsDirect) { 115 | this.gpsDirect = gpsDirect; 116 | } 117 | 118 | public float getGpsHeight() { 119 | return gpsHeight; 120 | } 121 | 122 | public void setGpsHeight(float gpsHeight) { 123 | this.gpsHeight = gpsHeight; 124 | } 125 | 126 | public BigDecimal getGpsPosX() { 127 | return gpsPosX; 128 | } 129 | 130 | public void setGpsPosX(BigDecimal gpsPosX) { 131 | this.gpsPosX = gpsPosX; 132 | } 133 | 134 | public BigDecimal getGpsPosY() { 135 | return gpsPosY; 136 | } 137 | 138 | public void setGpsPosY(BigDecimal gpsPosY) { 139 | this.gpsPosY = gpsPosY; 140 | } 141 | 142 | public float getGpsSpeed() { 143 | return gpsSpeed; 144 | } 145 | 146 | public void setGpsSpeed(float gpsSpeed) { 147 | this.gpsSpeed = gpsSpeed; 148 | } 149 | 150 | public byte getGpsValid() { 151 | return gpsValid; 152 | } 153 | 154 | public void setGpsValid(byte gpsValid) { 155 | this.gpsValid = gpsValid; 156 | } 157 | 158 | public Date getOfflineDatetime() { 159 | return offlineDatetime; 160 | } 161 | 162 | public void setOfflineDatetime(Date offlineDatetime) { 163 | this.offlineDatetime = offlineDatetime; 164 | } 165 | 166 | public Date getOnlineDatetime() { 167 | return onlineDatetime; 168 | } 169 | 170 | public void setOnlineDatetime(Date onlineDatetime) { 171 | this.onlineDatetime = onlineDatetime; 172 | } 173 | 174 | public Date getReviceDatetime() { 175 | return reviceDatetime; 176 | } 177 | 178 | public void setReviceDatetime(Date reviceDatetime) { 179 | this.reviceDatetime = reviceDatetime; 180 | } 181 | 182 | public Date getSendDatetime() { 183 | return sendDatetime; 184 | } 185 | 186 | public void setSendDatetime(Date sendDatetime) { 187 | this.sendDatetime = sendDatetime; 188 | } 189 | 190 | public byte getOnlineState() { 191 | return onlineState; 192 | } 193 | 194 | public void setOnlineState(byte onlineState) { 195 | this.onlineState = onlineState; 196 | } 197 | 198 | } 199 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | com.zhtkj.jt808 6 | jt808-server 7 | 0.0.1-SNAPSHOT 8 | jar 9 | 10 | jt808-server 11 | 12 | 13 | UTF-8 14 | 4.3.17.RELEASE 15 | 16 | 17 | 18 | 19 | org.springframework 20 | spring-beans 21 | ${spring.version} 22 | 23 | 24 | org.springframework 25 | spring-context 26 | ${spring.version} 27 | 28 | 29 | org.springframework 30 | spring-context-support 31 | ${spring.version} 32 | 33 | 34 | org.springframework 35 | spring-core 36 | ${spring.version} 37 | 38 | 39 | org.springframework 40 | spring-jdbc 41 | ${spring.version} 42 | 43 | 44 | ch.qos.logback 45 | logback-classic 46 | 1.2.3 47 | 48 | 49 | io.netty 50 | netty-all 51 | 4.1.25.Final 52 | 53 | 54 | mysql 55 | mysql-connector-java 56 | 6.0.6 57 | 58 | 59 | com.alibaba 60 | druid 61 | 1.1.10 62 | 63 | 64 | org.mybatis 65 | mybatis 66 | 3.4.6 67 | 68 | 69 | org.mybatis 70 | mybatis-spring 71 | 1.3.2 72 | 73 | 74 | joda-time 75 | joda-time 76 | 2.10 77 | 78 | 79 | 80 | 81 | jt808-server 82 | 83 | 84 | src/main/java 85 | 86 | **/*.xml 87 | 88 | false 89 | 90 | 91 | src/main/resources 92 | 93 | **/*.properties 94 | **/*.xml 95 | 96 | false 97 | 98 | 99 | 100 | 101 | org.apache.maven.plugins 102 | maven-compiler-plugin 103 | 3.7.0 104 | 105 | 1.8 106 | 1.8 107 | UTF-8 108 | 109 | 110 | 111 | 112 | 113 | org.apache.maven.plugins 114 | maven-shade-plugin 115 | 3.1.1 116 | 117 | false 118 | 119 | 120 | 121 | package 122 | 123 | shade 124 | 125 | 126 | 127 | 128 | com.zhtkj.jt808.server.ServerApplication 129 | 130 | 131 | META-INF/spring.handlers 132 | 133 | 134 | META-INF/spring.schemas 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | -------------------------------------------------------------------------------- /src/main/java/com/zhtkj/jt808/server/ServerHandler.java: -------------------------------------------------------------------------------- 1 | package com.zhtkj.jt808.server; 2 | 3 | import com.zhtkj.jt808.common.JT808Const; 4 | import com.zhtkj.jt808.service.TerminalMsgProcessService; 5 | import com.zhtkj.jt808.service.codec.MsgDecoder; 6 | import com.zhtkj.jt808.vo.PackageData; 7 | import com.zhtkj.jt808.vo.PackageData.MsgBody; 8 | import com.zhtkj.jt808.vo.req.EventMsg; 9 | import com.zhtkj.jt808.vo.req.LocationMsg; 10 | import com.zhtkj.jt808.vo.req.VersionMsg; 11 | 12 | import io.netty.buffer.ByteBuf; 13 | import io.netty.channel.ChannelHandlerContext; 14 | import io.netty.channel.ChannelInboundHandlerAdapter; 15 | import io.netty.util.ReferenceCountUtil; 16 | 17 | /** 18 | * ClassName: ServerHandler 19 | * @Description: 业务处理handler, 所有终端发过来的数据首先就是由这个handler处理 20 | */ 21 | public class ServerHandler extends ChannelInboundHandlerAdapter { 22 | 23 | private MsgDecoder msgDecoder; 24 | private TerminalMsgProcessService msgProcessService; 25 | 26 | public ServerHandler() { 27 | this.msgDecoder = ServerApplication.appCtx.getBean(MsgDecoder.class); 28 | this.msgProcessService = ServerApplication.appCtx.getBean(TerminalMsgProcessService.class); 29 | } 30 | 31 | @Override 32 | public void channelRead(ChannelHandlerContext ctx, Object msg) throws InterruptedException { 33 | try { 34 | ByteBuf buf = (ByteBuf) msg; 35 | if (buf.readableBytes() <= 0) { 36 | return; 37 | } 38 | byte[] bs = new byte[buf.readableBytes()]; 39 | buf.readBytes(bs); 40 | //字节数据转换为针对于808消息结构的业务对象 41 | PackageData pkg = this.msgDecoder.bytes2PackageData(bs); 42 | //引用channel,以便回送数据给终端 43 | pkg.setChannel(ctx.channel()); 44 | this.processPackageData(pkg); 45 | } catch (Exception e) { 46 | e.printStackTrace(); 47 | } finally { 48 | ReferenceCountUtil.release(msg); 49 | } 50 | } 51 | 52 | @Override 53 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { 54 | cause.printStackTrace(); 55 | } 56 | 57 | @Override 58 | public void channelActive(ChannelHandlerContext ctx) throws Exception { 59 | 60 | } 61 | 62 | @Override 63 | public void channelInactive(ChannelHandlerContext ctx) throws Exception { 64 | SessionManager.getInstance().removeSessionByChannelId(ctx.channel().id().asLongText()); 65 | } 66 | 67 | @Override 68 | public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { 69 | 70 | } 71 | 72 | //根据不同的消息类型,选择不同的业务处理 73 | private void processPackageData(PackageData packageData) throws Exception { 74 | MsgBody body = packageData.getMsgBody(); 75 | int bodyId = body.getBodyId(); 76 | //任务类业务处理,这里是接收终端主动上报的信息,包括登录、上报的位置信息、上报的事件等等 77 | if (bodyId == JT808Const.TASK_BODY_ID_LOGIN) { 78 | this.msgProcessService.processLoginMsg(packageData); 79 | } else if (bodyId == JT808Const.TASK_BODY_ID_GPS) { 80 | LocationMsg msg = this.msgDecoder.toLocationMsg(packageData); 81 | this.msgProcessService.processLocationMsg(msg); 82 | } else if (bodyId == JT808Const.TASK_BODY_ID_EVENT) { 83 | EventMsg msg = this.msgDecoder.toEventMsg(packageData); 84 | this.msgProcessService.processEventMsg(msg); 85 | } else if (bodyId == JT808Const.TASK_BODY_ID_SELFCHECK) { 86 | this.msgProcessService.processSelfCheckMsg(packageData); 87 | } else if (bodyId == JT808Const.TASK_BODY_ID_VERSION) { 88 | VersionMsg msg = this.msgDecoder.toVersionMsg(packageData); 89 | this.msgProcessService.processVersionMsg(msg); 90 | } else if (bodyId == JT808Const.TASK_BODY_ID_CONFIG) { 91 | this.msgProcessService.processConfigMsg(packageData); 92 | } 93 | 94 | //命令类业务处理,这里是接收下发命令的响应,不是下发命令 95 | if (bodyId == JT808Const.ACTION_BODY_ID_LOCKCAR || 96 | bodyId == JT808Const.ACTION_BODY_ID_LIMITSPEED || 97 | bodyId == JT808Const.ACTION_BODY_ID_LIMITUP || 98 | bodyId == JT808Const.ACTION_BODY_ID_PASSWORD || 99 | bodyId == JT808Const.ACTION_BODY_ID_CONTROL || 100 | bodyId == JT808Const.ACTION_BODY_ID_LOCKCARCOMPANY) { 101 | this.msgProcessService.processActionMsg(packageData); 102 | } else if (bodyId == JT808Const.ACTION_BODY_ID_IMGACT) { 103 | this.msgProcessService.processImageActionMsg(packageData); 104 | } 105 | 106 | //参数类业务处理,这里是接收下发参数的响应,不是下发参数 107 | if (bodyId == JT808Const.PARAM_BODY_ID_LINE || 108 | bodyId == JT808Const.PARAM_BODY_ID_GONG || 109 | bodyId == JT808Const.PARAM_BODY_ID_XIAO || 110 | bodyId == JT808Const.PARAM_BODY_ID_LIMSPCIRCLE || 111 | bodyId == JT808Const.PARAM_BODY_ID_PARKING || 112 | bodyId == JT808Const.PARAM_BODY_ID_BAN || 113 | bodyId == JT808Const.PARAM_BODY_ID_WORKPASSPORT || 114 | bodyId == JT808Const.PARAM_BODY_ID_INFO || 115 | bodyId == JT808Const.PARAM_BODY_ID_FINGER || 116 | bodyId == JT808Const.PARAM_BODY_ID_REDLIGHT || 117 | bodyId == JT808Const.PARAM_BODY_ID_DEVICECONFIG || 118 | bodyId == JT808Const.PARAM_BODY_ID_LOCKCAREXT || 119 | bodyId == JT808Const.PARAM_BODY_ID_NOTIFY || 120 | bodyId == JT808Const.PARAM_BODY_ID_CONTROLSWITCH || 121 | bodyId == JT808Const.PARAM_BODY_ID_THRESHOLDVALUE) { 122 | this.msgProcessService.processParamMsg(packageData); 123 | } 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /src/main/java/com/zhtkj/jt808/util/DigitUtil.java: -------------------------------------------------------------------------------- 1 | package com.zhtkj.jt808.util; 2 | 3 | public class DigitUtil { 4 | 5 | /** 6 | * @Description: 截取byte数组,含头含尾 7 | * @param src 8 | * @param start 9 | * @param end 10 | * @return byte[] 11 | */ 12 | public static byte[] sliceBytes(byte[] src, Integer start, Integer end) { 13 | byte[] target = new byte[end - start + 1]; 14 | for (int i = start; i <= end; i++) { 15 | target[i - start] = src[i]; 16 | } 17 | return target; 18 | } 19 | 20 | /** 21 | * @Description: 将1byte转为2进制字符串 22 | * @param b 23 | * @return String 24 | */ 25 | public static String byteToBinaryStr(byte b) { 26 | return "" + (byte) ((b >> 7) & 0x1) + (byte) ((b >> 6) & 0x1) 27 | + (byte) ((b >> 5) & 0x1) + (byte) ((b >> 4) & 0x1) 28 | + (byte) ((b >> 3) & 0x1) + (byte) ((b >> 2) & 0x1) 29 | + (byte) ((b >> 1) & 0x1) + (byte) ((b >> 0) & 0x1); 30 | } 31 | 32 | public static int byte2ToInt(byte[] src) { 33 | int targets = (src[1] & 0xff) | ((src[0] << 8) & 0xff00); 34 | return targets; 35 | } 36 | 37 | public static int byte4ToInt(byte[] src) { 38 | return (src[0] & 0xff) << 24 | (src[1] & 0xff) << 16 | (src[2] & 0xff) << 8 | src[3] & 0xff; 39 | } 40 | 41 | public static long byte4ToInt(byte[] bs, int pos) { 42 | int byte1 = 0; 43 | int byte2 = 0; 44 | int byte3 = 0; 45 | int byte4 = 0; 46 | int index = pos; 47 | byte1 = (0x000000FF & ((int) bs[index])); 48 | byte2 = (0x000000FF & ((int) bs[index + 1])); 49 | byte3 = (0x000000FF & ((int) bs[index + 2])); 50 | byte4 = (0x000000FF & ((int) bs[index + 3])); 51 | index = index + 4; 52 | return ((long) (byte1 << 24 | byte2 << 16 | byte3 << 8 | byte4)) & 0xFFFFFFFFL; 53 | } 54 | 55 | public static String byteToBinaryStr(byte src, Integer high, Integer low) { 56 | String str = ""; 57 | for (int i = high; i >= low; i--) { 58 | str += (byte) ((src >> i) & 0x1); 59 | } 60 | return str; 61 | } 62 | 63 | public static byte binaryStrToByte(String str){ 64 | byte bt = 0; 65 | for(int i = str.length()-1, j = 0; i >= 0; i--, j++){ 66 | bt += (Byte.parseByte(str.charAt(i) + "") * Math.pow(2, j)); 67 | } 68 | return bt; 69 | } 70 | 71 | public static byte[] shortTo2Byte(short s) { 72 | byte[] target = new byte[2]; 73 | for (int i = 0; i < 2; i++) { 74 | int offset = (target.length - 1 - i) * 8; 75 | target[i] = (byte) ((s >>> offset) & 0xff); 76 | } 77 | return target; 78 | } 79 | 80 | public static byte[] intTo4Byte(int src) { 81 | byte[] targets = new byte[4]; 82 | for (int i = 0; i < 4; i++) { 83 | int offset = (targets.length - 1 - i) * 8; 84 | targets[i] = (byte) ((src >>> offset) & 0xff); 85 | } 86 | return targets; 87 | } 88 | 89 | public static byte[] int32To4Byte(int src) { 90 | byte[] targets = new byte[4]; 91 | targets[0] = (byte) (src & 0xff); // 最低位 92 | targets[1] = (byte) ((src >> 8) & 0xff); //次低位 93 | targets[2] = (byte) ((src >> 16) & 0xff); // 次高位 94 | targets[3] = (byte) (src >>> 24); //最高位,无符号右移。 95 | return targets; 96 | } 97 | 98 | public static String bcdToStr(byte[] bytes) { 99 | StringBuffer sb = new StringBuffer(bytes.length * 2); 100 | for (int i = 0; i < bytes.length; i++) { 101 | sb.append((byte) ((bytes[i] & 0xf0) >>> 4)); 102 | sb.append((byte) (bytes[i] & 0x0f)); 103 | } 104 | return sb.toString().substring(0, 1).equalsIgnoreCase("0") ? sb 105 | .toString().substring(1) : sb.toString(); 106 | } 107 | 108 | public static String bcdToStr(byte bytes) { 109 | StringBuffer sb = new StringBuffer(2); 110 | sb.append((byte) ((bytes & 0xf0) >>> 4)); 111 | sb.append((byte) (bytes & 0x0f)); 112 | return sb.toString().substring(0, 1).equalsIgnoreCase("0") ? sb.toString().substring(1) : sb.toString(); 113 | } 114 | 115 | public static byte[] strToBcd(String asc) { 116 | int len = asc.length(); 117 | int mod = len % 2; 118 | if (mod != 0) { 119 | asc = "0" + asc; 120 | len = asc.length(); 121 | } 122 | byte abt[] = new byte[len]; 123 | if (len >= 2) { 124 | len = len / 2; 125 | } 126 | byte bbt[] = new byte[len]; 127 | abt = asc.getBytes(); 128 | int j, k; 129 | for (int p = 0; p < asc.length() / 2; p++) { 130 | if ((abt[2 * p] >= '0') && (abt[2 * p] <= '9')) { 131 | j = abt[2 * p] - '0'; 132 | } else if ((abt[2 * p] >= 'a') && (abt[2 * p] <= 'z')) { 133 | j = abt[2 * p] - 'a' + 0x0a; 134 | } else { 135 | j = abt[2 * p] - 'A' + 0x0a; 136 | } 137 | if ((abt[2 * p + 1] >= '0') && (abt[2 * p + 1] <= '9')) { 138 | k = abt[2 * p + 1] - '0'; 139 | } else if ((abt[2 * p + 1] >= 'a') && (abt[2 * p + 1] <= 'z')) { 140 | k = abt[2 * p + 1] - 'a' + 0x0a; 141 | } else { 142 | k = abt[2 * p + 1] - 'A' + 0x0a; 143 | } 144 | int a = (j << 4) + k; 145 | byte b = (byte) a; 146 | bbt[p] = b; 147 | } 148 | return bbt; 149 | } 150 | 151 | public static int get808PackCheckCode(byte[] bs) { 152 | int checkCode = 0; 153 | if (bs.length < 3) { 154 | checkCode = 0; 155 | } else { 156 | for (int i = 1; i < bs.length - 2; i++) { 157 | checkCode = checkCode ^ (int) bs[i]; 158 | } 159 | } 160 | return checkCode; 161 | } 162 | 163 | } 164 | -------------------------------------------------------------------------------- /src/main/java/com/zhtkj/jt808/service/ServerMsgProcessService.java: -------------------------------------------------------------------------------- 1 | package com.zhtkj.jt808.service; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.context.annotation.Scope; 7 | import org.springframework.stereotype.Service; 8 | 9 | import com.zhtkj.jt808.common.JT808Const; 10 | import com.zhtkj.jt808.entity.CarRuntime; 11 | import com.zhtkj.jt808.entity.DataAction; 12 | import com.zhtkj.jt808.entity.DataParam; 13 | import com.zhtkj.jt808.mapper.CarRuntimeMapper; 14 | import com.zhtkj.jt808.mapper.DataActionMapper; 15 | import com.zhtkj.jt808.mapper.DataParamMapper; 16 | import com.zhtkj.jt808.service.codec.MsgEncoder; 17 | 18 | import io.netty.channel.Channel; 19 | 20 | @Service 21 | @Scope("prototype") 22 | public class ServerMsgProcessService extends BaseMsgProcessService { 23 | 24 | @Autowired 25 | private MsgEncoder msgEncoder; 26 | 27 | @Autowired 28 | private CarRuntimeMapper carRuntimeMapper; 29 | 30 | @Autowired 31 | private DataActionMapper dataActionMapper; 32 | 33 | @Autowired 34 | private DataParamMapper dataParamMapper; 35 | 36 | //处理要发送给终端的指令 37 | public void processSendActionMsg() throws Exception { 38 | List actions = dataActionMapper.findSendActionData(); 39 | for (DataAction action: actions) { 40 | try { 41 | //根据不同的指令类型打包消息体byte[] 42 | int actionType = action.getActionType(); 43 | byte[] bodybs = null; 44 | if (actionType == 1) { //锁车命令 45 | bodybs = msgEncoder.encode4CommonActionBody(JT808Const.ACTION_BODY_ID_LOCKCAR, action); 46 | } else if (actionType == 2) { //限速命令 47 | bodybs = msgEncoder.encode4CommonActionBody(JT808Const.ACTION_BODY_ID_LIMITSPEED, action); 48 | } else if (actionType == 3) { //限举命令 49 | bodybs = msgEncoder.encode4CommonActionBody(JT808Const.ACTION_BODY_ID_LIMITUP, action); 50 | } else if (actionType == 6) { //管控命令 51 | bodybs = msgEncoder.encode4CommonActionBody(JT808Const.ACTION_BODY_ID_CONTROL, action); 52 | } else if (actionType == 7) { //运输公司锁车命令 53 | bodybs = msgEncoder.encode4CommonActionBody(JT808Const.ACTION_BODY_ID_LOCKCARCOMPANY, action); 54 | } else if (actionType == 4) { //抓拍指令 55 | bodybs = msgEncoder.encode4ImageActionBody(JT808Const.ACTION_BODY_ID_IMGACT, action); 56 | } else if (actionType == 5) { //密码指令 57 | List carRuntimes = carRuntimeMapper.findCarPassword(action.getPhoneNumber()); 58 | if (carRuntimes.size() > 0 && carRuntimes.get(0).getCarPassword() != null) { 59 | bodybs = msgEncoder.encode4PasswordActionBody( 60 | JT808Const.ACTION_BODY_ID_PASSWORD, action, carRuntimes.get(0).getCarPassword()); 61 | } else { 62 | continue; 63 | } 64 | } 65 | //打包消息byte[] 66 | byte[] msgbs = msgEncoder.encode4Msg(JT808Const.ACTION_HEAD_ID, action.getPhoneNumber(), bodybs); 67 | Channel channel = sessionManager.getChannelByKey(action.getPhoneNumber()); 68 | if (channel != null && channel.isOpen()) { 69 | //发送byte[]给终端并更新receive_result状态 70 | send2Terminal(channel, msgbs); 71 | dataActionMapper.updateActionReceiveResult(action.getActionId(), 1); 72 | } else { 73 | dataActionMapper.updateActionReceiveResult(action.getActionId(), -1); 74 | } 75 | } catch (Exception e) { 76 | dataActionMapper.updateActionReceiveResult(action.getActionId(), -1); 77 | e.printStackTrace(); 78 | } 79 | } 80 | } 81 | 82 | //处理要发送给终端的参数 83 | public void processSendParamMsg() throws Exception { 84 | List params = dataParamMapper.findSendParamData(); 85 | for (DataParam param: params) { 86 | try { 87 | int paramType = param.getParamType(); 88 | byte[] bodybs = null; 89 | if (paramType == 1) { 90 | bodybs = msgEncoder.encode4FenceParamBody(JT808Const.PARAM_BODY_ID_LINE, param); 91 | } else if (paramType == 2) { 92 | bodybs = msgEncoder.encode4FenceParamBody(JT808Const.PARAM_BODY_ID_GONG, param); 93 | } else if (paramType == 3) { 94 | bodybs = msgEncoder.encode4FenceParamBody(JT808Const.PARAM_BODY_ID_XIAO, param); 95 | } else if (paramType == 4) { 96 | bodybs = msgEncoder.encode4FenceParamBody(JT808Const.PARAM_BODY_ID_LIMSPCIRCLE, param); 97 | } else if (paramType == 5) { 98 | bodybs = msgEncoder.encode4FenceParamBody(JT808Const.PARAM_BODY_ID_PARKING, param); 99 | } else if (paramType == 6) { 100 | bodybs = msgEncoder.encode4FenceParamBody(JT808Const.PARAM_BODY_ID_BAN, param); 101 | } 102 | if (paramType == 7) { 103 | bodybs = msgEncoder.encode4DirectParamBody(JT808Const.PARAM_BODY_ID_WORKPASSPORT, param); 104 | } else if (paramType == 8) { 105 | bodybs = msgEncoder.encode4DirectParamBody(JT808Const.PARAM_BODY_ID_INFO, param); 106 | } else if (paramType == 9) { 107 | bodybs = msgEncoder.encode4DirectParamBody(JT808Const.PARAM_BODY_ID_FINGER, param); 108 | } else if (paramType == 10) { 109 | bodybs = msgEncoder.encode4DirectParamBody(JT808Const.PARAM_BODY_ID_REDLIGHT, param); 110 | } else if (paramType == 11) { 111 | bodybs = msgEncoder.encode4DirectParamBody(JT808Const.PARAM_BODY_ID_DEVICECONFIG, param); 112 | } else if (paramType == 12) { 113 | bodybs = msgEncoder.encode4DirectParamBody(JT808Const.PARAM_BODY_ID_LOCKCAREXT, param); 114 | } else if (paramType == 13) { 115 | bodybs = msgEncoder.encode4DirectParamBody(JT808Const.PARAM_BODY_ID_CONTROLSWITCH, param); 116 | } else if (paramType == 14) { 117 | bodybs = msgEncoder.encode4DirectParamBody(JT808Const.PARAM_BODY_ID_THRESHOLDVALUE, param); 118 | } else if (paramType == 15) { 119 | bodybs = msgEncoder.encode4DirectParamBody(JT808Const.PARAM_BODY_ID_NOTIFY, param); 120 | } 121 | byte[] msgbs = msgEncoder.encode4Msg(JT808Const.PARAM_HEAD_ID, param.getPhoneNumber(), bodybs); 122 | Channel channel = sessionManager.getChannelByKey(param.getPhoneNumber()); 123 | if (channel != null && channel.isOpen()) { 124 | //发送byte[]给终端并更新receive_result状态 125 | super.send2Terminal(channel, msgbs); 126 | dataParamMapper.updateParamReceiveResult(param.getParamId(), 1); 127 | } else { 128 | dataParamMapper.updateParamReceiveResult(param.getParamId(), -1); 129 | } 130 | } catch (Exception e) { 131 | dataParamMapper.updateParamReceiveResult(param.getParamId(), -1); 132 | e.printStackTrace(); 133 | } 134 | } 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /src/main/java/com/zhtkj/jt808/service/TerminalMsgProcessService.java: -------------------------------------------------------------------------------- 1 | package com.zhtkj.jt808.service; 2 | 3 | import java.io.File; 4 | import java.io.FileOutputStream; 5 | import java.io.IOException; 6 | import java.util.List; 7 | 8 | import org.joda.time.DateTime; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.context.annotation.Scope; 11 | import org.springframework.stereotype.Service; 12 | 13 | import com.zhtkj.jt808.common.JT808Const; 14 | import com.zhtkj.jt808.entity.Config; 15 | import com.zhtkj.jt808.mapper.CarEventMapper; 16 | import com.zhtkj.jt808.mapper.CarHistoryMapper; 17 | import com.zhtkj.jt808.mapper.CarRuntimeMapper; 18 | import com.zhtkj.jt808.mapper.ConfigMapper; 19 | import com.zhtkj.jt808.mapper.DataActionMapper; 20 | import com.zhtkj.jt808.mapper.DataParamMapper; 21 | import com.zhtkj.jt808.service.codec.MsgEncoder; 22 | import com.zhtkj.jt808.util.CarEventUtil; 23 | import com.zhtkj.jt808.util.CarHistoryUtil; 24 | import com.zhtkj.jt808.util.DigitUtil; 25 | import com.zhtkj.jt808.vo.PackageData; 26 | import com.zhtkj.jt808.vo.PackageData.MsgBody; 27 | import com.zhtkj.jt808.vo.Session; 28 | import com.zhtkj.jt808.vo.req.EventMsg; 29 | import com.zhtkj.jt808.vo.req.EventMsg.EventInfo; 30 | import com.zhtkj.jt808.vo.req.LocationMsg; 31 | import com.zhtkj.jt808.vo.req.LocationMsg.LocationInfo; 32 | import com.zhtkj.jt808.vo.req.VersionMsg; 33 | import com.zhtkj.jt808.vo.req.VersionMsg.VersionInfo; 34 | import com.zhtkj.jt808.vo.resp.RespMsgBody; 35 | 36 | @Service 37 | @Scope("prototype") 38 | public class TerminalMsgProcessService extends BaseMsgProcessService { 39 | 40 | @Autowired 41 | private MsgEncoder msgEncoder; 42 | 43 | @Autowired 44 | private CarRuntimeMapper carRuntimeMapper; 45 | 46 | @Autowired 47 | private CarHistoryMapper carHistoryMapper; 48 | 49 | @Autowired 50 | private CarEventMapper carEventMapper; 51 | 52 | @Autowired 53 | private DataActionMapper dataActionMapper; 54 | 55 | @Autowired 56 | private DataParamMapper dataParamMapper; 57 | 58 | @Autowired 59 | private ConfigMapper configMapper; 60 | 61 | //处理终端登录业务 62 | public void processLoginMsg(PackageData packageData) throws Exception { 63 | String terminalPhone = packageData.getMsgHead().getTerminalPhone(); 64 | Session session = new Session(terminalPhone, packageData.getChannel()); 65 | session.setLastCommunicateTime(new DateTime()); 66 | sessionManager.addSession(terminalPhone, session); 67 | carRuntimeMapper.setCarOnlineState(terminalPhone); 68 | //发送登录响应数据包给终端,暂时是不用验证就可以登录 69 | byte[] bs = this.msgEncoder.encode4LoginResp(packageData, new RespMsgBody((byte) 1)); 70 | super.send2Terminal(packageData.getChannel(), bs); 71 | } 72 | 73 | //处理基本位置信息业务 74 | public void processLocationMsg(LocationMsg msg) throws Exception { 75 | LocationInfo locationInfo = msg.getLocationInfo(); 76 | if (carRuntimeMapper.updateCarRuntime(locationInfo) == 0) { 77 | carRuntimeMapper.insertCarRuntime(locationInfo); 78 | } 79 | //判断是否需要写入位置信息到数据库 80 | if (CarHistoryUtil.isPersistent(locationInfo)) { 81 | carHistoryMapper.insertCarHistory(DateTime.now().toString("M"), locationInfo); 82 | } 83 | Session session = sessionManager.findSessionByKey(msg.getMsgHead().getTerminalPhone()); 84 | //如果session等于null则证明终端没有先发送登录包过来,需要主动断开该连接 85 | if (session == null) { 86 | msg.getChannel().close(); 87 | } else { 88 | session.setLastCommunicateTime(DateTime.now()); 89 | byte[] bs = this.msgEncoder.encode4LocationResp(msg, new RespMsgBody((byte) 1)); 90 | super.send2Terminal(msg.getChannel(), bs); 91 | } 92 | } 93 | 94 | //处理事件业务 95 | public void processEventMsg(EventMsg msg) throws Exception { 96 | EventInfo eventInfo = msg.getEventInfo(); 97 | //判断是否需要写入事件到数据库 98 | if (CarEventUtil.isPersistent(eventInfo)) { 99 | carEventMapper.insertCarEvent(DateTime.now().toString("M"), eventInfo, eventInfo.getLocationInfo()); 100 | } 101 | } 102 | 103 | //处理自检信息业务 104 | public void processSelfCheckMsg(PackageData packageData) { 105 | carRuntimeMapper.setCarOnlineState(packageData.getMsgHead().getTerminalPhone()); 106 | } 107 | 108 | //处理终端版本信息业务 109 | public void processVersionMsg(VersionMsg versionMsg) throws InterruptedException { 110 | VersionInfo versionInfo = versionMsg.getVersionInfo(); 111 | if (configMapper.updateConfig(versionInfo) == 0) { 112 | configMapper.insertConfig(versionInfo); 113 | } 114 | int replyResult = 3; 115 | Config config = configMapper.selectConfigByKey(versionInfo.getMac()).get(0); 116 | String[] versions = config.getVersion().replace("V", "").split("\\."); 117 | String[] sysVersions = config.getVersionSys().replace("V", "").split("\\."); 118 | int updateTag = config.getUpdateTag(); 119 | int updateCfgTag = config.getUpdateCfgTag(); 120 | int[] versionsInt = new int[4]; 121 | int[] sysVersionsInt = new int[4]; 122 | for (int i = 0; i < 4; i++) { 123 | if (versions.length >= (i + 1)) { 124 | versionsInt[i] = Integer.valueOf(versions[i]).intValue(); 125 | } else { 126 | versionsInt[i] = 0; 127 | } 128 | if (sysVersions.length >= (i + 1)) { 129 | sysVersionsInt[i] = Integer.valueOf(sysVersions[i]).intValue(); 130 | } else { 131 | sysVersionsInt[i] = 0; 132 | } 133 | } 134 | if (sysVersionsInt[0] > versionsInt[0] || 135 | sysVersionsInt[1] > versionsInt[1] || 136 | sysVersionsInt[2] > versionsInt[2] || 137 | sysVersionsInt[3] > versionsInt[3]) { 138 | if (updateTag == 1 && updateCfgTag == 0) { 139 | replyResult = 1; 140 | } else if (updateTag == 1 && updateCfgTag == 1) { 141 | replyResult = 2; 142 | } 143 | } else { 144 | replyResult = 0; 145 | } 146 | byte[] bs = msgEncoder.encode4VersionResp(versionMsg, new RespMsgBody((byte) replyResult)); 147 | super.send2Terminal(versionMsg.getChannel(), bs); 148 | } 149 | 150 | //处理终端配置更新业务 151 | public void processConfigMsg(PackageData packageData) throws Exception { 152 | byte[] bodybs = packageData.getMsgBody().getBodyBytes(); 153 | byte[] macbs = DigitUtil.sliceBytes(bodybs, 12, 28); 154 | String mac = new String(macbs); 155 | List configs = configMapper.selectConfigByKey(mac); 156 | if (configs.size() > 0) { 157 | Config config = configs.get(0); 158 | //车辆信息中车牌号包含4412或者终端手机号码是17775754123时,不下发配置文件 159 | if (!config.getCarNumber().contains("4412") && !config.getDevPhone().equals("17775754123")) { 160 | byte[] bs = msgEncoder.encode4ConfigResp(packageData, config); 161 | super.send2Terminal(packageData.getChannel(), bs); 162 | } 163 | } 164 | } 165 | 166 | //处理指令业务,这里是处理终端返回的指令执行响应,不是下发指令 167 | public void processActionMsg(PackageData packageData) { 168 | dataActionMapper.updateActionDealResult(packageData.getMsgBody()); 169 | } 170 | 171 | //处理抓拍业务 172 | public void processImageActionMsg(PackageData packageData) throws Exception { 173 | MsgBody msgBody = packageData.getMsgBody(); 174 | byte[] bodybs = msgBody.getBodyBytes(); 175 | long serialId = msgBody.getBodySerial(); 176 | //如果流水号很大则是事件抓拍,否则就是指令抓拍 177 | if (serialId > 888888) { 178 | //这里好像没什么用 179 | } else { 180 | //保存图片到服务器 181 | File file = new File(JT808Const.IMAGE_SAVE_PATH + serialId + ".jpg"); 182 | try (FileOutputStream out = new FileOutputStream(file)) { 183 | out.write(bodybs, 6, bodybs.length - 6); //减去标示符2位,唯一ID4位,共6位。 184 | out.flush(); 185 | } catch (IOException e) { 186 | throw new RuntimeException(e.getMessage(), e); 187 | } 188 | msgBody.setResult(1); 189 | //更新抓拍指令执行结果 190 | this.processActionMsg(packageData); 191 | } 192 | } 193 | 194 | //处理参数业务,这里是处理终端返回的参数执行响应 195 | public void processParamMsg(PackageData packageData) { 196 | dataParamMapper.updateParamResult(packageData.getMsgBody()); 197 | } 198 | 199 | } 200 | -------------------------------------------------------------------------------- /src/main/java/com/zhtkj/jt808/service/codec/MsgEncoder.java: -------------------------------------------------------------------------------- 1 | package com.zhtkj.jt808.service.codec; 2 | 3 | import java.io.UnsupportedEncodingException; 4 | 5 | import org.springframework.context.annotation.Scope; 6 | import org.springframework.stereotype.Component; 7 | 8 | import com.zhtkj.jt808.common.JT808Const; 9 | import com.zhtkj.jt808.entity.Config; 10 | import com.zhtkj.jt808.entity.DataAction; 11 | import com.zhtkj.jt808.entity.DataParam; 12 | import com.zhtkj.jt808.util.ArrayUtil; 13 | import com.zhtkj.jt808.util.DigitUtil; 14 | import com.zhtkj.jt808.vo.PackageData; 15 | import com.zhtkj.jt808.vo.req.EventMsg; 16 | import com.zhtkj.jt808.vo.req.LocationMsg; 17 | import com.zhtkj.jt808.vo.req.VersionMsg; 18 | import com.zhtkj.jt808.vo.resp.RespMsgBody; 19 | 20 | /** 21 | * ClassName: MsgEncoder 22 | * @Description: 消息编码器 23 | */ 24 | @Component 25 | @Scope("prototype") 26 | public class MsgEncoder { 27 | 28 | //编码整个消息包 29 | public byte[] encode4Msg(int headId, String terminalPhone, byte[] bodybs) { 30 | //消息头 31 | byte[] headbs = new byte[13]; 32 | headbs[0] = (byte) JT808Const.MSG_DELIMITER; 33 | //消息头标识Id 34 | byte[] headidbs = DigitUtil.shortTo2Byte((short) headId); 35 | headbs[1] = headidbs[0]; 36 | headbs[2] = headidbs[1]; 37 | //消息体属性 38 | //先获取消息体长度,并转成2个字节16位格式 39 | //808规范中用10bit表示长度,所以最大不能超过1024 40 | byte[] bodylengthbs = DigitUtil.shortTo2Byte((short) bodybs.length); 41 | //808规范中用10bit表示长度,所以只取低10bit,0~9 42 | String bodylength = "" + 43 | //第一个字节最后2bit 44 | + (byte) ((bodylengthbs[0] >> 1) & 0x1) + (byte) ((bodylengthbs[0] >> 0) & 0x1) 45 | //第二个字节8bit 46 | + (byte) ((bodylengthbs[1] >> 7) & 0x1) + (byte) ((bodylengthbs[1] >> 6) & 0x1) 47 | + (byte) ((bodylengthbs[1] >> 5) & 0x1) + (byte) ((bodylengthbs[1] >> 4) & 0x1) 48 | + (byte) ((bodylengthbs[1] >> 3) & 0x1) + (byte) ((bodylengthbs[1] >> 2) & 0x1) 49 | + (byte) ((bodylengthbs[1] >> 1) & 0x1) + (byte) ((bodylengthbs[1] >> 0) & 0x1); 50 | //加密方式为不加密,第10、11、12三位都为0,表示消息体不加密 51 | String encrypt = "000"; 52 | //暂无分包,第13bit为0 53 | String subpackage = "0"; 54 | //保留,第14,15bit为0 55 | String retain = "00"; 56 | //生成消息体属性 57 | byte[] bodyattrbs = new byte[2]; 58 | //消息体高8位 59 | bodyattrbs[0] = DigitUtil.binaryStrToByte(retain + subpackage + encrypt + bodylength.substring(0, 2)); 60 | //消息体低8位 61 | bodyattrbs[1] = DigitUtil.binaryStrToByte(bodylength.substring(2, 10)); 62 | headbs[3] = bodyattrbs[0]; 63 | headbs[4] = bodyattrbs[1]; 64 | //手机号码 65 | byte[] phonebs = DigitUtil.strToBcd(terminalPhone); 66 | headbs[5] = phonebs[0]; 67 | headbs[6] = phonebs[1]; 68 | headbs[7] = phonebs[2]; 69 | headbs[8] = phonebs[3]; 70 | headbs[9] = phonebs[4]; 71 | headbs[10] = phonebs[5]; 72 | //消息流水号 73 | headbs[11] = 0x00; 74 | headbs[12] = 0x00; 75 | 76 | //消息尾 77 | byte[] tailbs = new byte[] {0x00, (byte) JT808Const.MSG_DELIMITER}; 78 | 79 | //整个消息 80 | byte[] msgbs = ArrayUtil.concatAll(headbs, bodybs, tailbs); 81 | //设置校验码 82 | msgbs[msgbs.length - 2] = (byte) DigitUtil.get808PackCheckCode(msgbs); 83 | return msgbs; 84 | } 85 | 86 | //编码通用的应答消息体 87 | public byte[] encode4CommonRespBody(int bodyId, int replyResult) { 88 | byte[] src = DigitUtil.shortTo2Byte((short) bodyId); 89 | return ArrayUtil.concatAll(src, new byte[] {(byte) replyResult}); 90 | } 91 | 92 | //生成登录响应包 93 | public byte[] encode4LoginResp(PackageData packageData, RespMsgBody respMsgBody) { 94 | byte[] bodybs = this.encode4CommonRespBody(JT808Const.TASK_BODY_ID_LOGIN, respMsgBody.getReplyResult()); 95 | byte[] msgbs = this.encode4Msg(JT808Const.TASK_HEAD_ID, packageData.getMsgHead().getTerminalPhone(), bodybs); 96 | return msgbs; 97 | } 98 | 99 | //生成位置信息响应包 100 | public byte[] encode4LocationResp(LocationMsg msg, RespMsgBody respMsgBody) { 101 | byte[] bodybs = this.encode4CommonRespBody(JT808Const.TASK_BODY_ID_GPS, respMsgBody.getReplyResult()); 102 | byte[] msgbs = this.encode4Msg(JT808Const.TASK_HEAD_ID, msg.getMsgHead().getTerminalPhone(), bodybs); 103 | return msgbs; 104 | } 105 | 106 | //生成事件响应包 107 | public byte[] encode4EventResp(EventMsg msg, RespMsgBody respMsgBody) { 108 | byte[] bodybs = this.encode4CommonRespBody(JT808Const.TASK_BODY_ID_EVENT, respMsgBody.getReplyResult()); 109 | byte[] msgbs = this.encode4Msg(JT808Const.TASK_HEAD_ID, msg.getMsgHead().getTerminalPhone(), bodybs); 110 | return msgbs; 111 | } 112 | 113 | //生成终端版本信息上报响应包 114 | public byte[] encode4VersionResp(VersionMsg msg, RespMsgBody respMsgBody) { 115 | byte[] bodybs = this.encode4CommonRespBody(JT808Const.TASK_BODY_ID_VERSION, respMsgBody.getReplyResult()); 116 | byte[] msgbs = this.encode4Msg(JT808Const.TASK_HEAD_ID, msg.getMsgHead().getTerminalPhone(), bodybs); 117 | return msgbs; 118 | } 119 | 120 | //生成终端配置信息上报响应包 121 | public byte[] encode4ConfigResp(PackageData packageData, Config config) throws UnsupportedEncodingException { 122 | byte[] bodyidbs = DigitUtil.shortTo2Byte((short) JT808Const.TASK_BODY_ID_CONFIG); 123 | byte[] headserialbs = DigitUtil.int32To4Byte(packageData.getMsgHead().getHeadSerial()); 124 | byte[] macbs = config.getMac().getBytes(); 125 | byte[] configbs = (config.getCarNumber() + "," + config.getDevPhone() + "," 126 | + config.getVersion() + "," + config.getEcuType() + "," + config.getCarType()).getBytes(); 127 | byte[] bodybs = ArrayUtil.concatAll(bodyidbs, headserialbs, macbs, configbs); 128 | byte[] msgbs = this.encode4Msg(JT808Const.TASK_HEAD_ID, packageData.getMsgHead().getTerminalPhone(), bodybs); 129 | return msgbs; 130 | } 131 | 132 | //编码通用的要下发的指令消息体 133 | public byte[] encode4CommonActionBody(int msgType, DataAction action) { 134 | byte[] msgTypebs = new byte[2]; 135 | msgTypebs = DigitUtil.shortTo2Byte((short) msgType); 136 | byte[] serialbs = new byte[4]; 137 | serialbs = DigitUtil.intTo4Byte(action.getActionId()); 138 | byte[] valuebs = new byte[] {(byte)action.getActionValue()}; 139 | return ArrayUtil.concatAll(msgTypebs, serialbs, valuebs); 140 | } 141 | 142 | //编码抓拍指令消息体 143 | public byte[] encode4ImageActionBody(int msgType, DataAction action) { 144 | byte[] msgTypebs = new byte[2]; 145 | msgTypebs = DigitUtil.shortTo2Byte((short) msgType); 146 | byte[] serialbs = new byte[4]; 147 | serialbs = DigitUtil.intTo4Byte(action.getActionId()); 148 | byte[] valuebs = new byte[] {(byte)2, (byte)2, (byte)1, (byte)1, (byte)1, (byte)0, (byte)0}; 149 | return ArrayUtil.concatAll(msgTypebs, serialbs, valuebs); 150 | } 151 | 152 | //编码密码指令消息体 153 | public byte[] encode4PasswordActionBody(int msgType, DataAction action, String carPassword) { 154 | byte[] msgTypebs = new byte[2]; 155 | msgTypebs = DigitUtil.shortTo2Byte((short) msgType); 156 | byte[] serialbs = new byte[4]; 157 | serialbs = DigitUtil.intTo4Byte(action.getActionId()); 158 | return ArrayUtil.concatAll(msgTypebs, serialbs, carPassword.getBytes()); 159 | } 160 | 161 | //编码参数消息体(直接取值) 162 | public byte[] encode4DirectParamBody(int msgType, DataParam param) throws UnsupportedEncodingException { 163 | byte[] msgTypebs = new byte[2]; 164 | msgTypebs = DigitUtil.shortTo2Byte((short) msgType); 165 | byte[] serialbs = new byte[4]; 166 | serialbs = DigitUtil.intTo4Byte(param.getParamId()); 167 | return ArrayUtil.concatAll(msgTypebs, serialbs, 168 | new byte[] {param.getParamDeal()}, 169 | new byte[] {param.getLimitValue()}, 170 | param.getTypeValue().getBytes("GBK")); 171 | } 172 | 173 | //编码参数消息体(围栏类型) 174 | public byte[] encode4FenceParamBody(int msgType, DataParam param) throws UnsupportedEncodingException { 175 | byte[] msgTypebs = new byte[2]; 176 | msgTypebs = DigitUtil.shortTo2Byte((short) msgType); 177 | byte[] serialbs = new byte[4]; 178 | serialbs = DigitUtil.intTo4Byte(param.getParamId()); 179 | //将gps坐标点转成byte[] 180 | String[] points = param.getTypeValue().split(";"); 181 | byte[] pointbs = new byte[points.length * 8]; 182 | for (int i = 0; i < points.length; i++) { 183 | String[] point = points[i].split(","); 184 | float x = Float.parseFloat(point[0]); 185 | float y = Float.parseFloat(point[1]); 186 | x = x * 1000000 * 9 / 25; 187 | y = y * 1000000 * 9 / 25; 188 | int ix = (int)x; 189 | int iy = (int)y; 190 | byte[] bsx = new byte[4]; 191 | byte[] bsy = new byte[4]; 192 | bsx = DigitUtil.int32To4Byte(ix); 193 | bsy = DigitUtil.int32To4Byte(iy); 194 | pointbs[i * 8 + 0] = bsx[0]; 195 | pointbs[i * 8 + 1] = bsx[1]; 196 | pointbs[i * 8 + 2] = bsx[2]; 197 | pointbs[i * 8 + 3] = bsx[3]; 198 | pointbs[i * 8 + 4] = bsy[0]; 199 | pointbs[i * 8 + 5] = bsy[1]; 200 | pointbs[i * 8 + 6] = bsy[2]; 201 | pointbs[i * 8 + 7] = bsy[3]; 202 | } 203 | return ArrayUtil.concatAll(msgTypebs, serialbs, 204 | new byte[] {param.getParamDeal()}, 205 | new byte[] {param.getLimitValue()}, 206 | pointbs); 207 | } 208 | } 209 | -------------------------------------------------------------------------------- /src/main/java/com/zhtkj/jt808/service/codec/MsgDecoder.java: -------------------------------------------------------------------------------- 1 | package com.zhtkj.jt808.service.codec; 2 | 3 | import java.io.UnsupportedEncodingException; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | 7 | import org.springframework.context.annotation.Scope; 8 | import org.springframework.stereotype.Component; 9 | 10 | import com.zhtkj.jt808.common.JT808Const; 11 | import com.zhtkj.jt808.util.DigitUtil; 12 | import com.zhtkj.jt808.vo.PackageData; 13 | import com.zhtkj.jt808.vo.PackageData.MsgBody; 14 | import com.zhtkj.jt808.vo.PackageData.MsgHead; 15 | import com.zhtkj.jt808.vo.req.EventMsg; 16 | import com.zhtkj.jt808.vo.req.EventMsg.EventInfo; 17 | import com.zhtkj.jt808.vo.req.LocationMsg; 18 | import com.zhtkj.jt808.vo.req.LocationMsg.LocationInfo; 19 | import com.zhtkj.jt808.vo.req.VersionMsg; 20 | import com.zhtkj.jt808.vo.req.VersionMsg.VersionInfo; 21 | 22 | /** 23 | * ClassName: MsgDecoder 24 | * @Description: 消息解码器 25 | */ 26 | @Component 27 | @Scope("prototype") 28 | public class MsgDecoder { 29 | 30 | /** 31 | * @Description: 将byte[]解码成业务对象 32 | * @param bs 33 | * @return PackageData 34 | */ 35 | public PackageData bytes2PackageData(byte[] bs) { 36 | //先把数据包反转义一下 37 | List listbs = new ArrayList(); 38 | for (int i = 1; i < bs.length - 1; i++) { 39 | //如果当前位是0x7d,判断后一位是否是0x02或0x01,如果是,则反转义 40 | if ((bs[i] == (byte)0x7d) && (bs[i + 1] == (byte) 0x02)) { 41 | listbs.add((byte) JT808Const.MSG_DELIMITER); 42 | i++; 43 | } else if ((bs[i] == (byte) 0x7d) && (bs[i + 1] == (byte) 0x01)) { 44 | listbs.add((byte) 0x7d); 45 | i++; 46 | } else { 47 | listbs.add(bs[i]); 48 | } 49 | } 50 | byte[] newbs = new byte[listbs.size()]; 51 | for (int i = 0; i < listbs.size(); i++) { 52 | newbs[i] = listbs.get(i); 53 | } 54 | //将反转义后的byte[]转成业务对象 55 | PackageData pkg = new PackageData(); 56 | MsgHead msgHead = this.parseMsgHeadFromBytes(newbs); 57 | pkg.setMsgHead(msgHead); 58 | byte[] bodybs = DigitUtil.sliceBytes(newbs, 11, 11 + msgHead.getBodyLength() - 1); 59 | MsgBody msgBody = this.parseMsgBodyFromBytes(bodybs); 60 | pkg.setMsgBody(msgBody); 61 | return pkg; 62 | } 63 | 64 | //解码消息头 65 | private MsgHead parseMsgHeadFromBytes(byte[] data) { 66 | MsgHead msgHead = new MsgHead(); 67 | msgHead.setHeadId(DigitUtil.byte2ToInt(DigitUtil.sliceBytes(data, 0, 1))); 68 | boolean hasSubPack = ((byte) ((data[2] >> 5) & 0x1) == 1) ? true : false; 69 | msgHead.setHasSubPack(hasSubPack); 70 | int encryptType = ((byte) ((data[2] >> 2) & 0x1)) == 1 ? 1 : 0; 71 | msgHead.setEncryptType(encryptType); 72 | String bodyLen = DigitUtil.byteToBinaryStr(data[1], 1, 0) + DigitUtil.byteToBinaryStr(data[2], 7, 0); 73 | msgHead.setBodyLength(Integer.parseInt(bodyLen, 2));; 74 | msgHead.setTerminalPhone(new String(DigitUtil.bcdToStr(DigitUtil.sliceBytes(data, 3, 8)))); 75 | msgHead.setHeadSerial(DigitUtil.byte2ToInt(DigitUtil.sliceBytes(data, 9, 10))); 76 | return msgHead; 77 | } 78 | 79 | //解码消息体 80 | private MsgBody parseMsgBodyFromBytes(byte[] data) { 81 | MsgBody msgBody = new MsgBody(); 82 | msgBody.setBodyId(DigitUtil.byte2ToInt(DigitUtil.sliceBytes(data, 0, 1))); 83 | msgBody.setBodySerial(DigitUtil.byte4ToInt(DigitUtil.sliceBytes(data, 2, 5))); 84 | msgBody.setResult(data[6]); 85 | msgBody.setBodyBytes(data); 86 | return msgBody; 87 | } 88 | 89 | //解码基本位置包 90 | public LocationMsg toLocationMsg(PackageData packageData) throws UnsupportedEncodingException { 91 | LocationMsg locationMsg = new LocationMsg(packageData); 92 | LocationInfo locationInfo = new LocationInfo(); 93 | byte[] bodybs = locationMsg.getMsgBody().getBodyBytes(); 94 | //设置终端手机号 95 | locationInfo.setDevPhone(locationMsg.getMsgHead().getTerminalPhone()); 96 | //设置终端地址 97 | locationInfo.setTerminalIp(locationMsg.getChannel().remoteAddress().toString()); 98 | //处理状态 99 | locationInfo.setCarState(DigitUtil.byteToBinaryStr(bodybs[2]) + DigitUtil.byteToBinaryStr(bodybs[3])); 100 | //处理经度 101 | float gpsPosX = DigitUtil.byte4ToInt(bodybs, 4); 102 | locationInfo.setGpsPosX(gpsPosX*25/9/1000000); 103 | //处理纬度 104 | float gpsPosY = DigitUtil.byte4ToInt(bodybs, 8); 105 | locationInfo.setGpsPosY(gpsPosY*25/9/1000000); 106 | //处理高程 107 | float gpsHeight = DigitUtil.byte2ToInt(new byte[] {bodybs[12], bodybs[13]}); 108 | locationInfo.setGpsHeight(gpsHeight); 109 | //处理速度 110 | float gpsSpeed = DigitUtil.byte2ToInt(new byte[] {bodybs[14], bodybs[15]}); 111 | locationInfo.setGpsSpeed(gpsSpeed); 112 | //处理方向 113 | float gpsDirect = DigitUtil.byte2ToInt(new byte[] {bodybs[16], bodybs[17]}); 114 | locationInfo.setGpsDirect(gpsDirect/100); 115 | //处理设备发送时间 116 | String year = DigitUtil.bcdToStr(bodybs[18]); 117 | String month = DigitUtil.bcdToStr(bodybs[19]); 118 | String day = DigitUtil.bcdToStr(bodybs[20]); 119 | String hour = DigitUtil.bcdToStr(bodybs[21]); 120 | String minute = DigitUtil.bcdToStr(bodybs[22]); 121 | String second = DigitUtil.bcdToStr(bodybs[23]); 122 | String sendDatetime = "20" + year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second; 123 | locationInfo.setSendDatetime(sendDatetime); 124 | //处理车牌号码 125 | String carNumber = new String(DigitUtil.sliceBytes(bodybs, 24, 31), "GBK"); 126 | locationInfo.setCarNumber(carNumber); 127 | //处理司机ID 128 | locationInfo.setDriverId(new String(DigitUtil.sliceBytes(bodybs, 32, 41))); 129 | //处理核准证ID 130 | locationInfo.setWorkPassport(new String(DigitUtil.sliceBytes(bodybs, 42, 51))); 131 | //处理车厢状态 132 | locationInfo.setBoxClose(bodybs[52]); 133 | //处理举升状态 134 | locationInfo.setBoxUp(bodybs[53]); 135 | //处理空重状态 136 | locationInfo.setBoxEmpty(bodybs[54]); 137 | //处理违规情况 138 | locationInfo.setCarWeigui(bodybs[55]); 139 | locationMsg.setLocationInfo(locationInfo); 140 | return locationMsg; 141 | } 142 | 143 | //解码事件包 144 | public EventMsg toEventMsg(PackageData packageData) throws UnsupportedEncodingException { 145 | EventMsg eventMsg = new EventMsg(packageData); 146 | EventInfo eventInfo = new EventInfo(); 147 | LocationInfo locationInfo = new LocationInfo(); 148 | byte[] msgBodyBytes = eventMsg.getMsgBody().getBodyBytes(); 149 | //处理事件流水号 150 | long eventSerialId = DigitUtil.byte4ToInt(DigitUtil.sliceBytes(msgBodyBytes, 2, 5), 0); 151 | eventInfo.setEventSerialId(eventSerialId); 152 | //处理事件类型 153 | eventInfo.setEventType((int) msgBodyBytes[6]); 154 | 155 | //开始处理位置信息 156 | byte[] locationbs = DigitUtil.sliceBytes(msgBodyBytes, 3, msgBodyBytes.length - 1); 157 | //设置终端sim 158 | locationInfo.setDevPhone(eventMsg.getMsgHead().getTerminalPhone()); 159 | //设置终端地址 160 | locationInfo.setTerminalIp(eventMsg.getChannel().remoteAddress().toString()); 161 | //处理状态 162 | locationInfo.setCarState(DigitUtil.byteToBinaryStr(locationbs[2]) + DigitUtil.byteToBinaryStr(locationbs[3])); 163 | //处理经度 164 | float gpsPosX = DigitUtil.byte4ToInt(locationbs, 4); 165 | locationInfo.setGpsPosX(gpsPosX*25/9/1000000); 166 | //处理纬度 167 | float gpsPosY = DigitUtil.byte4ToInt(locationbs, 8); 168 | locationInfo.setGpsPosY(gpsPosY*25/9/1000000); 169 | //处理高程 170 | float gpsHeight = DigitUtil.byte2ToInt(new byte[] {locationbs[12], locationbs[13]}); 171 | locationInfo.setGpsHeight(gpsHeight); 172 | //处理速度 173 | float gpsSpeed = DigitUtil.byte2ToInt(new byte[] {locationbs[14], locationbs[15]}); 174 | locationInfo.setGpsSpeed(gpsSpeed); 175 | //处理方向 176 | float gpsDirect = DigitUtil.byte2ToInt(new byte[] {locationbs[16], locationbs[17]}); 177 | locationInfo.setGpsDirect(gpsDirect/100); 178 | //处理设备发送时间 179 | String year = DigitUtil.bcdToStr(locationbs[18]); 180 | String month = DigitUtil.bcdToStr(locationbs[19]); 181 | String day = DigitUtil.bcdToStr(locationbs[20]); 182 | String hour = DigitUtil.bcdToStr(locationbs[21]); 183 | String minute = DigitUtil.bcdToStr(locationbs[22]); 184 | String second = DigitUtil.bcdToStr(locationbs[23]); 185 | String sendDatetime = "20" + year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second; 186 | locationInfo.setSendDatetime(sendDatetime);//此时间在显示完毕更新 187 | //处理车牌号码 188 | String carNumber = new String(DigitUtil.sliceBytes(locationbs, 24, 31), "GBK"); 189 | locationInfo.setCarNumber(carNumber); 190 | //处理司机ID 191 | locationInfo.setDriverId(new String(DigitUtil.sliceBytes(locationbs, 32, 41))); 192 | //处理核准证ID 193 | locationInfo.setWorkPassport(new String(DigitUtil.sliceBytes(locationbs, 42, 51))); 194 | //处理车厢状态 195 | locationInfo.setBoxClose(locationbs[52]); 196 | //处理举升状态 197 | locationInfo.setBoxUp(locationbs[53]); 198 | //处理空重状态 199 | locationInfo.setBoxEmpty(locationbs[54]); 200 | //处理违规情况 201 | locationInfo.setCarWeigui(locationbs[55]); 202 | eventInfo.setLocationInfo(locationInfo); 203 | eventMsg.setEventInfo(eventInfo); 204 | return eventMsg; 205 | } 206 | 207 | //解码终端版本信息 208 | public VersionMsg toVersionMsg(PackageData packageData) throws UnsupportedEncodingException { 209 | VersionMsg versionMsg = new VersionMsg(packageData); 210 | VersionInfo versionInfo = new VersionInfo(); 211 | byte[] bodybs = packageData.getMsgBody().getBodyBytes(); 212 | Integer ecuType = (int) bodybs[8]; 213 | Integer carType = (int) bodybs[9]; 214 | byte[] infobs = new byte[bodybs.length - 10]; 215 | for (int i = 0; i < bodybs.length - 10; i++) { 216 | infobs[i] = bodybs[i + 10]; 217 | } 218 | String[] terminalInfo = new String(infobs, "utf8").split(","); 219 | versionInfo.setMac(terminalInfo[0]); 220 | versionInfo.setCarNumber(terminalInfo[1]); 221 | versionInfo.setDevPhone(packageData.getMsgHead().getTerminalPhone()); 222 | versionInfo.setVersion(terminalInfo[2]); 223 | versionInfo.setEcuType(ecuType.toString()); 224 | versionInfo.setCarType(carType.toString()); 225 | versionMsg.setVersionInfo(versionInfo); 226 | return versionMsg; 227 | } 228 | 229 | } 230 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------