a
554325746@qq.com
2019-12-25 603cb36a5123e46656b06a5deb8d7ac7ff81307f
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
package com.basic.security.utils;
 
import android.os.SystemClock;
import android.text.TextUtils;
 
import com.basic.security.base.BaseApplication;
import com.basic.security.manager.PersonManager;
import com.basic.security.manager.RemoteInDoorManager;
import com.basic.security.manager.RemoteOutdoorManager;
import com.basic.security.model.ModelAdapter;
import com.basic.security.model.Person;
import com.basic.security.model.PersonSocket;
import com.basic.security.utils.socket.BitmapListener;
import com.basic.security.utils.socket.YuvToJpgFrameBufferManager;
import com.google.gson.JsonElement;
import com.google.gson.JsonNull;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
 
import org.apache.commons.io.IOUtils;
 
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
public class SocketUtil {
    public ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    public Socket socket = null;
    public byte[] buffer = new byte[1];
    public DataInputStream dataInputStream;
    public DataOutputStream dataOutStream;
    public ObjectOutputStream objectOutputStream;
    public ObjectInputStream objectInputStream;
    public YuvToJpgFrameBufferManager mBufferManager;
    public byte[] imageBuff;
    public String remoteIp = "";
    public BitmapListener cameraDataListener;
 
    public SocketUtil() {
    }
 
    public static List<String> getRpcCallIp() {
        List<String> ipList = new ArrayList<>();
        if (Constants.isIndoor) {
            ipList = RemoteOutdoorManager.getOutdoorDeviceIp();
        }
        if (Constants.isOutdoor) {
            ipList = RemoteInDoorManager.getIndoorDeviceIp();
        }
        List<String> finalList = new ArrayList<>();
        for (String ip : ipList) {
            if (!TextUtils.isEmpty(ip)) {
                finalList.add(ip);
            }
        }
//        LogUtil.println("getRpcCallIp " + finalList);
        return finalList;
    }
 
    public static void rpcCallAsyncCommonSave(ModelAdapter modelAdapter) {
        rpcCallAsync(modelAdapter, PersonSocket.requestTypeAsyncSave);
    }
 
    public static void rpcCallAsyncCommonDelete(ModelAdapter modelAdapter) {
        rpcCallAsync(modelAdapter, PersonSocket.requestTypeAsyncDelete);
    }
 
    public static void rpcCallAsyncCommonSignal(String signalValue) {
        ModelAdapter modelAdapter = new ModelAdapter();
        modelAdapter.setString(PersonSocket.signalValue, signalValue);
        rpcCallAsync(modelAdapter, PersonSocket.signal);
    }
 
