1. 重构异步数据接收服务

2. 增加适配器协议服务
3. 增加适配器业务服务
This commit is contained in:
HuangXin 2023-08-13 00:22:12 +08:00
parent 132294ae8a
commit da50d2545b
26 changed files with 573 additions and 186 deletions

View File

@ -1,6 +1,6 @@
package com.zjyr.beidouservice;
import com.zjyr.beidouservice.adapter.impl.netty.impl.TcpServer;
import com.zjyr.beidouservice.service.BaidouAdapterService;
import jakarta.annotation.Resource;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.ApplicationArguments;
@ -15,10 +15,10 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
@MapperScan(basePackages = {"com.zjyr.beidouservice.mapper"})
public class BaidouServiceApplication implements ApplicationRunner {
/**
* The Tcp server.
* The Baidou adapter service.
*/
@Resource
private TcpServer tcpServer;
private BaidouAdapterService baidouAdapterService;
/**
* The entry point of application.
@ -31,6 +31,6 @@ public class BaidouServiceApplication implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
tcpServer.start();
baidouAdapterService.startBeidouAdapter();
}
}

View File

@ -26,10 +26,25 @@ import java.util.concurrent.TimeUnit;
@RequiredArgsConstructor
@Data
public class ChannelInit<T> extends ChannelInitializer<SocketChannel> {
/**
* The constant MAX_FRAME_LENGTH.
*/
private static final int MAX_FRAME_LENGTH = 1024 * BaseBinaryProtocol.MAX_LEN; //最大长度
/**
* The constant LENGTH_FIELD_LENGTH.
*/
private static final int LENGTH_FIELD_LENGTH = 2; //长度字段所占的字节数
/**
* The constant LENGTH_FIELD_OFFSET.
*/
private static final int LENGTH_FIELD_OFFSET = BaseBinaryProtocol.START.length(); //长度偏移
/**
* The constant LENGTH_ADJUSTMENT.
*/
private static final int LENGTH_ADJUSTMENT = 0;
/**
* The constant INITIAL_BYTES_TO_STRIP.
*/
private static final int INITIAL_BYTES_TO_STRIP = BaseBinaryProtocol.START.length();
/**

View File

@ -1,6 +1,5 @@
package com.zjyr.beidouservice.adapter.impl.netty;
import com.zjyr.beidouservice.pojo.vo.binary.MessageContent;
import jakarta.annotation.PreDestroy;
/**
@ -14,6 +13,14 @@ public interface ISocketServer {
*/
void start() throws Exception;
/**
* Send data int.
*
* @param <T> the type parameter
* @param data the data
* @param devId the dev id
* @return the int
*/
<T> int sendData(T data, Long devId);
/**

View File

@ -1,14 +1,14 @@
package com.zjyr.beidouservice.adapter.impl.netty;
import com.zjyr.beidouservice.common.impl.ControlDeviceTypeName;
import com.zjyr.beidouservice.adapter.impl.netty.notify.SocketNotifyEvent;
import com.zjyr.beidouservice.common.impl.SocketEventName;
import com.zjyr.beidouservice.misc.HelperUtils;
import com.zjyr.beidouservice.pojo.entry.ControlDevice;
import com.zjyr.beidouservice.pojo.vo.ControlAdapterSocketCtx;
import com.zjyr.beidouservice.pojo.vo.binary.BaseBinaryProtocol;
import com.zjyr.beidouservice.pojo.vo.binary.ControllerStatus;
import com.zjyr.beidouservice.pojo.vo.binary.HeartProtocol;
import com.zjyr.beidouservice.pojo.vo.binary.MessageContent;
import com.zjyr.beidouservice.service.impl.ControlDeviceServiceImpl;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
@ -17,6 +17,7 @@ import io.netty.handler.timeout.IdleStateEvent;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;
import java.net.InetSocketAddress;
@ -38,25 +39,32 @@ public class MessageHandler<T> extends SimpleChannelInboundHandler<BaseBinaryPro
public static ConcurrentHashMap<Long, ControlAdapterSocketCtx> ctxMap = new ConcurrentHashMap<>();
/**
* The Control device mapper.
* The Application event publisher.
*/
@Resource
private ControlDeviceServiceImpl controlDeviceService;
ApplicationEventPublisher applicationEventPublisher;
//@Resource
//private ControlDeviceServiceImpl controlDeviceService;
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent idleStateEvent) {
if (idleStateEvent.state() == IdleState.ALL_IDLE) {
log.info("{}:: Trigger Heart Signe", ctx.channel().id());
MessageContent<HeartProtocol> msgCont = MessageContent.<HeartProtocol>builder()
.msgBody(new HeartProtocol())
.build();
BaseBinaryProtocol<HeartProtocol> h = BaseBinaryProtocol.<HeartProtocol>builder()
.msgContent(msgCont)
.build();
// MessageContent<HeartProtocol> msgCont = MessageContent.<HeartProtocol>builder()
// .msgBody(new HeartProtocol())
// .build();
// BaseBinaryProtocol<HeartProtocol> h = BaseBinaryProtocol.<HeartProtocol>builder()
// .msgContent(msgCont)
// .build();
//
// ctx.writeAndFlush(h);
ctx.writeAndFlush(h);
SocketNotifyEvent notify = new SocketNotifyEvent(this,
ctx.channel(),
SocketEventName.SOCKET_EVT_IDLE_TIMEOUT,
null);
applicationEventPublisher.publishEvent(notify);
}
} else {
super.userEventTriggered(ctx, evt);
@ -68,7 +76,7 @@ public class MessageHandler<T> extends SimpleChannelInboundHandler<BaseBinaryPro
if (message.getMsgContent().getMsgBody() instanceof ControllerStatus status) {
log.info("{}:: Receive Message: {}",
ctx.channel().id(),
HelperUtils.bytesToHexString(status.getBeidouSignaltrength()));
HelperUtils.bytesToHexString(status.getBeidouSignalStrength()));
} else {
log.info("{}:: Receive Message: {}", ctx.channel().id(), "");
}
@ -81,23 +89,27 @@ public class MessageHandler<T> extends SimpleChannelInboundHandler<BaseBinaryPro
//List<ControlDevice> list = controlDeviceMapper.selectAll();
log.info("{}:: Connected <-- {}:{}", ctx.channel().id(), sa.getAddress().getHostAddress(), sa.getPort());
ControlDevice dev = ControlDevice.builder()
.deviceType(ControlDeviceTypeName.DEVICE_SOCKET_TCP)
.deviceAddr(sa.getAddress().getHostAddress())
.build();
// ControlDevice dev = ControlDevice.builder()
// .deviceType(BeidouAdapterTypeName.ADAPTER_SOCKET_TCP)
// .deviceAddr(sa.getAddress().getHostAddress())
// .build();
controlDeviceService.addControlDevice(dev);
if (ctxMap.get(dev.getId()) != null) {
ctxMap.remove(dev.getId());
} else {
ctxMap.put(dev.getId(), ControlAdapterSocketCtx.builder().controlAdapterId(dev.getId()).ctx(ctx).build());
}
//controlDeviceService.addControlDevice(dev);
// if (ctxMap.get(dev.getId()) != null) {
// ctxMap.remove(dev.getId());
// } else {
// ctxMap.put(dev.getId(),
// ControlAdapterSocketCtx.builder().controlAdapterId(dev.getId()).channel(ctx.channel()).build
// ());
// }
MessageContent<HeartProtocol> msgCont = MessageContent.<HeartProtocol>builder()
.msgBody(new HeartProtocol())
.build();
ctx.writeAndFlush(BaseBinaryProtocol.<HeartProtocol>builder().msgContent(msgCont).build());
// MessageContent<HeartProtocol> msgCont = MessageContent.<HeartProtocol>builder()
// .msgBody(new HeartProtocol())
// .build();
// ctx.writeAndFlush(BaseBinaryProtocol.<HeartProtocol>builder().msgContent(msgCont).build());
super.channelActive(ctx);
SocketNotifyEvent notify = new SocketNotifyEvent(this, ctx.channel(), SocketEventName.SOCKET_EVT_CONNECT, null);
applicationEventPublisher.publishEvent(notify);
}
@Override
@ -106,7 +118,7 @@ public class MessageHandler<T> extends SimpleChannelInboundHandler<BaseBinaryPro
log.info("{}:: Disonnected <-- {}", ctx.channel().id(), sa.getAddress().getHostAddress());
for (ConcurrentHashMap.Entry<Long, ControlAdapterSocketCtx> entry : ctxMap.entrySet()) {
if (entry.getValue().getCtx().channel().id() == ctx.channel().id()) {
if (entry.getValue().getChannel().id() == ctx.channel().id()) {
ctxMap.remove(entry.getKey());
}
}
@ -115,11 +127,32 @@ public class MessageHandler<T> extends SimpleChannelInboundHandler<BaseBinaryPro
ctx.close();
}
/**
* Channel send data.
*
* @param <E> the type parameter
* @param proMsg the pro msg
* @param devId the dev id
*/
public <E> void channelSendData(E proMsg, Long devId) {
ControlAdapterSocketCtx ctx = ctxMap.get(devId);
MessageContent<E> msg = MessageContent.<E>builder().msgBody(proMsg).build();
if (ctx != null) {
ctx.getCtx().channel().writeAndFlush(BaseBinaryProtocol.<E>builder().msgContent(msg).build());
if (ctx != null && ctx.getChannel() != null && ctx.getChannel().isActive()) {
ctx.getChannel().writeAndFlush(proMsg);
}
}
/**
* Channel send data.
*
* @param ctxChannel the ctx channel
* @param proMsg the pro msg
*/
public void channelSendData(Channel ctxChannel, T proMsg) {
if (ctxChannel != null && ctxChannel.isActive()) {
MessageContent<HeartProtocol> msgCont = MessageContent.<HeartProtocol>builder()
.msgBody(new HeartProtocol())
.build();
ctxChannel.writeAndFlush(BaseBinaryProtocol.<HeartProtocol>builder().msgContent(msgCont).build());
}
}
}

