mirror of
https://codeup.aliyun.com/67c68d4e484ca2f0a13ac3c1/ydc/jsowell-charger-web.git
synced 2026-04-20 11:05:18 +08:00
update 电单车协议
This commit is contained in:
@@ -3,16 +3,26 @@ package com.jsowell.netty.server.electricbicycles;
|
||||
import com.alibaba.fastjson2.JSON;
|
||||
import com.jsowell.netty.service.electricbicycles.EBikeBusinessService;
|
||||
import com.jsowell.pile.domain.ebike.AbsEBikeMessage;
|
||||
import io.netty.channel.*;
|
||||
import io.netty.channel.Channel;
|
||||
import io.netty.channel.ChannelHandler;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.SimpleChannelInboundHandler;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@ChannelHandler.Sharable
|
||||
@Slf4j
|
||||
@Component
|
||||
public class ElectricBicyclesServerHandler extends SimpleChannelInboundHandler<AbsEBikeMessage> {
|
||||
|
||||
private final Map<String, ResponseFuture> responseFutureMap = new ConcurrentHashMap<>();
|
||||
|
||||
@Autowired
|
||||
private EBikeBusinessService eBikeService;
|
||||
|
||||
@@ -21,4 +31,44 @@ public class ElectricBicyclesServerHandler extends SimpleChannelInboundHandler<A
|
||||
log.info("收到消息, channelId:{}, msg:{}", ctx.channel().id().toString(), JSON.toJSONString(msg));
|
||||
}
|
||||
|
||||
public String sendCommandAndWaitForResponse(Channel channel, String command, long timeout) throws InterruptedException {
|
||||
String requestId = generateRequestId();
|
||||
ResponseFuture future = new ResponseFuture();
|
||||
responseFutureMap.put(requestId, future);
|
||||
|
||||
// 发送命令
|
||||
channel.writeAndFlush(command);
|
||||
|
||||
// 等待响应
|
||||
return future.get(timeout, TimeUnit.MILLISECONDS);
|
||||
}
|
||||
|
||||
private String extractRequestId(String msg) {
|
||||
// 从响应消息中提取请求ID的逻辑
|
||||
// 这里需要根据您的协议格式进行实现
|
||||
return "";
|
||||
}
|
||||
|
||||
private String generateRequestId() {
|
||||
// 生成唯一的请求ID
|
||||
return String.valueOf(System.currentTimeMillis());
|
||||
}
|
||||
|
||||
private static class ResponseFuture {
|
||||
private final CountDownLatch latch = new CountDownLatch(1);
|
||||
private String response;
|
||||
|
||||
public void setResponse(String response) {
|
||||
this.response = response;
|
||||
latch.countDown();
|
||||
}
|
||||
|
||||
public String get(long timeout, TimeUnit unit) throws InterruptedException {
|
||||
if (latch.await(timeout, unit)) {
|
||||
return response;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user