    public static void rpcCallAsync(ModelAdapter modelAdapter, String requestType) {
        if (!Constants.isUseSocketRpc) {
            return;
        }
        BaseApplication.getApplication().executorService.execute(() -> {
            List<String> remoteIpList = getRpcCallIp();
            for (String remoteIp : remoteIpList) {
                try {
                    SocketUtil socketUtil = new SocketUtil();
                    try {
                        byte[] modelMapByteArray = new byte[]{};
                        modelMapByteArray = ObjectUtil.toByteArray(modelAdapter.model);
                        Map<String, String> requestMap = new HashMap<>();
                        requestMap.put(PersonSocket.modelMapByteArrayLength, modelMapByteArray.length + "");
                        requestMap.put(PersonSocket.requestType, requestType);
                        socketUtil.openSocket(remoteIp, Constants.personServerPort);
                        socketUtil.writeMap(requestMap);
                        if (modelMapByteArray.length > 0) {
                            socketUtil.writeByteArray(modelMapByteArray);
                        }
                        Map<String, String> responseMap = socketUtil.readJsonAsMap();
//                        System1.out.println("SocketUtil.rpcCallAsync " + responseMap + " " + requestType + " remoteIp=" + remoteIp + " " + Constants.personServerPort);
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        socketUtil.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
 
    public static void rpcCallSaveHintSignUp(ModelAdapter hintSignUpMassage) {
        rpcCallAsyncCommonSave(hintSignUpMassage);
    }
 
    public static void rpcCallSaveHintDoorAccess(ModelAdapter hintDoorAccess) {
        rpcCallAsyncCommonSave(hintDoorAccess);
    }
 
    public static void rpcCallSaveHintRecognize(ModelAdapter hintRecognize) {
        rpcCallAsyncCommonSave(hintRecognize);
    }
 
    public static void rpcCallSaveTimeRule(ModelAdapter timeRule) {
        rpcCallAsyncCommonSave(timeRule);
    }
 
    public static void rpcCallSaveVisit(ModelAdapter visit) {
        rpcCallAsyncCommonSave(visit);
    }
 
    public static void rpcCallInitTreeNodeList() {
        rpcCallAsyncCommonSignal(PersonSocket.signalInitTreeNodeList);
    }
 
    public static void rpcCallDeleteOrg(ModelAdapter org) {
        rpcCallAsyncCommonDelete(org);
    }
 
    public static void rpcCallSaveOrg(ModelAdapter org) {
        rpcCallAsyncCommonSave(org);
    }
 
    public static void rpcCallSendIdCard(IdCard idcard) {
        ModelAdapter modelAdapter = new ModelAdapter();
        modelAdapter.model = idcard.toMap();
        rpcCallAsyncCommonSave(modelAdapter);
    }
 
    public static void rpcCallSavePersonIdentity(ModelAdapter personIdentity) {
        rpcCallAsyncCommonSave(personIdentity);
    }
 
    public static void rpcCallSavePerson(ModelAdapter person) {
        byte[] personArray = new byte[]{};
        byte[] camera_image_path = person.getBlob(Person.camera_image_path);
        if (camera_image_path != null && camera_image_path.length > 0) {
            person.model.put(PersonSocket.camera_image_path_byte_array, camera_image_path);
        }
        rpcCallAsyncCommonSave(person);
    }
 
    public static void rpcCallDeletePersonIdentity(ModelAdapter personIdentity) {
        rpcCallAsyncCommonDelete(personIdentity);
    }
 
    public static void rpcCallDeletePerson(ModelAdapter person) {
        rpcCallAsyncCommonDelete(person);
    }
 
    public static ModelAdapter rpcCallFindPersonById(String personId) {
        List<String> remoteIpList = getRpcCallIp();
        for (String remoteIp : remoteIpList) {
            SocketUtil socketUtil = new SocketUtil();
            try {
                Map<String, String> requestMap = new HashMap<>();
                requestMap.put(Person.id, personId);
                requestMap.put(PersonSocket.requestType, PersonSocket.findPersonById);
                socketUtil.openSocket(remoteIp, Constants.personServerPort);
                socketUtil.writeMap(requestMap);
                Map<String, String> responseMap = socketUtil.readJsonAsMap();
                int modelMapByteArrayLength = Integer.parseInt(responseMap.get(PersonSocket.modelMapByteArrayLength));
                if (modelMapByteArrayLength > 0) {
                    byte[] personByteArray = new byte[modelMapByteArrayLength];
                    socketUtil.readFullByteArray(personByteArray);
                    Map<String, Object> personModel = (Map<String, Object>) ObjectUtil.toObject(personByteArray);//SerializationUtils.deserialize(personByteArray);
                    if (personModel != null) {
//                    System1.out.println("SocketUtil.rpcCallFindPersonById " + personModel);
                        ModelAdapter person = new ModelAdapter();
                        person.model = personModel;
                        byte[] camera_image_path_byte_array = (byte[]) person.model.get(PersonSocket.camera_image_path_byte_array);
                        if (camera_image_path_byte_array != null && camera_image_path_byte_array.length > 0) {
                            person.setBlob(Person.camera_image_path, camera_image_path_byte_array);
                        }
                        PersonManager.savePerson(person);
                        return person;
                    }
                } else {
//                System1.out.println("SocketUtil.rpcCallFindPersonById");
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                socketUtil.close();
            }
        }
        return null;
    }
 
    public static Map<String, String> rpcCall(String ip, int port, Map<String, String> requestMap) {
        SocketUtil socketUtil = new SocketUtil();
        try {
            socketUtil.openSocket(ip, port);
            socketUtil.writeMap(requestMap);
            return socketUtil.readJsonAsMap();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            socketUtil.close();
        }
        return null;
    }
 
    public static Map<String, String> rpcCallDownload(String ip, int port, String camera_image_path) {
        SocketUtil socketUtil = new SocketUtil();
        try {
            socketUtil.openSocket(ip, port);
            Map<String, String> requestMap = new HashMap<>();
            requestMap.put(Person.camera_image_path, camera_image_path);
            socketUtil.writeMap(requestMap);
            Map<String, Object> responseMap = socketUtil.readMap();
            if (Constants.TRUE.equals(responseMap.get(Constants.SUCCESS))) {
                int length = Integer.parseInt(responseMap.get(Constants.LENGTH) + "");
                byte[] fileBuffer = new byte[length];
                socketUtil.readFullByteArray(fileBuffer);
                FileWriter fileWriter = new FileWriter(camera_image_path);
                IOUtils.write(fileBuffer, fileWriter);
                fileWriter.flush();
                fileWriter.close();
                System1.out.println("SocketUtil.rpcCallDownload camera_image_path=" + camera_image_path);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            socketUtil.close();
        }
        return null;
    }
 
    public static void rpcCallAsyncDeleteBusinessRule(ModelAdapter business) {
        rpcCallAsyncCommonDelete(business);
    }
 
    public static void rpcCallSaveBusinessRule(ModelAdapter business) {
        rpcCallAsyncCommonSave(business);
    }
 
    public static void rpcCallDeleteTimeRule(ModelAdapter timeRule) {
        rpcCallAsyncCommonDelete(timeRule);
    }
 
    public Map<String, String> readJsonAsMap() throws Exception {
        String json;
        int len;
        while ((len = dataInputStream.read(buffer)) != -1) {
            for (int i = 0; i < len; i++) {
                if (buffer[i] == '\0') {
                    Map<String, String> messageMap = new HashMap<>();
                    try {
                        byte[] jsonByteArray = byteArrayOutputStream.toByteArray();
                        byteArrayOutputStream.reset();
                        json = new String(jsonByteArray, 0, jsonByteArray.length);
                        json = json.substring(0, json.lastIndexOf("}") + 1);
                        if (json.length() > 3) {
                            JsonParser parser = new JsonParser();
                            boolean isJSON = true;
                            JsonElement element = null;
                            try {
                                element = parser.parse(json);
                            } catch (JsonParseException e) {
                                System1.out.println("exception: " + e);
                                isJSON = false;
                            }
                            if (isJSON && element != null) {
                                JsonObject obj = element.getAsJsonObject();
                                for (Map.Entry<String, JsonElement> entry : obj.entrySet()) {
                                    if (!(entry.getValue() instanceof JsonNull)) {
                                        messageMap.put(entry.getKey(), entry.getValue().getAsString());
                                    }
                                }
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return messageMap;
                } else {
                    byteArrayOutputStream.write(buffer[i]);
                }
            }
        }
        throw new RuntimeException("inputStream.read(buffer) == -1");
    }
 
    public void close() {
        try {
            if (socket != null) {
                socket.close();
                socket = null;
            }
            if (byteArrayOutputStream != null) {
                byteArrayOutputStream.close();
                byteArrayOutputStream = null;
            }
            if (mBufferManager != null) {
                mBufferManager.close();
                mBufferManager = null;
            }
        } catch (IOException e) {
        }
    }
 
    public void setSocket(Socket socket) throws Exception {
        this.socket = socket;
        this.remoteIp = (((InetSocketAddress) socket.getRemoteSocketAddress()).getAddress()).toString().replace("/", "");
        BufferedInputStream inputStream = new BufferedInputStream(socket.getInputStream());
        BufferedOutputStream outputStream = new BufferedOutputStream(socket.getOutputStream());
        dataInputStream = new DataInputStream(socket.getInputStream());
        dataOutStream = new DataOutputStream(outputStream);
        if (byteArrayOutputStream == null) {
            byteArrayOutputStream = new ByteArrayOutputStream();
        }
        byteArrayOutputStream.reset();
    }
 
    public void openSocket(String ip, int port) throws Exception {
        close();
        SystemClock.sleep(Constants.reconnectInMilliSeconds);
        socket = new Socket();
        socket.connect(new InetSocketAddress(ip, port), 10000);
        this.setSocket(socket);
    }
 
    public void writeMessage(String key, String value) throws Exception {
        JsonObject jsonObj = new JsonObject();
        jsonObj.addProperty(key, value);
        dataOutStream.write(jsonObj.toString().getBytes());
        dataOutStream.write('\0');
        dataOutStream.flush();
    }
 
    public void writeMessage(Map<String, String> keyValues) throws Exception {
        JsonObject jsonObj = new JsonObject();
        for (Map.Entry<String, String> entry : keyValues.entrySet()) {
            jsonObj.addProperty(entry.getKey(), entry.getValue());
        }
        dataOutStream.write(jsonObj.toString().getBytes());
        dataOutStream.write('\0');
        dataOutStream.flush();
    }
 
    public void writeByteArray(byte[] byteArray) throws Exception {
        if (byteArray != null) {
            dataOutStream.write(byteArray);
            dataOutStream.flush();
        }
    }
 
    public void readFullByteArray(byte[] imageBuff) throws Exception {
        dataInputStream.readFully(imageBuff, 0, imageBuff.length);
    }
 
    public void readFullByteArray(byte[] imageBuff, int length) throws Exception {
        dataInputStream.readFully(imageBuff, 0, length);
    }
 
    public void readFrameInfo() throws Exception {
        Map<String, String> messageMap = this.readJsonAsMap();
        int length = Integer.parseInt(messageMap.get("length"));
        int width = Integer.parseInt(messageMap.get("width"));
        int height = Integer.parseInt(messageMap.get("height"));
        imageBuff = new byte[length];
        mBufferManager = new YuvToJpgFrameBufferManager(length, width, height);
    }
 
    public boolean readBitmapHeader(Map<String, String> frameInfo) {
        boolean success = frameInfo.get(Constants.SUCCESS).equals(Constants.TRUE);
        if (success) {
            int length = Integer.parseInt(frameInfo.get("length"));
            int width = Integer.parseInt(frameInfo.get("width"));
            int height = Integer.parseInt(frameInfo.get("height"));
            imageBuff = new byte[length];
            mBufferManager = new YuvToJpgFrameBufferManager(length, width, height);
        }
        return success;
    }
 
    public boolean readBitmapHeader() throws Exception {
        return readBitmapHeader((Map<String, String>) this.readObject());
    }
 
    public void setBitmapListener(BitmapListener cameraDataListener) {
        mBufferManager.setOnDataListener(cameraDataListener);
        this.cameraDataListener = cameraDataListener;
    }
 
    public Object readObject() throws Exception {
        return readJsonAsMap();
    }
 
    public boolean remoteIpAllowed() {
        return true;
    }
 
    public boolean remoteIpAllowed(Map<String, String> map) {
        if (remoteIpAllowed()) {
            map.put(Constants.SUCCESS, Constants.TRUE);
        } else {
            map.put(Constants.SUCCESS, Constants.FALSE);
        }
        return true;
    }
 
    public boolean writeBitmapHeader() throws Exception {
        boolean success;
        Map<String, String> map = new HashMap<>();
        if (remoteIpAllowed()) {
            map.put(Constants.SUCCESS, Constants.TRUE);
            map.put("type", "data");
            map.put("length", "460800");
            map.put("width", "640");
            map.put("height", "480");
            map.put("rotation", "270");
            success = true;
        } else {
            map.put(Constants.SUCCESS, Constants.FALSE);
            success = false;
        }
        writeMessage(map);
        return success;
    }
 
    public void writeMap(Map<String, String> map) throws Exception {
        writeMessage(map);
    }
 
    public Map<String, Object> readMap() throws Exception {
        return (Map<String, Object>) readObject();
    }
 
    public void writeResponseSuccess() throws Exception {
        Map<String, String> responseMap = new HashMap<>();
        responseMap.put(Constants.SUCCESS, Constants.TRUE);
        writeMap(responseMap);
    }
 
    public ModelAdapter readModelAdapterMap(Map<String, String> requestMap) throws Exception {
        int modelMapByteArrayLength = Integer.parseInt(requestMap.get(PersonSocket.modelMapByteArrayLength));
        if (modelMapByteArrayLength > 0) {
            byte[] personByteArray = new byte[modelMapByteArrayLength];
            readFullByteArray(personByteArray);
            Map<String, Object> modelMap = (Map<String, Object>) ObjectUtil.toObject(personByteArray);
            if (modelMap != null) {
                ModelAdapter modelAdapter = new ModelAdapter();
                modelAdapter.model = modelMap;
                return modelAdapter;
            }
        }
        return null;
    }
}