562935844@qq.com
2023-08-31 b77dc026ffd21dba8652d28409c51e27d3e5a76c
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
package com.hdl.sdk.connect.protocol;
 
 
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
 
import androidx.annotation.RequiresApi;
 
import com.google.gson.reflect.TypeToken;
import com.hdl.sdk.common.config.TopicConstant;
import com.hdl.sdk.common.event.EventDispatcher;
import com.hdl.sdk.common.exception.HDLLinkException;
import com.hdl.sdk.common.utils.ByteUtils;
import com.hdl.sdk.common.utils.LogUtils;
import com.hdl.sdk.common.utils.SPUtils;
import com.hdl.sdk.common.utils.gson.GsonConvert;
import com.hdl.sdk.connect.HDLLink;
import com.hdl.sdk.connect.bean.LinkResponse;
import com.hdl.sdk.connect.bean.request.AuthenticateRequest;
import com.hdl.sdk.connect.bean.response.DeviceDeleteResponse;
import com.hdl.sdk.connect.bean.response.DeviceInfoResponse;
import com.hdl.sdk.connect.callback.HDLLinkCallBack;
import com.hdl.sdk.connect.config.HDLLinkConfig;
import com.hdl.sdk.connect.socket.HDLAuthSocket;
import com.hdl.sdk.connect.socket.HDLSocket;
import com.hdl.sdk.connect.utils.AesUtil;
import com.hdl.sdk.socket.codec.ByteToMessageDecoder;
 
import java.util.ArrayList;
import java.util.List;
 
import android.util.Base64;
 
import kotlin.ParameterName;
 
/**
 * Created by Tong on 2021/9/22.
 * link协议粘包拆包
 */
public class LinkMessageDecoder extends ByteToMessageDecoder<LinkResponse> {
 
    private final List<Byte> bytes;
 
    private final byte[] head = "Topic:".getBytes();
//    private final byte[] body = "\r\n\r\n".getBytes();
 
    public LinkMessageDecoder() {
        this.bytes = new ArrayList<>();
    }
 
    /// <summary>
    /// 获取内容长度
    /// </summary>
    /// <param name="topMsgs"></param>
    /// <returns></returns>
    int getLenght(String[] topMsgs) {
        for (int i = 0; i < topMsgs.length; i++) {
            String topMsg = topMsgs[i].trim();
            if (topMsg.startsWith("Length:")) {
                return Integer.parseInt(topMsg.replace("Length:", ""));
            }
        }
        //找不到长度
        return -1;
    }
 
    /// <summary>
    /// 获取主题
    /// </summary>
    /// <param name="topMsgs"></param>
    /// <returns></returns>
    private String getTopic(String[] topMsgs) {
        for (int i = 0; i < topMsgs.length; i++) {
            String topMsg = topMsgs[i].trim();
            if (topMsg.startsWith("Topic:")) {
                return topMsg.replace("Topic:", "");
            }
        }
        //找不到主题
        return null;
    }
 
    /**
     * 获取数据的开始位置
     *
     * @param arrayList 接收到的所有数据
     * @return 数据位的开始索引
     */
    int getDataIndex(List<Byte> arrayList) {
        byte r = (byte) '\r';
        byte n = (byte) '\n';
        for (int i = 0; i < arrayList.size(); i++) {
            //找出数据内容前面的两个换行
            if (3 <= i && arrayList.get(i - 3) == r && arrayList.get(i - 2) == n && arrayList.get(i - 1) == r && arrayList.get(i) == n) {
                //剩余的数据
                return i + 1;
            }
        }
        return -1;
    }
 
