Commit e626dc50 by tiger

callback 逻辑

1 parent d8e74804
......@@ -30,7 +30,7 @@ public class Ocpp16Helper {
*/
private static PluralCache<String, AtomicInteger> seqFactorys = new PluralCache<>(100);
// 所有的dll协议均扫描进来
// 所有的协议均扫描进来
private static Map<Byte, Pair<Class<? extends TcpBase>, Class<? extends TcpData>>> protocols = Maps.newHashMap();
public static void scan() {
......@@ -64,16 +64,27 @@ public class Ocpp16Helper {
}
}
public static short generateSeq(String channelId) {
AtomicInteger ai = seqFactorys.get(channelId);
if (ai == null) {
ai = new AtomicInteger();
seqFactorys.put(channelId, ai);
}
public static short generateSeq(String pileId) {
AtomicInteger ai = getSeqGenerater(pileId);
int rs = ai.incrementAndGet();
return (short) rs; // 溢出自动清零
}
private static AtomicInteger getSeqGenerater(String pileId) {
AtomicInteger ai = seqFactorys.get(pileId);
if (ai == null) {
ai = new AtomicInteger(1);
seqFactorys.put(pileId, ai);
}
return ai;
}
public static void resetSeq(String pileId) {
AtomicInteger ai = getSeqGenerater(pileId);
log.info("【重置seq】{} : {} -> {}", pileId, ai.get(), 1);
ai.set(1);
}
/**
* TcpBase在build时自动填充
*/
......@@ -228,8 +239,8 @@ public class Ocpp16Helper {
byte[] data1 = ByteUtils.getBytes(data, 2, data.length - 4);
short crc = CrcUtils.calculateCRC(data1);
b.setCrc(crc);
ByteUtils.putShort(data, data.length - 2, crc);
// log.info("【{}】build crc:{}", d.getClass().getSimpleName(), crc);
}
......@@ -309,9 +320,9 @@ public class Ocpp16Helper {
return p;
}
/**
* long类型值转换成指定长度的二进制字符串
*
* @param number
* @param byteCount
* @return
......@@ -334,6 +345,7 @@ public class Ocpp16Helper {
/**
* 十六进制字符串转二进制字符串
*
* @param hexString
* @return
*/
......@@ -351,6 +363,7 @@ public class Ocpp16Helper {
/**
* 二进制字符串转成对应Long数值
*
* @param binaryString
* @return
*/
......@@ -370,6 +383,7 @@ public class Ocpp16Helper {
/**
* 二进制字符串转成16进制字符串
*
* @param binaryString
* @return
*/
......@@ -397,5 +411,4 @@ public class Ocpp16Helper {
return hexString.toString();
}
}
\ No newline at end of file
package cn.com.glsx.charging.modules.gbt.ocpp16;
import cn.com.glsx.charging.modules.gbt.ocpp16.tcp.base.TcpCallback;
import cn.com.glsx.charging.modules.gbt.ocpp16.tcp.base.TcpRsp;
import cn.com.glsx.charging.modules.gbt.ocpp16.tcp.data.TimeSettingReqData;
import cn.com.glsx.charging.modules.gbt.ocpp16.tcp.protocol.TimeSettingReq;
import cn.com.glsx.charging.modules.gbt.ocpp16.tcp.server.TcpServer;
public class ServerMain {
......@@ -37,6 +41,12 @@ public class ServerMain {
String host = "localhost";
int port = 8888;
start(host, port);
TcpServer server = start(host, port);
TimeSettingReq timeReq = new TimeSettingReq();
timeReq.setData(new TimeSettingReqData());
TcpCallback<TcpRsp> callback = server.sendSync(timeReq);
TcpRsp rsp = callback.get();
}
}
package cn.com.glsx.charging.modules.gbt.ocpp16.tcp.base;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import com.google.common.collect.Lists;
import cn.hutool.core.collection.CollectionUtil;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
@SuppressWarnings("rawtypes")
@Slf4j
@Getter
public class TcpCallback<Rsp extends TcpRsp> {
private CountDownLatch latch = new CountDownLatch(1);
private final Class<Rsp> rspClass;
private List<Rsp> results = Lists.newArrayList();
private long timeout = 1200;
public TcpCallback(Class<Rsp> rspClass) {
super();
this.rspClass = rspClass;
}
/**
* @param rsp
* 单条返回信息的
*/
public void callback(Rsp rsp) {
if (rsp != null) {
this.results.add(rsp);
latch.countDown();
}
}
public void callback(String ip, Rsp rsp) {
if (rsp != null) {
// log.info("【{}】3.收到Tcp回调:{} -> {}", ip, rsp.getMapper().getRemark(), rsp);
}
callback(rsp);
}
/**
* @param rsp
* 多条返回信息
*/
public void callbacks(Rsp rsp) {
if (rsp != null) {
this.results.add(rsp);
latch.countDown();
log.info("callback:" + rsp + " countdown:" + latch.getCount());
}
}
public Rsp get() {
return get(timeout);
}
public Rsp get(long timeout) {
List<Rsp> rs = gets(timeout);
return CollectionUtil.isEmpty(rs) ? null : rs.get(0);
}
public List<Rsp> gets(long timeout) {
try {
if (!isDone()) {
latch.await(timeout, TimeUnit.MILLISECONDS);
}
return results;
} catch (InterruptedException e) {
throw new RuntimeException("结果集异常:" + timeout + "ms", e);
}
}
public List<Rsp> gets() {
return gets(timeout);
}
public boolean isDone() {
return latch.getCount() <= 0;
}
public boolean isSuccess() {
return isDone() && CollectionUtil.isNotEmpty(results);
}
}
......@@ -5,6 +5,7 @@ import java.util.Map;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.google.common.collect.Maps;
import cn.com.glsx.charging.modules.gbt.ocpp16.tcp.handler.DefaultReqHandler;
import cn.com.glsx.charging.modules.gbt.ocpp16.tcp.handler.HeartbeatReqHandler;
import cn.com.glsx.charging.modules.gbt.ocpp16.tcp.handler.LoginReqHandler;
import cn.com.glsx.charging.modules.gbt.ocpp16.tcp.handler.ModelChargingReqHandler;
......@@ -63,7 +64,7 @@ public final class TcpMapper {
// public static TcpMapper CMD_NOTIFY_TIME = regist(0x56, "对时设置", TimeNotifyHandler.class);
// 运营交互帧类型码数据定义 0x31~0x47
public static TcpMapper CMD_REQ_START_CHARGING = regist(0x31, "充电桩主动申请启动充电 ", null);
public static TcpMapper CMD_REQ_START_CHARGING = regist(0x31, "充电桩主动申请启动充电 ", DefaultReqHandler.class);
public static TcpMapper CMD_RSP_START_CHARGING = regist(0x32, "充电桩主动申请启动充电应答", null);
......
package cn.com.glsx.charging.modules.gbt.ocpp16.tcp.client;
import java.net.InetSocketAddress;
import java.util.List;
import cn.com.glsx.charging.modules.gbt.ocpp16.Ocpp16Helper;
import cn.com.glsx.charging.modules.gbt.ocpp16.tcp.base.TcpBase;
......@@ -19,6 +20,7 @@ import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.handler.codec.bytes.ByteArrayDecoder;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import lombok.Getter;
......
......@@ -16,8 +16,7 @@ public class DefaultReqHandler implements TcpHandler<TcpReq<TcpData>, TcpRsp<Tcp
@Override
public TcpRsp<TcpData> handle(Channel channel, TcpReq<TcpData> req) {
TcpRsp<TcpData> rsp = new TcpRsp<>();
return rsp;
return null;
}
}
package cn.com.glsx.charging.modules.gbt.ocpp16.tcp.handler;
import cn.com.glsx.charging.modules.gbt.ocpp16.Ocpp16Helper;
import cn.com.glsx.charging.modules.gbt.ocpp16.tcp.base.TcpCallback;
import cn.com.glsx.charging.modules.gbt.ocpp16.tcp.base.TcpHandler;
import cn.com.glsx.charging.modules.gbt.ocpp16.tcp.base.TcpRsp;
import cn.com.glsx.charging.modules.gbt.ocpp16.tcp.data.TimeSettingRspData;
import cn.com.glsx.charging.modules.gbt.ocpp16.tcp.protocol.TimeSettingRsp;
import cn.com.glsx.charging.modules.gbt.ocpp16.tcp.server.ProxyHelper;
import cn.com.glsx.charging.util.ByteUtils;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
......@@ -19,10 +22,17 @@ import lombok.extern.slf4j.Slf4j;
@Slf4j
public class TimeSettingRspHandler implements TcpHandler<TimeSettingRsp, TimeSettingRsp> {
@Override
public TimeSettingRsp handle(Channel channel, TimeSettingRsp timeSettingRsp) {
TimeSettingRspData data = timeSettingRsp.getData();
log.info("对时设置响应 pointId {} time {}", Ocpp16Helper.bcdToStr(data.getPileId()), ByteUtils.parseCp56Time2aStr(data.getTime()) /*DateUtils.datetimeToStr(ByteUtils.parseCp56Time2a(timeSettingRsp.getData().getTime()))*/);
return null;
}
@Override
public TimeSettingRsp handle(Channel channel, TimeSettingRsp rsp) {
TimeSettingRspData data = rsp.getData();
log.info("对时设置响应 pointId {} time {}", Ocpp16Helper.bcdToStr(data.getPileId()), ByteUtils
.parseCp56Time2aStr(data.getTime()) /* DateUtils.datetimeToStr(ByteUtils.parseCp56Time2a(timeSettingRsp.getData().getTime())) */);
// TODO
String key = channel.attr(ProxyHelper.PILE_ID_KEY).get() + "+" + rsp.getSeq();
TcpCallback<TcpRsp> callback = ProxyHelper.getCallback(key);
callback.callback(rsp);
return null;
}
}
......@@ -6,16 +6,24 @@ import java.util.Map;
import com.google.common.collect.Maps;
import cn.com.glsx.charging.modules.gbt.ocpp16.Ocpp16Helper;
import cn.com.glsx.charging.util.JacksonUtils;
import cn.com.glsx.charging.util.TaskExecutor;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@SuppressWarnings("rawtypes")
public class ProxyHelper {
// ip -> proxyInfo
/** channel绑定key */
public static final AttributeKey<String> PILE_ID_KEY = AttributeKey.valueOf("pileId");
/** 心跳超时时间 */
public static int HEARTBEAT_TIMEOUT_SECONDS = 30; // 心跳过期时间(10秒每次,3次没心跳则过期)
// pileId -> proxyInfo
private static Map<String, ProxyInfo> proxys = Maps.newConcurrentMap();
// key -> TcpCallback
......@@ -24,10 +32,6 @@ public class ProxyHelper {
// notifyClass --> data-queue
// private static final Map<String, Queue<TcpNotify>> notifys = Maps.newHashMap();
public static String getIp(ChannelHandlerContext ctx) {
return getIp(ctx.channel());
}
public static String getIp(Channel channel) {
String ip = ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress();
return ip;
......@@ -38,13 +42,23 @@ public class ProxyHelper {
return port;
}
public static ProxyInfo addProxyInfo(Channel channel) {
String ip = getIp(channel);
ProxyInfo proxyInfo = proxys.get(ip);
public static ProxyInfo registProxyInfo(String pileId, Channel channel) {
// 标记连接
Attribute<String> attr = channel.attr(ProxyHelper.PILE_ID_KEY);
if (attr.get() != null) {
log.warn("【连接更换】{} -> {}", attr.get(), pileId);
}
attr.set(pileId);
ProxyInfo proxyInfo = proxys.get(pileId);
if (proxyInfo == null) {
proxyInfo = new ProxyInfo(channel);
proxys.put(ip, proxyInfo);
log.info("【{}】Proxy连接建立...", ip);
proxyInfo = new ProxyInfo(channel, pileId);
proxys.put(pileId, proxyInfo);
log.info("【{}】Proxy连接建立:{}", pileId, proxyInfo);
} else {
if (proxyInfo.getChannel().id() != channel.id()) {
log.warn("【警告】pileId:{} 包含两个连接,新:{} 会覆盖旧:{} ...", pileId, channel.toString(), proxyInfo.getChannel().toString());
}
}
proxyInfo.setChannel(channel);
proxyInfo.setLastTime(new Date());
......@@ -53,49 +67,39 @@ public class ProxyHelper {
// 连接断开,暂时不移除连接
public static void removeProxyInfo(Channel channel) {
String ip = getIp(channel);
removeProxyInfo(ip);
Attribute<String> attr = channel.attr(ProxyHelper.PILE_ID_KEY);
String pileId = attr.get();
removeProxyInfo(pileId);
}
private synchronized static void removeProxyInfo(String ip) {
ProxyInfo proxyInfo = proxys.get(ip);
private synchronized static void removeProxyInfo(String pileId) {
ProxyInfo proxyInfo = proxys.get(pileId);
if (proxyInfo != null && proxyInfo.getChannel().isActive()) {
return;
}
log.warn("Proxy:" + ip + "断联中。。。");
proxys.remove(ip); // 连接断开,暂时不移除连接
Ocpp16Helper.resetSeq(pileId);
log.warn("Proxy:" + pileId + "断联中。。。");
proxys.remove(pileId); // 连接断开,暂时移除连接
}
public static ProxyInfo getProxyInfo(Channel channel) {
String ip = getIp(channel);
return getProxyInfo(ip);
Attribute<String> attr = channel.attr(ProxyHelper.PILE_ID_KEY);
String pileId = attr.get();
return getProxyInfo(pileId);
}
public static ProxyInfo getProxyInfo(String ip) {
ProxyInfo proxyInfo = proxys.get(ip);
public static ProxyInfo getProxyInfo(String pileId) {
ProxyInfo proxyInfo = proxys.get(pileId);
if (proxyInfo == null) {
throw new ProxyException("【" + ip + "】Proxy连接不存在!!!");
throw new RuntimeException("【" + pileId + "】Proxy连接不存在!!!");
}
return proxyInfo;
}
public static class ProxyException extends RuntimeException {
public ProxyException() {
super();
}
public ProxyException(String message) {
super(message);
}
public ProxyException(Throwable cause) {
super(cause);
}
}
// TODO 心跳机制
// TODO 错误反馈机制
// web_req -> web_req_handler -> tcp_req -> tcp_req_handler -> dll_req -> dll_handler -> dll_rsp -> tcp_rsp -> tcp_rsp_handler -> web_rsp
......
......@@ -2,7 +2,10 @@ package cn.com.glsx.charging.modules.gbt.ocpp16.tcp.server;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonIgnore;
import cn.com.glsx.charging.util.DateUtils;
import cn.com.glsx.charging.util.JacksonUtils;
import io.netty.channel.Channel;
import lombok.Getter;
import lombok.Setter;
......@@ -21,6 +24,7 @@ public class ProxyInfo {
private int port;
/** Tcp连接 */
@JsonIgnore
private Channel channel;
/** 充电桩id */
......@@ -32,22 +36,25 @@ public class ProxyInfo {
/** 上次交互时间 */
private Date lastTime = new Date();
public ProxyInfo(Channel channel) {
public ProxyInfo(Channel channel, String pileId2) {
super();
this.channel = channel;
this.ip = ProxyHelper.getIp(channel);
this.port = ProxyHelper.getPort(channel);
this.pileId = pileId2;
}
private static int HEARTBEAT_TIMEOUT_SECONDS = 30; // 心跳过期时间(10秒每次,3次没心跳则过期)
// 3次心跳缺失,认为断联
public boolean isLastTimeout() {
return lastTime.before(DateUtils.addSecond(new Date(), -HEARTBEAT_TIMEOUT_SECONDS));
return lastTime.before(DateUtils.addSecond(new Date(), -ProxyHelper.HEARTBEAT_TIMEOUT_SECONDS));
}
public boolean isActive() {
return channel != null && channel.isActive();
}
@Override
public String toString() {
return JacksonUtils.toJson(this);
}
}
......@@ -5,6 +5,8 @@ import java.util.concurrent.ScheduledFuture;
import cn.com.glsx.charging.modules.gbt.ocpp16.Ocpp16Helper;
import cn.com.glsx.charging.modules.gbt.ocpp16.tcp.base.TcpBase;
import cn.com.glsx.charging.modules.gbt.ocpp16.tcp.base.TcpCallback;
import cn.com.glsx.charging.modules.gbt.ocpp16.tcp.base.TcpRsp;
import cn.com.glsx.charging.util.ByteUtils;
import cn.com.glsx.charging.util.Task;
import cn.com.glsx.charging.util.TaskExecutor;
......@@ -110,7 +112,7 @@ public class TcpServer {
}
@SuppressWarnings({ "rawtypes" })
public <T extends TcpBase> void sendSync(T data) {
public <T extends TcpBase> TcpCallback<TcpRsp> sendSync(T data) {
String ip = getIp(future.channel());
// seq字段处理
......@@ -122,10 +124,16 @@ public class TcpServer {
byte[] bs = Ocpp16Helper.build(data);
String key = future.channel().attr(ProxyHelper.PILE_ID_KEY).get() + "+" + data.getSeq();
TcpCallback<TcpRsp> callback = new TcpCallback<>(TcpRsp.class);
// ProxyHelper.addCallback(key, callback);
sendSync(bs);
log.info("【{}】【{}】send1: {} ", ip, data.getClass().getSimpleName(), ByteUtils.toHex(bs));
log.info("【{}】【{}】send2: {} ", ip, data.getClass().getSimpleName(), data);
return callback;
}
private void sendSync(byte[] bytes) {
......
......@@ -23,12 +23,6 @@ public class TcpServerHandler extends SimpleChannelInboundHandler<byte[]> {
String ip = TcpServer.getIp(ctx);
log.info("【{}】conn: 连接成功... {}", ip, ctx.channel().remoteAddress().toString());
log.info("**************************************************************");
ProxyHelper.addProxyInfo(ctx.channel());
// String json = new LoginQrcodeTcpReq().build();
// log.info("【{}】send: {}", ip, json);
// ctx.channel().writeAndFlush(json);
}
@Override
......@@ -38,8 +32,6 @@ public class TcpServerHandler extends SimpleChannelInboundHandler<byte[]> {
log.info("##############################################################");
ProxyHelper.removeProxyInfo(ctx.channel());
// rest sequence
}
// @Override
......@@ -80,7 +72,9 @@ public class TcpServerHandler extends SimpleChannelInboundHandler<byte[]> {
if (!Ocpp16Helper.verifyCrc(up)) {
log.warn("【警告】crc校验不通过:{}", up);
}
ProxyHelper.registProxyInfo(up.getData().getPileIdStr(), ctx.channel());
Class<? extends TcpHandler> handlerClass = mapper.getHandlerClass();
if (handlerClass == null && up instanceof TcpReq) {
handlerClass = DefaultReqHandler.class;
......@@ -105,8 +99,6 @@ public class TcpServerHandler extends SimpleChannelInboundHandler<byte[]> {
}
} catch (Exception e) {
log.error("【{}】{}", ip, e);
} finally {
ProxyHelper.addProxyInfo(ctx.channel());
}
}
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!