leutu
2024-06-03 3ef35e6cd16bbfa206b26bb3271eac40ad020bcb
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
package com.fastbee.base.session;
 
import com.fastbee.common.core.protocol.Message;
import com.fastbee.common.enums.ServerType;
import com.fastbee.common.exception.ServiceException;
import com.fastbee.common.utils.DateUtils;
import com.fastbee.common.utils.gateway.mq.Topics;
import com.fastbee.base.core.model.Response;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.mqtt.MqttMessageType;
import io.netty.handler.codec.mqtt.MqttVersion;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Mono;
import reactor.core.publisher.MonoSink;
 
import java.net.InetSocketAddress;
import java.util.*;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
 
/**
 * 会话
 *
 * @Author guanshubiao
 * @Date 2022/9/12 20:22
 */
@Data
@Slf4j
public class Session {
 
    private  boolean udp;
    private  Function<Session, Boolean> remover;
    protected Channel channel;
    /**
     * 客户端id
     */
    private String clientId;
    private String productId;
    private SessionManager sessionManager;
    private InetSocketAddress remoteAddress;
    private String remoteAddressStr;
 
    private long creationTime;
    private long lastAccessTime;
    private Map<Object, Object> attributes;
 
    private String sessionId;
    //原子计数器,报文没有消息流水号的,充当流水号
    private AtomicInteger serialNo = new AtomicInteger(0);
    private int keepAlive = 60;
 
 
    /*mqtt版本号*/
    private MqttVersion version;
    /*是否清楚会话*/
    private Boolean cleanSession = false;
    /*mqtt账号*/
    private String username;
    /*是否链接*/
    private Boolean connected = false;
    /*mqtt消息类型*/
    private MqttMessageType mqttMessageType;
    private int keepAliveMax = 120;
    /*主题*/
    private String topicName;
    /*Channel处理类上下文*/
    private ChannelHandlerContext handlerContext;
 
    private List<Topics> topics;
    private Integer topicCount;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date connected_at;
    private String ip;
    /*服务协议类型 MQTT,TCP UDP COAP*/
    private ServerType serverType;
 
    public Session(){
 
    }
 
    public Session(SessionManager sessionManager,
                   Channel channel,
                   InetSocketAddress remoteAddress,
                   Function<Session, Boolean> remover,
                   boolean udp,
                   ServerType serverType) {
        this.channel = channel;
        this.creationTime = DateUtils.getTimestamp();
        this.lastAccessTime = creationTime;
        this.sessionManager = sessionManager;
        this.remoteAddress = remoteAddress;
        this.remoteAddressStr = remoteAddress.toString();
        this.remover = remover;
        this.udp = udp;
        this.serverType = serverType;
        this.ip = remoteAddress.getHostName();
        this.connected = true;
        this.connected_at = DateUtils.getNowDate();
        if (sessionManager != null && sessionManager.getSessionKeys() != null) {
            this.attributes = new EnumMap(sessionManager.getSessionKeys());
        } else {
            this.attributes = new TreeMap<>();
        }
    }
 
    /**
     * 判断设备是否已经注册上线
     */
    public boolean isRegistered() {
        return clientId != null;
    }
 
    /*设备端注册*/
    public void register(Message message) {
        register(message.getClientId(), message);
    }
 
    public void register(String clientId, Message message) {
        //已经注册,不再发送注册包数据
        if (isRegistered()){
            return;
        }
        if (clientId == null) {
            throw new ServiceException("客户端注册clientId不能为空");
        }
        this.clientId = clientId.toUpperCase();
        if (sessionManager != null) {
            sessionManager.add(this);
        }
    }
 
    public Object getAttribute(Object name) {
        return attributes.get(name);
    }
 
    public void setAttribute(Object name, Object value) {
        attributes.put(name, value);
    }
 
    /**
     * 获取最后上线时间
     */
    public long access() {
        return lastAccessTime = DateUtils.getTimestamp();
    }
 
    /**
     * 获取远程端口
     */
    public InetSocketAddress remoteAddress() {
        return remoteAddress;
    }
 
    /**
     * 获取流水号
     */
    public int nextSerialNO() {
        int current;
        int next;
        do {
            current = serialNo.get();
            next = current > 0xffff ? 0 : current;
        } while (!serialNo.compareAndSet(current, next + 1));
        return next;
    }
 
    /**
     * 处理离线方法
     */
    public void invalidate() {
        if (isRegistered() && sessionManager != null) {
            sessionManager.remove(this);
        }
        remover.apply(this);
    }
 
    public boolean isUdp() {
        return udp;
    }
 
    private final Map<String, MonoSink> topicSubscribers = new HashMap<>();
 
    private static final Mono rejected = Mono.error(new RejectedExecutionException("设备端暂无响应"));
 
    /**
     * 异步发送通知类消息
     * 同步发送 mono.block()
     * 订阅回调 mono.doOnSuccess(处理成功).doOnError(处理异常).subscribe(开始订阅)
     */
    public Mono<Void> notify(Message message) {
        return mono(channel.writeAndFlush(Packet.of(this, message)));
    }
 
    public Mono<Void> notify(ByteBuf message) {
        return mono(channel.writeAndFlush(Packet.of(this, message)));
    }
 
    public static Mono<Void> mono(ChannelFuture channelFuture) {
        return Mono.create(sink -> channelFuture.addListener(future -> {
            if (future.isSuccess()) {
                sink.success();
            } else {
                sink.error(future.cause());
            }
        }));
    }
 
    /**
     * 异步发送消息,接收响应
     * 同步接收 mono.block()
     * 订阅回调 mono.doOnSuccess(处理成功).doOnError(处理异常).subscribe(开始订阅)
     */
    public <T> Mono<T> request(Message message, Class<T> responseClass) {
        String key = requestKey(message, responseClass);
        Mono<T> subscribe = this.subscribe(key);
        if (subscribe == null) {
            return rejected;
        }
        ChannelFuture channelFuture = channel.writeAndFlush(Packet.of(this, message));
        return Mono.create(sink -> channelFuture.addListener(future -> {
            if (future.isSuccess()) {
                sink.success(future);
            } else {
                sink.error(future.cause());
            }
        })).then(subscribe).doFinally(signal -> unsubscribe(key));
    }
 
    /**
     * 消息响应
     */
    public boolean response(Message message){
        MonoSink monoSink = topicSubscribers.get(responseKey(message));
        if (monoSink != null){
            monoSink.success(message);
            return true;
        }
        return false;
    }
 
    /**
     * 订阅
     */
    private Mono subscribe(String key) {
        synchronized (topicSubscribers) {
            if (!topicSubscribers.containsKey(key)) {
                return Mono.create(sink -> topicSubscribers.put(key, sink));
            }
        }
        return null;
    }
 
    /**
     * 取消订阅
     */
    private void unsubscribe(String key) {
        topicSubscribers.remove(key);
    }
 
    /*生成流水号*/
    private static String requestKey(Message request, Class responseClass) {
        String className = responseClass.getName();
        if (Response.class.isAssignableFrom(responseClass)) {
            String serNo = request.getSerNo();
            return new StringBuffer(34).append(className).append('.').append(serNo).toString();
        }
        return className;
    }
 
    /*返回流水号*/
    private static String responseKey(Object response) {
        String className = response.getClass().getName();
        if (response instanceof Response) {
            int serialNo = ((Response) response).getResponseSerialNo();
            return new StringBuffer(34).append(className).append('.').append(serialNo).toString();
        }
        return className;
    }
 
}