View File

@ -33,10 +33,10 @@ public class YuanRongProtocolDecode extends ByteToMessageDecoder {
int recvMajorId = buf.readInt();
int recvMinorId = buf.readInt();
int sendMajorId = buf.readInt();
Integer sendMinorId = buf.readInt();
int sendMinorId = buf.readInt();
byte cryptCytp = buf.readByte();
Integer timeStamp = buf.readInt();
Integer statusCode = buf.readInt();
int timeStamp = buf.readInt();
int statusCode = buf.readInt();
byte msgType = buf.readByte();
short msgSize = buf.readShort();
@ -50,7 +50,7 @@ public class YuanRongProtocolDecode extends ByteToMessageDecoder {
SensorStatusName phoneStatus = CommonEnumHandler.codeOf(SensorStatusName.class, buf.readByte());
ControllerStatus status = ControllerStatus.builder()
.beidouSignaltrength(beidouSignal)
.beidouSignalStrength(beidouSignal)
.wirelessStatus(wireStatus)
.telphoneStatus(phoneStatus)
.build();

View File

@ -3,8 +3,6 @@ package com.zjyr.beidouservice.adapter.impl.netty.impl;
import com.zjyr.beidouservice.adapter.impl.netty.ChannelInit;
import com.zjyr.beidouservice.adapter.impl.netty.ISocketServer;
import com.zjyr.beidouservice.config.NettySocketConfigure;
import com.zjyr.beidouservice.pojo.vo.binary.BaseBinaryProtocol;
import com.zjyr.beidouservice.pojo.vo.binary.MessageContent;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;

View File

@ -0,0 +1,44 @@
package com.zjyr.beidouservice.adapter.impl.netty.notify;
import com.zjyr.beidouservice.common.impl.SocketEventName;
import io.netty.channel.Channel;
import lombok.Getter;
import lombok.Setter;
import org.springframework.context.ApplicationEvent;
import java.util.List;
/**
* The type Socket notify event.
*/
@Setter
@Getter
public class SocketNotifyEvent extends ApplicationEvent {
/**
* The Evt message.
*/
private Object evtMessage;
/**
* The Socket event.
*/
private SocketEventName socketEvent;
/**
* The Ctx channel.
*/
private Channel ctxChannel;
/**
* Instantiates a new Socket notify event.
*
* @param source the source
* @param ctx the ctx
* @param evtType the evt type
* @param evtMessage the evt message
*/
public SocketNotifyEvent(Object source, Channel ctx, SocketEventName evtType, List<Object> evtMessage) {
super(source);
this.socketEvent = evtType;
this.evtMessage = evtMessage;
this.ctxChannel = ctx;
}
}

View File

@ -59,15 +59,6 @@ public final class CommonEnumHandler<E extends EnumerationBase> extends BaseType
return null;
}
/**
* Sets non null parameter.
*
* @param preparedStatement the prepared statement
* @param i the
* @param e the e
* @param jdbcType the jdbc type
* @throws SQLException the sql exception
*/
@Override
public void setNonNullParameter(PreparedStatement preparedStatement,
int i,
@ -76,14 +67,6 @@ public final class CommonEnumHandler<E extends EnumerationBase> extends BaseType
preparedStatement.setInt(i, e.getValue());
}
/**
* Gets nullable result.
*
* @param resultSet the result set
* @param s the s
* @return the nullable result
* @throws SQLException the sql exception
*/
@Override
public E getNullableResult(ResultSet resultSet, String s) throws SQLException {
if (resultSet.getObject(s) == null) {
@ -94,14 +77,6 @@ public final class CommonEnumHandler<E extends EnumerationBase> extends BaseType
return locateEnumStatus(val);
}
/**
* Gets nullable result.
*
* @param resultSet the result set
* @param index the index
* @return the nullable result
* @throws SQLException the sql exception
*/
@Override
public E getNullableResult(ResultSet resultSet, int index) throws SQLException {
if (resultSet.getObject(index) == null) {
@ -112,14 +87,6 @@ public final class CommonEnumHandler<E extends EnumerationBase> extends BaseType
return locateEnumStatus(val);
}
/**
* Gets nullable result.
*
* @param callableStatement the callable statement
* @param index the index
* @return the nullable result
* @throws SQLException the sql exception
*/
@Override
public E getNullableResult(CallableStatement callableStatement, int index) throws SQLException {
if (callableStatement.getObject(index) == null) {

View File

@ -3,18 +3,18 @@ package com.zjyr.beidouservice.common.impl;
import com.zjyr.beidouservice.common.EnumerationBase;
/**
* The enum Control device type name.
* The enum Beidou adapter type name.
*/
public enum ControlDeviceTypeName implements EnumerationBase {
public enum BeidouAdapterTypeName implements EnumerationBase {
/**
* Device socket tcp control device type name.
* Adapter socket tcp beidou adapter type name.
*/
DEVICE_SOCKET_TCP(0, "HOST_TOTAL_TRAFFIC"),
ADAPTER_SOCKET_TCP(0, "ADAPTER_SOCKET_TCP"),
/**
* Device socket udp control device type name.
* Adapter socket udp beidou adapter type name.
*/
DEVICE_SOCKET_UDP(1, "HOST_TOTAL_TRAFFIC"),
ADAPTER_SOCKET_UDP(1, "DEVICE_SOCKET_UDP"),
;
/**
@ -27,12 +27,12 @@ public enum ControlDeviceTypeName implements EnumerationBase {
private final String desc;
/**
* Instantiates a new Control device type name.
* Instantiates a new Beidou adapter type name.
*
* @param val the val
* @param desc the desc
*/
ControlDeviceTypeName(int val, String desc) {
BeidouAdapterTypeName(int val, String desc) {
this.code = val;
this.desc = desc;
}

View File

@ -2,17 +2,41 @@ package com.zjyr.beidouservice.common.impl;
import com.zjyr.beidouservice.common.EnumerationBase;
/**
* The enum Sensor status name.
*/
public enum SensorStatusName implements EnumerationBase {
/**
* Wireless noexists sensor status name.
*/
WIRELESS_NOEXISTS(0, "WIRELESS_NOEXISTS"),
/**
* Wireless normal sensor status name.
*/
WIRELESS_NORMAL(1, "WIRELESS_NORMAL"),
/**
* Wireless exception sensor status name.
*/
WIRELESS_EXCEPTION(2, "WIRELESS_EXCEPTION"),
;
/**
* The Code.
*/
private final Integer code;
/**
* The Desc.
*/
private final String desc;
/**
* Instantiates a new Sensor status name.
*
* @param val the val
* @param desc the desc
*/
SensorStatusName(int val, String desc) {
this.code = val;
this.desc = desc;

View File

@ -0,0 +1,59 @@
package com.zjyr.beidouservice.common.impl;
import com.zjyr.beidouservice.common.EnumerationBase;
/**
* The enum Socket event name.
*/
public enum SocketEventName implements EnumerationBase {
/**
* Socket evt connect socket event name.
*/
SOCKET_EVT_CONNECT(0, "SOCKET_EVT_CONNECT"),
/**
* Socket evt disconnect socket event name.
*/
SOCKET_EVT_DISCONNECT(1, "SOCKET_EVT_DISCONNECT"),
/**
* Socket evt recv socket event name.
*/
SOCKET_EVT_RECV(2, "SOCKET_EVT_DISCONNECT"),
/**
* Socket evt idle timeout socket event name.
*/
SOCKET_EVT_IDLE_TIMEOUT(3, "SOCKET_EVT_IDLE_TIMEOUT"),
;
/**
* The Code.
*/
private final Integer code;
/**
* The Desc.
*/
private final String desc;
/**
* Instantiates a new Socket event name.
*
* @param val the val
* @param desc the desc
*/
SocketEventName(int val, String desc) {
this.code = val;
this.desc = desc;
}
@Override
public Integer getValue() {
return this.code;
}
@Override
public String getDescription() {
return this.desc;
}
}

View File

@ -23,4 +23,12 @@ public interface ControlDeviceMapper {
* @return the int
*/
int addControlDevice(@Param("device") ControlDevice device);
/**
* Upgrade control device int.
*
* @param device the device
* @return the int
*/
int upgradeControlDevice(@Param("dev") ControlDevice device);
}

View File

@ -8,29 +8,28 @@ import lombok.NoArgsConstructor;
* The type Base protocol dto.
*
* @param <T> the type parameter
* @author <huangxin@cmhi.chinamoblie.com>
*/
@Data
@NoArgsConstructor
@JsonPropertyOrder({"ver", "cryptoType", "timeStamp", "msgContent"})
public class BaseProtocolDTO<T> {
/**
* 当前协议版本号
* The Ver.
*/
private Integer ver;
/**
* msgContent字段内容编码格式
* The Crypto type.
*/
private Integer cryptoType;
/**
* 当前UTC时间戳(ms)
* The Time stamp.
*/
private Long timeStamp;
/**
* 协议详细内容
* The Msg content.
*/
private T msgContent;
}

View File

@ -2,7 +2,7 @@ package com.zjyr.beidouservice.pojo.entry;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.zjyr.beidouservice.common.impl.ControlDeviceTypeName;
import com.zjyr.beidouservice.common.impl.BeidouAdapterTypeName;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
@ -35,9 +35,22 @@ public class ControlDevice {
/**
* The Device type.
*/
private ControlDeviceTypeName deviceType;
private BeidouAdapterTypeName deviceType;
/**
* The Device addr.
*/
private String deviceAddr;
/**
* The Beidou signal strength.
*/
private String beidouSignalStrength;
/**
* The Wireless status.
*/
private Integer wirelessStatus;
/**
* The Telphone status.
*/
private Integer telphoneStatus;
}

View File

@ -0,0 +1,37 @@
package com.zjyr.beidouservice.pojo.po;
import com.zjyr.beidouservice.common.impl.BeidouAdapterTypeName;
import lombok.Builder;
import lombok.Data;
/**
* The type Beidou adapter device.
*/
@Builder
@Data
public class BeidouAdapterDevice {
/**
* The Id.
*/
private Long id;
/**
* The Adapter type.
*/
private BeidouAdapterTypeName adapterType;
/**
* The Adapter addr.
*/
private String adapterAddr;
/**
* The Beidou signal strength.
*/
private String beidouSignalStrength;
/**
* The Wireless status.
*/
private Integer wirelessStatus;
/**
* The Telphone status.
*/
private Integer telphoneStatus;
}

View File

@ -1,9 +1,8 @@
package com.zjyr.beidouservice.pojo.vo;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.Channel;
import lombok.Builder;
import lombok.Data;
import lombok.RequiredArgsConstructor;
/**
* The type Control adapter socket ctx.
@ -16,7 +15,7 @@ public class ControlAdapterSocketCtx {
*/
private Long controlAdapterId;
/**
* The Ctx.
* The Channel.
*/
private ChannelHandlerContext ctx;
private Channel channel;
}

View File

@ -4,7 +4,7 @@ import lombok.Builder;
import lombok.Data;
/**
* The type Yuan rong bin protocol.
* The type Base binary protocol.
*
* @param <T> the type parameter
*/
@ -18,9 +18,12 @@ public class BaseBinaryProtocol<T> {
public static int VERSIN = 1;
/**
* The constant MIN_LEN.
* The Min len.
*/
public static int MIN_LEN = 39;
/**
* The Max len.
*/
public static int MAX_LEN = 1400;
/**
* The constant START.
@ -74,9 +77,4 @@ public class BaseBinaryProtocol<T> {
* The Msg content.
*/
private MessageContent<T> msgContent;
BaseBinaryProtocol () {
recvMajorId = recvMinorId = sendMajorId = sendMinorId = 0;
cryptoType = 0;
}
}

View File

@ -4,10 +4,22 @@ import com.zjyr.beidouservice.common.impl.SensorStatusName;
import lombok.Builder;
import lombok.Data;
/**
* The type Controller status.
*/
@Data
@Builder
public class ControllerStatus {
private byte[] beidouSignaltrength;
/**
* The Beidou signal strength.
*/
private byte[] beidouSignalStrength;
/**
* The Wireless status.
*/
private SensorStatusName wirelessStatus;
/**
* The Telphone status.
*/
private SensorStatusName telphoneStatus;
}

View File

@ -0,0 +1,15 @@
package com.zjyr.beidouservice.service;
import com.zjyr.beidouservice.pojo.vo.binary.HeartProtocol;
/**
* The interface Adapter protocol service.
*/
public interface AdapterProtocolService {
/**
* Create heart protocol heart protocol.
*
* @return the heart protocol
*/
HeartProtocol createHeartProtocol();
}

View File

@ -0,0 +1,47 @@
package com.zjyr.beidouservice.service;
import com.zjyr.beidouservice.pojo.po.BeidouAdapterDevice;
import java.util.List;
/**
* The interface Baidou adapter service.
*/
public interface BaidouAdapterService {
/**
* Start beidou adapter.
*/
void startBeidouAdapter();
/**
* Send commond.
*
* @param <T> the type parameter
* @param adapterId the adapter id
* @param command the command
*/
<T> void sendCommond(Long adapterId, T command);
/**
* Gets all adapter.
*
* @return the all adapter
*/
List<BeidouAdapterDevice> getAllAdapter();
/**
* Add new beidou adapter int.
*
* @param adapter the adapter
* @return the int
*/
int addNewBeidouAdapter(BeidouAdapterDevice adapter);
/**
* Gets adapter by addr.
*
* @param addr the addr
* @return the adapter by addr
*/
BeidouAdapterDevice getAdapterByAddr(String addr);
}

View File

@ -1,25 +0,0 @@
package com.zjyr.beidouservice.service;
import com.zjyr.beidouservice.pojo.entry.ControlDevice;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface ControlDeviceService {
/**
* Select all list.
*
* @return the list
*/
List<ControlDevice> selectAll();
/**
* Add control device int.
*
* @param device the device
* @return the int
*/
int addControlDevice(@Param("device") ControlDevice device);
ControlDevice getControllDeviceByAddr(String addr);
}

View File

@ -0,0 +1,149 @@
package com.zjyr.beidouservice.service.impl;
import com.zjyr.beidouservice.adapter.impl.netty.impl.TcpServer;
import com.zjyr.beidouservice.adapter.impl.netty.notify.SocketNotifyEvent;
import com.zjyr.beidouservice.common.impl.BeidouAdapterTypeName;
import com.zjyr.beidouservice.mapper.ControlDeviceMapper;
import com.zjyr.beidouservice.pojo.entry.ControlDevice;
import com.zjyr.beidouservice.pojo.po.BeidouAdapterDevice;
import com.zjyr.beidouservice.pojo.vo.ControlAdapterSocketCtx;
import com.zjyr.beidouservice.pojo.vo.binary.BaseBinaryProtocol;
import com.zjyr.beidouservice.pojo.vo.binary.HeartProtocol;
import com.zjyr.beidouservice.pojo.vo.binary.MessageContent;
import com.zjyr.beidouservice.service.AdapterProtocolService;
import com.zjyr.beidouservice.service.BaidouAdapterService;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Service;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import static com.zjyr.beidouservice.common.impl.SocketEventName.SOCKET_EVT_CONNECT;
/**
* The type Baidou socket adapter service.
*
* @param <T> the type parameter
*/
@Service
@Slf4j
public class BaidouSocketAdapterServiceImpl<T extends ApplicationEvent> implements BaidouAdapterService,
ApplicationListener<T> {
/**
* The Ctx map.
*/
private final ConcurrentHashMap<Long, ControlAdapterSocketCtx> ctxMap = new ConcurrentHashMap<>();
/**
* The Control device mapper.
*/
@Resource
ControlDeviceMapper controlDeviceMapper;
/**
* The Adapter protocol service.
*/
@Resource
AdapterProtocolService adapterProtocolService;
/**
* The Tcp server.
*/
@Resource
private TcpServer tcpServer;
@Override
public void startBeidouAdapter() {
tcpServer.start();
}
@Override
public <E> void sendCommond(Long adapterId, E command) {
}
@Override
public void onApplicationEvent(@Nonnull T evtContent) {
if (evtContent instanceof SocketNotifyEvent event) {
log.info("Recvie {} event data {}", event.getSocketEvent(), event.getEvtMessage());
switch (event.getSocketEvent()) {
case SOCKET_EVT_CONNECT, SOCKET_EVT_IDLE_TIMEOUT -> {
MessageContent<HeartProtocol> msgCont = MessageContent.<HeartProtocol>builder().msgBody(
adapterProtocolService.createHeartProtocol()).build();
event.getCtxChannel().writeAndFlush(BaseBinaryProtocol.<HeartProtocol>builder()
.msgContent(msgCont)
.build());
if (event.getSocketEvent() == SOCKET_EVT_CONNECT) {
InetSocketAddress sa = (InetSocketAddress) event.getCtxChannel().remoteAddress();
BeidouAdapterDevice a = BeidouAdapterDevice.builder()
.adapterType(BeidouAdapterTypeName.ADAPTER_SOCKET_TCP)
.adapterAddr(sa.getAddress().getHostAddress())
.build();
addNewBeidouAdapter(a);
}
}
}
}
}
@Override
public List<BeidouAdapterDevice> getAllAdapter() {
List<ControlDevice> controlDevices = controlDeviceMapper.selectAll();
if (!controlDevices.isEmpty()) {
List<BeidouAdapterDevice> adapterDevices = new ArrayList<>();
for (ControlDevice c : controlDevices) {
adapterDevices.add(BeidouAdapterDevice.builder()
.id(c.getId())
.adapterType(c.getDeviceType())
.adapterAddr(c.getDeviceAddr())
.beidouSignalStrength(c.getBeidouSignalStrength())
.wirelessStatus(c.getWirelessStatus())
.telphoneStatus(c.getTelphoneStatus())
.build());
}
return adapterDevices;
}
return new ArrayList<>();
}
@Override
public int addNewBeidouAdapter(BeidouAdapterDevice adapter) {
ControlDevice device = ControlDevice.builder()
.id(adapter.getId())
.deviceType(adapter.getAdapterType())
.deviceAddr(adapter.getAdapterAddr())
.beidouSignalStrength(adapter.getBeidouSignalStrength())
.wirelessStatus(adapter.getWirelessStatus())
.telphoneStatus(adapter.getTelphoneStatus())
.build();
BeidouAdapterDevice dev = getAdapterByAddr(adapter.getAdapterAddr());
if (dev == null) {
return controlDeviceMapper.addControlDevice(device);
} else {
adapter.setId(dev.getId());
return controlDeviceMapper.upgradeControlDevice(device);
}
}
@Override
public BeidouAdapterDevice getAdapterByAddr(String addr) {
for (BeidouAdapterDevice v : getAllAdapter()) {
if (addr.equals(v.getAdapterAddr())) {
return v;
}
}
return null;
}
}

View File

@ -0,0 +1,19 @@
package com.zjyr.beidouservice.service.impl;
import com.zjyr.beidouservice.pojo.vo.binary.HeartProtocol;
import com.zjyr.beidouservice.service.AdapterProtocolService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
/**
* The type Beidou socket protocol service.
*/
@Service
@Slf4j
public class BeidouSocketProtocolServiceImpl implements AdapterProtocolService {
@Override
public HeartProtocol createHeartProtocol() {
return new HeartProtocol();
}
}

View File

@ -1,43 +0,0 @@
package com.zjyr.beidouservice.service.impl;
import com.zjyr.beidouservice.mapper.ControlDeviceMapper;
import com.zjyr.beidouservice.pojo.entry.ControlDevice;
import com.zjyr.beidouservice.service.ControlDeviceService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
@Slf4j
public class ControlDeviceServiceImpl implements ControlDeviceService {
@Resource
ControlDeviceMapper controlDeviceMapper;
@Override
public List<ControlDevice> selectAll() {
return controlDeviceMapper.selectAll();
}
@Override
public ControlDevice getControllDeviceByAddr(String addr) {
for (ControlDevice v : selectAll()) {
if (addr.equals(v.getDeviceAddr())) {
return v;
}
}
return null;
}
@Override
public int addControlDevice(ControlDevice device) {
ControlDevice dev = getControllDeviceByAddr(device.getDeviceAddr());
if (dev == null) {
return controlDeviceMapper.addControlDevice(device);
} else {
device.setId(dev.getId());
}
return 0;
}
}

View File

@ -5,17 +5,29 @@
<id column="id" property="id"/>
<result column="deviceType" property="deviceType"/>
<result column="deviceAddr" property="deviceAddr"/>
<result column="beidouSignalStrength" property="beidouSignalStrength"/>
<result column="wirelessStatus" property="wirelessStatus"/>
<result column="telphoneStatus" property="telphoneStatus"/>
</resultMap>
<select id="selectAll" resultMap="control_device">
SELECT *
SELECT id, deviceAddr, deviceType, beidouSignalStrength, wirelessStatus, telphoneStatus
FROM control_device
</select>
<update id="upgradeControlDevice" parameterType="com.zjyr.beidouservice.pojo.entry.ControlDevice">
UPDATE control_device
SET beidouSignalStrength = #{dev.beidouSignalStrength},
wirelessStatus = #{dev.wirelessStatus},
telphoneStatus = #{dev.telphoneStatus}
WHERE deviceAddr = #{dev.deviceAddr}
</update>
<insert id="addControlDevice" useGeneratedKeys="true" keyProperty="id"
parameterType="com.zjyr.beidouservice.pojo.entry.ControlDevice">
INSERT IGNORE INTO control_device(deviceAddr, deviceType)
SELECT #{device.deviceAddr}, #{device.deviceType} FROM DUAL WHERE NOT EXISTS (SELECT deviceAddr FROM control_device
INSERT IGNORE INTO control_device(deviceAddr, deviceType, beidouSignalStrength, wirelessStatus, telphoneStatus)
SELECT #{device.deviceAddr}, #{device.deviceType}, #{device.beidouSignalStrength}, #{device.wirelessStatus},
#{device.telphoneStatus} FROM DUAL WHERE NOT EXISTS (SELECT deviceAddr FROM control_device
WHERE deviceAddr = #{device.deviceAddr})
</insert>
</mapper>

View File

@ -1,6 +1,6 @@
package com.zjyr.beidouservice.mapper;
import com.zjyr.beidouservice.common.impl.ControlDeviceTypeName;
import com.zjyr.beidouservice.common.impl.BeidouAdapterTypeName;
import com.zjyr.beidouservice.pojo.entry.ControlDevice;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
@ -28,7 +28,7 @@ public class ControlDeviceMapperTest {
@Test
public void a2_addControlDevice() {
ControlDevice dev = ControlDevice.builder().deviceType(ControlDeviceTypeName.DEVICE_SOCKET_TCP).deviceAddr(
ControlDevice dev = ControlDevice.builder().deviceType(BeidouAdapterTypeName.ADAPTER_SOCKET_TCP).deviceAddr(
"127.0.0.2").build();
int i = controlDeviceMapper.addControlDevice(dev);
System.out.println("Add " + i);