黄学彪
2020-12-17 9f326f4000847e6167d8166fa2f6a66f53cb3734
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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
using System;
using System.Collections.Generic;
using ZigBee.Common;
using Shared;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using Newtonsoft.Json.Linq;
using MQTTnet;
using Shared.Common;
using Shared.Phone.UserView;
using MQTTnet.Client;
using System.Threading.Tasks;
 
namespace ZigBee.Device
{
    /// <summary>ƒ
    /// ZigBee网关对象
    /// </summary>
    [System.Serializable]
    public class ZbGateway : ZbGatewayData
    {
        #region 一堆变量
        /// <summary>
        /// 主网关
        /// </summary>
        [Newtonsoft.Json.JsonIgnore]
        public static ZbGateway MainGateWay
        {
            get
            {
                ZbGateway mainWay = null;
                for (int i = 0; i < GateWayList.Count; i++)
                {
                    if (GateWayList[i].HomeId == Config.Instance.HomeId)
                    {
                        //2020.07.16变更:别管那么多,如果住宅ID一样,先确定就是它了(不然有时候经常返回null,有可能是刷新不到)
                        mainWay = GateWayList[i];
                        if (mainWay.IsMainGateWay == true)
                        {
                            //然后如果它确实是主网关,直接break
                            break;
                        }
                    }
                }
                return mainWay;
            }
        }
 
        /// <summary>
        /// 是否使用远程连接模式
        /// </summary>
        [Newtonsoft.Json.JsonIgnore]
        public static bool IsRemote;
 
        /// <summary>
        /// 网关保存路径
        /// </summary>
        /// <value>The file path.</value>
        [Newtonsoft.Json.JsonIgnore]
        public string FilePath
        {
            get
            {
                var fileName = "Gateway_" + DeviceType.ZbGateway.ToString() + "_" + this.GwId;
                return fileName;
            }
        }
 
        /// <summary>
        /// 等待从网关接收数据的时间
        /// </summary>
        /// <value>The wait receive data time.</value>
        [Newtonsoft.Json.JsonIgnore]
        public int WaitReceiveDataTime
        {
            get
            {
                if (Device.ZbGateway.RemoteMqttClient != null && Device.ZbGateway.RemoteMqttClient.IsConnected)
                {
                    return 10000;
                }
                else
                {
                    return 3000;
                }
            }
        }
 
        /// <summary>
        /// 局域网加密密码
        /// </summary>
        private string password;
        /// <summary>
        /// 局域网加密密钥
        /// </summary>
        [Newtonsoft.Json.JsonIgnore]
        public string Password
        {
            get
            {
                if (password == null)
                {
                    password = Guid.NewGuid().ToString().Substring(0, 16);
                }
                return password;
            }
        }
 
        /// <summary>
        /// 网关远程连接的一个标识ID,获取到了就不再改变
        /// </summary>
        [Newtonsoft.Json.JsonIgnore]
        private static string RemoteClientId = new Random().Next(10, 99).ToString();
 
        /// <summary>
        /// 网关是否加密
        /// </summary>
        [Newtonsoft.Json.JsonIgnore]
        public bool IsEncry;
        /// <summary>
        /// 网关当前公钥
        /// </summary>
        [Newtonsoft.Json.JsonIgnore]
        public string PubKey;
        /// <summary>
        /// 所有的网关列表
        /// </summary>
        [Newtonsoft.Json.JsonIgnore]
        public static List<ZbGateway> GateWayList = new List<ZbGateway>();
 
        /// <summary>
        /// 网关推送数据
        /// <para>第一个参数:如果为 DeviceInComingRespon:设备新上报</para>
        /// <para>第一个参数:如果为 DeviceStatusReport:设备上报</para>
        /// <para>第一个参数:如果为 IASInfoReport:IAS安防信息上报</para>
        /// <para>第一个参数:如果为 DeviceStatusReport:设备上报</para>
        /// <para>第一个参数:如果为 EnOrWithdrawSucceedReport:通过外部方式布防撤防成功时报告</para>
        /// <para>第一个参数:如果为 DownloadFileProgress:下载进度</para>
        /// <para>第一个参数:如果为 CordinatorUpgradePercent:协调器升级百分比</para>
        /// <para>第一个参数:如果为 DeviceUpgradePercent:节点设备升级百分比</para>
        /// <para>第一个参数:如果为 VirtualDriveUpgrade:虚拟设备升级进度</para>
        /// <para>第一个参数:如果为 ZoneTriggerReport:防区被触发时报告</para>
        /// <para>第一个参数:如果为 LogicExecuteReport:逻辑被调用反馈</para>
        /// <para>第一个参数:如果为 TimingWillArrive:时间点条件推迟执行</para>
        /// <para>第一个参数: 如果为 ModeTriggerReport:模式安防动作被最终激活时发送报警信息</para>
        /// <para>第一个参数:如果为 EnOrWithdrawSucceedReport:通过外部方式布防撤防成功时报告息</para>
        /// <para>第一个参数:如果为 PushTargetInfoReport:胁迫密码撤防时短信推送</para>
        /// <para>第一个参数:如果为 DDevice/IsGetEpointInfo:有新设备加入zigbee网络反馈</para>设备请求APP获取升级数据
        /// <para>第一个参数:如果为 Device/DeviceJoinZbNet:获取新设备所有端点信息是否成功反馈</para>
        /// <para>第一个参数:如果为 DeviceRequestAcUpdateData: 设备请求空调发升级数据</para>
        /// </summary>
        [Newtonsoft.Json.JsonIgnore]
        public Action<string, object> ReportAction;
 
        /// <summary>
        /// 网关文件流内容通知
        /// </summary>
        [Newtonsoft.Json.JsonIgnore]
        public Action<string, byte[]> FileContentAction;
 
        /// <summary>
        /// 网关回复数据内容通知
        /// </summary>
        [Newtonsoft.Json.JsonIgnore]
        public Action<string, string> GwResDataAction;
 
        /// <summary>
        /// 与网关通讯时发送和接收数据通知
        /// </summary>
        [Newtonsoft.Json.JsonIgnore]
        public Action<string, string> Actions;
 
        #endregion
 