    void initReceiveData(List<Byte> list) {
 
        int index = 0;
        boolean isMatch = false;
        for (; index < list.size() - head.length; index++) {
            isMatch = true;
            for (int j = 0, k = 0; j < head.length; j++, k++) {
                if (head[j] != list.get(index + k)) {
                    isMatch = false;
                    break;
                }
            }
            if (isMatch) {
                break;
            }
        }
 
        if (0 < index && isMatch) {
            List<Byte> tempList = new ArrayList<Byte>();
            for (int i = index; i < list.size(); i++) {
                tempList.add(list.get(i));
            }
 
            list.clear();
            for (int i = 0; i < tempList.size(); i++) {
                list.add(tempList.get(i));
            }
        }
    }
 
 
    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    protected synchronized LinkResponse decoder(Object msg, String ipaddress) throws Exception {
        if (msg instanceof byte[]) {
            bytes.addAll(ByteUtils.toByteList((byte[]) msg));
            //如果多条命令打包在一条数据中,都需要处理完
            while (true) {
                initReceiveData(bytes);
                byte[] recevieBytes = ByteUtils.toByteArray(bytes);
                String data = new String(recevieBytes);
 
                String[] topMsgs = data.split("\r\n");
 
                String topic = getTopic(topMsgs);
                if (topic == null) {
                    break;
                }
 
                int lenght = getLenght(topMsgs);
 
                if (lenght <= 0) {
                    //头部数据还没有接收完成
                    break;
                }
                //是否已经获取完整所有的数据
                byte[] body = new byte[lenght];
                int index = getDataIndex(bytes);
                if (bytes.size() < index + lenght) {
                    //当前数据还没有接收完成
                    break;
                }
                //复制出body数据
                System.arraycopy(recevieBytes, index, body, 0, body.length);
 
                //保留剩余的数据,以次用
                bytes.clear();
                for (int i = index + lenght; i < recevieBytes.length; i++) {
                    bytes.add(recevieBytes[i]);
                }
                LinkResponse response = new LinkResponse();
                response.setSource_ipAddress(ipaddress);
                response.setTopic(topic);
                if (HDLLinkConfig.getInstance().ifNeedEncrypt(response.getTopic())) {
                    //需要解密
                    byte[] bodyBytes = AesUtil.aesDecrypt(body, HDLLinkConfig.getInstance().getLocalSecret());
                    if (bodyBytes != null) {
                        body = bodyBytes;
                    } else {
                        try {
                            //之前的版本这块是明文的
                            if (!topic.contains("heartbeat_reply")) {
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
                                    LogUtils.e("解密失败,数据内容是:\r\n" + Base64.encodeToString(body, Base64.NO_WRAP));
                                else {
                                    LogUtils.e("解密失败,数据内容是:\r\n" + new String(body, "utf-8"));
                                }
                            }
                        } catch (Exception e) {
                        }
                    }
                }
 
                String bodyString = new String(body, "utf-8");
                response.setData(bodyString);
                LogUtils.i("接收到数据:" + response.getTopic() + "\r\n" + response.getData());
 
                String updateLocalSecret = String.format(TopicConstant.LINK_BROADCAST, HDLLinkConfig.getInstance().getGatewayId());
                String deleteNetwork = "";
                if (HDLLinkConfig.getInstance().getDeviceInfoBean() != null) {
                    deleteNetwork = String.format(TopicConstant.DELETE_NOTIFY, HDLLinkConfig.getInstance().getDeviceInfoBean().getOID());
                }
 
                if (response.getTopic().equals("/user/all/custom/gateway/search")) {
                    HDLAuthSocket.getInstance().UploadGatewayInfo(new HDLLinkCallBack() {
                        @Override
                        public void onSuccess(String msg) {
                            LogUtils.i("UploadGatewayInfo onSucceed");
                        }
 
                        @Override
                        public void onError(HDLLinkException e) {
                            LogUtils.i("UploadGatewayInfo onError");
                        }
                    });
                } else if (response.getTopic().equals(updateLocalSecret) || response.getTopic().equals(TopicConstant.LINK_BROADCAST)) {
                    try {
                        DeviceInfoResponse deviceInfoResponse = GsonConvert.getGson().fromJson(response.getData(), new TypeToken<DeviceInfoResponse>() {
                        }.getType());
 
                        if (!TextUtils.isEmpty(deviceInfoResponse.getObjects().getLocalSecret())) {
                            byte[] baseBytes = Base64.decode(deviceInfoResponse.getObjects().getLocalSecret(), Base64.NO_WRAP);
                            String mackey = "";
                            if (!TextUtils.isEmpty(SPUtils.getString("auth_mackey_key", ""))) {
                                mackey = SPUtils.getString("auth_mackey_key", "");
                                byte[] bodyBytes = AesUtil.aesDecrypt(baseBytes, mackey.substring(mackey.length() - 16));
                                String localSecret = new String(bodyBytes, "utf-8");
                                Log.d("panlili", "更新密钥----->localSecret= " + localSecret);
                                HDLLinkConfig.getInstance().setLocalSecret(localSecret);
                            }
                        }
                    } catch (Exception e) {
                        LogUtils.i("LinkMessageDecoder.java:getLocalSecret----->e= " + e.getMessage());
                    }
                } else if (response.getTopic().equals(deleteNetwork)) {
                    try {
                        DeviceDeleteResponse deviceDeleteResponse = GsonConvert.getGson().fromJson(response.getData(), new TypeToken<DeviceDeleteResponse>() {
                        }.getType());
                        HDLSocket.getInstance().deleteNetwork(deviceDeleteResponse.getObjects().get(0).getOID(), new HDLLinkCallBack() {
                            @Override
                            public void onSuccess(String msg) {
                                LogUtils.i("deleteNetwork onSucceed");
                                if (HDLLink.getInstance().listener != null) {
                                    HDLLink.getInstance().listener.onSuccess(msg);
                                }
                            }
 
                            @Override
                            public void onError(HDLLinkException e) {
                                LogUtils.i("deleteNetwork onError");
                                if (HDLLink.getInstance().listener != null) {
                                    HDLLink.getInstance().listener.onFailure();
                                }
                            }
                        });
                    } catch (Exception e) {
                        LogUtils.i("LinkMessageDecoder.java:deleteNetwork----->e= " + e.getMessage());
                    }
                }
 
                //非正常数据,返回
                if (!((bodyString.startsWith("{") && bodyString.endsWith("}"))
                        || (bodyString.startsWith("[") && bodyString.endsWith("]")))) {
                    continue;
                }
                //解析完成,topic发送一次
                EventDispatcher.getInstance().post(response.getTopic(), response);
            }
            return null;
 
        }
        return null;
    }
}