#
Junjie
2025-07-06 7c4bbcb2ceed34e82212b82d2aa551a87bdaaa0d
#
1个文件已添加
4个文件已修改
306 ■■■■ 已修改文件
src/main/java/com/zy/core/ServerBootstrap.java 17 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/zy/core/thread/ShuttleThread.java 2 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/zy/core/thread/fake/FakeNyShuttleThread.java 228 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/zy/core/thread/impl/NyShuttleThread.java 55 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/zy/core/utils/FakeDeviceUtils.java 4 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/zy/core/ServerBootstrap.java
@@ -7,10 +7,10 @@
import com.zy.core.cache.SlaveConnection;
import com.zy.core.enums.SlaveType;
import com.zy.core.properties.DeviceConfig;
import com.zy.core.thread.fake.FakeNyShuttleThread;
import com.zy.core.thread.impl.LfdZyForkLiftMasterThread;
import com.zy.core.thread.impl.NyShuttleThread;
import com.zy.core.utils.DeviceMsgUtils;
import com.zy.core.utils.FakeDeviceUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
@@ -31,8 +31,6 @@
    private RedisUtil redisUtil;
    @Autowired
    private DeviceMsgUtils deviceMsgUtils;
    @Autowired
    private FakeDeviceUtils fakeDeviceUtils;
    @PostConstruct
@@ -85,17 +83,8 @@
    }
    private void initFakeThread(){
        String fakeDeviceConfig = fakeDeviceUtils.getFakeDeviceConfig();
        if(null != fakeDeviceConfig){
            List<DeviceConfig> deviceConfigs = JSON.parseArray(fakeDeviceConfig, DeviceConfig.class);
            for (DeviceConfig device : deviceConfigs) {
                if (device.getDeviceType().equals(String.valueOf(SlaveType.ForkLift))) {
                    initForkLiftThread(device);
                } else if (device.getDeviceType().equals(String.valueOf(SlaveType.Shuttle))) {
                    initShuttleThread(device);
                }
            }
        }
        ThreadHandler thread = new FakeNyShuttleThread(redisUtil);
        new Thread(thread).start();
    }
src/main/java/com/zy/core/thread/ShuttleThread.java
@@ -7,8 +7,6 @@
    DeviceConfig getDeviceConfig();
    boolean isFake();
    void stopThread();
}
src/main/java/com/zy/core/thread/fake/FakeNyShuttleThread.java
New file
@@ -0,0 +1,228 @@
package com.zy.core.thread.fake;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zy.common.SpringUtils;
import com.zy.common.exception.CoolException;
import com.zy.common.utils.RedisUtil;
import com.zy.core.News;
import com.zy.core.ThreadHandler;
import com.zy.core.cache.SlaveConnection;
import com.zy.core.enums.SlaveType;
import com.zy.core.properties.DeviceConfig;
import com.zy.core.thread.impl.NyShuttleThread;
import com.zy.core.utils.FakeDeviceUtils;
import lombok.extern.slf4j.Slf4j;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@Slf4j
@SuppressWarnings("all")
public class FakeNyShuttleThread implements ThreadHandler {
    private RedisUtil redisUtil;
    private JSONObject fakeStatusDemo = JSONObject.parseObject("{\"mode\":1,\"extend\":{\"countQuantity\":400,\"suspendState\":0,\"minCellVoltage\":3279,\"chargeCycleTimes\":0,\"maxCellVoltage\":3281,\"surplusQuantity\":204,\"voltage\":5248},\"hasLift\":false,\"hasPallet\":false,\"batteryVoltage\":5248,\"runDirection\":\"2\",\"currentCode\":\"{\\\"x\\\":12,\\\"y\\\":37,\\\"z\\\":3}\",\"errorCode\":\"0\",\"hasCharge\":false,\"batteryPower\":\"51\",\"speed\":0,\"deviceStatus\":1}");
    private HashMap<String, Socket> fakeServerMap = new HashMap();
    private HashMap<String, JSONObject> fakeStatusMap = new HashMap();
    private boolean fake = false;
    public FakeNyShuttleThread(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }
    @Override
    public void run() {
        News.info("Fake Server is Started");
        while (true) {
            try {
                initFakeDeviceServer();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
    private void initFakeDeviceServer() {
        FakeDeviceUtils fakeDeviceUtils = SpringUtils.getBean(FakeDeviceUtils.class);
        String fakeDeviceConfig = fakeDeviceUtils.getFakeDeviceConfig();
        if(null != fakeDeviceConfig){
            List<DeviceConfig> deviceConfigs = JSON.parseArray(fakeDeviceConfig, DeviceConfig.class);
            for (DeviceConfig device : deviceConfigs) {
                if (!device.getDeviceType().equals(String.valueOf(SlaveType.Shuttle))) {
                    continue;
                }
                if (!device.getThreadImpl().equals("NyShuttleThread")) {
                    continue;
                }
                if (fakeServerMap.containsKey(String.valueOf(SlaveType.Shuttle) + device.getDeviceNo())) {
                    continue;
                }
                Thread fakeThread = new Thread(() -> {
                    try {
                        ServerSocket serverSocket = new ServerSocket(device.getPort());
                        Socket fakeSocket = serverSocket.accept();
                        fakeServerMap.put(String.valueOf(SlaveType.Shuttle) + device.getDeviceNo(), fakeSocket);
                        fakeStatusMap.put(String.valueOf(SlaveType.Shuttle) + device.getDeviceNo(), JSON.parseObject(JSON.toJSONString(fakeStatusDemo)));
                        while (true) {
                            if(fakeSocket == null) {
                                fakeServerMap.remove(String.valueOf(SlaveType.Shuttle) + device.getDeviceNo());
                                break;
                            }
                            if(fakeSocket.isClosed()) {
                                fakeSocket = null;
                                continue;
                            }
                            handleClient(fakeSocket, device);
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                });
                fakeThread.start();
                // init
                ThreadHandler thread = new NyShuttleThread(device, redisUtil);;
                new Thread(thread).start();
                SlaveConnection.put(SlaveType.Shuttle, device.getDeviceNo(), thread);
            }
        }
    }
    private void handleClient(Socket socket, DeviceConfig device) throws IOException {
        try {
            // 获取输入流
            BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            // 读取服务器的响应
            StringBuffer sb = new StringBuffer();
            char[] chars = new char[2048];//缓冲区
            while (true) {
                reader.read(chars);
                String trim = new String(chars);
                sb.append(trim);
                if (trim.lastIndexOf("\r\n") != -1) {
                    break;
                }
            }
            JSONObject result = JSON.parseObject(sb.toString());
            log.info("收到Client Data: {}", JSON.toJSONString(result));
            processCommand(result, device);
        } catch (Exception e) {
//            e.printStackTrace();
            socket.close();
            fakeServerMap.remove(String.valueOf(SlaveType.Shuttle) + device.getDeviceNo());
        }
    }
    public void processCommand(JSONObject result, DeviceConfig device) throws IOException {
        String response = null;
        JSONObject fakeStatus = fakeStatusMap.get(String.valueOf(SlaveType.Shuttle) + device.getDeviceNo());
        JSONObject request = result.getJSONObject("request");
        JSONObject body = request.getJSONObject("body");
        String requestType = body.getString("requestType");
        Integer taskId = body.getInteger("taskId");
        if (requestType.equals("liftUp")) {
            fakeStatus.put("hasLift", true);
        } else if (requestType.equals("liftDown")) {
            fakeStatus.put("hasLift", false);
        } else if (requestType.equals("charge")) {
            fakeStatus.put("hasCharge", true);
        } else if (requestType.equals("stopCharge")) {
            fakeStatus.put("hasCharge", false);
        } else if (requestType.equals("updateFloor")) {
            String currentCode = fakeStatus.getString("currentCode");
            JSONObject point = JSON.parseObject(currentCode);
            point.put("z", body.getInteger("z"));
            fakeStatus.put("currentCode", JSON.toJSONString(point));
        } else if (requestType.equals("move")) {
            String pathList = body.getString("path");
            List<JSONObject> list = JSON.parseArray(pathList, JSONObject.class);
            for (JSONObject path : list) {
                String currentCode = fakeStatus.getString("currentCode");
                JSONObject point = JSON.parseObject(currentCode);
                point.put("x", path.getInteger("xp"));
                point.put("y", path.getInteger("yp"));
                point.put("z", path.getInteger("z"));
                fakeStatus.put("currentCode", JSON.toJSONString(point));
                try {
                    Thread.sleep(1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else if (requestType.equals("readState")) {
            response = genereateFakeStatusResponse(taskId, fakeStatus);
        }
        fakeStatusMap.put(String.valueOf(SlaveType.Shuttle) + device.getDeviceNo(), fakeStatus);
        if (response != null) {
            Socket fakeSocket = fakeServerMap.get(String.valueOf(SlaveType.Shuttle) + device.getDeviceNo());
            OutputStreamWriter writer = new OutputStreamWriter(fakeSocket.getOutputStream());
            writer.write(response + "\r\n");
            writer.flush();
        }
    }
    public String genereateFakeStatusResponse(Integer taskId, JSONObject fakeStatus) {
        JSONObject result = new JSONObject();
        JSONObject response = new JSONObject();
        result.put("msgType", "responseMsg");
        result.put("robotId", 5001);
        result.put("response", response);
        JSONObject header = new JSONObject();
        JSONObject body = new JSONObject();
        response.put("header", header);
        response.put("body", body);
        header.put("responseId", taskId);
        header.put("version", "GV-APP-F427-N24036-1112");
        body.put("responseType", "state");
        body.put("workingMode", fakeStatus.getInteger("mode"));
        body.put("free", fakeStatus.getInteger("deviceStatus"));
        body.put("point", fakeStatus.getString("currentCode"));
        body.put("powerPercent", fakeStatus.getString("batteryPower"));
        body.put("voltage", fakeStatus.getInteger("batteryVoltage"));
        body.put("errCode", new ArrayList<Integer>(){{add(fakeStatus.getInteger("errorCode"));add(0);}});
        body.put("liftPosition", fakeStatus.getBoolean("hasLift") == true ? 2 : 1);
        body.put("loadState", fakeStatus.getBoolean("hasPallet") == true ? 1 : 0);
        body.put("runDir", fakeStatus.getString("runDirection"));
        body.put("chargState", fakeStatus.getBoolean("hasCharge") == true ? 1 : 0);
        body.put("speed", fakeStatus.getInteger("speed"));
        JSONObject extend = fakeStatus.getJSONObject("extend");
        body.put("suspendState", extend.getInteger("suspendState"));
        body.put("maxCellVoltage", extend.getInteger("maxCellVoltage"));
        body.put("minCellVoltage", extend.getInteger("minCellVoltage"));
        body.put("voltage", extend.getInteger("voltage"));
        body.put("chargeCycleTimes", extend.getInteger("chargeCycleTimes"));
        body.put("surplusQuantity", extend.getInteger("surplusQuantity"));
        body.put("countQuantity", extend.getInteger("countQuantity"));
        return JSON.toJSONString(result);
    }
    @Override
    public boolean connect() {
        return true;
    }
    @Override
    public void close() {
    }
}
src/main/java/com/zy/core/thread/impl/NyShuttleThread.java
@@ -13,11 +13,11 @@
import com.zy.core.cache.OutputQueue;
import com.zy.core.enums.SlaveType;
import com.zy.core.thread.ShuttleThread;
import io.netty.handler.timeout.ReadTimeoutException;
import lombok.extern.slf4j.Slf4j;
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.MessageFormat;
import java.util.*;
@@ -29,21 +29,16 @@
    private DeviceConfig deviceConfig;
    private RedisUtil redisUtil;
    private Socket socket;
    private ServerSocket serverSocket;
    private boolean fake = false;
    private boolean stopThread = false;
    public NyShuttleThread(DeviceConfig deviceConfig, RedisUtil redisUtil) {
        this.deviceConfig = deviceConfig;
        this.redisUtil = redisUtil;
        this.fake = deviceConfig.getFake();
    }
    @Override
    public void run() {
        News.info("{}号四向车线程启动", deviceConfig.getDeviceNo());
        this.connect();
        //监听消息
        Thread innerThread = new Thread(() -> {
@@ -52,9 +47,8 @@
                    break;
                }
                System.out.println("read");
                try {
                    this.connect();
                    Thread.sleep(200);
                    listenSocketMessage();
                } catch (Exception e) {
@@ -71,7 +65,6 @@
                    break;
                }
                System.out.println("executeThread");
                try {
                    DeviceMsgUtils deviceMsgUtils = null;
                    try {
@@ -93,35 +86,6 @@
            }
        });
        executeThread.start();
        if (this.fake) {
            Thread fakeThread = new Thread(() -> {
                try {
                    serverSocket = new ServerSocket(deviceConfig.getPort());
                    while (true) {
                        if(stopThread) {
                            break;
                        }
                        System.out.println("fakeThread");
                        Socket accept = serverSocket.accept();
                        handleClient(accept);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            });
            fakeThread.start();
        }
    }
    private void handleClient(Socket socket) throws IOException {
        InputStream inputStream = socket.getInputStream();
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("test".getBytes());
        outputStream.flush();
        socket.close();
    }
    private void executeCommand(DeviceCommandMsgModel deviceCommandMsg) {
@@ -151,9 +115,9 @@
            DeviceMsgUtils deviceMsgUtils = null;
            try {
                deviceMsgUtils = SpringUtils.getBean(DeviceMsgUtils.class);
            }catch (Exception e){
            } catch (Exception e) {
            }
            if(deviceMsgUtils == null) {
            if (deviceMsgUtils == null) {
                return;
            }
@@ -172,6 +136,7 @@
            }
            JSONObject result = JSON.parseObject(sb.toString());//得到响应结果集
            log.info("收到Server Data: {}", JSON.toJSONString(result));
            String msgType = result.getString("msgType");
            if ("responseMsg".equals(msgType)) {
@@ -198,7 +163,7 @@
            deviceMsgModel.setDeviceOriginMsg(sb.toString());
            deviceMsgUtils.sendDeviceMsg(SlaveType.Shuttle, deviceConfig.getDeviceNo(), deviceMsgModel);
        } catch (Exception e) {
            e.printStackTrace();
//            e.printStackTrace();
        }
    }
@@ -254,6 +219,10 @@
    @Override
    public boolean connect() {
        try {
            if(this.socket != null) {
                return true;
            }
            InetAddress address = InetAddress.getByName(deviceConfig.getIp());
            if (address.isReachable(10000)) {
                Socket socket = new Socket(deviceConfig.getIp(), deviceConfig.getPort());
@@ -285,8 +254,4 @@
        this.stopThread = true;
    }
    @Override
    public boolean isFake() {
        return this.fake;
    }
}
src/main/java/com/zy/core/utils/FakeDeviceUtils.java
@@ -55,10 +55,6 @@
                throw new CoolException("设备线程不存在");
            }
            if (!shuttleThread.isFake()) {
                throw new CoolException("不允许删除真实设备线程");
            }
            shuttleThread.stopThread();
        }