kaiyu
2020-09-30 37e2672f7c9d59621672444b03d3713580dc1364
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
package com.moral.webSocketServer;
 
import com.alibaba.fastjson.JSON;
import com.moral.common.util.ParameterUtils;
import com.moral.entity.Device;
import com.moral.entity.Sensor;
import com.moral.service.DeviceService;
import com.moral.service.SensorService;
import com.moral.util.RabbitMQUtils;
import com.rabbitmq.client.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
 
import javax.annotation.PostConstruct;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
 
@Slf4j
@ServerEndpoint("/web/testWebSocket/{param}")
@Component
/** 
* @Description: 用于测试的websocket
        * @Param: 
        * @return: 
        * @Author: 下雨听风
        * @Date: 2020/9/30
        */ 
public class BSTestWebsocketServer {
 
    public static DeviceService deviceService;
 
    public static SensorService sensorService;
 
    /**
     * concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
     */
    private static ConcurrentHashMap<String, BSTestWebsocketServer> webSocketMap = new ConcurrentHashMap<>();
    /**
     * 与某个客户端的连接会话,需要通过它来给客户端发送数据
     */
    private Session session;
 
    private String orgId;
 
    private String accountId;
 
    private String regionCode;
 
    private String mac;
 
    private final String exchange = "screens_data";
 
    private static Map<String, Sensor> sensors;
 
 
    @PostConstruct
    public void init() {
        sensors = new HashMap<>();
        List<Sensor> allSensors = sensorService.getAllSensors();
        for (Sensor sensor : allSensors) {
            sensors.put(sensor.getSensorKey(), sensor);
        }
    }
 
    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("param") String param) {
        this.session = session;
        String[] params = param.split("&");
        this.accountId = params[0];
        this.orgId = params[1];
        this.regionCode = params[2];
 
        if (webSocketMap.containsKey(accountId)) {
            webSocketMap.remove(accountId);
            webSocketMap.put(accountId, this);
        } else {
            webSocketMap.put(accountId, this);
        }
 
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("orgId", orgId);
        paramMap.put("regionCode", regionCode);
        ParameterUtils.getRegionType4RegionCode(paramMap);
        List<Device> deviceList = deviceService.queryDevice(paramMap);
 
        try {
            Connection connection = RabbitMQUtils.getConnection();
            final Channel channel = connection.createChannel();
            //生成临时队列
            String queue = channel.queueDeclare().getQueue();
 
            //交换机与队列通过routingKey进行绑定
            String routingKey = "";
            for (Device d : deviceList) {
                routingKey = orgId + "." + d.getMac();
                channel.queueBind(queue, exchange, routingKey);
            }
 
 
            //消费消息,手动确认模式。
            channel.basicQos(1);//每次只消费一条数据
            channel.basicConsume(queue, false, new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    //对从MQ中取出的数据做转换,并且发送风速到客户端                    
                    Map message = (Map) JSON.parse((String) JSON.parse(new String(body)));
                    sendWindInfo(message);
                    
                    //判断是否接收到客户端发送的mac,如果接收到则返回指定mac设备信息
                    if(mac!=null&&(!mac.equals(0)))
                        sendDeviceInfo(message,deviceList);
                    
                    //手动确认
                    channel.basicAck(envelope.getDeliveryTag(), false);
                    
                    //判断socket是否已经断开
                    if (!webSocketMap.containsKey(accountId)) {
                        RabbitMQUtils.closeConnectionChannel(connection, channel);
                    }
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
 
    }
 
    @OnClose
    public void onClose() {
        if (webSocketMap.containsKey(accountId)) {
            webSocketMap.remove(accountId);
        }
    }
 
    //接收到客户端消息操作
    @OnMessage
    public void onMessage(String message, Session session) {
        if (!ObjectUtils.isEmpty(message)) {
            Map<String, Object> map = JSON.parseObject(message);
            this.mac = (String) map.get("mac");
        }
    }
 
    @OnError
    public void onError(Session session, Throwable error) {
        log.error(error.getMessage());
    }
 
    public void sendMessage(String message) throws IOException {
        try {
            if (session.isOpen()) {
                this.session.getBasicRemote().sendText(message);
            }
        } catch (IOException e) {
 
            //log.error(e.getMessage());
        }
    }
 
    /** 
    * @Description: 从客户端连接到socket就一直开始发送风向数据
            * @Param: [param]
            * @return: void
            * @Author: 陈凯裕
            * @Date: 2020/9/30
            */ 
    private void sendWindInfo(Map<String, Object> param) {
        try {
            Map<String, Object> map = new HashMap<>();
            if (param.get("e23") != null && param.get("mac") != null) {
                map.put("风向", param.get("e23"));
                map.put("mac", param.get("mac"));
                sendMessage(JSON.toJSONString(map));
            }
        } catch (IOException e) {
            log.error("发送风向标数据异常");
        }
    }
 
    /** 
    * @Description: 接收前端mac以及accountid,传送前端指定mac号的设备信息
            * @Param: [param]
            * @return: void
            * @Author: 陈凯裕
            * @Date: 2020/9/30
            */ 
    private void sendDeviceInfo(Map<String, Object> param,List<Device> deviceList) {
        String deviceMac = (String) param.get("mac");
        if (mac.equals(deviceMac)) {
            try {
                Map<String, Object> map = new HashMap<>();
                param.forEach((key, value) -> {
                    Sensor sensor = sensors.get(key);
                    if (!ObjectUtils.isEmpty(sensor)) {
                        String unit = ObjectUtils.isEmpty(sensor.getUnit()) ? "" : (String) sensor.getUnit();
                        map.put(sensor.getName(), value + unit);
                    }
                });
                String mac = (String) param.get("mac");
                map.put("mac", mac);
                map.put("flag",1);
                for (Device device : deviceList) {
                    if(mac.equals(device.getMac())){
                        map.put("名称",device.getName());
                        map.put("地址",device.getAddress());
                        break;
                    }
                }
                sendMessage(JSON.toJSONString(map));
            } catch (IOException e) {
                log.error("根据mac发送设备数据异常");
            }
        }
    }
 
 
}