Commit 8b373441 authored by zengtianlai3's avatar zengtianlai3

日志打印格式化和项目代码优化

parent bce0537f
...@@ -14,55 +14,28 @@ import java.util.List; ...@@ -14,55 +14,28 @@ import java.util.List;
*/ */
@Slf4j @Slf4j
public class DeviceDecoder extends ByteToMessageDecoder { public class DeviceDecoder extends ByteToMessageDecoder {
public final int BASE_LENGTH = 2 + 2 + 1+1+1; public final int BASE_LENGTH = 2 + 2 + 1 + 1 + 1;
@Override @Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) { protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) {
byte[] packet=new byte[buffer.readableBytes()]; byte[] packet = new byte[buffer.readableBytes()];
buffer.readBytes(packet); buffer.readBytes(packet);
buffer.resetReaderIndex(); buffer.resetReaderIndex();
Util.DEBUG_HEX("SERVER -> IN",packet,packet.length); Util.DEBUG_HEX("SERVER -> IN", packet, packet.length);
try { try {
if (buffer.readableBytes() < BASE_LENGTH) { if (buffer.readableBytes() < BASE_LENGTH) {
return; return;
} }
buffer.markReaderIndex(); buffer.markReaderIndex();
short stx = buffer.readShort();//55AA->21930 short stx = buffer.readShort();
short len = buffer.readShortLE(); short len = buffer.readShortLE();
// char cmd = buffer.readChar();
// char ack = buffer.readChar();//stx:21930,len:52,cmd:退,ack:ꭵ
// short cmd = buffer.readUnsignedByte();
// short ack = buffer.readUnsignedByte();//stx:21930,len:52,cmd:144,ack:0
// byte cmd = buffer.readByte();
// byte ack = buffer.readByte();////stx:21930,len:52,cmd:-112,ack:0
byte cmd = buffer.readByte(); byte cmd = buffer.readByte();
byte ack = buffer.readByte();////stx:21930,len:52,cmd:-112,ack:0 byte ack = buffer.readByte();
// int cmd2 = cmd & 0xFF;
// int ack2 = ack & 0xFF;//stx:21930,len:52,cmd:144,ack:0
// byte[] cmd_bytes = new byte[1];
// buffer.readBytes(cmd_bytes);
// String cmd = new String(cmd_bytes, 0, cmd_bytes.length);
//
// byte[] ack_bytes = new byte[1];
// buffer.readBytes(ack_bytes);
// String ack = new String(ack_bytes, 0, ack_bytes.length);//: stx:21930,len:52,cmd:�,ack:
log.debug("stx:" + stx + ",len:" + len + ",cmd:" + cmd + ",ack:" + ack);//stx:21930,len:52,cmd:-112,ack:0 int real_len = len;
int real_len = len ;
int cmd_ack_len = 2; int cmd_ack_len = 2;
if (buffer.readableBytes() < real_len - cmd_ack_len+1) { if (buffer.readableBytes() < real_len - cmd_ack_len + 1) {
buffer.resetReaderIndex(); buffer.resetReaderIndex();
return; return;
} }
...@@ -74,7 +47,7 @@ public class DeviceDecoder extends ByteToMessageDecoder { ...@@ -74,7 +47,7 @@ public class DeviceDecoder extends ByteToMessageDecoder {
byte end = buffer.readByte(); byte end = buffer.readByte();
DeviceProtocol protocol = new DeviceProtocol(stx, len, cmd, ack, content,end); DeviceProtocol protocol = new DeviceProtocol(stx, len, cmd, ack, content, end);
out.add(protocol); out.add(protocol);
} catch (Exception e) { } catch (Exception e) {
......
...@@ -43,7 +43,6 @@ public class DeviceManager { ...@@ -43,7 +43,6 @@ public class DeviceManager {
} }
private void startTcpService() { private void startTcpService() {
log.debug("tcp server start......,prot:" + port);
sessionContexts = new HashMap<String, SessionContext>(); sessionContexts = new HashMap<String, SessionContext>();
channelInitializer = new DeviceChannelInitializer(handler); channelInitializer = new DeviceChannelInitializer(handler);
server = new TcpServer(port, channelInitializer); server = new TcpServer(port, channelInitializer);
......
...@@ -22,7 +22,6 @@ import org.springframework.beans.factory.annotation.Autowired; ...@@ -22,7 +22,6 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.util.Date;
@Component @Component
@ChannelHandler.Sharable @ChannelHandler.Sharable
...@@ -48,7 +47,8 @@ public class DeviceServerHandler extends SimpleChannelInboundHandler<Object> { ...@@ -48,7 +47,8 @@ public class DeviceServerHandler extends SimpleChannelInboundHandler<Object> {
String remoteIp = socketAddr.getHostString(); String remoteIp = socketAddr.getHostString();
int remotePort = socketAddr.getPort(); int remotePort = socketAddr.getPort();
DeviceProtocol protocol = (DeviceProtocol) msg; DeviceProtocol protocol = (DeviceProtocol) msg;
String channelId = channel.id().asLongText();
log.debug("设备服务器,channelRead0:{},{}", channelId, HexUtil.bytes2hex(protocol.getContent()));
/* /*
TODO: TODO:
1.透传前先进行鉴权 1.透传前先进行鉴权
...@@ -57,7 +57,6 @@ public class DeviceServerHandler extends SimpleChannelInboundHandler<Object> { ...@@ -57,7 +57,6 @@ public class DeviceServerHandler extends SimpleChannelInboundHandler<Object> {
*/ */
byte cmd = protocol.getCmd(); byte cmd = protocol.getCmd();
int cmdInt = cmd & 0xFF; int cmdInt = cmd & 0xFF;
log.debug("recev msg " + HexUtil.bytes2hex(protocol.getContent()));
boolean auth = false; boolean auth = false;
if (cmdInt == Consts.CMD_LICENSE) { if (cmdInt == Consts.CMD_LICENSE) {
...@@ -80,8 +79,7 @@ public class DeviceServerHandler extends SimpleChannelInboundHandler<Object> { ...@@ -80,8 +79,7 @@ public class DeviceServerHandler extends SimpleChannelInboundHandler<Object> {
public void channelRegistered(ChannelHandlerContext ctx) throws Exception { public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
// TODO Auto-generated method stub // TODO Auto-generated method stub
super.channelRegistered(ctx); super.channelRegistered(ctx);
log.debug("client channelRegistered"); log.debug("设备服务器,channelRegistered:{}", ctx.channel().id().asLongText());
log.debug("channel.id().asLongText():" + ctx.channel().id().asLongText());
} }
@Override @Override
...@@ -91,8 +89,7 @@ public class DeviceServerHandler extends SimpleChannelInboundHandler<Object> { ...@@ -91,8 +89,7 @@ public class DeviceServerHandler extends SimpleChannelInboundHandler<Object> {
InetSocketAddress socketAddr = (InetSocketAddress) ctx.channel().remoteAddress(); InetSocketAddress socketAddr = (InetSocketAddress) ctx.channel().remoteAddress();
String clientIp = socketAddr.getHostString(); String clientIp = socketAddr.getHostString();
int port = socketAddr.getPort(); int port = socketAddr.getPort();
log.debug("client connected,ip:" + clientIp + ",port:" + port); log.debug("设备服务器,channelActive:{}", ctx.channel().id().asLongText());
log.debug("channel.id().asLongText():" + ctx.channel().id().asLongText());
// TODO 以下为模拟的测试代码 // TODO 以下为模拟的测试代码
...@@ -129,6 +126,8 @@ public class DeviceServerHandler extends SimpleChannelInboundHandler<Object> { ...@@ -129,6 +126,8 @@ public class DeviceServerHandler extends SimpleChannelInboundHandler<Object> {
super.channelInactive(ctx); super.channelInactive(ctx);
SocketChannel channel = (SocketChannel) ctx.channel(); SocketChannel channel = (SocketChannel) ctx.channel();
String channelId = channel.id().asLongText(); String channelId = channel.id().asLongText();
log.debug("设备服务器,channelInactive:{}", channelId);
DeviceClientInactiveEvent deviceClientInactiveEvent = new DeviceClientInactiveEvent(); DeviceClientInactiveEvent deviceClientInactiveEvent = new DeviceClientInactiveEvent();
deviceClientInactiveEvent.setChannelId(channelId); deviceClientInactiveEvent.setChannelId(channelId);
eventPublisher.publishEvent(deviceClientInactiveEvent); eventPublisher.publishEvent(deviceClientInactiveEvent);
...@@ -139,20 +138,16 @@ public class DeviceServerHandler extends SimpleChannelInboundHandler<Object> { ...@@ -139,20 +138,16 @@ public class DeviceServerHandler extends SimpleChannelInboundHandler<Object> {
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
// TODO Auto-generated method stub // TODO Auto-generated method stub
super.channelReadComplete(ctx); super.channelReadComplete(ctx);
log.debug("client channelReadComplete"); log.debug("设备服务器,channelReadComplete:{}", ctx.channel().id().asLongText());
log.debug("channel.id().asLongText():" + ctx.channel().id().asLongText());
} }
@Override @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// TODO Auto-generated method stub // TODO Auto-generated method stub
super.exceptionCaught(ctx, cause); super.exceptionCaught(ctx, cause);
InetSocketAddress socketAddr = (InetSocketAddress) ctx.channel().remoteAddress(); log.debug("设备服务器,exceptionCaught:{}", ctx.channel().id().asLongText());
String clientIp = socketAddr.getHostString();
int port = socketAddr.getPort();
cause.printStackTrace(); cause.printStackTrace();
ctx.close(); ctx.close();
log.error("client has error,ip:" + clientIp + ",port:" + port);
} }
private boolean handlerCheckAuth(SocketChannel channel, String remoteIp, int remotePort, DeviceProtocol protocol) { private boolean handlerCheckAuth(SocketChannel channel, String remoteIp, int remotePort, DeviceProtocol protocol) {
...@@ -173,7 +168,7 @@ public class DeviceServerHandler extends SimpleChannelInboundHandler<Object> { ...@@ -173,7 +168,7 @@ public class DeviceServerHandler extends SimpleChannelInboundHandler<Object> {
AuthManager authManager = SpringUtil.getBean(AuthManager.class); AuthManager authManager = SpringUtil.getBean(AuthManager.class);
boolean license = authManager.auth(appId, sn, sign); boolean license = authManager.auth(appId, sn, sign);
log.debug("auth result " + license + "," + appId + "," + sn + "," + sign); log.info("设备鉴权信息和结果,{},{},{},{} ", appId, sn, sign, license);
String channelId = channel.id().asLongText(); String channelId = channel.id().asLongText();
if (license) { if (license) {
SessionContext session = new SessionContext(); SessionContext session = new SessionContext();
...@@ -191,7 +186,6 @@ public class DeviceServerHandler extends SimpleChannelInboundHandler<Object> { ...@@ -191,7 +186,6 @@ public class DeviceServerHandler extends SimpleChannelInboundHandler<Object> {
deviceManager.putSession(appId, session); deviceManager.putSession(appId, session);
//TODO 创建透传的客户端 //TODO 创建透传的客户端
log.info("forward client begin start ..." + appId);
CreateForwarClientEvent event = new CreateForwarClientEvent(); CreateForwarClientEvent event = new CreateForwarClientEvent();
event.setAppId(appId); event.setAppId(appId);
eventPublisher.publishEvent(event); eventPublisher.publishEvent(event);
......
...@@ -2,8 +2,6 @@ package iot.sixiang.license.event; ...@@ -2,8 +2,6 @@ package iot.sixiang.license.event;
import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.SocketChannel;
import iot.sixiang.license.device.DeviceManager; import iot.sixiang.license.device.DeviceManager;
import iot.sixiang.license.device.DeviceProtocol;
import iot.sixiang.license.forward.ForwardManager;
import iot.sixiang.license.model.SessionContext; import iot.sixiang.license.model.SessionContext;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
...@@ -20,7 +18,6 @@ public class DeviceClientBeForcedOfflineEventHandler { ...@@ -20,7 +18,6 @@ public class DeviceClientBeForcedOfflineEventHandler {
} }
// @Async("asyncExecutor")
@EventListener @EventListener
public void handlerEvent(DeviceClientBeForcedOfflineEvent event) { public void handlerEvent(DeviceClientBeForcedOfflineEvent event) {
String appId = event.getAppId(); String appId = event.getAppId();
...@@ -30,10 +27,10 @@ public class DeviceClientBeForcedOfflineEventHandler { ...@@ -30,10 +27,10 @@ public class DeviceClientBeForcedOfflineEventHandler {
SocketChannel deviceClientChannel = deviceSessionContext.getClientChannel(); SocketChannel deviceClientChannel = deviceSessionContext.getClientChannel();
if (deviceClientChannel != null) { if (deviceClientChannel != null) {
deviceClientChannel.close(); deviceClientChannel.close();
log.info("device client be forced offline success ..." + appId); log.debug("device client be forced offline success ..." + appId);
} }
} else { } else {
log.info("device client be forced offline undo ..." + appId); log.debug("device client be forced offline undo ..." + appId);
} }
} }
......
package iot.sixiang.license.event; package iot.sixiang.license.event;
import io.netty.channel.socket.SocketChannel;
import iot.sixiang.license.device.DeviceManager; import iot.sixiang.license.device.DeviceManager;
import iot.sixiang.license.model.SessionContext; import iot.sixiang.license.model.SessionContext;
import iot.sixiang.license.util.SpringUtil;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener; import org.springframework.context.event.EventListener;
...@@ -21,14 +19,13 @@ public class DeviceClientInactiveEventHandler { ...@@ -21,14 +19,13 @@ public class DeviceClientInactiveEventHandler {
} }
// @Async("asyncExecutor")
@EventListener @EventListener
public void handlerEvent(DeviceClientInactiveEvent event) { public void handlerEvent(DeviceClientInactiveEvent event) {
String channelId = event.getChannelId(); String channelId = event.getChannelId();
SessionContext session = deviceManager.getSessionByChannelId(channelId); SessionContext session = deviceManager.getSessionByChannelId(channelId);
if (session == null) { if (session == null) {
log.debug("device client inactive undo ..." ); log.debug("device client inactive undo ...");
return; return;
} else { } else {
String appId = session.getAppId(); String appId = session.getAppId();
......
...@@ -21,7 +21,6 @@ public class DeviceClientLicenseEventHandler { ...@@ -21,7 +21,6 @@ public class DeviceClientLicenseEventHandler {
} }
// @Async("asyncExecutor")
@EventListener @EventListener
public void handlerEvent(DeviceClientLicenseEvent event) { public void handlerEvent(DeviceClientLicenseEvent event) {
String appId = event.getAppId(); String appId = event.getAppId();
......
...@@ -20,7 +20,6 @@ public class ForwardClientBeForcedOfflineEventHandler { ...@@ -20,7 +20,6 @@ public class ForwardClientBeForcedOfflineEventHandler {
} }
// @Async("asyncExecutor")
@EventListener @EventListener
public void handlerEvent(ForwardClientBeForcedOfflineEvent event) { public void handlerEvent(ForwardClientBeForcedOfflineEvent event) {
String appId = event.getAppId(); String appId = event.getAppId();
...@@ -29,10 +28,10 @@ public class ForwardClientBeForcedOfflineEventHandler { ...@@ -29,10 +28,10 @@ public class ForwardClientBeForcedOfflineEventHandler {
SocketChannel forwardClientChannel = forwardSessionContext.getClientChannel(); SocketChannel forwardClientChannel = forwardSessionContext.getClientChannel();
if (forwardClientChannel != null) { if (forwardClientChannel != null) {
forwardClientChannel.close(); forwardClientChannel.close();
log.info("forward client be forced offline success ..." + appId); log.debug("forward client be forced offline success ..." + appId);
} }
}else { } else {
log.info("forward client be forced offline undo ..." + appId); log.debug("forward client be forced offline undo ..." + appId);
} }
......
...@@ -3,7 +3,6 @@ package iot.sixiang.license.event; ...@@ -3,7 +3,6 @@ package iot.sixiang.license.event;
import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.SocketChannel;
import iot.sixiang.license.forward.ForwardManager; import iot.sixiang.license.forward.ForwardManager;
import iot.sixiang.license.model.SessionContext; import iot.sixiang.license.model.SessionContext;
import iot.sixiang.license.util.SpringUtil;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener; import org.springframework.context.event.EventListener;
...@@ -22,7 +21,6 @@ public class ForwardClientConnectEventHandler { ...@@ -22,7 +21,6 @@ public class ForwardClientConnectEventHandler {
} }
// @Async("asyncExecutor")
@EventListener @EventListener
public void handlerEvent(ForwardClientConnectEvent event) { public void handlerEvent(ForwardClientConnectEvent event) {
...@@ -41,11 +39,9 @@ public class ForwardClientConnectEventHandler { ...@@ -41,11 +39,9 @@ public class ForwardClientConnectEventHandler {
session.setClientChannel(channel); session.setClientChannel(channel);
forwardManager.putSession(appId, session);
forwardManager.putSession(appId,session); log.debug("forward client connect:" + event);
log.debug("forward client connect:"+event);
} }
......
...@@ -23,16 +23,15 @@ public class ForwardClientInactiveEventHandler { ...@@ -23,16 +23,15 @@ public class ForwardClientInactiveEventHandler {
} }
// @Async("asyncExecutor")
@EventListener @EventListener
public void handlerEvent(ForwardClientInactiveEvent event) { public void handlerEvent(ForwardClientInactiveEvent event) {
String channelId = event.getChannelId(); String channelId = event.getChannelId();
SessionContext session = forwardManager.getSessionByChannelId(channelId); SessionContext session = forwardManager.getSessionByChannelId(channelId);
if (session == null) { if (session == null) {
log.debug("forward client inactive undo ..." ); log.debug("forward client inactive undo ...");
return; return;
}else{ } else {
String appId = session.getAppId(); String appId = session.getAppId();
boolean result = forwardManager.removeSessionByChannelId(channelId); boolean result = forwardManager.removeSessionByChannelId(channelId);
if (result) { if (result) {
...@@ -40,7 +39,7 @@ public class ForwardClientInactiveEventHandler { ...@@ -40,7 +39,7 @@ public class ForwardClientInactiveEventHandler {
DeviceClientBeForcedOfflineEvent deviceClientBeForcedOfflineEvent = new DeviceClientBeForcedOfflineEvent(); DeviceClientBeForcedOfflineEvent deviceClientBeForcedOfflineEvent = new DeviceClientBeForcedOfflineEvent();
deviceClientBeForcedOfflineEvent.setAppId(appId); deviceClientBeForcedOfflineEvent.setAppId(appId);
eventPublisher.publishEvent(deviceClientBeForcedOfflineEvent); eventPublisher.publishEvent(deviceClientBeForcedOfflineEvent);
log.debug("forward client inactive success ..." ); log.debug("forward client inactive success ...");
} }
} }
......
...@@ -25,7 +25,6 @@ public class ForwardClientRequestEventHandler { ...@@ -25,7 +25,6 @@ public class ForwardClientRequestEventHandler {
} }
// @Async("asyncExecutor")
@EventListener @EventListener
public void handlerEvent(ForwardClientRequestEvent event) { public void handlerEvent(ForwardClientRequestEvent event) {
String deviceChannelId = event.getDeviceChannelId(); String deviceChannelId = event.getDeviceChannelId();
...@@ -35,7 +34,7 @@ public class ForwardClientRequestEventHandler { ...@@ -35,7 +34,7 @@ public class ForwardClientRequestEventHandler {
String appId = deviceSessionContext.getAppId(); String appId = deviceSessionContext.getAppId();
SessionContext forwardSessionContext = forwardManager.getSessionContextByAppId(appId); SessionContext forwardSessionContext = forwardManager.getSessionContextByAppId(appId);
log.info("forward client request:" + appId+","+forwardSessionContext); log.debug("forward client request:" + appId + "," + forwardSessionContext);
SocketChannel clientChannel = forwardSessionContext.getClientChannel(); SocketChannel clientChannel = forwardSessionContext.getClientChannel();
clientChannel.writeAndFlush(protocol); clientChannel.writeAndFlush(protocol);
......
...@@ -25,7 +25,6 @@ public class ForwardMessageResponseEventHandler { ...@@ -25,7 +25,6 @@ public class ForwardMessageResponseEventHandler {
} }
// @Async("asyncExecutor")
@EventListener @EventListener
public void handlerEvent(ForwardMessageResponseEvent event) { public void handlerEvent(ForwardMessageResponseEvent event) {
String channelId = event.getChannelId(); String channelId = event.getChannelId();
...@@ -36,17 +35,15 @@ public class ForwardMessageResponseEventHandler { ...@@ -36,17 +35,15 @@ public class ForwardMessageResponseEventHandler {
String appId = forwardSessionContext.getAppId(); String appId = forwardSessionContext.getAppId();
SessionContext deviceSessionContext = deviceManager.getSessionContextByAppId(appId); SessionContext deviceSessionContext = deviceManager.getSessionContextByAppId(appId);
if(deviceSessionContext!=null){ if (deviceSessionContext != null) {
SocketChannel deviceClientChannel = deviceSessionContext.getClientChannel(); SocketChannel deviceClientChannel = deviceSessionContext.getClientChannel();
log.info("forward client response..." + appId+",forward session:"+deviceSessionContext); log.debug("forward client response..." + appId + ",forward session:" + deviceSessionContext);
deviceClientChannel.writeAndFlush(protocol); deviceClientChannel.writeAndFlush(protocol);
}else{ } else {
log.info("forward client response undo ..." + appId); log.debug("forward client response undo ..." + appId);
} }
} }
......
...@@ -17,12 +17,11 @@ public class ForwardClient { ...@@ -17,12 +17,11 @@ public class ForwardClient {
ForwardClientHandler handler; ForwardClientHandler handler;
public ForwardClient() { public ForwardClient() {
log.debug("ProxyNodeClient ProxyNodeClientHandler*****" + handler);
}
public void startTcp(String host, int port,String appId) { }
log.debug("begin connect the server " + host + ",port " + port);
public void startTcp(String host, int port, String appId) {
log.debug("桥接客户端,开始连接桥接服务:{},{},{}", host, port, appId);
ForwardConnectionListener listener = new ForwardConnectionListener(); ForwardConnectionListener listener = new ForwardConnectionListener();
listener.setAppId(appId); listener.setAppId(appId);
listener.setHost(host); listener.setHost(host);
......
...@@ -4,15 +4,11 @@ import io.netty.channel.ChannelHandler; ...@@ -4,15 +4,11 @@ import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler; import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.SocketChannel;
import iot.sixiang.license.device.DeviceManager;
import iot.sixiang.license.device.DeviceProtocol; import iot.sixiang.license.device.DeviceProtocol;
import iot.sixiang.license.event.DeviceClientInactiveEvent;
import iot.sixiang.license.event.EventPublisher; import iot.sixiang.license.event.EventPublisher;
import iot.sixiang.license.event.ForwardClientInactiveEvent; import iot.sixiang.license.event.ForwardClientInactiveEvent;
import iot.sixiang.license.event.ForwardMessageResponseEvent; import iot.sixiang.license.event.ForwardMessageResponseEvent;
import iot.sixiang.license.model.SessionContext;
import iot.sixiang.license.util.HexUtil; import iot.sixiang.license.util.HexUtil;
import iot.sixiang.license.util.SpringUtil;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
...@@ -29,7 +25,6 @@ public class ForwardClientHandler extends SimpleChannelInboundHandler<Object> { ...@@ -29,7 +25,6 @@ public class ForwardClientHandler extends SimpleChannelInboundHandler<Object> {
public ForwardClientHandler() { public ForwardClientHandler() {
super(); super();
log.debug("ProxyNodeClientHandler ****");
} }
@Override @Override
...@@ -41,11 +36,9 @@ public class ForwardClientHandler extends SimpleChannelInboundHandler<Object> { ...@@ -41,11 +36,9 @@ public class ForwardClientHandler extends SimpleChannelInboundHandler<Object> {
InetSocketAddress socketAddr = (InetSocketAddress) ctx.channel().remoteAddress(); InetSocketAddress socketAddr = (InetSocketAddress) ctx.channel().remoteAddress();
String serverIp = socketAddr.getHostString(); String serverIp = socketAddr.getHostString();
int serverPort = socketAddr.getPort(); int serverPort = socketAddr.getPort();
log.debug("channelRead0...");
DeviceProtocol protocol = (DeviceProtocol) msg; DeviceProtocol protocol = (DeviceProtocol) msg;
log.info("桥接服务器响应:"+ HexUtil.bytes2hex(protocol.getContent()));
String channelId = channel.id().asLongText(); String channelId = channel.id().asLongText();
log.debug("桥接客户端,channelRead0:{},{}", channelId, HexUtil.bytes2hex(protocol.getContent()));
ForwardMessageResponseEvent forwardMessageResponseEvent = new ForwardMessageResponseEvent(); ForwardMessageResponseEvent forwardMessageResponseEvent = new ForwardMessageResponseEvent();
forwardMessageResponseEvent.setChannelId(channelId); forwardMessageResponseEvent.setChannelId(channelId);
...@@ -57,30 +50,17 @@ public class ForwardClientHandler extends SimpleChannelInboundHandler<Object> { ...@@ -57,30 +50,17 @@ public class ForwardClientHandler extends SimpleChannelInboundHandler<Object> {
@Override @Override
public void channelRegistered(ChannelHandlerContext ctx) { public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
// TODO Auto-generated method stub // TODO Auto-generated method stub
super.channelRegistered(ctx);
try { log.debug("桥接客户端,channelRegistered:{}", ctx.channel().id().asLongText());
super.channelRegistered(ctx);
log.debug("channelRegistered----------->");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} }
@Override @Override
public synchronized void channelActive(ChannelHandlerContext ctx) throws Exception { public synchronized void channelActive(ChannelHandlerContext ctx) throws Exception {
// TODO Auto-generated method stub // TODO Auto-generated method stub
super.channelActive(ctx); super.channelActive(ctx);
try { log.debug("桥接客户端,channelActive:{}", ctx.channel().id().asLongText());
SocketChannel channel = (SocketChannel) ctx.channel();
log.debug("channelActive********"+ctx.channel().id().asLongText());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} }
@Override @Override
...@@ -89,6 +69,8 @@ public class ForwardClientHandler extends SimpleChannelInboundHandler<Object> { ...@@ -89,6 +69,8 @@ public class ForwardClientHandler extends SimpleChannelInboundHandler<Object> {
super.channelInactive(ctx); super.channelInactive(ctx);
SocketChannel channel = (SocketChannel) ctx.channel(); SocketChannel channel = (SocketChannel) ctx.channel();
String channelId = channel.id().asLongText(); String channelId = channel.id().asLongText();
log.debug("桥接客户端,channelInactive:{}", channelId);
ForwardClientInactiveEvent forwardClientInactiveEvent = new ForwardClientInactiveEvent(); ForwardClientInactiveEvent forwardClientInactiveEvent = new ForwardClientInactiveEvent();
forwardClientInactiveEvent.setChannelId(channelId); forwardClientInactiveEvent.setChannelId(channelId);
eventPublisher.publishEvent(forwardClientInactiveEvent); eventPublisher.publishEvent(forwardClientInactiveEvent);
...@@ -99,31 +81,22 @@ public class ForwardClientHandler extends SimpleChannelInboundHandler<Object> { ...@@ -99,31 +81,22 @@ public class ForwardClientHandler extends SimpleChannelInboundHandler<Object> {
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
// TODO Auto-generated method stub // TODO Auto-generated method stub
super.channelReadComplete(ctx); super.channelReadComplete(ctx);
log.debug("channelReadComplete"); log.debug("桥接客户端,channelReadComplete:{}", ctx.channel().id().asLongText());
} }
@Override @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// TODO Auto-generated method stub // TODO Auto-generated method stub
super.exceptionCaught(ctx, cause); super.exceptionCaught(ctx, cause);
InetSocketAddress socketAddr = (InetSocketAddress) ctx.channel().remoteAddress(); log.debug("桥接客户端,exceptionCaught:{}", ctx.channel().id().asLongText());
String clientIp = socketAddr.getHostString();
int port = socketAddr.getPort();
cause.printStackTrace(); cause.printStackTrace();
ctx.close(); ctx.close();
log.error("client has error,ip:" + clientIp + ",port:" + port);
} }
@Override @Override
public synchronized void userEventTriggered(ChannelHandlerContext ctx, Object obj) throws Exception { public synchronized void userEventTriggered(ChannelHandlerContext ctx, Object obj) throws Exception {
try { log.debug("桥接客户端,userEventTriggered:{}", ctx.channel().id().asLongText());
SocketChannel channel = (SocketChannel) ctx.channel();
log.debug("userEventTriggered");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} }
} }
...@@ -20,14 +20,13 @@ public class ForwardConnectionListener extends BaseConnectionListener { ...@@ -20,14 +20,13 @@ public class ForwardConnectionListener extends BaseConnectionListener {
public void operationComplete(ChannelFuture channelFuture) throws Exception { public void operationComplete(ChannelFuture channelFuture) throws Exception {
AlarmService alarmService = SpringUtil.getBean(AlarmService.class); AlarmService alarmService = SpringUtil.getBean(AlarmService.class);
if (!channelFuture.isSuccess()) { if (!channelFuture.isSuccess()) {
//TODO 失败进行告警 //TODO 失败进行告警
log.debug("桥接客户端,连接服务器失败:{},{},{}", this.host, this.port, this.appId);
String remoteIp = this.host;
String remotePort = String.valueOf(this.port);
int typeId = 1; int typeId = 1;
String title = "连接服器失败"; String title = "连接服器失败";
String content = "连接服务器:" + remoteIp + ":"+ remotePort +"失败"; String content = "连接服务器:" + this.host + ":" + this.port + "失败";
alarmService.addAlarm(typeId,title,content); alarmService.addAlarm(typeId, title, content);
//TODO forward client连接失败,则强制踢掉设备客户端 //TODO forward client连接失败,则强制踢掉设备客户端
...@@ -36,7 +35,7 @@ public class ForwardConnectionListener extends BaseConnectionListener { ...@@ -36,7 +35,7 @@ public class ForwardConnectionListener extends BaseConnectionListener {
EventPublisher eventPublisher = SpringUtil.getBean(EventPublisher.class); EventPublisher eventPublisher = SpringUtil.getBean(EventPublisher.class);
eventPublisher.publishEvent(deviceClientBeForcedOfflineEvent); eventPublisher.publishEvent(deviceClientBeForcedOfflineEvent);
} else { } else {
log.debug("桥接客户端,连接服务器成功:{},{},{}", this.host, this.port, this.appId);
OperateManager operateManager = SpringUtil.getBean(OperateManager.class); OperateManager operateManager = SpringUtil.getBean(OperateManager.class);
operateManager.autoIncrement(); operateManager.autoIncrement();
SocketChannel channel = (SocketChannel) channelFuture.channel(); SocketChannel channel = (SocketChannel) channelFuture.channel();
...@@ -50,25 +49,17 @@ public class ForwardConnectionListener extends BaseConnectionListener { ...@@ -50,25 +49,17 @@ public class ForwardConnectionListener extends BaseConnectionListener {
EventPublisher eventPublisher = SpringUtil.getBean(EventPublisher.class); EventPublisher eventPublisher = SpringUtil.getBean(EventPublisher.class);
eventPublisher.publishEvent(forwardClientConnectEvent); eventPublisher.publishEvent(forwardClientConnectEvent);
log.debug("Successful connection to the server");
log.info("forward client connect success ..." + appId);
// byte ack2 = 0x01;
short stx = 21930; short stx = 21930;
byte ack = 0x0; byte ack = 0x0;
int len = 3; int len = 3;
byte cmd = 0x1; byte cmd = 0x1;
byte[] content = new byte[1];
byte[] content = new byte[1];
content[0] = 0x7e; content[0] = 0x7e;
byte end = 0x1; byte end = 0x1;
// stx:21930,len:76,cmd:1,ack:0
DeviceProtocol protocol = new DeviceProtocol( stx, len, cmd, ack, content,end);
DeviceProtocol protocol = new DeviceProtocol(stx, len, cmd, ack, content, end);
DeviceClientLicenseEvent deviceClientLicenseEvent = new DeviceClientLicenseEvent(); DeviceClientLicenseEvent deviceClientLicenseEvent = new DeviceClientLicenseEvent();
......
...@@ -18,10 +18,10 @@ public class ForwardDecoder extends ByteToMessageDecoder { ...@@ -18,10 +18,10 @@ public class ForwardDecoder extends ByteToMessageDecoder {
protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) { protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) {
// 可读长度必须大于等于基本长度 // 可读长度必须大于等于基本长度
try { try {
byte[] packet=new byte[buffer.readableBytes()]; byte[] packet = new byte[buffer.readableBytes()];
buffer.readBytes(packet); buffer.readBytes(packet);
buffer.resetReaderIndex(); buffer.resetReaderIndex();
Util.DEBUG_HEX("SERVER -> IN",packet,packet.length); Util.DEBUG_HEX("SERVER -> IN", packet, packet.length);
if (buffer.readableBytes() < BASE_LENGTH) { if (buffer.readableBytes() < BASE_LENGTH) {
return; return;
...@@ -36,13 +36,10 @@ public class ForwardDecoder extends ByteToMessageDecoder { ...@@ -36,13 +36,10 @@ public class ForwardDecoder extends ByteToMessageDecoder {
byte cmd = buffer.readByte(); byte cmd = buffer.readByte();
byte ack = buffer.readByte();////stx:21930,len:52,cmd:-112,ack:0 byte ack = buffer.readByte();////stx:21930,len:52,cmd:-112,ack:0
log.debug("stx:" + stx + ",len:" + len);
int real_len = len;//注意,透传前已经去掉了END一个字符 int real_len = len;//注意,透传前已经去掉了END一个字符
int cmd_ack_len = 2; int cmd_ack_len = 2;
if (buffer.readableBytes() < real_len - cmd_ack_len+1) { if (buffer.readableBytes() < real_len - cmd_ack_len + 1) {
buffer.resetReaderIndex(); buffer.resetReaderIndex();
return; return;
} }
...@@ -55,14 +52,13 @@ public class ForwardDecoder extends ByteToMessageDecoder { ...@@ -55,14 +52,13 @@ public class ForwardDecoder extends ByteToMessageDecoder {
byte end = buffer.readByte(); byte end = buffer.readByte();
log.debug("ForwardDecoder.msg.getLen()...." + real_len);
DeviceProtocol protocol = new DeviceProtocol(stx, real_len, cmd, ack, content,end); DeviceProtocol protocol = new DeviceProtocol(stx, real_len, cmd, ack, content, end);
out.add(protocol); out.add(protocol);
} catch (Exception e) { } catch (Exception e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
log.error("DeviceDecoder error!"); log.error("Decoder error");
} }
} }
......
...@@ -13,19 +13,13 @@ public class ForwardEncoder extends MessageToByteEncoder<DeviceProtocol> { ...@@ -13,19 +13,13 @@ public class ForwardEncoder extends MessageToByteEncoder<DeviceProtocol> {
protected void encode(ChannelHandlerContext tcx, DeviceProtocol msg, ByteBuf out) throws Exception { protected void encode(ChannelHandlerContext tcx, DeviceProtocol msg, ByteBuf out) throws Exception {
try { try {
// short stx = in.readShort();//55AA->21930
// short len = in.readShortLE();
out.writeShort(msg.getStx()); out.writeShort(msg.getStx());
// out.writeShort(msg.getLen());
out.writeShortLE(msg.getLen()); out.writeShortLE(msg.getLen());
out.writeByte(msg.getCmd()); out.writeByte(msg.getCmd());
out.writeByte(msg.getAck()); out.writeByte(msg.getAck());
log.debug("ForwardEncoder.msg.getLen()...." + msg.getLen());
if (msg.getContent() == null) { if (msg.getContent() == null) {
// logger.debug("body数据为空"); // log.debug("body数据为空");
} else { } else {
out.writeBytes(msg.getContent()); out.writeBytes(msg.getContent());
} }
...@@ -33,7 +27,7 @@ public class ForwardEncoder extends MessageToByteEncoder<DeviceProtocol> { ...@@ -33,7 +27,7 @@ public class ForwardEncoder extends MessageToByteEncoder<DeviceProtocol> {
} catch (Exception e) { } catch (Exception e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
log.error("DeviceEncoder error---->"); log.error("Encoder error");
} }
} }
} }
package iot.sixiang.license.net;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ClassUtils;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.*;
import java.security.cert.CertificateException;
public class MySSLContext {
static Logger logger = LoggerFactory.getLogger(MySSLContext.class.getName());
private static SSLContext sslContext;
public static SSLContext getSSLContext(String serverKeystorePath, String serverKeystorePwd,
String tserverKeystorePath, String serverTrustKeystorePwd) {
try {
KeyStore keyStore = KeyStore.getInstance("JKS");
KeyStore trustKeyStore = KeyStore.getInstance("JKS");
try {
keyStore.load(ClassUtils.getDefaultClassLoader().getResourceAsStream("static/kserver.keystore"),
serverKeystorePwd.toCharArray());
trustKeyStore.load(ClassUtils.getDefaultClassLoader().getResourceAsStream("static/tserver.keystore"),
serverTrustKeystorePwd.toCharArray());
/*
* keyStore.load(new FileInputStream(serverKeystorePath),
* serverKeystorePwd.toCharArray()); trustKeyStore.load(new
* FileInputStream(tserverKeystorePath),
* serverTrustKeystorePwd.toCharArray());
*/
} catch (CertificateException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
try {
keyManagerFactory.init(keyStore, serverKeystorePwd.toCharArray());
} catch (UnrecoverableKeyException e) {
e.printStackTrace();
}
trustManagerFactory.init(trustKeyStore);
sslContext = SSLContext.getInstance("TLS");
try {
sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
// sslContext.init(keyManagerFactory.getKeyManagers(),null,
// null);
logger.debug("SSLContext init success");
} catch (KeyManagementException e) {
e.printStackTrace();
}
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
return sslContext;
}
}
package iot.sixiang.license.net;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.X509ExtendedTrustManager;
import java.net.Socket;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
public class MyX509TrustManager extends X509ExtendedTrustManager {
@Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public X509Certificate[] getAcceptedIssuers() {
// TODO Auto-generated method stub
return null;
}
@Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1, Socket arg2) throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1, SSLEngine arg2) throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1, Socket arg2) throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1, SSLEngine arg2) throws CertificateException {
// TODO Auto-generated method stub
}
}
package iot.sixiang.license.net;
public class NetMsgSeq {
private static short seq = 1;
public static synchronized short getSeq() {
if (seq > 65535) {
seq = 1;
}
seq++;
return seq;
}
}
...@@ -6,16 +6,11 @@ import io.netty.channel.ChannelOption; ...@@ -6,16 +6,11 @@ import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup; import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
//import com.xiezuo.rsretail.node.ConnectionListener;
public class TcpClient { public class TcpClient {
static Logger logger = LoggerFactory.getLogger(TcpClient.class);
private int port; private int port;
private String host; private String host;
private int index;
private BaseChannelInitializer channelInitializer; private BaseChannelInitializer channelInitializer;
private BaseConnectionListener connectionListener; private BaseConnectionListener connectionListener;
......
...@@ -2,24 +2,17 @@ package iot.sixiang.license.net; ...@@ -2,24 +2,17 @@ package iot.sixiang.license.net;
import io.netty.bootstrap.ServerBootstrap; import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelId;
import io.netty.channel.ChannelOption; import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup; import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger; import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import java.util.LinkedHashMap;
import java.util.Map;
@Slf4j
public class TcpServer { public class TcpServer {
static Logger logger = LoggerFactory.getLogger(TcpServer.class.getName());
private int port; private int port;
private BaseChannelInitializer channelInitializer; private BaseChannelInitializer channelInitializer;
public static Map<ChannelId, SocketChannel> clients = new LinkedHashMap<ChannelId, SocketChannel>();
public TcpServer(int port, BaseChannelInitializer channelInitializer) { public TcpServer(int port, BaseChannelInitializer channelInitializer) {
this.port = port; this.port = port;
...@@ -33,7 +26,7 @@ public class TcpServer { ...@@ -33,7 +26,7 @@ public class TcpServer {
//创建两个线程组 bossGroup、workerGroup //创建两个线程组 bossGroup、workerGroup
EventLoopGroup bossGroup = new NioEventLoopGroup(4); EventLoopGroup bossGroup = new NioEventLoopGroup(4);
EventLoopGroup workerGroup = new NioEventLoopGroup(4); EventLoopGroup workerGroup = new NioEventLoopGroup(4);
logger.debug("begin open the port:" + port); log.debug("Tcp服务,开始监听端口:{}",port);
try { try {
//创建服务端的启动对象,设置参数 //创建服务端的启动对象,设置参数
ServerBootstrap b = new ServerBootstrap(); ServerBootstrap b = new ServerBootstrap();
...@@ -57,7 +50,7 @@ public class TcpServer { ...@@ -57,7 +50,7 @@ public class TcpServer {
} }
} finally { } finally {
logger.debug("close the server"); log.debug("Tcp服务,停止退出");
workerGroup.shutdownGracefully(); workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully(); bossGroup.shutdownGracefully();
} }
......
...@@ -4,9 +4,6 @@ import io.netty.channel.socket.SocketChannel; ...@@ -4,9 +4,6 @@ import io.netty.channel.socket.SocketChannel;
import io.netty.util.concurrent.DefaultEventExecutorGroup; import io.netty.util.concurrent.DefaultEventExecutorGroup;
import io.netty.util.concurrent.EventExecutorGroup; import io.netty.util.concurrent.EventExecutorGroup;
import iot.sixiang.license.consts.Consts; import iot.sixiang.license.consts.Consts;
import iot.sixiang.license.forward.ForwardClientHandler;
import iot.sixiang.license.forward.ForwardDecoder;
import iot.sixiang.license.forward.ForwardEncoder;
import iot.sixiang.license.net.BaseChannelInitializer; import iot.sixiang.license.net.BaseChannelInitializer;
public class OperateChannelInitializer extends BaseChannelInitializer { public class OperateChannelInitializer extends BaseChannelInitializer {
......
...@@ -3,7 +3,6 @@ package iot.sixiang.license.operate; ...@@ -3,7 +3,6 @@ package iot.sixiang.license.operate;
import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler; import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.SocketChannel;
import iot.sixiang.license.device.DeviceProtocol; import iot.sixiang.license.device.DeviceProtocol;
import iot.sixiang.license.event.EventPublisher; import iot.sixiang.license.event.EventPublisher;
import iot.sixiang.license.event.OperateSAMStatusResponseEvent; import iot.sixiang.license.event.OperateSAMStatusResponseEvent;
...@@ -39,38 +38,24 @@ public class OperateClientHandler extends SimpleChannelInboundHandler<Object> { ...@@ -39,38 +38,24 @@ public class OperateClientHandler extends SimpleChannelInboundHandler<Object> {
@Override @Override
public void channelRegistered(ChannelHandlerContext ctx) { public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
// TODO Auto-generated method stub // TODO Auto-generated method stub
try { super.channelRegistered(ctx);
super.channelRegistered(ctx); log.debug("运维客户端,channelRegistered:{}", ctx.channel().id().asLongText());
SocketChannel channel = (SocketChannel) ctx.channel();
log.debug("channelRegistered "+ctx.channel().id().asLongText());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} }
@Override @Override
public synchronized void channelActive(ChannelHandlerContext ctx) throws Exception { public synchronized void channelActive(ChannelHandlerContext ctx) throws Exception {
// TODO Auto-generated method stub // TODO Auto-generated method stub
super.channelActive(ctx); super.channelActive(ctx);
try { log.debug("运维客户端,channelActive:{}", ctx.channel().id().asLongText());
SocketChannel channel = (SocketChannel) ctx.channel();
log.debug("channelActive "+ctx.channel().id().asLongText());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} }
@Override @Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception { public void channelInactive(ChannelHandlerContext ctx) throws Exception {
// TODO Auto-generated method stub // TODO Auto-generated method stub
super.channelInactive(ctx); super.channelInactive(ctx);
SocketChannel channel = (SocketChannel) ctx.channel(); log.debug("运维客户端,channelInactive:{}", ctx.channel().id().asLongText());
log.debug("channelInactive "+ctx.channel().id().asLongText());
ctx.close(); ctx.close();
} }
...@@ -78,30 +63,21 @@ public class OperateClientHandler extends SimpleChannelInboundHandler<Object> { ...@@ -78,30 +63,21 @@ public class OperateClientHandler extends SimpleChannelInboundHandler<Object> {
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
// TODO Auto-generated method stub // TODO Auto-generated method stub
super.channelReadComplete(ctx); super.channelReadComplete(ctx);
SocketChannel channel = (SocketChannel) ctx.channel(); log.debug("运维客户端,channelReadComplete:{}", ctx.channel().id().asLongText());
log.debug("channelReadComplete "+ctx.channel().id().asLongText());
} }
@Override @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// TODO Auto-generated method stub // TODO Auto-generated method stub
super.exceptionCaught(ctx, cause); super.exceptionCaught(ctx, cause);
SocketChannel channel = (SocketChannel) ctx.channel(); log.debug("运维客户端,exceptionCaught:{}", ctx.channel().id().asLongText());
log.debug("exceptionCaught "+ctx.channel().id().asLongText());
cause.printStackTrace(); cause.printStackTrace();
ctx.close(); ctx.close();
} }
@Override @Override
public synchronized void userEventTriggered(ChannelHandlerContext ctx, Object obj) throws Exception { public synchronized void userEventTriggered(ChannelHandlerContext ctx, Object obj) {
try { log.debug("运维客户端,userEventTriggered:{}", ctx.channel().id().asLongText());
SocketChannel channel = (SocketChannel) ctx.channel();
log.debug("userEventTriggered");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} }
} }
...@@ -14,17 +14,19 @@ import lombok.extern.slf4j.Slf4j; ...@@ -14,17 +14,19 @@ import lombok.extern.slf4j.Slf4j;
public class OperateConnectionListener extends BaseConnectionListener { public class OperateConnectionListener extends BaseConnectionListener {
@Override @Override
public void operationComplete(ChannelFuture channelFuture) throws Exception { public void operationComplete(ChannelFuture channelFuture) {
if (!channelFuture.isSuccess()) { if (!channelFuture.isSuccess()) {
//TODO 失败进行告警 //TODO 失败进行告警
log.info("运维客户端,连接服务器失败:{},{}", this.host, this.port);
AlarmService alarmService = SpringUtil.getBean(AlarmService.class); AlarmService alarmService = SpringUtil.getBean(AlarmService.class);
String remoteIp = this.host;
String remotePort = String.valueOf(this.port);
int typeId = 1; int typeId = 1;
String title = "连接服器失败"; String title = "连接服器失败";
String content = "连接服务器:" + remoteIp + ":"+ remotePort +"失败"; String content = "连接服务器:" + this.host + ":" + this.port + "失败";
alarmService.addAlarm(typeId,title,content); alarmService.addAlarm(typeId, title, content);
} else { } else {
log.info("运维客户端,连接服务器成功:{},{}", this.host, this.port);
//TODO 查询SAM状态 //TODO 查询SAM状态
OperateSAMStatusRequestEvent operateSAMStatusQueryEvent = new OperateSAMStatusRequestEvent(); OperateSAMStatusRequestEvent operateSAMStatusQueryEvent = new OperateSAMStatusRequestEvent();
short stx = 21930; short stx = 21930;
......
...@@ -4,7 +4,6 @@ import io.netty.buffer.ByteBuf; ...@@ -4,7 +4,6 @@ import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder; import io.netty.handler.codec.ByteToMessageDecoder;
import iot.sixiang.license.device.DeviceProtocol; import iot.sixiang.license.device.DeviceProtocol;
import iot.sixiang.license.util.Util;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import java.util.List; import java.util.List;
...@@ -53,7 +52,7 @@ public class OperateDecoder extends ByteToMessageDecoder { ...@@ -53,7 +52,7 @@ public class OperateDecoder extends ByteToMessageDecoder {
} catch (Exception e) { } catch (Exception e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
log.error(e.getMessage()); log.error("Decoder error");
} }
} }
......
...@@ -28,7 +28,7 @@ public class OperateEncoder extends MessageToByteEncoder<DeviceProtocol> { ...@@ -28,7 +28,7 @@ public class OperateEncoder extends MessageToByteEncoder<DeviceProtocol> {
} catch (Exception e) { } catch (Exception e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
log.error(e.getMessage()); log.error("Encoder error");
} }
} }
} }
package iot.sixiang.license.util; package iot.sixiang.license.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException; import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware; import org.springframework.context.ApplicationContextAware;
...@@ -9,37 +7,25 @@ import org.springframework.stereotype.Component; ...@@ -9,37 +7,25 @@ import org.springframework.stereotype.Component;
@Component @Component
public class SpringUtil implements ApplicationContextAware { public class SpringUtil implements ApplicationContextAware {
static Logger logger = LoggerFactory.getLogger(SpringUtil.class.getName()); private static ApplicationContext applicationContext;
private static ApplicationContext applicationContext;
@Override
@Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { if (SpringUtil.applicationContext == null) {
if (SpringUtil.applicationContext == null) { SpringUtil.applicationContext = applicationContext;
SpringUtil.applicationContext = applicationContext; }
} }
logger.info(
"========ApplicationContext配置成功,在普通类可以通过调用SpringUtils.getAppContext()获取applicationContext对象,applicationContext=" // 获取applicationContext
+ SpringUtil.applicationContext + "========"); public static ApplicationContext getApplicationContext() {
} return applicationContext;
}
// 获取applicationContext
public static ApplicationContext getApplicationContext() {
return applicationContext; // 通过class获取Bean.
} public static <T> T getBean(Class<T> clazz) {
return getApplicationContext().getBean(clazz);
// // 通过name获取 Bean. }
// public static Object getBean(String name) {
// return getApplicationContext().getBean(name);
// }
//
// 通过class获取Bean.
public static <T> T getBean(Class<T> clazz) {
return getApplicationContext().getBean(clazz);
}
//
// // 通过name,以及Clazz返回指定的Bean
// public static <T> T getBean(String name, Class<T> clazz) {
// return getApplicationContext().getBean(name, clazz);
// }
} }
\ No newline at end of file
...@@ -2,11 +2,6 @@ package iot.sixiang.license.util; ...@@ -2,11 +2,6 @@ package iot.sixiang.license.util;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.net.Inet4Address; import java.net.Inet4Address;
import java.net.InetAddress; import java.net.InetAddress;
...@@ -19,215 +14,211 @@ import java.util.ArrayList; ...@@ -19,215 +14,211 @@ import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.List; import java.util.List;
@Slf4j @Slf4j
public class Util { public class Util {
public static boolean Debug=false; public static boolean Debug = false;
public static void logInit(String path){
public static byte asciiToByte(byte ascii) {
} byte ret;
if (ascii >= 'A') {
public static byte asciiToByte(byte ascii) ret = (byte) ((ascii - 'A') + 0X0A);
{ ret &= 0x0f;
byte ret; return ret;
if(ascii>='A'){ } else {
ret = (byte)((ascii-'A')+0X0A); ret = (byte) (ascii - (byte) 0x30);
ret&=0x0f; ret = (byte) (ret & 0x0f);
return ret; return ret;
}else{ }
ret = (byte)(ascii-(byte)0x30); }
ret = (byte)(ret&0x0f);
return ret; public static byte byteToAscii(byte data) {
} byte ret = 0x0f;
} if (data >= 0X0A) {
ret = (byte) ((data - 0X0A) + 'A');
public static byte byteToAscii(byte data){ } else {
byte ret=0x0f; ret = (byte) (data + '0');
if(data>=0X0A){ }
ret=(byte)((data-0X0A)+'A');
}else{ return ret;
ret=(byte)(data+'0'); }
}
public static int AsciiToHexByte(byte[] dst, byte[] src) {
return ret; if (src.length == 0) {
} return 0;
}
public static int AsciiToHexByte(byte[] dst,byte[] src){
if(src.length==0){ if ((src.length % 2) != 0) {
return 0; return 0;
} }
if((src.length%2)!=0){ for (int i = 0; i < src.length; ) {
return 0; dst[i / 2] = (byte) (asciiToByte(src[i]) << 4);
} dst[i / 2] += asciiToByte(src[i + 1]);
i += 2;
for(int i=0;i<src.length;){ }
dst[i/2]=(byte)(asciiToByte(src[i])<<4);
dst[i/2]+=asciiToByte(src[i+1]); return src.length / 2;
i+=2; }
}
public static int AsciiToHexByte(byte[] dst, int dstOffset, byte[] src, int srcOffset, int len) {
return src.length/2; if (len == 0) {
} return 0;
}
public static int AsciiToHexByte(byte[] dst,int dstOffset,byte[] src,int srcOffset,int len){
if(len==0){ if ((len % 2) != 0) {
return 0; return 0;
} }
if((len%2)!=0){ for (int i = 0; i < len; ) {
return 0; dst[(i / 2) + dstOffset] = (byte) (asciiToByte(src[i + srcOffset]) << 4);
} dst[(i / 2) + dstOffset] += asciiToByte(src[i + 1 + srcOffset]);
i += 2;
for(int i=0;i<len;){ }
dst[(i/2)+dstOffset]=(byte)(asciiToByte(src[i+srcOffset])<<4);
dst[(i/2)+dstOffset]+=asciiToByte(src[i+1+srcOffset]); return len / 2;
i+=2; }
}
public static int HexToAsciiByte(byte[] dst, byte[] src) {
return len/2;
} for (int i = 0; i < src.length; i++) {
dst[i * 2] = byteToAscii((byte) ((src[i] >> 4) & 0x0f));
public static int HexToAsciiByte(byte[] dst,byte[] src){ dst[(i * 2) + 1] = byteToAscii((byte) (src[i] & 0x0f));
}
for(int i=0;i<src.length;i++){
dst[i*2]=byteToAscii((byte)((src[i]>>4)&0x0f)); return src.length * 2;
dst[(i*2)+1]=byteToAscii((byte)(src[i]&0x0f)); }
}
public static int IndexOfByte(byte[] src, int offer, int len, byte data) {
return src.length*2; for (int i = offer; i < len; i++) {
} if (data == src[i]) {
return i;
public static int IndexOfByte(byte[] src,int offer,int len,byte data){ }
for(int i=offer;i<len;i++){ }
if(data==src[i]){
return i; return len;
} }
}
public static void DEBUG_HEX(String tag, byte[] data, int datalen) {
return len;
}
String hexStr = "";
public static void DEBUG_HEX(String tag,byte[] data,int datalen){ int i = 0;
for (i = 0; i < datalen; i++) {
String hexStr=""; if ((i % 16) == 0) {
int i=0; log.debug(hexStr);
for( i=0;i<datalen;i++){ hexStr = "";
}
if((i%16)==0){ if (Integer.toHexString(data[i] & 0xff).length() == 1) {
log.info(hexStr); hexStr += "0";
hexStr=""; }
} hexStr += Integer.toHexString(data[i] & 0xff).toUpperCase() + " ";
if(Integer.toHexString(data[i]&0xff).length()==1){
hexStr+="0"; if ((i % 16) == 15) {
}
hexStr+=Integer.toHexString(data[i]&0xff).toUpperCase()+" "; for (int j = (i - 15); j <= i; j++) {
if (data[j] > 0x20 && data[j] <= 0x7e) {
if((i%16)==15){ hexStr += String.valueOf((char) (data[j] & 0xff));
} else {
for(int j=(i-15);j<=i;j++){ hexStr += '.';
if(data[j]>0x20&&data[j]<=0x7e){ }
hexStr+=String.valueOf((char)(data[j]&0xff)); }
}else{
hexStr+='.'; }
} }
} if ((i % 16) != 0) {
} for (int j = 0; j < 16; j++) {
} if (j < (16 - (i % 16))) {
if((i%16)!=0){ hexStr += "-- ";
}
for(int j=0;j<16;j++){ }
if(j<(16-(i%16))){
hexStr+="-- "; for (int j = (i - (i % 16)); j < i; j++) {
} if (data[j] > 0x20 && data[j] <= 0x7e) {
} hexStr += String.valueOf((char) (data[j] & 0xff));
} else {
for(int j=(i-(i%16));j<i;j++){ hexStr += '.';
if(data[j]>0x20&&data[j]<=0x7e){ }
hexStr+=String.valueOf((char)(data[j]&0xff)); }
}else{
hexStr+='.'; }
} log.debug(hexStr);
} }
} public static void INFO(String tag, String content) {
log.info(hexStr); if (!Debug) {
} return;
}
public static void INFO(String tag,String content){ SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
if(!Debug){
return ; System.out.println("I-[" + df.format(new Date()) + "][" + tag + "]:" + content);
}
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); }
System.out.println("I-["+df.format(new Date())+"]["+tag+"]:"+content); public static void DEBUG(String tag, String content) {
if (!Debug) {
} return;
}
public static void DEBUG(String tag,String content){
if(!Debug){ SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return ;
} System.out.println("D-[" + df.format(new Date()) + "][" + tag + "]:" + content);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); }
System.out.println("D-["+df.format(new Date())+"]["+tag+"]:"+content); public static void ERROR(String tag, Object content) {
} SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static void ERROR(String tag,Object content){ System.out.println("E-[" + df.format(new Date()) + "][" + tag + "]:" + content);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); if (content instanceof Exception) {
System.out.println("E-["+df.format(new Date())+"]["+tag+"]:"+content);
StackTraceElement stack[] = ((Exception) content).getStackTrace();
if (content instanceof Exception) {
for (int i = 0; i < stack.length; i++) {
StackTraceElement stack[] = ((Exception)content).getStackTrace(); StackTraceElement s = stack[i];
for (int i = 0; i < stack.length; i++) System.out.format("Class:%d\t%s\n", i, s.getClass());//������
{
System.out.format("ClassName:%d\t%s\n", i, s.getClassName());//����
StackTraceElement s = stack[i];
System.out.format("MethodName:%d\t%s\n", i, s.getMethodName());//������
System.out.format("Class:%d\t%s\n", i, s.getClass());//������
System.out.format("FileName:%d\t%s\n", i, s.getFileName());//�ļ���
System.out.format("ClassName:%d\t%s\n", i, s.getClassName());//����
System.out.format("LineNumber:%d\t%s\n", i, s.getLineNumber());//����
System.out.format("MethodName:%d\t%s\n", i, s.getMethodName());//������
System.out.println("-------------------------------------------");//����
System.out.format("FileName:%d\t%s\n", i, s.getFileName());//�ļ���
}
System.out.format("LineNumber:%d\t%s\n", i, s.getLineNumber());//����
}
System.out.println("-------------------------------------------");//����
} }
} public static String HexToStr(byte[] data, int offset, int length, boolean space) {
String hexStr = "";
for (int i = offset; i < (length + offset); i++) {
} if (Integer.toHexString(data[i] & 0xff).length() == 1) {
hexStr += "0";
public static String HexToStr(byte[] data,int offset,int length,boolean space){ }
String hexStr=""; hexStr += Integer.toHexString(data[i] & 0xff).toUpperCase();
for(int i=offset;i<(length+offset);i++){ if (space) {
if(Integer.toHexString(data[i]&0xff).length()==1){ hexStr += " ";
hexStr+="0"; }
} }
hexStr+=Integer.toHexString(data[i]&0xff).toUpperCase(); return hexStr;
if(space){ }
hexStr+=" ";
}
}
return hexStr;
}
public static List<String> getLocalIPList() { public static List<String> getLocalIPList() {
List<String> ipList = new ArrayList<String>(); List<String> ipList = new ArrayList<String>();
try { try {
...@@ -252,67 +243,66 @@ public class Util { ...@@ -252,67 +243,66 @@ public class Util {
} }
return ipList; return ipList;
} }
public static int CRC16(byte[] p,int offer,int len) public static int CRC16(byte[] p, int offer, int len) {
{
//Ԥ�� 1 �� 16 λ�ļĴ���Ϊʮ������FFFF, �ƴ˼Ĵ���Ϊ CRC�Ĵ����� int crc = 0xFFFF;
int crc = 0xFFFF; int i, j;
int i, j; for (i = 0; i < len; i++) {
for (i = 0; i < len; i++) {
//�ѵ�һ�� 8 λ���������� �� 16 λ�� CRC�Ĵ����ĵ� 8 λ�����, �ѽ������ CRC�Ĵ��� crc = ((crc & 0xFF00) | (crc & 0x00FF) ^ (p[i + offer] & 0xFF));
crc = ((crc & 0xFF00) | (crc & 0x00FF) ^ (p[i+offer] & 0xFF)); for (j = 0; j < 8; j++) {
for (j = 0; j < 8; j++) {
//�� CRC �Ĵ�������������һλ( ����λ)�� 0 ����λ, ��������ƺ���Ƴ�λ if ((crc & 0x0001) > 0) {
if ((crc & 0x0001) > 0) {
//����Ƴ�λΪ 1, CRC�Ĵ��������ʽA001������� crc = crc >> 1;
crc = crc >> 1; crc = crc ^ 0xA001;
crc = crc ^ 0xA001; } else
} else
//����Ƴ�λΪ 0,�ٴ�����һλ crc = crc >> 1;
crc = crc >> 1; }
} }
} return crc;
return crc;
} }
public static String UnicodeToUTF8(String content){ public static String UnicodeToUTF8(String content) {
try { try {
return new String(content.getBytes("UTF-8")); return new String(content.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
return null; return null;
} }
public static String splitLineString(String content,int lineLength) { public static String splitLineString(String content, int lineLength) {
String tmp=""; String tmp = "";
int offset=0; int offset = 0;
int length=content.length(); int length = content.length();
while(length>0) { while (length > 0) {
if(length<lineLength) { if (length < lineLength) {
tmp+=content.substring(offset)+"\n"; tmp += content.substring(offset) + "\n";
length=0; length = 0;
}else { } else {
tmp+=content.substring(offset,lineLength+offset)+"\n"; tmp += content.substring(offset, lineLength + offset) + "\n";
offset+=lineLength; offset += lineLength;
length-=lineLength; length -= lineLength;
} }
} }
return tmp; return tmp;
} }
public static byte[] getSHA256(byte[] content) { public static byte[] getSHA256(byte[] content) {
MessageDigest messageDigest; MessageDigest messageDigest;
try { try {
messageDigest = MessageDigest.getInstance("SHA-256"); messageDigest = MessageDigest.getInstance("SHA-256");
messageDigest.update(content); messageDigest.update(content);
return messageDigest.digest(); return messageDigest.digest();
} catch (NoSuchAlgorithmException e) { } catch (NoSuchAlgorithmException e) {
e.printStackTrace(); e.printStackTrace();
} }
return null; return null;
} }
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment