#
Junjie
17 小时以前 c8de85433e5800a7b5595a96d99f4b49f24c38b4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package com.zy.core.network;
 
import com.zy.asrs.entity.DeviceConfig;
import com.zy.core.ThreadHandler;
import com.zy.core.model.CommandResponse;
import com.zy.core.model.command.StationCommand;
import com.zy.core.network.api.ZyStationConnectApi;
import com.zy.core.network.entity.ZyStationStatusEntity;
import java.util.List;
import com.zy.core.network.fake.ZyStationFakeConnect;
import com.zy.core.network.real.ZyStationRealConnect;
import lombok.extern.slf4j.Slf4j;
 
/**
 * 输送站连接驱动
 */
@Slf4j
public class ZyStationConnectDriver implements ThreadHandler {
 
    private boolean connected = false;
    private DeviceConfig deviceConfig;
    private ZyStationConnectApi zyStationConnectApi;
    private volatile boolean closed = false;
    private Thread selfThread;
 
    public ZyStationConnectDriver(DeviceConfig deviceConfig) {
        this.deviceConfig = deviceConfig;
    }
 
    @Override
    @SuppressWarnings("InfiniteLoopStatement")
    public void run() {
        selfThread = Thread.currentThread();
        while (!closed && !Thread.currentThread().isInterrupted()) {
            try {
                if (!connected) {
                    connect();
                }
                Thread.sleep(1000);
            } catch (InterruptedException ie) {
                Thread.currentThread().interrupt();
                break;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
 
    @Override
    public boolean connect() {
        if (deviceConfig.getFake() == 0) {
            zyStationConnectApi = new ZyStationRealConnect(deviceConfig);
        } else {
            zyStationConnectApi = new ZyStationFakeConnect(deviceConfig);
        }
 
        boolean connect = zyStationConnectApi.connect();
        connected = connect;
        return connect;
    }
 
    @Override
    public void close() {
        closed = true;
        Thread t = selfThread;
        if (t != null) {
            try { t.interrupt(); } catch (Exception ignore) {}
        }
        if (zyStationConnectApi != null) {
            zyStationConnectApi.disconnect();
            zyStationConnectApi = null;
        }
        connected = false;
    }
 
    public void start() {
        Thread t = new Thread(this);
        t.start();
    }
 
    public List<ZyStationStatusEntity> getStatus() {
        if (zyStationConnectApi == null) {
            return null;
        }
        return zyStationConnectApi.getStatus();
    }
 
    public CommandResponse sendCommand(StationCommand command) {
        return zyStationConnectApi.sendCommand(command);
    }
}