        #region 网关API
        #region 网关信息
        /// <summary>
        ///获取网关版本信息
        /// <para> gateway:当前网关</para>
        /// </summary>
        public async System.Threading.Tasks.Task<GetGwVersionAllData> GetZbGwVersionInfoAsync()
        {
            return await System.Threading.Tasks.Task.Run(async () =>
            {
                GetGwVersionAllData d = null;
                Action<string, string> action = (topic, message) =>
                {
                    var gatewayID = topic.Split('/')[0];
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
 
                    if (topic == gatewayID + "/" + "Error_Respon")
                    {
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString());
 
                        if (temp == null)
                        {
                            d = new GetGwVersionAllData { errorMessageBase = "网关错误回复,且数据是空" };
                        }
                        else
                        {
                            d = new GetGwVersionAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) };
                        }
                    }
 
                    if (topic == gatewayID + "/" + "GetZbGwVersionRespon")
                    {
                        var getGwVersion = Newtonsoft.Json.JsonConvert.DeserializeObject<GetGwVersionData>(jobject["Data"].ToString());
 
                        if (getGwVersion == null)
                        {
                            d = new GetGwVersionAllData { errorMessageBase = "网关错误回复,且数据是空" };
                        }
                        else
                        {
                            d = new GetGwVersionAllData { getGwVersion = getGwVersion };
                            //Save();
                            DebugPrintLog($"UI收到通知后的主题_{topic}");
                        }
                    }
                };
                Actions += action;
                DebugPrintLog("GetGwVersionData_Actions 启动" + "_" + System.DateTime.Now.ToString());
                try
                {
                    var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 92 } };
                    Send("GetZbGwVersion", jObject.ToString());
                }
                catch { }
 
                var dateTime = DateTime.Now;
                while ((DateTime.Now - dateTime).TotalMilliseconds < WaitReceiveDataTime)
                {
                    await System.Threading.Tasks.Task.Delay(10);
                    if (d != null)
                    {
                        break;
                    }
                }
                if ((DateTime.Now - dateTime).TotalMilliseconds > WaitReceiveDataTime)
                {
                    d = new GetGwVersionAllData { errorMessageBase = " 回复超时,请重新操作" };
                }
                Actions -= action;
                DebugPrintLog("GetGwVersionData_Actions 退出" + System.DateTime.Now.ToString());
 
                return d;
            });
        }
        #endregion
 
        #region 获取网关信息
        /// <summary>
        /// 获取网关信息
        /// <para> gateway:当前网关</para>
        /// </summary>
        public async System.Threading.Tasks.Task<GetGwAllData> GetZbGwInfoAsync()
        {
            return await System.Threading.Tasks.Task.Run(async () =>
            {
                GetGwAllData data = null;
                Action<string, string> action = (topic, message) =>
                {
                    var gatewayID = topic.Split('/')[0];
                    if (topic == gatewayID + "/" + "GetZbGwInfo_Respon")
                    {
                        var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
                        var getGwInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<GetGwData>(jobject["Data"].ToString());
 
                        if (getGwInfo == null)
                        {
                            data = new GetGwAllData { errorMessageBase = "网关返回的数据为空" };
                        }
                        else
                        {
                            data = new GetGwAllData { getGwData = getGwInfo };
                            DebugPrintLog($"UI收到通知后的主题_{topic}");
                        }
                    }
                };
                Actions += action;
 
                DebugPrintLog("GetGwData_Actions 启动" + "_" + System.DateTime.Now.ToString());
                var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 95 } };
                Send("GetZbGwInfo", jObject.ToString());
 
                var dateTime = DateTime.Now;
                while ((DateTime.Now - dateTime).TotalMilliseconds < WaitReceiveDataTime)
                {
                    await System.Threading.Tasks.Task.Delay(10);
                    if (data != null)
                    {
                        break;
                    }
                }
 
                Actions -= action;
                DebugPrintLog("GetGwData_Actions 退出" + System.DateTime.Now.ToString());
 
                return data;
            });
        }
        #endregion
 
        #region 读取协调器MAC地址.
        ///<summary >
        /// 读取协调器MAC地址/端点默认是08
        /// </summary>
        public async System.Threading.Tasks.Task<GetMacResponData> ReadMacAsync()
        {
            return await System.Threading.Tasks.Task.Run(async () =>
            {
                GetMacResponData d = null;
                Action<string, string> action = (topic, message) =>
                {
                    var gatewayID = topic.Split('/')[0];
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
 
                    if (topic == gatewayID + "/" + "Error_Respon")
                    {
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString());
 
                        if (temp == null)
                        {
                            d = new GetMacResponData { errorMessageBase = "网关错误回复,且数据是空" };
                        }
                        else
                        {
                            d = new GetMacResponData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) };
                        }
                    }
 
                    if (topic == gatewayID + "/" + "ZbGw/GetMac_Respon")
                    {
                        var tempData = Newtonsoft.Json.JsonConvert.DeserializeObject<MacAddrData>(jobject["Data"].ToString());
 
                        if (tempData == null)
                        {
                            d = new GetMacResponData { errorMessageBase = "网关返回的数据为空" };
                        }
                        else
                        {
                            d = new GetMacResponData { macAddrData = tempData };
                            DebugPrintLog($"UI收到通知后的主题_{ topic}");
                        }
                    }
                };
 
                Actions += action;
                var jObject = new JObject { { "Cluster_ID", 64512 }, { "Command", 13 } };
                Send(("ZbGw/GetMac"), jObject.ToString());
 
                var dateTime = DateTime.Now;
                while ((DateTime.Now - dateTime).TotalMilliseconds < WaitReceiveDataTime)
                {
                    await System.Threading.Tasks.Task.Delay(10);
                    if (d != null)
                    {
                        break;
                    }
                }
                if ((DateTime.Now - dateTime).TotalMilliseconds > WaitReceiveDataTime)
                {
                    d = new GetMacResponData { errorMessageBase = " 回复超时,请重新操作" };
                }
                Actions -= action;
                return d;
            });
        }
        #endregion
 
        #region 修改网关名称
        /// <summary>
        /// 修改网关名称
        ///<para>gwName:网关名称</para>
        /// </summary>
        public async System.Threading.Tasks.Task<GwReNameAllData> GwReNameAsync(string gwName)
        {
            return await System.Threading.Tasks.Task.Run(async () =>
            {
                GwReNameAllData d = null;
                Action<string, string> action = (topic, message) =>
                {
                    var gatewayID = topic.Split('/')[0];
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
 
                    if (topic == gatewayID + "/" + "Error_Respon")
                    {
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString());
 
                        if (temp == null)
                        {
                            d = new GwReNameAllData { errorMessageBase = "网关错误回复,且数据是空" };
                        }
                        else
                        {
                            d = new GwReNameAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) };
                        }
                    }
 
                    if (topic == gatewayID + "/" + "GwReName_Respon")
                    {
                        var gwRename = Newtonsoft.Json.JsonConvert.DeserializeObject<ZbGateway.GwReNameData>(jobject["Data"].ToString());
 
                        if (gwRename == null)
                        {
                            d = new GwReNameAllData { errorMessageBase = "网关返回的数据为空" };
                        }
                        else
                        {
                            d = new GwReNameAllData { gwReNameData = gwRename };
                            DebugPrintLog($"UI收到通知后的主题_{ topic}");
                        }
                    }
                };
                Actions += action;
                DebugPrintLog("GwReName_Actions 启动" + System.DateTime.Now.ToString());
                try
                {
                    var bytes = new byte[32];
                    var reamarkGwBytes = System.Text.Encoding.UTF8.GetBytes(gwName);
                    System.Array.Copy(reamarkGwBytes, 0, bytes, 0, 32 < reamarkGwBytes.Length ? 32 : reamarkGwBytes.Length);
                    gwName = System.Text.Encoding.UTF8.GetString(bytes);
 
                    var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 91 } };
                    var data = new JObject { { "GwName", gwName } };
                    jObject.Add("Data", data);
                    Send("GwReName", jObject.ToString());
                }
                catch { }
 
                var dateTime = DateTime.Now;
                while ((DateTime.Now - dateTime).TotalMilliseconds < WaitReceiveDataTime)
                {
                    await System.Threading.Tasks.Task.Delay(10);
                    if (d != null)
                    {
                        break;
                    }
                }
                if ((DateTime.Now - dateTime).TotalMilliseconds > WaitReceiveDataTime)
                {
                    d = new GwReNameAllData { errorMessageBase = " 回复超时,请重新操作" };
                }
                Actions -= action;
                DebugPrintLog("GwReName_Actions 退出" + System.DateTime.Now.ToString());
 
                return d;
            });
        }
        #endregion
 
        #region 设定网关住宅id
        /// <summary>
        /// 设定网关住宅id
        /// <para>homeId:住宅id</para>
        /// </summary>
        public async System.Threading.Tasks.Task<GwSetHomeIdAllData> GwSetHomeIdAsync(string homeId)
        {
            return await System.Threading.Tasks.Task.Run(async () =>
            {
                GwSetHomeIdAllData d = null;
                Action<string, string> action = (topic, message) =>
                {
                    var gatewayID = topic.Split('/')[0];
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
 
                    if (topic == gatewayID + "/" + "Error_Respon")
                    {
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString());
 
                        if (temp == null)
                        {
                            d = new GwSetHomeIdAllData { errorMessageBase = "网关错误回复,且数据是空" };
                        }
                        else
                        {
                            d = new GwSetHomeIdAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) };
                        }
                    }
 
                    if (topic == gatewayID + "/" + "GwSetHomeId_Respon")
                    {
                        var gwSetHomeId = Newtonsoft.Json.JsonConvert.DeserializeObject<ZbGateway.GwSetHomeIdData>(jobject["Data"].ToString());
                        if (gwSetHomeId == null)
                        {
                            d = new GwSetHomeIdAllData { errorMessageBase = "网关返回的数据为空" };
                        }
                        else
                        {
                            d = new GwSetHomeIdAllData { gwSetHomeIdData = gwSetHomeId };
                            DebugPrintLog($"UI收到通知后的主题_{ topic}");
                        }
                    }
                };
                Actions += action;
                DebugPrintLog("GwReName_Actions 启动" + System.DateTime.Now.ToString());
                try
                {
                    //账号ID
                    string accountId = string.Empty;
                    if (homeId != string.Empty)
                    {
                        accountId = Config.Instance.Guid;
                    }
                    var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 82 } };
                    var data = new JObject { { "HomeId", homeId }, { "AccountId", accountId } };
                    jObject.Add("Data", data);
                    //住宅ID的设置,固定使用局域网,不存在远程的说法
                    SendLocation("GwSetHomeId", System.Text.Encoding.UTF8.GetBytes(jObject.ToString()));
                }
                catch { }
 
                var dateTime = DateTime.Now;
                while ((DateTime.Now - dateTime).TotalMilliseconds < WaitReceiveDataTime)
                {
                    await System.Threading.Tasks.Task.Delay(10);
                    if (d != null)
                    {
                        break;
                    }
                }
 
                if ((DateTime.Now - dateTime).TotalMilliseconds > WaitReceiveDataTime)
                {
                    d = new GwSetHomeIdAllData { errorMessageBase = " 回复超时,请重新操作" };
                }
 
                Actions -= action;
                DebugPrintLog("GwReName_Actions 退出" + System.DateTime.Now.ToString());
 
                return d;
            });
        }
        #endregion
 
        #region 允许设备入网
        ///<summary >
        /// 搜索新入网的设备(允许设备入网)
        /// <para>Time:0-255,0:关闭搜索,255:一直开启</para>
        /// </summary>
        public async void AddNewDeviceToGateway(int time = 3)
        {
            await System.Threading.Tasks.Task.Run(async () =>
            {
                Action<string, string> action1 = (topic, message) => { };
                Actions += action1;
                var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 94 } };
                var data = new JObject { { "Time", time } };
                jObject.Add("Data", data);
                Send(("SearchNewDevice"), jObject.ToString());
 
                Actions -= action1;
            });
        }
        #endregion
 
        #region 协调器恢复出厂设置
        ///<summary >
        ///zigbee协调器恢复出厂设置
        /// <para>DelAllInfo:0/1</para>
        ///<para> 0:仅将协调器恢复出厂设置,不删除网关保存的设备列表,组列表,场景列表等信息。</para>
        ///<para>1:将协调器恢复出厂设置,并删除网关保存的设备列表,组列表,场景列表等信息。</para>
        /// </summary>
        public void GwOperationReset(int delAllInfo)
        {
            Action<string, string> action = (topic, message) => { };
            Actions += action;
            try
            {
                var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 160 } };
                var data = new JObject { { "DelAllInfo", delAllInfo } };
                jObject.Add("Data", data);
                Send(("ZbGwOperation/Reset"), jObject.ToString());
            }
            catch { }
 
            Actions -= action;
        }
        #endregion
 
        #region 网关恢复出厂设置
        ///<summary >
        ///网关恢复出厂设置
        /// <para>该指令用于网关linux系统恢复出厂设置。恢复出厂设置后,系统将自动重启</para>
        /// <para>0:命令已接收,系统即将恢复出厂并重启。</para>
        /// </summary>
        public async System.Threading.Tasks.Task<GwLinuxResetResponData> GwLinuxResetAsync()
        {
            return await System.Threading.Tasks.Task.Run(async () =>
            {
                GwLinuxResetResponData d = null;
                Action<string, string> action = (topic, message) =>
                {
                    var gatewayID = topic.Split('/')[0];
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
 
                    if (topic == gatewayID + "/" + "Error_Respon")
                    {
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString());
 
                        if (temp == null)
                        {
                            d = new GwLinuxResetResponData { errorMessageBase = "网关错误回复,且数据是空" };
                        }
                        else
                        {
                            d = new GwLinuxResetResponData { errorMessageBase = CommonDevice.ErrorMess(temp.Error) };
                        }
                    }
 
                    if (topic == gatewayID + "/" + "GwLinuxReset_Respon")
                    {
                        var result = Newtonsoft.Json.JsonConvert.DeserializeObject<int>(jobject["Data"].ToString());
 
                        if (result == null)
                        {
                            d = new GwLinuxResetResponData { errorMessageBase = "网关返回的数据为空" };
                        }
                        else
                        {
                            d = new GwLinuxResetResponData { Result = result };
                            DebugPrintLog($"UI收到通知后的主题_{ topic}");
                        }
                    }
                };
                Actions += action;
                DebugPrintLog("GwLinuxReset Actions 启动" + System.DateTime.Now.ToString());
 
                try
                {
                    var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 84 } };
                    Send("GwLinuxReset", jObject.ToString());
                }
                catch { }
 
                var dateTime = DateTime.Now;
                while ((DateTime.Now - dateTime).TotalMilliseconds < WaitReceiveDataTime)
                {
                    await System.Threading.Tasks.Task.Delay(10);
                    if (d != null)
                    {
                        break;
                    }
                }
                if ((DateTime.Now - dateTime).TotalMilliseconds > WaitReceiveDataTime)
                {
                    d = new GwLinuxResetResponData { errorMessageBase = " 回复超时,请重新操作" };
                }
                Actions -= action;
                DebugPrintLog("GwLinuxReset Actions 退出" + System.DateTime.Now.ToString());
 
                return d;
            });
        }
        #endregion
 
        #region 重启网关系统
        ///<summary >
        ///重启网关系统
        /// <para>发送该指令将使网关主动断开所有mqtt连接并执行重启。重启时间大约需要60秒</para>
        /// <para>返回值是0:命令已接收,系统即将重启。</para>
        /// </summary>
        public async System.Threading.Tasks.Task<GwRebootResponAllData> GwRebootAsync()
        {
            return await System.Threading.Tasks.Task.Run(async () =>
            {
                GwRebootResponAllData d = null;
                Action<string, string> action = (topic, message) =>
                {
                    var gatewayID = topic.Split('/')[0];
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
 
                    if (topic == gatewayID + "/" + "Error_Respon")
                    {
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString());
 
                        if (temp == null)
                        {
                            d = new GwRebootResponAllData { errorMessageBase = "网关错误回复,且数据是空" };
                        }
                        else
                        {
                            d = new GwRebootResponAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) };
                        }
                    }
 
                    if (topic == gatewayID + "/" + "GwReboot_Respon")
                    {
                        var result = Newtonsoft.Json.JsonConvert.DeserializeObject<int>(jobject["Data"].ToString());
 
                        if (result == null)
                        {
                            d = new GwRebootResponAllData { errorMessageBase = "网关返回的数据为空" };
                        }
                        else
                        {
                            d = new GwRebootResponAllData { Result = result };
                            DebugPrintLog($"UI收到通知后的主题_{ topic}");
                        }
                    }
                };
                Actions += action;
                DebugPrintLog("GwReboot Actions 启动" + System.DateTime.Now.ToString());
 
                try
                {
                    var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 83 } };
                    Send("GwReboot", jObject.ToString());
                }
                catch { }
 
                var dateTime = DateTime.Now;
                while ((DateTime.Now - dateTime).TotalMilliseconds < WaitReceiveDataTime)
                {
                    await System.Threading.Tasks.Task.Delay(10);
                    if (d != null)
                    {
                        break;
                    }
                }
                if ((DateTime.Now - dateTime).TotalMilliseconds > WaitReceiveDataTime)
                {
                    d = new GwRebootResponAllData { errorMessageBase = " 回复超时,请重新操作" };
                }
                Actions -= action;
                DebugPrintLog("GwReboot Actions 退出" + System.DateTime.Now.ToString());
 
                return d;
            });
        }
        #endregion
 
        #region 网关和协调器升级
        ///<summary >
        ///保存zigbee协调器组网信息
        /// </summary>
        public async System.Threading.Tasks.Task<SaveNVFileResponseAllData> SaveNVFile(string imageName, string imagePath)
        {
            return await System.Threading.Tasks.Task.Run(async () =>
            {
                SaveNVFileResponseAllData d = null;
                Action<string, string> action = (topic, message) =>
                {
                    var gatewayID = topic.Split('/')[0];
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
 
                    if (topic == gatewayID + "/" + "Error_Respon")
                    {
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString());
 
                        if (temp == null)
                        {
                            d = new SaveNVFileResponseAllData { errorMessageBase = "网关错误回复,且数据是空" };
                        }
                        else
                        {
                            d = new SaveNVFileResponseAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) };
                        }
                    }
 
                    if (topic == gatewayID + "/" + "ZbGwOperation/SaveNVFile_Respon")
                    {
                        var zbGwOperationSaveNVFileData = Newtonsoft.Json.JsonConvert.DeserializeObject<ZbGateway.SaveNVFileResponseData>(jobject["Data"].ToString());
 
                        if (zbGwOperationSaveNVFileData == null)
                        {
                            d = new SaveNVFileResponseAllData { errorMessageBase = "网关返回的数据为空" };
                        }
                        else
                        {
                            d = new SaveNVFileResponseAllData { saveNVFileResponseData = zbGwOperationSaveNVFileData };
                            DebugPrintLog($"UI收到通知后的主题_{ topic}");
                        }
                    }
                };
                Actions += action;
                DebugPrintLog("ZbGwOperation/SaveNVFile Actions 启动" + System.DateTime.Now.ToString());
 
                try
                {
                    var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 500 } };
                    var data = new JObject { { "ImageName", imageName }, { "ImagePath", imagePath } };
                    jObject.Add("Data", data);
                    Send(("ZbGwOperation/SaveNVFile"), jObject.ToString());
                }
                catch { }
 
                var dateTime = DateTime.Now;
                while ((DateTime.Now - dateTime).TotalMilliseconds < WaitReceiveDataTime)
                {
                    await System.Threading.Tasks.Task.Delay(10);
                    if (d != null)
                    {
                        break;
                    }
                }
                if ((DateTime.Now - dateTime).TotalMilliseconds > WaitReceiveDataTime)
                {
                    d = new SaveNVFileResponseAllData { errorMessageBase = " 回复超时,请重新操作" };
                }
                Actions -= action;
                DebugPrintLog("ZbGwOperation/SaveNVFile Actions 退出" + System.DateTime.Now.ToString());
 
                return d;
            });
        }
        #endregion
 
        #region 协调器恢复组网信息
        ///<summary >
        ///协调器恢复组网信息
        /// </summary>
        public async System.Threading.Tasks.Task<RestoreNVAllDtta> RestoreNV(string imageName, string imagePath)
        {
            return await System.Threading.Tasks.Task.Run(async () =>
            {
                RestoreNVAllDtta d = null;
                Action<string, string> action = (topic, message) =>
                {
                    var gatewayID = topic.Split('/')[0];
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
 
                    if (topic == gatewayID + "/" + "Error_Respon")
                    {
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString());
 
                        if (temp == null)
                        {
                            d = new RestoreNVAllDtta { errorMessageBase = "网关错误回复,且数据是空" };
                        }
                        else
                        {
                            d = new RestoreNVAllDtta { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) };
                        }
                    }
 
 
                    if (topic == gatewayID + "/" + "ZbGwOperation/RestoreNV_Respon")
                    {
                        var tempData = Newtonsoft.Json.JsonConvert.DeserializeObject<ZbGateway.RestoreNVDtta>(jobject["Data"].ToString());
 
                        if (tempData == null)
                        {
                            d = new RestoreNVAllDtta { errorMessageBase = "网关返回的数据为空" };
                        }
                        else
                        {
                            d = new RestoreNVAllDtta { restoreNVDtta = tempData };
                            DebugPrintLog($"UI收到通知后的主题_{ topic}");
 
                        }
                    }
                };
                Actions += action;
                DebugPrintLog("ZbGwOperation/RestoreNV Actions 启动" + System.DateTime.Now.ToString());
 
                try
                {
                    var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 501 } };
                    var data = new JObject { { "ImageName", imageName }, { "ImagePath", imagePath } };
                    jObject.Add("Data", data);
                    Send(("ZbGwOperation/RestoreNV"), jObject.ToString());
                }
                catch { }
 
                var dateTime = DateTime.Now;
                while ((DateTime.Now - dateTime).TotalMilliseconds < WaitReceiveDataTime)
                {
                    await System.Threading.Tasks.Task.Delay(10);
                    if (d != null)
                    {
                        break;
                    }
                }
                if ((DateTime.Now - dateTime).TotalMilliseconds > WaitReceiveDataTime)
                {
                    d = new RestoreNVAllDtta { errorMessageBase = " 回复超时,请重新操作" };
                }
                Actions -= action;
                DebugPrintLog("ZbGwOperation/RestoreNV Actions 退出" + System.DateTime.Now.ToString());
 
                return d;
            });
        }
        #endregion
 
        #region 获取协调器当前信道.
        ///<summary >
        /// 获取协调器当前信道
        /// </summary>
        public async System.Threading.Tasks.Task<GwGetChannelResponData> GetChannelAsync()
        {
            return await System.Threading.Tasks.Task.Run(async () =>
            {
                GwGetChannelResponData d = null;
                Action<string, string> action = (topic, message) =>
                {
                    var gatewayID = topic.Split('/')[0];
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
 
                    if (topic == gatewayID + "/" + "Error_Respon")
                    {
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString());
                        if (temp == null)
                        {
                            d = new GwGetChannelResponData { errorMessageBase = "网关错误回复,且数据是空" };
                        }
                        else
                        {
                            d = new GwGetChannelResponData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) };
                        }
                    }
 
                    if (topic == gatewayID + "/" + "ZbGw/GetChannel_Respon")
                    {
                        var channel = Newtonsoft.Json.JsonConvert.DeserializeObject<int>(jobject["Data"]["Channel"].ToString());
                        d = new GwGetChannelResponData { channel = channel };
                        DebugPrintLog($"UI收到通知后的主题_{ topic}");
                    }
                };
 
                Actions += action;
                DebugPrintLog("ZbGw/GetChannel Actions 启动" + System.DateTime.Now.ToString());
 
                try
                {
                    var jObject = new JObject { { "Cluster_ID", 64512 }, { "Command", 8 } };
                    Send(("ZbGw/GetChannel"), jObject.ToString());
                }
                catch { }
 
                var dateTime = DateTime.Now;
                while ((DateTime.Now - dateTime).TotalMilliseconds < WaitReceiveDataTime)
                {
                    await System.Threading.Tasks.Task.Delay(10);
                    if (d != null)
                    {
                        break;
                    }
                }
                if ((DateTime.Now - dateTime).TotalMilliseconds > WaitReceiveDataTime)
                {
                    d = new GwGetChannelResponData { errorMessageBase = " 回复超时,请重新操作" };
                }
                Actions -= action;
                DebugPrintLog("ZbGw/GetChannel Actions 退出" + System.DateTime.Now.ToString());
                return d;
            });
        }
        #endregion
 
        #region 更改协调器当前信道
        ///<summary >
        /// 更改协调器当前信道
        /// <para>Channel:要更改的信道: 11 -26</para>
        /// </summary>
        public async System.Threading.Tasks.Task<ChangeChannelResponAllData> ChangeChannelAsync(int channel)
        {
            return await System.Threading.Tasks.Task.Run(async () =>
            {
                ChangeChannelResponAllData d = null;
                Action<string, string> action = (topic, message) =>
                {
                    var gatewayID = topic.Split('/')[0];
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
 
                    if (topic == gatewayID + "/" + "Error_Respon")
                    {
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString());
 
                        if (temp == null)
                        {
                            d = new ChangeChannelResponAllData { errorMessageBase = "网关错误回复,且数据是空" };
                        }
                        else
                        {
                            d = new ChangeChannelResponAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) };
                        }
                    }
 
                    if (topic == gatewayID + "/" + "ZbGw/ChangeChannel_Respon")
                    {
                        var tempInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<ChangeChannelResponData>(jobject["Data"].ToString());
 
                        if (tempInfo == null)
                        {
                            d = new ChangeChannelResponAllData { errorMessageBase = "网关返回的数据为空" };
                        }
                        else
                        {
                            d = new ChangeChannelResponAllData { changeChannelResponData = tempInfo };
                            DebugPrintLog($"UI收到通知后的主题_{ topic}");
 
                        }
                    }
                };
 
                Actions += action;
                try
                {
                    var jObject = new JObject { { "Cluster_ID", 64512 }, { "Command", 9 } };
                    var data = new JObject { { "Channel", channel } };
                    jObject.Add("Data", data);
                    Send(("ZbGw/ChangeChannel"), jObject.ToString());
                }
                catch { }
 
                var dateTime = DateTime.Now;
                while ((DateTime.Now - dateTime).TotalMilliseconds < WaitReceiveDataTime)
                {
                    await System.Threading.Tasks.Task.Delay(10);
                    if (d != null)
                    {
                        break;
                    }
                }
                if ((DateTime.Now - dateTime).TotalMilliseconds > WaitReceiveDataTime)
                {
                    d = new ChangeChannelResponAllData { errorMessageBase = " 回复超时,请重新操作" };
                }
                Actions -= action;
                return d;
            });
        }
        #endregion
 
        #region 数据透传1(数据是十六进制形式的字符串)
        ///<summary >
        ///客户端向节点设备透传数据,(数据是十六进制形式的字符串)
        /// <para>deviceAddr:设备的mac地址</para>
        /// <para>devicePoint:设备端口号</para>
        ///  <para>PassData:透传的数据,最大256个字符,也就是透传128个字节</para>
        /// </summary>
        public async void ClientDataPassthrough(string deviceAddr, int devicePoint, string passData)
        {
            await System.Threading.Tasks.Task.Run(async () =>
            {
                Action<string, string> action = (topic, message) => { };
                Actions += action;
                try
                {
                    var jObject = new JObject { { "DeviceAddr", deviceAddr }, { "Epoint", devicePoint }, { "Cluster_ID", 64513 }, { "Command", 0 } };
                    Send(("ClientDataPassthrough"), jObject.ToString());
                }
                catch { }
                Actions -= action;
            });
        }
 
        #region 数据透传2(数据是二进制流)
        ///<summary >
        /// 客户端发送文件流到网关(数据是二进制流)
        ///<para> passData: 透传数据</para>
        ///<para>Result 0: 数据写入成功,请求发送下一个数据包</para>
        ///<para>Result1:数据写入失败</para>
        ///<para>Result2:数据解析错误</para>
        ///<para>Result3:发送数据大小超出限制</para>
        /// </summary>
        public async System.Threading.Tasks.Task<Panel.PanelSwitchLevelInfo> ClientDataPassthroughBytesAsync(string deviceAddr, int devicePoint, long dataLength, byte[] passData)
        {
            var myDevice = Shared.Phone.HdlDeviceCommonLogic.Current.GetDevice(deviceAddr, devicePoint);
 
            Panel.PanelSwitchLevelInfo result = null;
 
            if (myDevice.Gateway == null)
            {
                result = new Panel.PanelSwitchLevelInfo { errorMessageBase = "当前没有网关" };
                return result;
            }
            return await System.Threading.Tasks.Task.Run(async () =>
            {
                Action<string, string> action = (topic, message) =>
                {
                    var gatewayID = topic.Split('/')[0];
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
 
                    if (topic == gatewayID + "/" + "Error_Respon")
                    {
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString());
 
                        if (temp == null)
                        {
                            result = new Panel.PanelSwitchLevelInfo { errorMessageBase = "网关错误回复,且数据是空" };
                        }
 
                        else
                        {
                            result = new Panel.PanelSwitchLevelInfo { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) };
                        }
                    }
 
                    if (topic == gatewayID + "/" + "ZbDataPassthrough")
                    {
                        var clientDataPassthroughResponseData = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ClientDataPassthroughResponseData>(jobject["Data"].ToString());
 
                        if (clientDataPassthroughResponseData == null)
                        {
                            result = new Panel.PanelSwitchLevelInfo { errorMessageBase = "网关返回的数据为空" };
                        }
                        else
                        {
                            if (clientDataPassthroughResponseData?.PassData != null)
                            {
                                var data = clientDataPassthroughResponseData.PassData;
                                if (data.Length == 14)
                                {
                                    var command = data[4].ToString() + data[5].ToString() + data[2].ToString() + data[3].ToString();
                                    if (command == "0407")
                                    {
                                        var level1 = Convert.ToInt32(data[10].ToString() + data[11].ToString(), 16);
                                        var level2 = Convert.ToInt32(data[12].ToString() + data[13].ToString(), 16);
                                        result = new Panel.PanelSwitchLevelInfo { panelDirectionsLevel = level1, panelBacklightLevel = level2 };
                                        System.Console.WriteLine($"UI收到通知后的主题_command:0406_{ topic}");
                                    }
                                }
                            }
                        }
                    }
                };
 
                myDevice.Gateway.Actions += action;
                System.Console.WriteLine("ClientDataPassthrough_Actions 启动" + System.DateTime.Now.ToString());
 
                try
                {
                    var sendDataBytes = new byte[12 + dataLength];
                    sendDataBytes[0] = 0xfe;
                    //设备端点,1个bytes
                    sendDataBytes[1] = Convert.ToByte(devicePoint);
                    //设备mac地址,小端结构,8个bytes
                    //var addrAllBytes = new byte[8];
                    int j = 0;
                    for (int i = 14; i >= 0; i = i - 2)
                    {
                        var curByte = deviceAddr.Substring(i, 2); //00 0d 6f ff fe 04 51 52
 
                        sendDataBytes[2 + j] = Convert.ToByte(string.Format("0x{0}", curByte), 16);
                        j++;
                    }
                    //数据长度,1个bytes
                    sendDataBytes[10] = Convert.ToByte(dataLength % 256);   // DataLen 0x01 到 0x800 (即每次最大发送2048字节)2
                    sendDataBytes[11] = Convert.ToByte(dataLength / 256);
                    //透传数据
                    System.Array.Copy(passData, 0, sendDataBytes, 12, dataLength);
                    await Send("ClientDataPassthrough", sendDataBytes);
                }
                catch { }
 
                var dateTime = DateTime.Now;
                while ((DateTime.Now - dateTime).TotalMilliseconds < WaitReceiveDataTime)
                {
                    await System.Threading.Tasks.Task.Delay(10);
                    if (result != null)
                    {
                        break;
                    }
                }
                if ((DateTime.Now - dateTime).TotalMilliseconds > WaitReceiveDataTime)
                {
                    result = new Panel.PanelSwitchLevelInfo { errorMessageBase = " 回复超时,请重新操作" };
                }
                myDevice.Gateway.Actions -= action;
                System.Console.WriteLine("ClientDataPassthrough_Actions 退出" + System.DateTime.Now.ToString());
 
                return result;
            });
        }
        #endregion
 
        #endregion
 
        #region 启用或关闭透传数据上传接口
        /// <summary>
        /// 启用或关闭透传数据上传接口
        /// </summary>
        /// <returns>The scene new identifier async.</returns>
        /// <param name="gateway">Gateway.</param>
        /// <param name="IsOn">0:关闭透传数据上传 ;1:开启透传数据上传</param>
        public async System.Threading.Tasks.Task<PassthroughAllData> GetSceneNewIdAsync(int IsOn)
        {
            return await System.Threading.Tasks.Task.Run(async () =>
            {
                PassthroughAllData d = null;
                Action<string, string> action = (topic, message) =>
                {
                    var gatewayID = topic.Split('/')[0];
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
 
                    if (topic == gatewayID + "/" + "Error_Respon")
                    {
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString());
 
                        if (temp == null)
                        {
                            d = new PassthroughAllData { errorMessageBase = "网关错误回复,且数据是空" };
                        }
                        else
                        {
                            d = new PassthroughAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) };
                        }
                    }
 
                    if (topic == gatewayID + "/" + "ZbDataPassthrough")
                    {
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<string>(jobject["Data"].ToString());
 
                        d = new PassthroughAllData { passData = temp };
                        DebugPrintLog($"UI收到通知后的主题_{ topic}");
                    }
                };
                Actions += action;
                DebugPrintLog("ZbDataPassthrough_Actions 启动" + "_" + System.DateTime.Now.ToString());
 
                try
                {
                    var jObject = new JObject { { "Cluster_ID", 64513 }, { "Command", 1 } };
                    Send("GetZbGwVersion", jObject.ToString());
                }
                catch { }
 
                var dateTime = DateTime.Now;
                while ((DateTime.Now - dateTime).TotalMilliseconds < WaitReceiveDataTime)
                {
                    await System.Threading.Tasks.Task.Delay(10);
                    if (d != null)
                    {
                        break;
                    }
                }
                if ((DateTime.Now - dateTime).TotalMilliseconds > WaitReceiveDataTime)
                {
                    d = new PassthroughAllData { errorMessageBase = " 回复超时,请重新操作" };
                }
                Actions -= action;
                DebugPrintLog("GetGwVersionData_Actions 退出" + System.DateTime.Now.ToString());
 
                return d;
            });
        }
        #endregion
 
        #region 网关升级
        /// <summary>
        /// 网关升级
        /// </summary>
        /// <returns>The upgrade async.</returns>
        /// <param name="imageName">Image name:(升级固件名称,名称中要带有“LINUXMODULE”标识,否则将不会升级。最大128字节</param>
        public async System.Threading.Tasks.Task<LinuxUpgradeAllData> LinuxUpgradeAsync(string imageName)
        {
            return await System.Threading.Tasks.Task.Run(async () =>
            {
                LinuxUpgradeAllData d = null;
 
                Action<string, string> action = (topic, message) =>
                {
                    var gatewayID = topic.Split('/')[0];
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
 
                    if (topic == gatewayID + "/" + "Error_Respon")
                    {
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString());
 
                        if (temp == null)
                        {
                            d = new LinuxUpgradeAllData { errorMessageBase = "网关错误回复,且数据是空" };
                        }
 
                        else
                        {
                            d = new LinuxUpgradeAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) };
                        }
                    }
 
                    if (topic == gatewayID + "/" + "ZbGwOperation/LinuxUpgrade_Respon")
                    {
                        var result = Newtonsoft.Json.JsonConvert.DeserializeObject<int>(jobject["Data"]["Result"].ToString());
                        d = new LinuxUpgradeAllData { Result = result };
                        DebugPrintLog($"UI收到通知后的主题_{ topic}");
                    }
                };
                Actions += action;
                DebugPrintLog("ZbGwOperation/LinuxUpgrade_Actions 启动" + "_" + System.DateTime.Now.ToString());
 
                try
                {
                    var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 503 } };
                    var data = new JObject {
                         { "IsForce", 0},
                         { "SaveChange", 1},
                        { "ImageName", imageName},
                        { "ImagePath", "/tmp"}
                    };
                    jObject.Add("Data", data);
                    Send(("ZbGwOperation/LinuxUpgrade"), jObject.ToString());
                }
                catch { }
                var dateTime = DateTime.Now;
                while ((DateTime.Now - dateTime).TotalMilliseconds < 30 * 1000)
                {
                    await System.Threading.Tasks.Task.Delay(10);
                    if (d != null)
                    {
                        break;
                    }
                }
                if ((DateTime.Now - dateTime).TotalMilliseconds > 30 * 1000)
                {
                    d = new LinuxUpgradeAllData { errorMessageBase = " 回复超时,请重新操作" };
                }
                Actions -= action;
                DebugPrintLog("ZbGwOperation/LinuxUpgrade_Actions 退出" + System.DateTime.Now.ToString());
 
                return d;
            });
        }
        #endregion
 
        #region 协调器升级
        /// <summary>
        /// 协调器升级
        /// </summary>
        /// <returns>The NVA sync.</returns>
        /// <param name="imageName">Image name:(升级镜像名称,名称中要带有“ZBMODULE”标识,否则不允许升级。最大128字节。)</param>
        public async System.Threading.Tasks.Task<ZbGwOperationUpgradeAllData> UpgradeNVAsync(string imageName)
        {
            return await System.Threading.Tasks.Task.Run(async () =>
            {
                ZbGwOperationUpgradeAllData d = null; ;
                Action<string, string> action = (topic, message) =>
                {
                    var gatewayID = topic.Split('/')[0];
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
 
                    if (topic == gatewayID + "/" + "Error_Respon")
                    {
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString());
 
                        if (temp == null)
                        {
                            d = new ZbGwOperationUpgradeAllData { errorMessageBase = "网关错误回复,且数据是空" };
                        }
 
                        else
                        {
                            d = new ZbGwOperationUpgradeAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) };
                        }
                    }
 
                    if (topic == gatewayID + "/" + "ZbGwOperation/Upgrade_Respon")
                    {
                        zbGwOperationUpgradeData = Newtonsoft.Json.JsonConvert.DeserializeObject<ZbGateway.ZbGwOperationUpgradeData>(jobject["Data"].ToString());
 
                        if (zbGwOperationUpgradeData == null)
                        {
                            d = new ZbGwOperationUpgradeAllData { errorMessageBase = "网关返回的数据为空" };
                        }
                        else
                        {
                            d = new ZbGwOperationUpgradeAllData { bGwOperationUpgradeData = zbGwOperationUpgradeData };
                            DebugPrintLog($"UI收到通知后的主题_{ topic}");
                        }
                    }
                };
                Actions += action;
                DebugPrintLog("ZbGwOperation/Upgrade_Actions 启动" + "_" + System.DateTime.Now.ToString());
 
                try
                {
                    var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 502 } };
                    var data = new JObject { { "ImageName", imageName }, { "ImagePath", "/tmp" } };
                    jObject.Add("Data", data);
                    Send(("ZbGwOperation/Upgrade"), jObject.ToString());
                }
                catch
                { }
                var dateTime = DateTime.Now;
                while ((DateTime.Now - dateTime).TotalMilliseconds < 30 * 1000)
                {
                    await System.Threading.Tasks.Task.Delay(10);
                    if (d != null)
                    {
                        break;
                    }
                }
                if ((DateTime.Now - dateTime).TotalMilliseconds > 30 * 1000)
                {
                    d = new ZbGwOperationUpgradeAllData { errorMessageBase = " 回复超时,请重新操作" };
 
                }
                Actions -= action;
                DebugPrintLog("ZbGwOperation/Upgrade_Actions 退出" + System.DateTime.Now.ToString());
 
                return d;
            });
        }
        #endregion
 
        #region 下载云端固件.
        /// <summary>
        /// 下载云端网关或协调器固件.
        /// </summary>
        /// <returns>The file async.</returns>
        /// <param name="distributedMark">Distributed mark:固件唯一标识</param>
        /// <param name="imageName">Image name:固件版本</param>
        public async System.Threading.Tasks.Task<CommonDevice.DownloadFileResponAllData> DownloadFileAsync(string distributedMark, string imageName)
        {
            return await System.Threading.Tasks.Task.Run(async () =>
            {
                CommonDevice.DownloadFileResponAllData d = null; ;
                Action<string, string> action = (topic, message) =>
                {
                    var gatewayID = topic.Split('/')[0];
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
 
                    if (topic == gatewayID + "/" + "Error_Respon")
                    {
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString());
 
                        if (temp == null)
                        {
                            d = new CommonDevice.DownloadFileResponAllData { errorMessageBase = "网关错误回复,且数据是空" };
                        }
 
                        else
                        {
                            d = new CommonDevice.DownloadFileResponAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) };
                        }
                    }
 
                    if (topic == gatewayID + "/" + "DownloadFile_Respon")
                    {
                        var downloadFileResponData = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.DownloadFileResponData>(jobject["Data"].ToString());
 
                        if (downloadFileResponData == null)
                        {
                            d = new CommonDevice.DownloadFileResponAllData { errorMessageBase = "网关返回的数据为空" };
                        }
                        else
                        {
                            d = new CommonDevice.DownloadFileResponAllData { downloadFileResponData = downloadFileResponData };
                            DebugPrintLog($"UI收到通知后的主题_{ topic}");
                        }
                    }
                };
                Actions += action;
                DebugPrintLog("DownloadFile_Actions 启动" + "_" + System.DateTime.Now.ToString());
 
                try
                {
                    var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 6000 } };
                    var data = new JObject {
                        { "DistributeMark", distributedMark},
                        { "DownloadPath", "/tmp" },
                        { "FileName", imageName }
                     };
                    jObject.Add("Data", data);
                    Send(("DownloadFile"), jObject.ToString());
                }
                catch { }
                var dateTime = DateTime.Now;
                while ((DateTime.Now - dateTime).TotalMilliseconds < 30 * 1000)
                {
                    await System.Threading.Tasks.Task.Delay(10);
                    if (d != null)
                    {
                        break;
                    }
                }
                if ((DateTime.Now - dateTime).TotalMilliseconds > 30 * 1000)
                {
                    d = new CommonDevice.DownloadFileResponAllData { errorMessageBase = " 回复超时,请重新操作" };
 
                }
                Actions -= action;
                DebugPrintLog("DownloadFile_Actions 退出" + System.DateTime.Now.ToString());
 
                return d;
            });
        }
        #endregion
 
        #region 查看网关记录的虚拟驱动.
        /// <summary>
        /// 查看网关记录的虚拟驱动
        /// </summary>
        public async System.Threading.Tasks.Task<CheckVDDriveCodeResponseAllData> CheckVDDriveCodeAsync()
        {
            return await System.Threading.Tasks.Task.Run(async () =>
            {
                CheckVDDriveCodeResponseAllData d = null; ;
                Action<string, string> action = (topic, message) =>
                {
                    var gatewayID = topic.Split('/')[0];
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
 
                    if (topic == gatewayID + "/" + "Error_Respon")
                    {
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString());
 
                        if (temp == null)
                        {
                            d = new CheckVDDriveCodeResponseAllData { errorMessageBase = "网关错误回复,且数据是空" };
                        }
 
                        else
                        {
                            d = new CheckVDDriveCodeResponseAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) };
                        }
                    }
 
                    if (topic == gatewayID + "/" + "VirtualDrive/CatDriveCode_Respon")
                    {
                        var vDriveDriveCodeResponData = Newtonsoft.Json.JsonConvert.DeserializeObject<VDriveDriveCodeResponData>(jobject["Data"].ToString());
 
                        if (vDriveDriveCodeResponData == null)
                        {
                            d = new CheckVDDriveCodeResponseAllData { errorMessageBase = "网关返回的数据为空" };
                        }
                        else
                        {
                            d = new CheckVDDriveCodeResponseAllData { vDriveDriveCodeResponData = vDriveDriveCodeResponData };
                            DebugPrintLog($"UI收到通知后的主题_{ topic}");
                        }
                    }
                };
                Actions += action;
                DebugPrintLog("VirtualDriveDriveCode_Actions 启动" + "_" + System.DateTime.Now.ToString());
 
                try
                {
                    var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 505 } };
                    Send(("VirtualDrive/CatDriveCode"), jObject.ToString());
                }
                catch { }
 
                var dateTime = DateTime.Now;
                while ((DateTime.Now - dateTime).TotalMilliseconds < WaitReceiveDataTime)
                {
                    await System.Threading.Tasks.Task.Delay(10);
                    if (d != null)
                    {
                        break;
                    }
                }
                if ((DateTime.Now - dateTime).TotalMilliseconds > WaitReceiveDataTime)
                {
                    d = new CheckVDDriveCodeResponseAllData { errorMessageBase = " 回复超时,请重新操作" };
                }
                Actions -= action;
                DebugPrintLog("VirtualDriveDriveCode_Actions 退出" + System.DateTime.Now.ToString());
 
                return d;
            });
        }
 
        #endregion
 
        #region 升级虚拟驱动设备.
        /// <summary>
        /// 升级虚拟驱动设备
        /// <para>oTAImageName:升级镜像名称</para>
        /// <para>driveCode:驱动代号</para>
        /// </summary>
        public async System.Threading.Tasks.Task<VirtualDriveUpgradeResponseAllData> VirtualDriveUpgradeAsync(string imageName, int driveCode)
        {
            return await System.Threading.Tasks.Task.Run(async () =>
            {
                VirtualDriveUpgradeResponseAllData d = null; ;
                Action<string, string> action = (topic, message) =>
                {
                    var gatewayID = topic.Split('/')[0];
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
 
                    if (topic == gatewayID + "/" + "Error_Respon")
                    {
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString());
 
                        if (temp == null)
                        {
                            d = new VirtualDriveUpgradeResponseAllData { errorMessageBase = "网关错误回复,且数据是空" };
                        }
 
                        else
                        {
                            d = new VirtualDriveUpgradeResponseAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) };
                        }
                    }
 
                    if (topic == gatewayID + "/" + "VirtualDrive/Upgrade_Respon")
                    {
                        virtualDriveUpgradeResponData = Newtonsoft.Json.JsonConvert.DeserializeObject<VirtualDriveUpgradeResponData>(jobject["Data"].ToString());
 
                        if (virtualDriveUpgradeResponData == null)
                        {
                            d = new VirtualDriveUpgradeResponseAllData { errorMessageBase = "网关返回的数据为空" };
                        }
                        else
                        {
                            d = new VirtualDriveUpgradeResponseAllData { virtualDriveUpgradeResponData = virtualDriveUpgradeResponData };
                            DebugPrintLog($"UI收到通知后的主题_{topic}");
                        }
                    }
                };
                Actions += action;
                DebugPrintLog("VirtualDrive/Upgrade_Actions 启动" + "_" + System.DateTime.Now.ToString());
 
                try
                {
                    var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 504 } };
                    var data = new JObject { { "ImageName", imageName }, { "ImagePath", "/tmp" }, { "DriveCode", driveCode } };
                    jObject.Add("Data", data);
                    Send(("VirtualDrive/Upgrade"), jObject.ToString());
                }
                catch { }
                var dateTime = DateTime.Now;
                while ((DateTime.Now - dateTime).TotalMilliseconds < 30 * 1000)
                {
                    await System.Threading.Tasks.Task.Delay(10);
                    if (d != null)
                    {
                        break;
                    }
                }
                if ((DateTime.Now - dateTime).TotalMilliseconds > 30 * 1000)
                {
                    d = new VirtualDriveUpgradeResponseAllData { errorMessageBase = " 回复超时,请重新操作" };
                }
                Actions -= action;
                DebugPrintLog("VirtualDrive/Upgrade_Actions 退出" + System.DateTime.Now.ToString());
 
                return d;
            });
        }
 
        #endregion
 
        #region 客户端上传文件到网关.
        /// <summary>
        /// 客户端上传文件到网关
        /// </summary>
        /// <returns>The admin password async.</returns>
        /// <param name="fileName">上传文件后,保存的文件名称</param>
        /// <param name="filePath">文件保存在系统的目录路径,如果目录不存在系统将自动创建该目录。如:/tmp/. </param>
        public async System.Threading.Tasks.Task<CreateFileResponseAllData> CreateFileAsync(string fileName, string filePath = "/etc/hdlDat")
        {
            return await System.Threading.Tasks.Task.Run(async () =>
            {
                CreateFileResponseAllData dataRes = null;
 
                Action<string, string> action = (topic, message) =>
                {
                    var gatewayID = topic.Split('/')[0];
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
 
                    if (topic == gatewayID + "/" + "Error_Respon")
                    {
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString());
 
                        if (temp == null)
                        {
                            dataRes = new CreateFileResponseAllData { errorMessageBase = "网关错误回复,且数据是空" };
                        }
                        else
                        {
                            dataRes = new CreateFileResponseAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) };
                        }
                    }
 
                    if (topic == gatewayID + "/" + "FileTransfer/CreateFile_Respon")
                    {
                        var result = Newtonsoft.Json.JsonConvert.DeserializeObject<int>(jobject["Data"]["Result"].ToString());
                        dataRes = new CreateFileResponseAllData { Result = result };
                        DebugPrintLog($"UI收到通知后的主题_{ topic}");
                    }
                };
                Actions += action;
                DebugPrintLog("FileTransfer/CreateFile_Actions 启动" + System.DateTime.Now.ToString());
 
                try
                {
                    var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 3000 } };
                    var data = new JObject { { "FileName", fileName }, { "FilePath", filePath } };
                    jObject.Add("Data", data);
                    Send(("FileTransfer/CreateFile"), jObject.ToString());
                }
                catch { }
 
                var dateTime = DateTime.Now;
                while ((DateTime.Now - dateTime).TotalMilliseconds < WaitReceiveDataTime)
                {
                    await System.Threading.Tasks.Task.Delay(10);
                    if (dataRes != null)
                    {
                        break;
                    }
                }
                if ((DateTime.Now - dateTime).TotalMilliseconds > WaitReceiveDataTime)
                {
                    dataRes = new CreateFileResponseAllData { errorMessageBase = " 回复超时,请重新操作" };
                };
 
                Actions -= action;
                DebugPrintLog("FileTransfer/CreateFile_Actions 退出" + System.DateTime.Now.ToString());
                return dataRes;
            });
        }
        #endregion
 
        #region 客户端发送文件流到网关
        ///<summary >
        /// 客户端发送文件流到网关
        ///<para>Result 0: 数据写入成功,请求发送下一个数据包</para>
        ///<para>Result1:数据写入失败</para>
        ///<para>Result2:数据解析错误</para>
        ///<para>Result3:发送数据大小超出限制</para>
        /// </summary>
        public async System.Threading.Tasks.Task<SendFileResponseAllData> SendFileAsync(byte[] data)
        {
            if (data == null)
            {
                return new SendFileResponseAllData { errorMessageBase = "数据内容是空" };
            }
            return await System.Threading.Tasks.Task.Run(async () =>
            {
                var isRespond = true;
                SendFileResponseAllData dataRes = null;
                Action<string, string> action = (topic, message) =>
                {
                    var gatewayID = topic.Split('/')[0];
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
 
                    if (topic == gatewayID + "/FileTransfer/SendFile_Respon")
                    {
                        var result = Newtonsoft.Json.JsonConvert.DeserializeObject<int>(jobject["Data"]["Result"].ToString());
                        dataRes = new SendFileResponseAllData { Result = result };
                        if (result == 0)
                        {
                            isRespond = true;
                        }
                        DebugPrintLog($"UI收到通知后的主题_{ topic}");
                    }
                };
                Actions += action;
                DebugPrintLog("FileTransfer/SendFile_Actions 启动" + System.DateTime.Now.ToString());
 
                try
                {
                    var fileBytes = data;
                    var size = 2048;
                    var dateTime = DateTime.Now;
                    for (int i = 0, tempSize = 0; i < fileBytes.Length; i += tempSize)
                    {
                        while (!isRespond)
                        {
                            if (WaitReceiveDataTime < (DateTime.Now - dateTime).TotalMilliseconds)
                            {
                                return new SendFileResponseAllData { errorMessageBase = "回复超时,请重新操作" }; ;
                            }
                            await System.Threading.Tasks.Task.Delay(10);
                        }
                        isRespond = false;
 
                        byte finish = 0;
                        if (i + size < fileBytes.Length)
                        {
                            tempSize = size;
                        }
                        else if (i + size == fileBytes.Length)
                        {
                            tempSize = size;
                            finish = 1;
                        }
                        else
                        {
                            tempSize = fileBytes.Length % size;
                            finish = 1;
                        }
                        var bytes = new byte[8 + tempSize];
                        bytes[0] = 0xfe;
                        bytes[1] = 0;
                        bytes[2] = 0;
                        bytes[3] = 0;
                        bytes[4] = 0;
                        bytes[5] = finish;//0x00 或 0x01
                        bytes[6] = Convert.ToByte(tempSize % 256);   // DataLen 0x01 到 0x800 (即每次最大发送2048字节)2
                        bytes[7] = Convert.ToByte(tempSize / 256);
                        System.Array.Copy(fileBytes, i, bytes, 8, tempSize);
                        dateTime = DateTime.Now;
                        await Send("FileTransfer/SendFile", bytes);
                        DebugPrintLog($"上传到网关当前数据数量_{i}_是不是最后一个_{finish}_{System.DateTime.Now.ToString()}");
                    }
                }
                catch { }
                finally
                {
                    Actions -= action;
                }
                DebugPrintLog("Security/ChangeAdminPassword_Actions 退出" + System.DateTime.Now.ToString());
                return dataRes;
            });
        }
        #endregion
 
        #region 查看网关目录文件信息.
        /// <summary>
        /// 查看网关目录文件信息
        /// </summary>
        /// <returns>The admin password async.</returns>
        /// <param name="filePath">文件保存在系统的目录路径,如果目录不存在系统将自动创建该目录。如:/tmp/. </param>
        public async System.Threading.Tasks.Task<FileTransferLsDiResponseAllData> FileTransferLsDirAsync(string filePath = "/etc/hdlDat")
        {
            return await System.Threading.Tasks.Task.Run(async () =>
            {
                FileTransferLsDiResponseAllData dataRes = null;
 
                Action<string, string> action = (topic, message) =>
                {
                    var gatewayID = topic.Split('/')[0];
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
 
                    if (topic == gatewayID + "/" + "Error_Respon")
                    {
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString());
 
                        if (temp == null)
                        {
                            dataRes = new FileTransferLsDiResponseAllData { errorMessageBase = "网关错误回复,且数据是空" };
                        }
                        else
                        {
                            dataRes = new FileTransferLsDiResponseAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) };
                        }
                    }
 
                    if (topic == gatewayID + "/" + "FileTransfer/lsDir_Respon")
                    {
                        var resultlsDir = Newtonsoft.Json.JsonConvert.DeserializeObject<FileTransferLsDiResponseData>(jobject["Data"].ToString());
                        if (resultlsDir != null)
                        {
                            dataRes = new FileTransferLsDiResponseAllData { fileTransferLsDiResponseData = resultlsDir };
                            DebugPrintLog($"UI收到通知后的主题_{ topic}");
                        }
                        else
                        {
                            dataRes = new FileTransferLsDiResponseAllData { errorMessageBase = "收到的网关返回数据是空" };
                        }
                    }
                };
                Actions += action;
                DebugPrintLog("FileTransfer/lsDir_Actions 启动" + System.DateTime.Now.ToString());
                try
                {
                    var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 3002 } };
                    var data = new JObject { { "FilePath", filePath } };
                    jObject.Add("Data", data);
                    Send(("FileTransfer/lsDir"), jObject.ToString());
                }
                catch { }
 
                var dateTime = DateTime.Now;
                while ((DateTime.Now - dateTime).TotalMilliseconds < WaitReceiveDataTime)
                {
                    await System.Threading.Tasks.Task.Delay(10);
                    if (dataRes != null)
                    {
                        break;
                    }
                }
                if ((DateTime.Now - dateTime).TotalMilliseconds > WaitReceiveDataTime)
                {
                    dataRes = new FileTransferLsDiResponseAllData { errorMessageBase = " 回复超时,请重新操作" };
                };
                Actions -= action;
                DebugPrintLog("FileTransfer/lsDir_Actions 退出" + System.DateTime.Now.ToString());
                return dataRes;
            });
        }
        #endregion
 
        #region 查看单个文件信息.
        /// <summary>
        /// 查看单个文件信息
        /// </summary>
        /// <returns>The admin password async.</returns>
        /// <param name="filePath">文件保存在系统的目录路径,如果目录不存在系统将自动创建该目录。如:/tmp/. </param>
        public async System.Threading.Tasks.Task<FileTransferGetFileInfoResponseAllData> GetCurrentFileInfoAsync(string fileName, string filePath = "/etc/hdlDat/")
        {
            return await System.Threading.Tasks.Task.Run(async () =>
            {
                FileTransferGetFileInfoResponseAllData dataRes = null;
 
                Action<string, string> action = (topic, message) =>
                {
                    var gatewayID = topic.Split('/')[0];
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
 
                    if (topic == gatewayID + "/" + "Error_Respon")
                    {
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString());
 
                        if (temp == null)
                        {
                            dataRes = new FileTransferGetFileInfoResponseAllData { errorMessageBase = "网关错误回复,且数据是空" };
                        }
                        else
                        {
                            dataRes = new FileTransferGetFileInfoResponseAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) };
                        }
                    }
 
                    if (topic == gatewayID + "/" + "FileTransfer/GetFileInfo_Respon")
                    {
                        var resultlsDir = Newtonsoft.Json.JsonConvert.DeserializeObject<FileTransferGetFileInfoResponseData>(jobject["Data"].ToString());
                        if (resultlsDir != null)
                        {
                            dataRes = new FileTransferGetFileInfoResponseAllData { fileTransferGetFileInfoResponseData = resultlsDir };
                            DebugPrintLog($"UI收到通知后的主题_{ topic}");
                        }
                        else
                        {
                            dataRes = new FileTransferGetFileInfoResponseAllData { errorMessageBase = "收到的网关返回数据是空" };
                        }
                    }
                };
                Actions += action;
                DebugPrintLog("FileTransfer/GetFileInfo_Actions 启动" + System.DateTime.Now.ToString());
                try
                {
                    var tempFilePath = filePath + fileName;
                    var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 3007 } };
                    var data = new JObject { { "File", tempFilePath } };
                    jObject.Add("Data", data);
                    Send(("FileTransfer/GetFileInfo"), jObject.ToString());
                }
                catch { }
 
                var dateTime = DateTime.Now;
                while ((DateTime.Now - dateTime).TotalMilliseconds < WaitReceiveDataTime)
                {
                    await System.Threading.Tasks.Task.Delay(10);
                    if (dataRes != null)
                    {
                        break;
                    }
                }
                if ((DateTime.Now - dateTime).TotalMilliseconds > WaitReceiveDataTime)
                {
                    dataRes = new FileTransferGetFileInfoResponseAllData { errorMessageBase = " 回复超时,请重新操作" };
                };
                Actions -= action;
                DebugPrintLog("FileTransfer/GetFileInfo_Actions 退出" + System.DateTime.Now.ToString());
                return dataRes;
            });
        }
        #endregion
 
        #region 客户端设定要下载的文件名称和路径
        /// <summary>
        /// 客户端设定要下载的文件名称和路径
        /// <para>fileName:下载的文件名称.</para>
        /// <para>blockStartAddress:可忽略,默认为0。下载开始地址,用于断点续传。如:文件总大小为1000Byte,客户端下载了200Byte后连接意外断开。当客户端重新连接后想继续下载后续文件流而不想从文件头重新开始下载,可将该参数设置为200,网关将从第2001Byte开始发送文件流。</para>
        /// <para>filePath">文件所在系统的目录路径。如:/tmp.</para>
        /// </summary>
        public async System.Threading.Tasks.Task<SetDownloadFileResponseAllData> SetDownloadFileAsync(string fileName, int blockStartAddress = 0, string filePath = "/etc/hdlDat")
        {
            return await System.Threading.Tasks.Task.Run(async () =>
            {
                SetDownloadFileResponseAllData dataRes = null;
 
                Action<string, string> action = (topic, message) =>
                {
                    var gatewayID = topic.Split('/')[0];
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
 
                    if (topic == gatewayID + "/" + "Error_Respon")
                    {
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString());
 
                        if (temp == null)
                        {
                            dataRes = new SetDownloadFileResponseAllData { errorMessageBase = "网关错误回复,且数据是空" };
                        }
                        else
                        {
                            dataRes = new SetDownloadFileResponseAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) };
                        }
                    }
 
                    if (topic == gatewayID + "/" + "FileTransfer/SetDownloadFile_Respon")
                    {
                        var tempData = Newtonsoft.Json.JsonConvert.DeserializeObject<SetDownloadFileResponseData>(jobject["Data"].ToString());
                        if (tempData != null)
                        {
                            dataRes = new SetDownloadFileResponseAllData { };
                            var tempDa = new SetDownloadFileResponseData();
                            if (tempData.Result == 0)
                            {
                                this.byteSource.Clear();
                            }
                            tempDa.Result = tempData.Result;
                            dataRes.setDownloadFileResponseData = tempDa;
                            DebugPrintLog($"UI收到通知后的主题_{ topic}");
                        }
                        else
                        {
                            dataRes = new SetDownloadFileResponseAllData { errorMessageBase = "收到的网关返回数据是空" };
                        }
                    }
                };
                Actions += action;
                DebugPrintLog("FileTransfer/SetDownloadFile_Actions 启动" + System.DateTime.Now.ToString());
                try
                {
                    var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 3003 } };
                    var data = new JObject {
                    { "FileName", fileName },
                        { "FilePath", filePath },
                    { "BlockStartAddress", blockStartAddress }
                 };
                    jObject.Add("Data", data);
                    Send(("FileTransfer/SetDownloadFile"), jObject.ToString());
                }
                catch { }
 
                var dateTime = DateTime.Now;
                while ((DateTime.Now - dateTime).TotalMilliseconds < WaitReceiveDataTime)
                {
                    await System.Threading.Tasks.Task.Delay(10);
                    if (dataRes != null)
                    {
                        break;
                    }
                }
                if ((DateTime.Now - dateTime).TotalMilliseconds > WaitReceiveDataTime)
                {
                    dataRes = new SetDownloadFileResponseAllData { errorMessageBase = " 回复超时,请重新操作" };
                };
                Actions -= action;
                DebugPrintLog("FileTransfer/SetDownloadFile_Actions 退出" + System.DateTime.Now.ToString());
                return dataRes;
            });
        }
        #endregion
 
        #region 网关发送文件流到客户端
        private List<byte> byteSource = new List<byte>();
        ///<summary >
        /// 下载文件中的数据
        /// </summary>
        public void DownloadFileConfirmAsync(byte[] fileBytes)
        {
            int result = 0;
 
            if (fileBytes[5] != 1)
            {
                if (fileBytes.Length == 2056)
                {
                    result = 0;
                    var tempBytes = new byte[2048];
                    System.Array.Copy(fileBytes, 8, tempBytes, 0, 2048);
                    byteSource.AddRange(tempBytes);
                }
                else
                {
                    var tempBytes = new byte[fileBytes.Length - 8];
                    System.Array.Copy(fileBytes, 8, tempBytes, 0, tempBytes.Length);
                    byteSource.AddRange(tempBytes);
                    return;
                }
            }
            else
            {
                var tempBytes = new byte[fileBytes.Length - 8];
                System.Array.Copy(fileBytes, 8, tempBytes, 0, tempBytes.Length);
                byteSource.AddRange(tempBytes);
                return;
            }
 
            try
            {
                var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 3004 } };
                var data = new JObject { { "Result", result } };
                jObject.Add("Data", data);
                Send("FileTransfer/DownloadFile_Respon", jObject.ToString());
            }
            catch { }
        }
        #endregion
 
        #region 删除文件或目录
        /// <summary>
        /// 删除文件或目录
        /// </summary>
        /// <returns>The admin password async.</returns>
        /// <param name="path">删除目录或文件的路径。如:/tmp/,则删除tmp目录。/tmp/aa.txt,则删除tmp目录下的aa.txt文件。 </param>
        public async System.Threading.Tasks.Task<DelFileOrDirResponseAllData> DelFileOrDirAsync(string path = "/etc/hdlDat")
        {
            return await System.Threading.Tasks.Task.Run(async () =>
            {
                DelFileOrDirResponseAllData dataRes = null;
 
                Action<string, string> action = (topic, message) =>
                {
                    var gatewayID = topic.Split('/')[0];
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
 
                    if (topic == gatewayID + "/" + "Error_Respon")
                    {
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString());
 
                        if (temp == null)
                        {
                            dataRes = new DelFileOrDirResponseAllData { errorMessageBase = "网关错误回复,且数据是空" };
                        }
                        else
                        {
                            dataRes = new DelFileOrDirResponseAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) };
                        }
                    }
 
                    if (topic == gatewayID + "/" + "FileTransfer/DelFileOrDir_Respon")
                    {
                        var resultDelFileOrDir = Newtonsoft.Json.JsonConvert.DeserializeObject<DelFileOrDirResponseData>(jobject["Data"].ToString());
                        if (resultDelFileOrDir != null)
                        {
                            dataRes = new DelFileOrDirResponseAllData { delFileOrDirResponseData = resultDelFileOrDir };
                            DebugPrintLog($"UI收到通知后的主题_{ topic}");
                        }
                        else
                        {
                            dataRes = new DelFileOrDirResponseAllData { errorMessageBase = "收到的网关返回数据是空" };
                        }
                    }
                };
                Actions += action;
                DebugPrintLog("FileTransfer/DelFileOrDir_Actions 启动" + System.DateTime.Now.ToString());
 
                try
                {
                    var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 3005 } };
                    var data = new JObject { { "Path", path } };
                    jObject.Add("Data", data);
                    Send(("FileTransfer/DelFileOrDir"), jObject.ToString());
                }
                catch { }
 
                var dateTime = DateTime.Now;
                while ((DateTime.Now - dateTime).TotalMilliseconds < WaitReceiveDataTime)
                {
                    await System.Threading.Tasks.Task.Delay(10);
                    if (dataRes != null)
                    {
                        break;
                    }
                }
                if ((DateTime.Now - dateTime).TotalMilliseconds > WaitReceiveDataTime)
                {
                    dataRes = new DelFileOrDirResponseAllData { errorMessageBase = " 回复超时,请重新操作" };
                };
                Actions -= action;
                DebugPrintLog("FileTransfer/DelFileOrDir_Actions 退出" + System.DateTime.Now.ToString());
                return dataRes;
            });
        }
        #endregion
 
        #region 创建一个目录.
        /// <summary>
        /// 创建一个目录
        /// </summary>
        /// <returns>The admin password async.</returns>
        /// <param name="path">删除目录或文件的路径。如:/tmp/,则删除tmp目录。/tmp/aa.txt,则删除tmp目录下的aa.txt文件。 </param>
        public async System.Threading.Tasks.Task<CreateDirResponseAllData> CreateDirAsync(string path = "/etc/hdlDat")
        {
            return await System.Threading.Tasks.Task.Run(async () =>
            {
                CreateDirResponseAllData dataRes = null;
 
                Action<string, string> action = (topic, message) =>
                {
                    var gatewayID = topic.Split('/')[0];
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
 
                    if (topic == gatewayID + "/" + "Error_Respon")
                    {
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString());
 
                        if (temp == null)
                        {
                            dataRes = new CreateDirResponseAllData { errorMessageBase = "网关错误回复,且数据是空" };
                        }
                        else
                        {
                            dataRes = new CreateDirResponseAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) };
                        }
                    }
 
                    if (topic == gatewayID + "/" + "FileTransfer/CreateDir_Respon")
                    {
                        var resultCreateDir = Newtonsoft.Json.JsonConvert.DeserializeObject<CreateDirResponseData>(jobject["Data"].ToString());
                        if (resultCreateDir != null)
                        {
                            dataRes = new CreateDirResponseAllData { createDirResponseData = resultCreateDir };
                            DebugPrintLog($"UI收到通知后的主题_{ topic}");
                        }
                        else
                        {
                            dataRes = new CreateDirResponseAllData { errorMessageBase = "收到的网关返回数据是空" };
                        }
                    }
                };
                Actions += action;
                DebugPrintLog("FileTransfer/CreateDir_Actions 启动" + System.DateTime.Now.ToString());
                try
                {
                    var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 3006 } };
                    var data = new JObject { { "Path", path } };
                    jObject.Add("Data", data);
                    Send(("FileTransfer/CreateDir"), jObject.ToString());
                }
                catch { }
 
                var dateTime = DateTime.Now;
                while ((DateTime.Now - dateTime).TotalMilliseconds < WaitReceiveDataTime)
                {
                    await System.Threading.Tasks.Task.Delay(10);
                    if (dataRes != null)
                    {
                        break;
                    }
                }
                if ((DateTime.Now - dateTime).TotalMilliseconds > WaitReceiveDataTime)
                {
                    dataRes = new CreateDirResponseAllData { errorMessageBase = " 回复超时,请重新操作" };
                };
                Actions -= action;
                DebugPrintLog("FileTransfer/CreateDir_Actions 退出" + System.DateTime.Now.ToString());
                return dataRes;
            });
        }
        #endregion
 
        #region 客户端发送密钥到网关
        ///<summary >
        /// 客户端发送DES密钥到网关
        /// <para>DES密钥经RSA公钥加密转成base64后所得的字符串信息</para>
        /// </summary>
        public async System.Threading.Tasks.Task<SendKeyResponData> SendAesKeyAsync(string aesKey)
        {
            return await System.Threading.Tasks.Task.Run(async () =>
            {
                SendKeyResponData sendKeyResponData = null;
                Action<string, string> action = (topic, message) =>
                {
                    var gatewayID = topic.Split('/')[0];
 
                    if (topic == gatewayID + "/" + "SendAESKey_Respon")
                    {
                        var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
                        var result = Newtonsoft.Json.JsonConvert.DeserializeObject<int>(jobject["Data"]["Result"].ToString());
                        sendKeyResponData = new SendKeyResponData { Result = result };
                        DebugPrintLog($"UI收到通知后的主题_{ topic}");
                    }
                };
 
                Actions += action;
                DebugPrintLog($"SendAESKey_Actions 启动_{System.DateTime.Now.ToString()}");
 
                try
                {
                    var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 100 } };
                    var data = new JObject { { "AesKey", aesKey } };
                    jObject.Add("Data", data);
                    Send(("SendAESKey"), jObject.ToString());
                }
                catch { }
 
                var dateTime = DateTime.Now;
                while ((DateTime.Now - dateTime).TotalMilliseconds < WaitReceiveDataTime)
                {
                    await System.Threading.Tasks.Task.Delay(10);
                    if (sendKeyResponData != null)
                    {
                        break;
                    }
                }
 
                Actions -= action;
                DebugPrintLog($"SendAESKey_Actions 退出_{System.DateTime.Now.ToString()}");
                return sendKeyResponData;
            });
        }
 
 
        #endregion
        #endregion
 
        #region 设备状态更新
        /// <summary>
        /// 设备状态监听列表
        /// <para>进入当前界面时要添加</para>
        /// <para>退出当前界面时要关闭</para>
        /// </summary>
        public static readonly List<IStatus> StatusList = new List<IStatus>();
 
        /// <summary>
        /// 设备信息变化
        /// <para>type:如果为 DeviceInComingRespon:设备新上报</para>
        /// <para>type:如果为 IASInfoReport:RemoveDeviceRespon</para>
        /// <para>type:如果为 DeviceStatusReport:设备上报</para>
        /// <para>type:如果为 IASInfoReport:IAS安防信息上报</para>
        /// <para>type:如果为 OnlineStatusChange: 设备在线状态更新</para>
        /// </summary>
        /// <param name="commonDevice">Common device.</param>
        public static void UpdateDeviceInfo(CommonDevice commonDevice, string type)
        {
            if (commonDevice == null)
            {
                return;
            }
            for (int i = 0; i < StatusList.Count; i++)
            {
                StatusList[i].DeviceInfoChange(commonDevice, type);
            }
        }
        #endregion
 
        #region 本地通讯连接
        /// <summary>
        /// 本地连接是否连接成功
        /// </summary>
        [Newtonsoft.Json.JsonIgnore]
        public bool LocalIsConnected;
        /// <summary>
        /// 局域网的MQTT
        /// </summary>
        private IMqttClient localMqttClient = new MqttFactory().CreateMqttClient();
        /// <summary>
        /// 本地mqtt是否正在连接中
        /// </summary>
        private bool localMqttIsConnecting;
        /// <summary>
        /// 本地连接的一个客户端ID(app启动之后就不变了)
        /// </summary>
        private static Guid LocalConnectGuid = Guid.NewGuid();
 
        public async Task SendAesKey()
        {
            if (PubKey != null)
            {
                IsEncry = false;
                var rsaString = ZigBee.Common.SecuritySet.RSAEncrypt(PubKey, Password);
                var resultVerityfy = await SendAesKeyAsync(rsaString);
                if (resultVerityfy == null)
                {
                    resultVerityfy = await SendAesKeyAsync(rsaString);
                }
 
                if (resultVerityfy != null && resultVerityfy.Result == 0)
                {
                    IsEncry = true;
                }
            }
        }
 
        public async Task StartLocalMqtt(string brokerName)
        {
            if (localMqttIsConnecting
                || Shared.Common.Config.Instance.HomeId == ""
                || LocalIsConnected)
            {
                return;
            }
            await Task.Factory.StartNew(async () =>
            {
                try
                {
                    lock (localMqttClient)
                    {
                        //表示后面将进行连接
                        localMqttIsConnecting = true;
 
                        //(3)当[连接Mqtt成功后]或者[Mqtt转发数据给网关成功后],处理接收到数据包响应时在mqttClient_ApplicationMessageReceived这个方法处理
                        if (localMqttClient.ApplicationMessageReceivedHandler == null)
                        {
                            localMqttClient.UseApplicationMessageReceivedHandler((e) =>
                                {
                                    if (!localMqttClient.IsConnected)
                                    {
                                        return;
                                    }
                                    mqttClient_MqttMsgPublishReceived(e);
                                });
                        }
 
                        if (localMqttClient.DisconnectedHandler == null)
                        {
                            localMqttClient.UseDisconnectedHandler(async (e) =>
                            {
                                DebugPrintLog($" 本地连接断开_网关IP:{brokerName}_网关是否加:{IsEncry}");
                                await DisConnectLocalMqttClient("StartLocalMqtt.DisconnectedHandler");
                                //await StartLocalMqtt("ReConnect");
                            });
                        }
                        if (localMqttClient.ConnectedHandler == null)
                        {
                            localMqttClient.UseConnectedHandler(async (e) =>
                            {
                                DebugPrintLog($" 本地连接成功_网关IP:{brokerName}_网关是否加:{IsEncry}_当前密码:{Password}");
                                IsRemote = false;
                                //Log写入(调试用)
                                if (Shared.Phone.HdlUserCenterResourse.HideOption.WriteSendAndReceveDataToFile == 1)
                                {
                                    Shared.Phone.HdlLogLogic.Current.WriteLog(2, "本地连接成功");
                                }
                            });
                        }
 
                        var dateTime = DateTime.Now;
 
                        new System.Threading.Thread(async () =>
                        {
                            try
                            {
                                if (localMqttClient.Options == null)
                                {
                                    var options = new MQTTnet.Client.Options.MqttClientOptionsBuilder()//MQTT连接参数填充
                                    .WithClientId(LocalConnectGuid.ToString())//客户端ID
                                    .WithTcpServer(brokerName, 1883)//TCP服务端  1883  ,即MQTT服务端
                                    .WithCredentials("", "")//"", "")//凭证  帐号 密码
                                    .WithCommunicationTimeout(new TimeSpan(0, 0, 60)) //重连超时时间,默认5s
                                    .WithKeepAlivePeriod(new TimeSpan(0, 0, 15)) //保持连接时间,默认5s,心跳包
                                    .Build();//
                                    await localMqttClient.ConnectAsync(options);
                                }
                                else
                                {
                                    await DisConnectLocalMqttClient("StartLocalMqtt");
                                    await localMqttClient.ReconnectAsync();
                                }
                                LocalIsConnected = true;
                                await SendAesKey();
                            }
                            catch { }
                            dateTime = DateTime.MinValue;
                        })
                        { IsBackground = true }.Start();
                        while (dateTime != DateTime.MinValue)
                        {
                            System.Threading.Thread.Sleep(100);
                        }
                    }
                }
                catch (Exception ex)
                {
                    //Log写入(调试用)
                    if (Shared.Phone.HdlUserCenterResourse.HideOption.WriteSendAndReceveDataToFile == 1)
                    {
                        Shared.Phone.HdlLogLogic.Current.WriteLog(2, "本地连接异常:\r\n" + ex.Message);
                    }
                    DebugPrintLog($"局域网通讯连接出异常:{ex.Message}");
                }
                finally
                {
                    localMqttIsConnecting = false;
                }
            });
        }
 
        /// <summary>
        /// 断开服务器连接
        /// </summary>
        public async Task DisConnectLocalMqttClient(string s)
        {
            try
            {
                if (LocalIsConnected)
                {
                    LocalIsConnected = false;
                    //这个东西也要弄
                    localMqttIsConnecting = false;
                    DebugPrintLog($"Local主动断开_{s}");
                    //await localMqttClient.DisconnectAsync(new MQTTnet.Client.Disconnecting.MqttClientDisconnectOptions {  }, CancellationToken.None);
                    await localMqttClient.DisconnectAsync();
                }
            }
            catch (Exception ex)
            {
                DebugPrintLog($"Local断开通讯连接出异常:{ex.Message}");
            }
        }
 
        /// <summary>
        /// 强制断开本地的网关连接
        /// </summary>
        public async Task CloseLocalConnectionOnForce()
        {
            try
            {
                await localMqttClient.DisconnectAsync();
            }
            catch { }
            finally
            {
                LocalIsConnected = false;
                //这个东西也要弄
                localMqttIsConnecting = false;
            }
        }
 
        #endregion
 
        #region 远程通讯连接
 
        /// <summary>
        /// 当前有帐号下所有的云端网关列表及信息
        /// </summary>
        public static Dictionary<string, Shared.Phone.GatewayResult> DicGatewayBaseInfo = new Dictionary<string, Shared.Phone.GatewayResult> { };
        /// <summary>
        /// 外网的MQTT是否正在连接
        /// </summary>
        private static bool remoteMqttIsConnecting;
        /// <summary>
        /// 远程MqttClient
        /// </summary>
        public static IMqttClient RemoteMqttClient = new MqttFactory().CreateMqttClient();
        /// <summary>
        /// 远程连接是否完成
        /// </summary>
        private static bool remoteIsConnected;
        /// <summary>
        /// 远程开始连接的时间点
        /// </summary>
        private static DateTime RemoteConnectTime = DateTime.Now;
 
        /// <summary>
        /// 启动远程Mqtt
        /// </summary>
        public static async Task StartRemoteMqtt()
        {
            //追加:没有远程连接的权限
            if (Config.Instance.Home.IsRemoteControl == false
               || Config.Instance.Home.Id == ""
               || remoteIsConnected)
            {
                return;
            }
            //如果远程还在连接中
            if (remoteMqttIsConnecting == true)
            {
                //如果这个变量一直处于连接中的状态,但是已经过去了10秒了,还是true的话,说明这里是有点问题的,需要重新创建
                if ((DateTime.Now - RemoteConnectTime).TotalMilliseconds < 10 * 1000)
                {
                    return;
                }
            }
            //记录起这次远程连接的时间点
            RemoteConnectTime = DateTime.Now;
 
            //初始化远程mqtt事件
            InitRemoteMqttEvent();
 
            try
            {
                //获取远程mqtt链接信息
                var pra = new { attachClientId = RemoteClientId, homeType = "ZIGBEE" };
                var result = Shared.Phone.HdlHttpLogic.Current.RequestResponseFromZigbeeHttps("home-wisdom/app/mqtt/getRemoteInfo", RestSharp.Method.POST, pra);
                if (result != null && result.Code == Shared.Phone.HttpMessageEnum.A成功)
                {
                    var jobject = JObject.Parse(result.Data.ToString());
 
                    var connEmqClientId = jobject["clientId"]?.ToString();
                    var connEmqUserName = jobject["userName"]?.ToString();
                    var connEmqPwd = jobject["passWord"]?.ToString();
                    //记录起当前的客户端ID
                    Config.Instance.ConnEmqClientId = connEmqClientId;
 
                    var connEmqDomainPorts = jobject["url"].ToString().Replace("//", "").Split(':');
                    var domain = connEmqDomainPorts[1];
                    var port = connEmqDomainPorts[2];
 
                    var options = new MQTTnet.Client.Options.MqttClientOptionsBuilder()
                      .WithClientId(connEmqClientId)
                      .WithTcpServer(domain, int.Parse(port))
                      .WithCredentials(connEmqUserName, connEmqPwd)
                      .WithKeepAlivePeriod(TimeSpan.FromSeconds(20))
                      .WithCleanSession()
                      .Build();
                    await DisConnectRemoteMqttClient("StartRemoteMqtt");
                    await RemoteMqttClient.ConnectAsync(options, CancellationToken.None);
 
                    remoteIsConnected = true;
                }
            }
            catch { }
            finally
            {
                //最终要释放连接状态
                remoteMqttIsConnecting = false;
            }
        }
 
        /// <summary>
        /// 初始化远程mqtt事件
        /// </summary>
        private static void InitRemoteMqttEvent()
        {
            lock (RemoteMqttClient)
            {
                //表示后面将进行连接
                remoteMqttIsConnecting = true;
 
                //(3)当[连接云端的Mqtt成功后]或者[以及后面App通过云端Mqtt转发数据给网关成功后],处理接收到云端数据包响应时在mqttServerClient_ApplicationMessageReceived这个方法处理
                if (RemoteMqttClient.ApplicationMessageReceivedHandler == null)
                {
                    RemoteMqttClient.UseApplicationMessageReceivedHandler((e) =>
                    {
                        //这里是特殊的主题
                        if (e.ApplicationMessage.Topic == "/ZigbeeGateWayToClient/" + Config.Instance.ConnEmqClientId + "/Push/NotifySqueeze"//踢人下线
                           || e.ApplicationMessage.Topic == "/ZigbeeGateWayToClient/" + Config.Instance.Guid + "/Push/Deleted"//分享删除
                           || e.ApplicationMessage.Topic == "/ZigbeeGateWayToClient/" + Config.Instance.Guid + "/Push/DeletedShareData"//分享删除
                           || e.ApplicationMessage.Topic == "/ZigbeeGateWayToClient/" + Config.Instance.Guid + "/Push/Update"//成员权限变更
                           || e.ApplicationMessage.Topic == "/ZigbeeGateWayToClient/" + Config.Instance.Home.Id + "_" + Config.Instance.Guid + "/PrimaryUserDelYou")//子账号被删除
                        {
                            mqttRemoteClient_MqttMsgPublishReceived(e);
                            return;
                        }
                        if (!RemoteMqttClient.IsConnected || !IsRemote)
                        {
                            return;
                        }
                        mqttRemoteClient_MqttMsgPublishReceived(e);
                    });
                }
 
                if (RemoteMqttClient.DisconnectedHandler == null)
                {
                    RemoteMqttClient.UseDisconnectedHandler(async (e) =>
                    {
                        DebugPrintLog($"远程连接断开");
                        await DisConnectRemoteMqttClient("StartRemoteMqtt.DisconnectedHandler");
                    });
                }
 
                if (RemoteMqttClient.ConnectedHandler == null)
                {
                    RemoteMqttClient.UseConnectedHandler(async (e) =>
                    {
                        DebugPrintLog($"远程连接成功");
 
                        if (Config.Instance.Home.IsOtherShare == true)
                        {
                            //订阅一个成员被删除的主题
                            string myGuid = Config.Instance.Guid;
                            await RemoteMqttClient.SubscribeAsync("/ZigbeeGateWayToClient/" + myGuid + "/Push/Deleted");
                            //订阅一个分享数据已经变更的主题
                            await RemoteMqttClient.SubscribeAsync("/ZigbeeGateWayToClient/" + myGuid + "/Push/DeletedShareData");
                            //订阅一个子账号被删除的主题
                            await RemoteMqttClient.SubscribeAsync("/ZigbeeGateWayToClient/" + Config.Instance.Home.Id + "_" + myGuid + "/PrimaryUserDelYou");
                            //订阅一个成员权限已经变更的主题
                            await RemoteMqttClient.SubscribeAsync("/ZigbeeGateWayToClient/" + myGuid + "/Push/Update");
                        }
                        //订阅一个挤下线的主题
                        await RemoteMqttClient.SubscribeAsync("/ZigbeeGateWayToClient/" + Config.Instance.ConnEmqClientId + "/Push/NotifySqueeze");
 
                        //如果这个函数卡久了的话,会接收到云端推送的挤下线主题,不知道为什么
                        new System.Threading.Thread(async () =>
                        {
                            await InitGateWayBaseInfomation();
 
                            //没有主网关时主动读取,获取主网关信息
                            var gateWayList = GateWayList.FindAll(obj => obj.HomeId == Shared.Common.Config.Instance.HomeId);
                            if (gateWayList.Find(obj => obj.IsMainGateWay == true) == null)
                            {
                                if (gateWayList.Count == 1)
                                {
                                    gateWayList[0].IsMainGateWay = true;
                                }
                                else
                                {
                                    for (int i = 0; i < gateWayList.Count; i++)
                                    {
                                        var gateWay = gateWayList[i];
                                        var info = await gateWay.GetZbGwInfoAsync();
                                        if (info == null || info.getGwData == null)
                                        {
                                            continue;
                                        }
                                        if (info.getGwData.IsDominant == 1)
                                        {
                                            for (int j = 0; j < gateWayList.Count; j++)
                                            {
                                                if (gateWayList[i].GwId == info.getGwData.GwId)
                                                {
                                                    gateWayList[i].IsMainGateWay = true;
                                                }
                                                else
                                                {
                                                    gateWayList[i].IsMainGateWay = false;
                                                }
                                            }
                                            break;
                                        }
                                    }
                                }
                            }
                        })
                        { IsBackground = true }.Start();
                    });
                }
            }
        }
 
        /// <summary>
        /// 初始化当前帐号所有的云端网关信息
        /// </summary>
        /// <returns></returns>
        private static async Task InitGateWayBaseInfomation()
        {
            if (Config.Instance.Home.IsRemoteControl == false)
            {
                //没有远程连接的权限
                return;
            }
            //获取云端网关信息
            var listGatewayInfo = Shared.Phone.HdlGatewayLogic.Current.GetGateWayListFromDataBase(Config.Instance.Home.Id);
            if (listGatewayInfo == null) { return; }
 
            foreach (var info in listGatewayInfo.Values)
            {
                try
                {
                    //有可能云端是这么处理:如果没有远程权限,则不给AesKey
                    if (string.IsNullOrEmpty(info.AesKey) == true) { continue; }
                    //保存缓存
                    DicGatewayBaseInfo[info.Mac] = info;
                    //我也不知道这个是干嘛的
                    await RemoteMqttClient.SubscribeAsync($"/ZigbeeGateWayToClient/" + info.Id + "/#", MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce);
                }
                catch (Exception ex)
                {
                    Shared.Phone.HdlLogLogic.Current.WriteLog(ex);
                }
            }
        }
 
        /// <summary>
        /// 断开远程Mqtt的链接
        /// </summary>
        public static async Task DisConnectRemoteMqttClient(string s = "")
        {
            try
            {
                if (remoteIsConnected)
                {
                    remoteIsConnected = false;
                    //这个东西也要弄
                    remoteMqttIsConnecting = false;
                    DebugPrintLog($"Remote主动断开_{s}");
                    //await RemoteMqttClient.DisconnectAsync(new MQTTnet.Client.Disconnecting.MqttClientDisconnectOptions { }, CancellationToken.None);
                    await RemoteMqttClient.DisconnectAsync();
                }
            }
            catch (Exception e)
            {
                DebugPrintLog($"Remote断开通讯连接出异常:{e.Message}");
            }
        }
 
        /// <summary>
        /// 强制断开远程Mqtt的链接
        /// </summary>
        /// <returns></returns>
        public static async Task CloseRemoteConnectionOnForce()
        {
            try
            {
                await RemoteMqttClient?.DisconnectAsync();
            }
            catch { }
            finally
            {
                remoteIsConnected = false;
                //这个东西也要弄
                remoteMqttIsConnecting = false;
            }
        }
 
        #endregion
 
        #region 数据发送
 
        /// <summary>
        /// 发送消息到服务器
        /// </summary>
        /// <returns>The send.</returns>
        /// <param name="topic">Topic.</param>
        /// <param name="cluster_ID">Cluster identifier.</param>
        /// <param name="commnand">Commnand.</param>
        /// <param name="message">Message.</param>
        public void Send(string topic, Cluster_ID cluster_ID, Command commnand, Newtonsoft.Json.Linq.JObject message = null)
        {
            var jObject = new Newtonsoft.Json.Linq.JObject() {
                                    {
                    "Cluster_ID", (int)cluster_ID },
                                    {
                    "Command", (int)commnand }
            };
            if (message != null)
            {
                jObject.Add("Data", message);
            }
            Send(topic, System.Text.Encoding.UTF8.GetBytes(jObject.ToString()));
        }
 
        /// <summary>
        /// 远程发送数据格式
        /// </summary>
        async System.Threading.Tasks.Task SendRemoteMsg(string topicName, byte[] message, bool retain = false)
        {
            try
            {
                if (this.GwId == string.Empty || !DicGatewayBaseInfo.ContainsKey(this.GwId))
                {
                    return;
                }
                var gateWayBaseInfomation = DicGatewayBaseInfo[this.GwId];
                message = SecuritySet.AesEncryptBytes(message, gateWayBaseInfomation.AesKey);
                var topicEncStr = $"/ClientToZigbeeGateWay/{gateWayBaseInfomation.Id}/Common/{topicName}";
                //(6)构建Mqtt需要发布的数据包,发布给云端的MqttBroker
                if (remoteIsConnected)
                {
                    try
                    {
                        await RemoteMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topicEncStr, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce });
                    }
                    catch (Exception e)
                    {
                        await DisConnectRemoteMqttClient(e.Message);
                        await StartRemoteMqtt();
                        if (remoteIsConnected)
                        {
                            await RemoteMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topicEncStr, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce });
                        }
                    }
                }
            }
            catch
            {
            }
        }
 
        /// <summary>
        /// 发送消息到服务器
        /// </summary>
        /// <returns></returns>
        /// <param name="topic"></param>
        /// <param name="message"></param>
        /// <param name="retain"></param>
        public async System.Threading.Tasks.Task Send(string topic, byte[] message, bool retain = false)
        {
            try
            {
                if (Shared.Common.Config.Instance.HomeId == "")
                {
                    return;
                }
 
                //Log写入(调试用)
                if (Shared.Phone.HdlUserCenterResourse.HideOption.WriteSendAndReceveDataToFile == 1)
                {
                    string text = "远程发送:";
                    if (IsRemote == false) { text = "本地发送:"; }
                    text += topic + "\r\n";
                    text += Encoding.UTF8.GetString(message) + "\r\n";
                    Shared.Phone.HdlLogLogic.Current.WriteLog(2, text);
                }
 
                if (IsRemote)
                {
                    await SendRemoteMsg(topic, message, retain);
                    DebugPrintLog($"远程——发送到网关的主题:{topic}_发送到网关的数据:{System.Text.Encoding.UTF8.GetString(message)}");//{System.DateTime.Now.ToString()}");// DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")
                }
                else
                {
                    DebugPrintLog($"局域网——发送到网关的主题:{topic}_发送到网关的数据:{System.Text.Encoding.UTF8.GetString(message)}_是否加密:{IsEncry}");
 
                    if (IsEncry)
                    {
                        //文件流不用加密
                        if (topic != "FileTransfer/SendFile")
                        {
                            message = SecuritySet.AesEncryptBytes(message, password);
                        }
                    }
                    if (LocalIsConnected)
                    {
                        try
                        {
                            await localMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topic, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce, Retain = retain });
                        }
                        catch (Exception e)
                        {
                            DebugPrintLog($"Local主动断开_{e.Message}");
                            await DisConnectLocalMqttClient(e.Message);
                            await StartLocalMqtt("ReConnect");
                            if (LocalIsConnected)
                            {
                                DebugPrintLog($"局域网——二次发送到网关的主题:{topic}_发送到网关的数据:{System.Text.Encoding.UTF8.GetString(message)}_是否加密:{IsEncry}");
                                await localMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topic, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce, Retain = retain });
                            }
                            //Log写入(调试用)
                            if (Shared.Phone.HdlUserCenterResourse.HideOption.WriteSendAndReceveDataToFile == 1)
                            {
                                Shared.Phone.HdlLogLogic.Current.WriteLog(2, "本地连接异常断开");
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                DebugPrintLog($"Send:{ex.Message}");
            }
        }
 
        /// <summary>
        /// 发送消息到服务器
        /// </summary>
        /// <returns></returns>
        /// <param name="topic"></param>
        /// <param name="message"></param>
        /// <param name="retain"></param>
        public async System.Threading.Tasks.Task Send(string topic, string message, bool retain = false)
        {
            if (string.IsNullOrEmpty(message))
            {
                return;
            }
            await Send(topic, System.Text.Encoding.UTF8.GetBytes(message), retain);
        }
 
        /// <summary>
        /// 强制指定使用本地局域网发送消息到服务器
        /// </summary>
        /// <returns></returns>
        /// <param name="topic"></param>
        /// <param name="message"></param>
        /// <param name="retain"></param>
        public async Task SendLocation(string topic, byte[] message, bool retain = false)
        {
            try
            {
                if (Shared.Common.Config.Instance.HomeId == "")
                {
                    return;
                }
 
                DebugPrintLog($"局域网——发送到网关的主题:{topic}_发送到网关的数据:{System.Text.Encoding.UTF8.GetString(message)}_是否加密:{IsEncry}");
 
                if (IsEncry)
                {
                    //文件流不用加密
                    if (topic != "FileTransfer/SendFile")
                    {
                        message = SecuritySet.AesEncryptBytes(message, password);
                    }
                }
                if (LocalIsConnected)
                {
                    try
                    {
                        await localMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topic, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce, Retain = retain });
                    }
                    catch (Exception e)
                    {
                        DebugPrintLog($"Local主动断开_{e.Message}");
                        await DisConnectLocalMqttClient(e.Message);
                        await StartLocalMqtt("ReConnect");
                        if (LocalIsConnected)
                        {
                            DebugPrintLog($"局域网——二次发送到网关的主题:{topic}_发送到网关的数据:{System.Text.Encoding.UTF8.GetString(message)}_是否加密:{IsEncry}");
                            await localMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topic, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce, Retain = retain });
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                DebugPrintLog($"Send:{ex.Message}");
            }
        }
 
        #endregion
 
        #region 数据接收处理
 
        /// <summary>
        /// 接收远程数据处理
        /// </summary>
        /// <param name="sender">Sender.</param>
        /// <param name="e">E.</param>
        static void mqttRemoteClient_MqttMsgPublishReceived(MqttApplicationMessageReceivedEventArgs e)
        {
            try
            {
                var topic = e.ApplicationMessage.Topic.TrimStart('/');
                var payload = e.ApplicationMessage.Payload;
 
                var message = string.Empty;
                //你当前的IP及端口在云端不存在,请重新登录连接下!
 
                var topics = topic.Split("/");
                if (topics.Length < 3)
                {
                    return;
                }
                if (topics[0] != "ZigbeeGateWayToClient")
                {
                    return;
                }
                if (topics[2] == "NotifyGateWayInfoChange")
                {
                    InitGateWayBaseInfomation();
                    return;
                }
                if (topics[2] == "Common")
                {
                    var macMark = topics[1];
                    topic = topic.Substring(topics[0].Length + topics[1].Length + topics[2].Length + 3);
                    if (payload[0] == (byte)'{' && payload[payload.Length - 1] == (byte)'}')
                    {
                        message = System.Text.Encoding.UTF8.GetString(payload);
                    }
                    else
                    {
                        foreach (var key in DicGatewayBaseInfo.Keys)
                        {
                            var value = DicGatewayBaseInfo[key];
                            if (value.Id == macMark)
                            {
                                topic = $"{key}/{topic}";
                                message = System.Text.Encoding.UTF8.GetString(ZigBee.Common.SecuritySet.AesDecryptBytes(e.ApplicationMessage.Payload, value.AesKey));
                                break;
                            }
                        }
                    }
                }
 
                DebugPrintLog($"远程返回的主题:{ topic}_远程返回的数据_{message}");//{System.DateTime.Now.ToString()}");// DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")
 
                ReceiveMessage(topic, message, payload);
            }
            catch (Exception ex)
            {
                DebugPrintLog($"接收云端数据异常:{ex.Message} ");
            }
        }
 
        /// <summary>
        /// 接收局域网中的数据
        /// 当订阅消息成功后,该事件会被调用
        /// </summary>
        /// <param name="sender">Sender.</param>
        /// <param name="e">E.</param>
        void mqttClient_MqttMsgPublishReceived(MqttApplicationMessageReceivedEventArgs e)
        {
            try
            {
                var topic = e.ApplicationMessage.Topic;
                string payloadString = "";
 
                if (IsEncry)
                {
                    //主题
                    //下载的字节流不需要解密
                    if (topic.Split('/')[0] + "/" + topic.Split('/')[1] == topic.Split('/')[0] + "/" + "FileTransfer")
                    {
                        if (topic.Split('/')[2] != "DownloadFile")
                        {
                            payloadString = System.Text.Encoding.UTF8.GetString(Common.SecuritySet.AesDecryptBytes(e.ApplicationMessage.Payload, Password));
                        }
                    }
                    else if (topic == topic.Split('/')[0] + "/" + "SendAESKey_Respon") { }//回复主题是秘文,数据是明文
                    else
                    {
                        payloadString = System.Text.Encoding.UTF8.GetString(Common.SecuritySet.AesDecryptBytes(e.ApplicationMessage.Payload, Password));
                    }
                }
                else
                {
                    payloadString = System.Text.Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
                }
                DebugPrintLog($"网关返回的主题:{topic}_网关返回的负载:{payloadString}");
                ReceiveMessage(topic, payloadString, e.ApplicationMessage.Payload);
            }
            catch (Exception ex)
            {
                DebugPrintLog($"接收网关数据异常:{ex.Message}");
            }
        }
 
        /// <summary>
        /// 数据接收处理
        /// </summary>
        /// <param name="topic">Topic.</param>
        /// <param name="message">Message.</param>
        /// <param name="e">E.</param>
        static void ReceiveMessage(string topic, string message, byte[] payload)
        {
            try
            {
                if (string.IsNullOrEmpty(message))
                {
                    message = "{}";
                }
                var gatewayID = topic.Split('/')[0];//网关返回的网关ID
                var reportStatus = "";
                reportStatus = topic.Split('/')[1];//主题为设备上报的主题
                string addr = "";//上报的设备addr
                string epoint = "";//上报的设备epoint
                string cluID = "";//上报的设备cluID
                string attrId = "";//上报的设备attrId
                if (reportStatus == "DeviceStatusReport")
                {
                    addr = topic.Split('/')[2];
                    epoint = topic.Split('/')[3];
                    cluID = topic.Split('/')[4];
                    attrId = topic.Split('/')[5];
                }
 
                //Log写入(调试用)
                if (Shared.Phone.HdlUserCenterResourse.HideOption.WriteSendAndReceveDataToFile == 1)
                {
                    string text = "网关回复:" + topic + "\r\n";
                    text += message + "\r\n";
                    Shared.Phone.HdlLogLogic.Current.WriteLog(2, text);
                }
 
                //全局接收网关推送的的逻辑(为了执行速度,尽可能的别加耗时的操作)
                Shared.Phone.HdlGatewayReceiveLogic.Current.GatewayOverallMsgReceive(gatewayID, topic, reportStatus, message);
 
                var gwa = GateWayList.Find(obj => obj.GwId == gatewayID);
                if (gwa == null)
                {
                    return;
                }
 
                if (gwa.Actions != null)
                {
                    gwa?.Actions(topic, message);
                }
 
                gwa.GwResDataAction?.Invoke(topic, message);
 
                var jobject = new Newtonsoft.Json.Linq.JObject();
                if (topic.Split('/')[0] + "/" + topic.Split('/')[1] == topic.Split('/')[0] + "/" + "FileTransfer")
                {
                    if (topic.Split('/')[2] == "DownloadFile")
                    {
                        gwa.DownloadFileConfirmAsync(payload);
                        message = System.Text.Encoding.UTF8.GetString(payload);
                        gwa.FileContentAction?.Invoke(topic, payload);
                        DebugPrintLog($"网关返回数据流_{message}");
                        return;
                    }
                }
                else
                {
                    jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
                }
 
                #region 远程,主网关上报通知
                if (IsRemote)
                {
                    if (topic == gatewayID + "/" + "BeMainGw_Report")
                    {
                        var gwData = Newtonsoft.Json.JsonConvert.DeserializeObject<ZbGateway.GetGwData>(jobject["Data"].ToString());
                        if (gwData != null)
                        {
                            var gwList = GateWayList.FindAll(obj => obj.HomeId == Shared.Common.Config.Instance.HomeId);
                            for (int i = 0; i < gwList.Count; i++)
                            {
                                if (gwList[i].GwId == gatewayID)
                                {
                                    gwList[i].IsMainGateWay = true;
                                }
                                else
                                {
                                    gwList[i].IsMainGateWay = false;
                                }
                            }
                        }
                    }
                }
 
                #endregion
 
                #region 设备在线状态更新反馈
 
                //2020.05.11 删除
 
                #endregion
 
                #region 设备状态上报
                if (topic == gatewayID + "/" + "DeviceStatusReport" + "/" + addr + "/" + epoint + "/" + cluID + "/" + attrId)
                {
                    var deviceID = jobject.Value<int>("Device_ID");
                    var deviceAddr = jobject.Value<string>("DeviceAddr");
                    var tempEpoint = jobject.Value<int>("Epoint");
                    var dataId = jobject.Value<int>("Data_ID");
 
                    var tempDevice = new CommonDevice { DeviceID = deviceID, DeviceAddr = deviceAddr, DeviceEpoint = tempEpoint };
                    tempDevice.DeviceStatusReport = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.DeviceStatusReportData>(jobject["Data"].ToString());
                    UpdateDeviceInfo(tempDevice, "DeviceStatusReport");
                }
                #endregion
                #region 门锁操作事件通知
                else if (topic == gatewayID + "/" + "DoorLock/DoorLockOperatingEventNotificationCommand")
                {
                    var deviceID = jobject.Value<int>("Device_ID");
                    switch ((DeviceType)(deviceID))
                    {
                        case DeviceType.DoorLock:
                            var doorLock = new DoorLock() { DeviceID = jobject.Value<int>("Device_ID"), DeviceAddr = jobject.Value<string>("DeviceAddr"), DeviceEpoint = jobject.Value<int>("Epoint"), CurrentGateWayId = gwa.GwId };
                            var OperatingEventNotificationDatad = Newtonsoft.Json.JsonConvert.DeserializeObject<ZigBee.Device.DoorLock.DoorLockOperatingEventNotificationCommand>(jobject["Data"].ToString());
                            if (OperatingEventNotificationDatad != null)
                            {
                                doorLock.doorLockOperatingEventNotificationCommand = OperatingEventNotificationDatad;
                            }
                            if (gwa.ReportAction != null)
                            {
                                DebugPrintLog("DoorLockProgrammingEventNotificationCommand已经通知");
                                gwa.ReportAction("DoorLockProgrammingEventNotificationCommand", doorLock);
                            }
                            UpdateDeviceInfo(doorLock, "DoorLockProgrammingEventNotificationCommand");
                            break;
                    }
                }
                #endregion
                #region 门锁编程事件通知
                else if (topic == gatewayID + "/" + "DoorLock/DoorLockProgrammingEventNotificationCommand")
                {
                    var deviceID = jobject.Value<int>("Device_ID");
                    switch ((DeviceType)(deviceID))
                    {
                        case DeviceType.DoorLock:
                            var doorLock = new DoorLock() { DeviceID = jobject.Value<int>("Device_ID"), DeviceAddr = jobject.Value<string>("DeviceAddr"), DeviceEpoint = jobject.Value<int>("Epoint"), CurrentGateWayId = gwa.GwId };
                            var ProgrammingEventNotificationData = Newtonsoft.Json.JsonConvert.DeserializeObject<ZigBee.Device.DoorLock.DoorLockProgrammingEventNotificationCommand>(jobject["Data"].ToString());
                            if (ProgrammingEventNotificationData != null)
                            {
                                doorLock.doorLockProgrammingEventNotificationCommand = ProgrammingEventNotificationData;
                            }
                            if (gwa.ReportAction != null)
                            {
                                DebugPrintLog("DoorLockProgrammingEventNotificationCommand已经通知");
                                gwa.ReportAction("DoorLockProgrammingEventNotificationCommand", doorLock);
                            }
                            UpdateDeviceInfo(doorLock, "DoorLockProgrammingEventNotificationCommand");
                            break;
                    }
                }
                #endregion
                #region IAS安防信息上报
 
                //2020.05.11 删除
 
                #endregion
                #region 下载进度上报
                else if (topic == gatewayID + "/" + "DownloadFile_Progress")
                {
                    gwa.downloadFileProgressResponData = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.DownloadFileProgressResponData>(jobject["Data"].ToString());
                    if (gwa.downloadFileProgressResponData == null)
                    {
                        return;
                    }
                    //上报类型通知
                    if (gwa.ReportAction != null)
                    {
                        DebugPrintLog("DownloadFileProgress");
                        gwa.ReportAction("DownloadFileProgress", gwa);
                    }
                }
                else if (topic == gatewayID + "/" + "ZbGwOperation/Upgrade_Respon")
                {
                    gwa.zbGwOperationUpgradeData = Newtonsoft.Json.JsonConvert.DeserializeObject<ZbGwOperationUpgradeData>(jobject["Data"].ToString());
                    if (gwa.zbGwOperationUpgradeData == null)
                    {
                        return;
                    }
                    //上报类型通知
                    if (gwa.ReportAction != null)
                    {
                        DebugPrintLog("协调器升级百分比");
                        gwa.ReportAction("CordinatorUpgradePercent", gwa);
                    }
                }
                else if (topic == gatewayID + "/" + "OTA/Schedule_Respon")
                {
                    gwa.oTAScheduleResponData = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.OTAScheduleResponData>(jobject["Data"].ToString());
 
                    if (gwa.oTAScheduleResponData == null)
                    {
                        return;
                    }
 
                    //上报类型通知
                    if (gwa.ReportAction != null)
                    {
                        DebugPrintLog("节点设备升级百分比");
                        gwa.ReportAction("DeviceUpgradePercent", gwa);
                    }
                }
                else if (topic == gatewayID + "/" + "VirtualDrive/Upgrade_Respon")
                {
                    gwa.virtualDriveUpgradeResponData = Newtonsoft.Json.JsonConvert.DeserializeObject<VirtualDriveUpgradeResponData>(jobject["Data"].ToString());
 
                    if (gwa.virtualDriveUpgradeResponData == null)
                    {
                        return;
                    }
                    //上报类型通知
                    if (gwa.ReportAction != null)
                    {
                        DebugPrintLog("虚拟驱动升级百分比");
                        gwa.ReportAction("VirtualDriveUpgrade", gwa);
                    }
                }
                #endregion
                #region 重启网关系统
                else if (topic == gatewayID + "/" + "GwReboot_Respon")
                {
                    var gwRebootResponData = Newtonsoft.Json.JsonConvert.DeserializeObject<GwRebootResponData>(jobject["Data"].ToString());
 
                    if (gwRebootResponData == null)
                    {
                        return;
                    }
                    //上报类型通知
                    if (gwa.ReportAction != null)
                    {
                        DebugPrintLog("GwReboot_Respon已经通知");
                        gwa.ReportAction("GwReboot_Respon", gwRebootResponData);
                    }
                }
                #endregion
                #region 防区被触发时报告
                else if (topic == gatewayID + "/" + "Security/ZoneTriggerReport")
                {
                    var ias = new Safeguard() { DataID = jobject.Value<int>("Data_ID"), GateWayId = gwa.GwId };
                    ias.zoneTriggerReportData = Newtonsoft.Json.JsonConvert.DeserializeObject<Safeguard.ZoneTriggerReportData>(jobject["Data"].ToString());
 
                    if (ias.zoneTriggerReportData == null)
                    {
                        return;
                    }
                    //上报类型通知
                    if (gwa.ReportAction != null)
                    {
                        DebugPrintLog("ZoneTriggerReport已经通知");
                        gwa.ReportAction("ZoneTriggerReport", ias.zoneTriggerReportData);
                    }
                }
                #endregion
                #region 逻辑被调用反馈
                else if (topic == gatewayID + "/" + "Logic/Execute_Respon")
                {
                    //var logic = new Logic() { DataID = jobject.Value<int>("Data_ID"), GateWayId = gwa.GwId };
                    //logic.logicExecuteRespo = Newtonsoft.Json.JsonConvert.DeserializeObject<Logic.ExecuteResponse>(jobject["Data"].ToString());
 
                    //if (logic.logicExecuteRespo == null)
                    //{
                    //    return;
                    //}
                    ////上报类型通知
                    //if (gwa.ReportAction != null)
                    //{
                    //    DebugPrintLog("LogicExecuteReport已经通知");
                    //    gwa.ReportAction("LogicExecuteReport", logic.logicExecuteRespo);
                    //}
                }
                #endregion
                #region 时间点条件推迟执行
                else if (topic == gatewayID + "/" + "Logic/TimingWillArrive")
                {
                    //var logic = new Logic() { DataID = jobject.Value<int>("Data_ID"), GateWayId = gwa.GwId };
                    //logic.timingWillArriveData = Newtonsoft.Json.JsonConvert.DeserializeObject<Logic.TimingWillArriveData>(jobject["Data"].ToString());
 
                    //if (logic.timingWillArriveData == null)
                    //{
                    //    return;
                    //}
                    ////上报类型通知
                    //if (gwa.ReportAction != null)
                    //{
                    //    DebugPrintLog("TimingWillArrive已经通知");
                    //    gwa.ReportAction("TimingWillArrive", logic.timingWillArriveData);
                    //}
                }
                #endregion
                #region 模式安防动作被最终激活时发送报警信息
                else if (topic == gatewayID + "/" + "Security/ModeTriggerReport")
                {
                    var ias = new Safeguard() { DataID = jobject.Value<int>("Data_ID"), GateWayId = gwa.GwId };
                    ias.modeTriggerReportData = Newtonsoft.Json.JsonConvert.DeserializeObject<Safeguard.ModeTriggerReportData>(jobject["Data"].ToString());
                    if (ias.modeTriggerReportData == null)
                    {
                        return;
                    }
                    //上报类型通知
                    if (gwa.ReportAction != null)
                    {
                        DebugPrintLog("ModeTriggerReport已经通知");
                        gwa.ReportAction("ModeTriggerReport", ias.modeTriggerReportData);
                    }
                }
                #endregion
                #region 通过外部方式布防撤防成功时报告息
                else if (topic == gatewayID + "/" + "Security/EnOrWithdrawSucceedReport")
                {
                    var ias = new Safeguard() { DataID = jobject.Value<int>("Data_ID"), GateWayId = gwa.GwId };
                    ias.enOrWithdrawSucceedReportData = Newtonsoft.Json.JsonConvert.DeserializeObject<Safeguard.EnOrWithdrawSucceedReportData>(jobject["Data"].ToString());
                    if (ias.enOrWithdrawSucceedReportData == null)
                    {
                        return;
                    }
                    //上报类型通知
                    if (gwa.ReportAction != null)
                    {
                        DebugPrintLog("EnOrWithdrawSucceedReport");
                        gwa.ReportAction("EnOrWithdrawSucceedReport", ias.enOrWithdrawSucceedReportData);
                    }
                }
                #endregion
                #region 胁迫密码撤防时短信推送
                else if (topic == gatewayID + "/" + "Security/PushTargetInfo")
                {
                    var ias = new Safeguard() { DataID = jobject.Value<int>("Data_ID"), GateWayId = gwa.GwId };
                    ias.coercedPWDWithdrawReportData = Newtonsoft.Json.JsonConvert.DeserializeObject<Safeguard.CoercedPWDWithdrawReportData>(jobject["Data"].ToString());
                    if (ias.coercedPWDWithdrawReportData == null)
                    {
                        return;
                    }
                    //上报类型通知
                    if (gwa.ReportAction != null)
                    {
                        DebugPrintLog("PushTargetInfoReport");
                        gwa.ReportAction("PushTargetInfoReport", ias.coercedPWDWithdrawReportData);
                    }
                }
                #endregion
 
                #region 设备请求APP获取升级数据
                else if (topic == gatewayID + "/" + "ZbDataPassthrough")
                {
                    //上报类型通知
                    if (gwa.ReportAction != null)
                    {
                        var clientDataPassthrough = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ClientDataPassthroughResponseData>(jobject["Data"].ToString());
                        if (clientDataPassthrough != null)
                        {
                            DebugPrintLog("DeviceRequestAcUpdateData");
                            gwa.ReportAction("DeviceRequestAcUpdateData", clientDataPassthrough);
                        }
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                DebugPrintLog($"处理回复的数据抛出异常:{ex.Message}");
            }
 
        }
 
        #endregion
 
        #region 保存缓存
 
        /// <summary>
        /// 重新保存设备
        /// </summary>
        public void ReSave()
        {
            if (Shared.Common.Config.Instance.Home.IsShowTemplate == true)
            {
                //展示模板时,不允许保存文件(防止属性上报用的)
                return;
            }
            Global.WriteFileByBytesByHomeId(FilePath, System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(this)));
        }
        #endregion
 
        #region 调试打印
 
        /// <summary>
        /// 调试时打开打印信息,true:打印,false:不打印
        /// </summary>
        /// <param name="msg">Message.</param>
        /// <param name="flage">If set to <c>true</c> flage.</param>
        public static void DebugPrintLog(string msg, bool flage = true)
        {
#if DEBUG
            if (flage == true)
            {
                //if (msg.Contains("DeviceInfoRespon") == true)
                {
                    System.Console.WriteLine(msg + "  " + System.DateTime.Now.ToLongTimeString() + " " + System.DateTime.Now.Millisecond);
                }
            }
#endif
        }
 
        #endregion
    }
}