import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
@Service
@Slf4j
public class WarehouseWsServiceImpl implements WarehouseWsService {
private String url = "ws://10.60.2.166:8888/external/websocket/robot/real-data";
private LinkedList<String> queue = new LinkedList<>();
WarehouseWsServiceImpl() throws InterruptedException {
new Thread(() -> {
subRcsData();
}).start();
new Thread(() -> {
while (true) {
runHandleWs();
}
}).start();
}
public void forwardData(String data) {
WarehouseWs.pushMessage(data);
}
private void subRcsData() {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
WebSocketListener socketListener = new WebSocketListener() {
@Override
public void onOpen(WebSocket webSocket, Response response) {
log.info("WebSocket connection opened");
}
@Override
public void onMessage(WebSocket webSocket, String text) {
queue.offer(text);
}
@Override
public void onClosed(WebSocket webSocket, int code, String reason) {
log.info("WebSocket connection closed: " + code + ", " + reason);
subRcsData();
}
@Override
public void onFailure(WebSocket webSocket, Throwable t, Response response) {
log.info("WebSocket connection failure: " + t.getMessage());
subRcsData();
}
};
client.newWebSocket(request, socketListener);
}
private void runHandleWs() {
String text = queue.poll();
if (text == null) {
return;
}
RcsWs rcsWs = JSON.parseObject(text, RcsWs.class);
List<ActivateThreeD> allaAct = new ArrayList<>();
if (FloorAxisMan.getAllFloorName().size() <= 0) {
return;
}
String floorName = "1";
for (RcsRobot item : rcsWs.getRobot()) {
ActivateThreeD activateThreeD = new ActivateThreeD();
activateThreeD.model.id = item.getRobotCode();
activateThreeD.model.modelName = item.getModelName() + ".glb";
activateThreeD.model.status.local.x = FloorAxisMan.getTrans(floorName)
.getX(item.getPosition().getX());
activateThreeD.model.status.local.y = FloorAxisMan.getTrans(floorName)
.getY(item.getPosition().getZ());
activateThreeD.model.status.local.z = FloorAxisMan.getTrans(floorName)
.getZ(item.getPosition().getY());
activateThreeD.model.status.local.angle = item.getAngle();
activateThreeD.model.status.size.length = item.getLength();
activateThreeD.model.status.size.width = item.getWidth();
activateThreeD.model.status.size.height = item.getHeight();
activateThreeD.model.property = String.format("{\"battery\":%f,\"speed\":%f,\"status\":%d}",
item.getBattery(),
item.getSpeed(), item.getStatus());
allaAct.add(activateThreeD);
}
String sendString = JSON.toJSONString(allaAct);
forwardData(sendString);
}
}