JLChen
2020-06-04 6d55af8792cf8fbef0055e677b900fc352dba9a2
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
using System;
using System.Collections.Generic;
using System.Text;
using Shared;
using Shared.SimpleControl.Phone;
using Shared.SimpleControl.R;
using SmartHome.UI.SimpleControl.Phone.Music;
using System.Xml;
using System.Security;
using com.hdl.on;
using SmartHome;
 
namespace Shared.SimpleControl.Phone.Music
{
    class MyMusic : FrameLayout
    {
        public override void RemoveFromParent ()
        {
            UserMiddle.DevicePageView.ScrollEnabled = true;
            base.RemoveFromParent ();
            clearA31Threads ();
            clearOldThreads ();
        }
 
        /// <summary>
        /// 加载所有音乐的滑动视图
        /// </summary>
        MusicVerticalScrolViewLayout verticalScrolViewLayout;
 
        string openWeb (string url)
        {
            try {
                var webClient = new Shared.Net.MyWebClient (2000);
                return webClient.DownloadString (url);
            } catch (Exception e) {
                System.Console.WriteLine (e.Message);
                return null;
            }
        }
 
        static List<System.Threading.Thread> threadLists = new List<System.Threading.Thread> ();
 
        static void clearA31Threads ()
        {
            var threads = threadLists.FindAll ((obj) => { return obj.Name == "A31"; });
            foreach (var thread in threads) {
                try {
                    threadLists.Remove (thread);
                    if (thread.IsAlive) {
                        thread.Abort ();
                    }
                } catch (Exception e) {
                    System.Console.WriteLine (e.Message);
                }
            }
        }
 
        static void clearOldThreads ()
        {
            var threads = threadLists.FindAll ((obj) => { return obj.Name == "Old"; });
            foreach (var thread in threads) {
                try {
                    threadLists.Remove (thread);
                    thread.Abort ();
                } catch (Exception e) {
                    System.Console.WriteLine (e.Message);
                }
            }
        }
 
        public void Show (bool reload)
        {
            UserMiddle.DevicePageView.ScrollEnabled = false;
 
            BackgroundColor = 0xff2F2F2F;
            var tTopFrameLayout = new FrameLayout {
                Height = Application.GetRealHeight (36),
                BackgroundColor = SkinStyle.Current.MusicTopFrameLayout,
            };
            AddChidren (tTopFrameLayout);
 
            var topFrameLayout = new FrameLayout {
                Height = Application.GetRealHeight (100),
                Y = tTopFrameLayout.Bottom,
                BackgroundColor = SkinStyle.Current.MusicTopFrameLayout,
            };
            AddChidren (topFrameLayout);
 
            #region   总音量控制层
            /*
            var bottomFrameLayout = new FrameLayout {
                Height = Application.GetRealHeight (134),
                Y = topFrameLayout.Bottom,
                BackgroundColor = 0xFF181818,
            };
            //AddChidren (bottomFrameLayout);
 
            var voiceVol = new Button {
                Width = Application.GetRealWidth (107),
                Height = Application.GetRealHeight (127),
                X = Application.GetRealWidth (-3),
                Gravity = Gravity.CenterVertical,
                UnSelectedImagePath = "MusicIcon/PlayVoice.png",
            };
            bottomFrameLayout.AddChidren (voiceVol);
 
            var frameLayoutVol = new FrameLayout {
                Width = Application.GetRealWidth (450),
                Height = Application.GetRealHeight (50),
                X = Application.GetRealWidth (90),
                Gravity = Gravity.CenterVertical,
            };
            bottomFrameLayout.AddChidren (frameLayoutVol);
 
            allVol = new HorizontalSeekBar {
                Width = Application.GetRealWidth (450 - 45),
                Height = Application.GetRealHeight (50),
                Radius = (uint)Application.GetRealHeight (25),
                X = Application.GetRealWidth (13),
                Max = 100,
                Progress = 50,
                SleepTime = 1000,
                ProgressColor = 0xffFE5E00,
            };
            frameLayoutVol.AddChidren (allVol);
            allVol.ProgressChanged += allVol_ProgressChanged;
 
            muteVol = new Button {
                Width = Application.GetRealWidth (107),
                Height = Application.GetRealWidth (127),
                X = Application.GetRealWidth (515),
                Gravity = Gravity.CenterVertical,
                UnSelectedImagePath = "MusicIcon/PlayMute.png",
                SelectedImagePath = "MusicIcon/PlayMuteSelected.png",
            };
            bottomFrameLayout.AddChidren (muteVol);
            muteVol.MouseDownEventHandler += MuteVol_MouseDownEventHandler;
 
            var line = new Button {
                Height = Application.GetRealHeight (4),
                Y = topFrameLayout.Bottom,
                UnSelectedImagePath = "MusicIcon/MusicThread.png",
            };
            //AddChidren (line);
            */
            #endregion
 
            FrameLayout frayout = new FrameLayout {
                Width = LayoutParams.MatchParent,
                Height = Application.GetRealHeight (1000),
                BackgroundImagePath = "MusicIcon/MusicBackgroun.png",
                Y = topFrameLayout.Bottom,
            };
            AddChidren (frayout);
 
            verticalScrolViewLayout = new MusicVerticalScrolViewLayout ();
 
            verticalScrolViewLayout.ReplaceChanged += (arg1, arg2) => {
                var d = true;
                if (arg1.Tag.GetType () == typeof (A31MusicModel) && arg2.Tag.GetType () == typeof (A31MusicModel)) {
                    MainPage.Loading.Start (Language.StringByID (MyInternationalizationString.disposition) + "...");
                    System.Threading.Tasks.Task.Run (() => {
                        try {
                            var serverMusic = arg1.Tag as A31MusicModel;
                            var clientMusic = arg2.Tag as A31MusicModel;
 
                            if (clientMusic.ServerClientType == 1) {
                                d = false;
                                return;
                            }
                            if (serverMusic.ServerClientType == -1 && clientMusic.ServerClientType == -1) {
                                if (serverMusic.ServerIP == clientMusic.ServerIP) {
                                    d = false;
                                    return;
                                }
                            }
 
                            if (serverMusic.ServerClientType == 1 && clientMusic.ServerClientType == -1) {
                                if (serverMusic.IPAddress == clientMusic.ServerIP) {
                                    d = false;
                                    return;
                                }
                            }
 
                            clearA31Threads ();
                            var IP = "";
                            if (serverMusic.ServerClientType == -1) {
                                IP = serverMusic.ServerIP;
                            } else {
                                IP = serverMusic.IPAddress;
                            }
 
                            var statusEx = openWeb ("http://" + IP + "/httpapi.asp?command=getStatusEx");
                            if (statusEx == null) {
                                statusEx = openWeb ("http://" + IP + "/httpapi.asp?command=getStatusEx");
                            }
                            if (statusEx == null) {
                                return;
                            }
                            var serverIfon = Newtonsoft.Json.JsonConvert.DeserializeObject<a31wifi> (statusEx);
                            if (serverIfon == null) {
                                return;
                            }
                            string ssid = "";
                            foreach (var b in serverIfon.ssid) {
                                ssid += System.Convert.ToString (b, 16).ToUpper ().Length < 2 ? "0" + System.Convert.ToString (b, 16).ToUpper () : System.Convert.ToString (b, 16).ToUpper ();
                            }
 
                            System.Threading.Thread.Sleep (1000);
                            if (null == openWeb ("http://" + clientMusic.IPAddress + "/httpapi.asp?command=ConnectMasterAp:ssid=" + ssid + ":ch=" + serverIfon.WifiChannel + ":auth=OPEN:encry=NONE:pwd=:chext=0:JoinGroupMaster:eth" + serverIfon.eth2 + ":wifi" + serverIfon.ra0 + ":uuid" + serverIfon.uuid)) {
                                if (null == openWeb ("http://" + clientMusic.IPAddress + "/httpapi.asp?command=ConnectMasterAp:ssid=" + ssid + ":ch=" + serverIfon.WifiChannel + ":auth=OPEN:encry=NONE:pwd=:chext=0:JoinGroupMaster:eth" + serverIfon.eth2 + ":wifi" + serverIfon.ra0 + ":uuid" + serverIfon.uuid)) {
                                    return;
                                }
                            }
                            System.DateTime dateTime = DateTime.Now;
                            while ((DateTime.Now - dateTime).TotalSeconds < 10) {
                                System.Threading.Thread.Sleep (1000);
                                try {
                                    var result = openWeb ("http://" + serverMusic.IPAddress + "/httpapi.asp?command=multiroom:getSlaveList");
                                    if (result != null) {
                                        var tmepSlaves = Newtonsoft.Json.JsonConvert.DeserializeObject<Slaves> (result);
                                        if (tmepSlaves != null && tmepSlaves.slave_list != null) {
                                            if (null != tmepSlaves.slave_list.Find ((obj) => obj.uuid.Replace ("uuid:", "") == clientMusic.UniqueDeviceName)) {
                                                //已经添加成功
                                                break;
                                            }
                                        }
                                    }
                                } catch (Exception e) { System.Console.WriteLine (e.Message); }
                            }
 
                        } catch (Exception e) { System.Console.WriteLine (e.Message); } finally {
                            Application.RunOnMainThread (() => {
                                MainPage.Loading.Hide ();
                                if (d) {
                                    //this.RemoveFromParent ();
                                    //MyMusic mymusic = new MyMusic ();
                                    //MainPage.MainFrameLayout.AddChidren (mymusic);
                                    //mymusic.Show (true);
 
                                    UserMiddle.DevicePageView.PageIndex = 0;
                                    var myMusic = new MyMusic ();
                                    UserMiddle.DevicePageView.AddChidren (myMusic);
                                    myMusic.Show (true);
                                    UserMiddle.DevicePageView.PageIndex = 1;
 
 
                                }
 
                            });
                        }
                    });
                }
            };
 
            verticalScrolViewLayout.LongPressAction += (arg) => {
 
                if (arg.Tag.GetType () == typeof (A31MusicModel)) {
                    var clientMusic = arg.Tag as A31MusicModel;
                    if (clientMusic != null && clientMusic.ServerClientType == -1) {
                        MainPage.Loading.Start ();
                        System.Threading.Tasks.Task.Run (() => {
                            openWeb ("http://" + clientMusic.ServerIP + "/httpapi.asp?command=multiroom:SlaveKickout:" + clientMusic.IPAddress);
                            Application.RunOnMainThread (() => {
                                MainPage.Loading.Hide ();
                                //this.RemoveFromParent ();
                                //MyMusic music = new MyMusic ();
                                //MainPage.MainFrameLayout.AddChidren (music);
                                //music.Show (true);
 
                                UserMiddle.DevicePageView.PageIndex = 0;
                                var myMusic = new MyMusic ();
                                UserMiddle.DevicePageView.AddChidren (myMusic);
                                myMusic.Show (true);
                                UserMiddle.DevicePageView.PageIndex = 1;
 
                            });
                        });
                    }
                }
            };
            frayout.AddChidren (verticalScrolViewLayout);
 
            var back = new Button {
                Width = Application.GetMinRealAverage (72),
                Height = Application.GetMinRealAverage (89),
                X = Application.GetRealWidth (-1),
                Gravity = Gravity.CenterVertical,
                UnSelectedImagePath = "MusicIcon/MusicBack.png",
            };
            topFrameLayout.AddChidren (back);
            back.MouseDownEventHandler += back_MouseDownEventHandler;
 
            var wifi = new Button {
                Width = Application.GetMinRealAverage (50),
                Height = Application.GetMinRealAverage (50),
                UnSelectedImagePath = "MusicIcon/wifi.png",
                //UnSelectedImagePath = "MusicIcon/set.png",
                X = Application.GetRealWidth (450),
                Gravity = Gravity.CenterVertical,
            };
            topFrameLayout.AddChidren (wifi);
            wifi.MouseUpEventHandler += (sender, e) => {
                var wifiSet = new WiFiSet ();
                MainPage.MainFrameLayout.AddChidren (wifiSet);
                wifiSet.Show ();
                MainPage.Loading.Start (Language.StringByID (MyInternationalizationString.load));
                System.Threading.Tasks.Task.Run (() => {
                    Application.RunOnMainThread (() => {
                        MainPage.Loading.Hide ();
                        wifiSet.Init ();
                    });
                });
            };
 
            var device = new Button {
                Width = Application.GetRealWidth (200),
                Height = Application.GetRealHeight (60),
                TextID = MyInternationalizationString.MusicDevicelist,
                Gravity = Gravity.Center,
                TextColor = SkinStyle.Current.MusicTextColor,
            };
            topFrameLayout.AddChidren (device);
 
            var a31search = new Button {
                Width = Application.GetMinRealAverage (60),
                Height = Application.GetMinRealAverage (80),
                X = Application.GetRealWidth (545),
                Gravity = Gravity.CenterVertical,
                UnSelectedImagePath = "MusicIcon/seekdevice.png",
            };
            topFrameLayout.AddChidren (a31search);
            a31search.MouseUpEventHandler += (sender, e) => {
                //RemoveFromParent ();
                //MyMusic mymusic = new MyMusic ();
                //MainPage.MainFrameLayout.AddChidren (mymusic);
                //mymusic.Show (true);
 
                UserMiddle.DevicePageView.PageIndex = 0;
                var myMusic = new MyMusic ();
                UserMiddle.DevicePageView.AddChidren (myMusic);
                myMusic.Show (true);
                UserMiddle.DevicePageView.PageIndex = 1;
 
            };
            initOldMusic (verticalScrolViewLayout);
 
            if (reload || A31MusicModel.A31MusicModelList.Count == 0) {
                refreshDevice (verticalScrolViewLayout);
            } else {
                clearA31Threads ();
                for (int i = 0; i < A31MusicModel.A31MusicModelList.Count; i++) {
                    var a31player = A31MusicModel.A31MusicModelList [i];
                    ///这个状态是之前保存的,加载完成后要标记为不在线,后面再读取正确的状态
                    if (!a31player.IsCanShow) {
                        continue;
                    }
                    if (a31player.ServerClientType == 1) {
                        if (a31player.Slave != null && "0" != a31player.Slave.slaves) {
                            for (int j = 0; j < a31player.Slave.slave_list.Count; j++) {
                                ///最后一个从播放器
                                if (a31player.Slave.slave_list.Count - 1 == j) {
                                    var tempA31Player = A31MusicModel.A31MusicModelList.Find ((obj) => a31player.Slave.slave_list [j].uuid.Replace ("uuid:", "") == obj.UniqueDeviceName);
                                    if (tempA31Player != null) {
                                        ///标记从播放器最后一个
                                        if (!tempA31Player.IsEnd) {
                                            tempA31Player.IsEnd = true;
                                        }
                                    }
                                }
                            }
                        }
                    }
 
                    ///加载界面时默认不在线
                    a31player.IsOnLine = false;
                    addViews (a31player);
                }
                ///读取正确的信息,包括IP和端口及名称
                seach ((obj) => {
                    try {
                        if (obj == null) {
                            ///这里要读取主从关系
                            readServerOrClientMode (false);
                            A31MusicModel.Save ();
                            return;
                        }
                        var a31MusicModel = A31MusicModel.A31MusicModelList.Find ((music) => music.UniqueDeviceName == obj.UniqueDeviceName);
                        if (a31MusicModel != null) {
                            a31MusicModel.IPAddress = obj.IPAddress;
                            a31MusicModel.Port = obj.Port;
                            a31MusicModel.Name = obj.Name;
                            a31MusicModel.IsCanShow = true;
                            a31MusicModel.IsOnLine = true;
                        }
                    } catch (Exception e) { System.Console.WriteLine (e.Message); }
                });
            }
        }
        ///旧音乐
        void initOldMusic (MusicVerticalScrolViewLayout verticalScrolViewLayout)
        {
            foreach (Room room in Room.Lists) {
                var musiceList = room.DeviceList.FindAll (tempDevice => { return tempDevice.Type == DeviceType.MusicModel; });
                foreach (var tempDevice in musiceList) {
 
                    var MusicModelBackground = new FrameLayout {
                        Width = Application.GetRealWidth (640 - 24),
                        Height = Application.GetRealHeight (190 + 20),
                        X = Application.GetRealWidth (12),
                        Y = verticalScrolViewLayout.ChildrenCount * Application.GetRealHeight (190 + 20),
                        Tag = tempDevice,
                    };
                    verticalScrolViewLayout.AddChidren (MusicModelBackground);
 
                    var frameLayout = new FrameLayout {
                        // Y = Application.GetRealHeight (20) + verticalScrolViewLayout.ChildrenCount * Application.GetRealHeight (190 + 20),
                        Y = Application.GetRealHeight (20),
                        X = Application.GetRealWidth (12),
                        Width = Application.GetRealWidth (640 - 24),
                        Height = Application.GetRealHeight (190),
                        BackgroundColor = SkinStyle.Current.MusicPalyerView,//0xff181818,
                        //Radius = (uint)Application.GetRealHeight (10),
                        Tag = tempDevice,
                    };
                    MusicModelBackground.AddChidren (frameLayout);
 
                    var titelFrameLayout = new FrameLayout () {
                        Height = Application.GetRealHeight (80),
                        Y = Application.GetRealHeight (3),
                    };
                    frameLayout.AddChidren (titelFrameLayout);
 
                    var Living = new Button {
                        Width = Application.GetRealWidth (300),
                        Height = Application.GetRealHeight (80),
                        Text = tempDevice.Name,
                        TextAlignment = TextAlignment.CenterLeft,
                        X = Application.GetRealWidth (29),
                        Gravity = Gravity.CenterVertical,
                        TextColor = SkinStyle.Current.MusicTextColor,
                    };
                    titelFrameLayout.AddChidren (Living);
 
                    var btnPlayMusic = new Button {
                        Width = Application.GetRealWidth (80),
                        Height = Application.GetRealHeight (80),
                        X = Application.GetRealWidth (515),//510
                        Gravity = Gravity.CenterVertical,
                        UnSelectedImagePath = "MusicIcon/MusicPlay.png",
                        SelectedImagePath = "MusicIcon/MusicPlaySelected.png",
                        Tag = tempDevice,
                    };
                    titelFrameLayout.AddChidren (btnPlayMusic);
                    btnPlayMusic.MouseUpEventHandler += (sender, e) => {
                        Button button = (Button)sender;
                        MusicModel musicModel = (MusicModel)button.Tag;
                        if (button.IsSelected) {
                            button.IsSelected = false;
                            if (musicModel.MusicType == 2) {
                                Control.ControlBytesSend (Command.ControlMusicModel, musicModel.SubnetID, musicModel.DeviceID, MusicModel.MusiceBytes ("*Z1OFF"));
                            } else {
                                Control.ControlBytesSend (Command.ControlMusicModel, musicModel.SubnetID, musicModel.DeviceID, MusicModel.MusiceBytes ("*S" + musicModel.SourceID + "PLAYSTOP"));
 
                            }
                        } else {
                            button.IsSelected = true;
                            if (musicModel.MusicType == 2) {
                                Control.ControlBytesSend (Command.ControlMusicModel, musicModel.SubnetID, musicModel.DeviceID, MusicModel.MusiceBytes ("*Z1ON"));
                            } else {
                                Control.ControlBytesSend (Command.ControlMusicModel, musicModel.SubnetID, musicModel.DeviceID, MusicModel.MusiceBytes ("*S" + musicModel.SourceID + "PLAYSTOP"));
 
                            }
 
                        }
 
                    };
 
                    var image = new Button {
                        Width = Application.GetRealWidth (80),
                        Height = Application.GetRealHeight (80),
                        X = Application.GetRealWidth (30),
                        UnSelectedImagePath = "MusicIcon/musicplay1.png",
                        Y = Application.GetRealHeight (220 - 130),
                        Tag = tempDevice,
                    };
                    frameLayout.AddChidren (image);
 
                    var currentMusic = new Button {
                        Width = Application.GetRealWidth (300),
                        Height = Application.GetRealHeight (50),
                        X = Application.GetRealWidth (135),
                        Y = Application.GetRealHeight (210 - 130),
                        Text = "UnKown",
                        Tag = tempDevice,
                        TextSize = 12,
                        TextAlignment = TextAlignment.CenterLeft,
                        TextColor = SkinStyle.Current.MusicTextColor,
                    };
                    frameLayout.AddChidren (currentMusic);
 
                    EventHandler<MouseEventArgs> CurrentPlayPage = (sender, e) => {
                        Room.CurrentRoom = room;
                        //Button button = (Button)sender;
                        Button button = image;
                        if (((MusicModel)button.Tag).SourceID == "5") {
                            RadioPage radioPage = new RadioPage ();
                            MainPage.MainFrameLayout.AddChidren (radioPage);
                            radioPage.Show ((MusicModel)button.Tag);
                        } else {
                            PlayPage playMusic = new PlayPage ();
                            MainPage.MainFrameLayout.AddChidren (playMusic);
                            playMusic.Show ((MusicModel)button.Tag, (button.Tag as MusicModel).SDCardSongList);
                        }
                    };
                    image.MouseUpEventHandler += CurrentPlayPage;
                    currentMusic.MouseUpEventHandler += CurrentPlayPage;
                    Living.MouseUpEventHandler += CurrentPlayPage;
 
 
                    var voice = new Button {
                        Width = Application.GetRealWidth (33),
                        Height = Application.GetRealHeight (31),
                        X = Application.GetRealWidth (145),
                        Y = Application.GetRealHeight (275 - 130),
                        UnSelectedImagePath = "MusicIcon/MusicVoice.png",
                    };
                    frameLayout.AddChidren (voice);
 
                    var horizontalSeekBarvol = new HorizontalSeekBar {
                        Width = Application.GetRealWidth (380),
                        Height = Application.GetRealHeight (50),
                        Radius = (uint)Application.GetRealHeight (25),
                        Y = Application.GetRealHeight (275 - 140),
                        X = Application.GetRealWidth (200),
                        Max = tempDevice.GetType () == typeof (MusicModel) ? 79 : 100,
                        Tag = tempDevice,
                        ProgressColor = 0xffFE5E00,
                        ThumbRadius = 9,
                        ThumbColor = SkinStyle.Current.HorizontalSeekBarThumbColor,
                    };
                    frameLayout.AddChidren (horizontalSeekBarvol);
                    horizontalSeekBarvol.ProgressChanged += (sender, e) => {
                        var seekBar = (HorizontalSeekBar)sender;
                        MusicModel musicModel = (MusicModel)(sender as HorizontalSeekBar).Tag;
                        Control.ControlBytesSend (Command.ControlMusicModel, musicModel.SubnetID, musicModel.DeviceID,
                       MusicModel.MusiceBytes ("*Z1VOL" + (79 - seekBar.Progress)));
                    };
 
                    if (tempDevice.Type == DeviceType.MusicModel) {
                        var music = tempDevice as MusicModel;
                        System.Threading.Tasks.Task.Run (() => {
                            System.Threading.Thread.CurrentThread.Name = "Old";
                            threadLists.Add (System.Threading.Thread.CurrentThread);
                            var dateTime = DateTime.Now.AddSeconds (-5);
                            while (true) {
                                if (5 <= (DateTime.Now - dateTime).TotalSeconds) {
                                    dateTime = DateTime.Now;
                                    Control.ControlBytesSend (Command.ControlMusicModel, music.SubnetID, music.DeviceID, MusicModel.MusiceBytes ("*Z1STATUS?"), SendCount.Zero);
                                }
                                Application.RunOnMainThread (() => {
                                    try {
                                        if (music.PlayStatus == MusicModel.Status.Play) {
                                            btnPlayMusic.IsSelected = true;
                                        } else {
                                            btnPlayMusic.IsSelected = false;
                                        }
 
                                        //当前的音乐名称
                                        currentMusic.Text = music.curPlayMusicName.Replace (".mp3", "") == string.Empty ? "UnKown" : music.curPlayMusicName.Replace (".mp3", "");
 
                                        horizontalSeekBarvol.Progress = 79 - int.Parse (music.CurVol);
 
 
                                    } catch (Exception e) {
                                        var d = e.Message;
                                    }
                                });
                                //等待1秒
                                System.Threading.Thread.Sleep (500);
                            }
                        });
                    }
 
                }
            }
        }
        ///搜索A31音乐播放器
        void seach (Action<A31MusicModel> action, int time = 5 * 1000, string uid = "AllUniqueDeviceName")
        {
            System.Threading.Tasks.Task.Run (() => {
                System.Net.Sockets.UdpClient udpClient = null;
                int localPort = 65535;
                for (; 1024 < localPort; localPort--) {
                    try {
                        udpClient = new System.Net.Sockets.UdpClient (localPort);
                        break;
                    } catch (Exception e) { System.Console.WriteLine (e.Message); }
                }
 
                System.Threading.Tasks.Task.Run (() => {
                    var tempDateTime = DateTime.Now;
                    while (udpClient != null) {
                        try {
                            if (time < (DateTime.Now - tempDateTime).TotalMilliseconds) {
                                var tempBytes = System.Text.Encoding.UTF8.GetBytes ("完成");
                                udpClient.Send (tempBytes, tempBytes.Length, new System.Net.IPEndPoint (System.Net.IPAddress.Parse ("127.0.0.1"), localPort));
                            } else {
                                var stringBuilder = new StringBuilder ();
                                stringBuilder.AppendLine ("M-SEARCH * HTTP/1.1");
                                stringBuilder.AppendLine ("St: ssdp:wiimudevice");
                                stringBuilder.AppendLine ("Mx: 3");
                                stringBuilder.AppendLine ("Host: 239.255.255.250:1900");
                                stringBuilder.AppendLine ("Man: \"ssdp:discover\"");
                                stringBuilder.AppendLine ();
                                var tempBytes = System.Text.Encoding.ASCII.GetBytes (stringBuilder.ToString ());
                                //请求获取A31服务器信息
                                udpClient.Send (tempBytes, tempBytes.Length, new System.Net.IPEndPoint (System.Net.IPAddress.Parse ("239.255.255.250"), 1900));
                                udpClient.Send (tempBytes, tempBytes.Length, new System.Net.IPEndPoint (System.Net.IPAddress.Parse ("239.255.255.250"), 1900));
                                //如果1000毫秒没有数据回复,就关闭当前Socket,不再等待接收数据
                            }
                            System.Threading.Thread.Sleep (500);
                        } catch (Exception e) { System.Console.WriteLine (e.Message); }
                    }
                });
                while (true) {
                    try {
                        //接收回来的数据
                        var remoteIpEndPoint = new System.Net.IPEndPoint (0, 0);
                        //开始在这里等待接收数据,
                        var receviceBytes = udpClient.Receive (ref remoteIpEndPoint);
                        if (receviceBytes == null) {
                            break;
                        }
                        if ("完成" == System.Text.Encoding.UTF8.GetString (receviceBytes)) {
                            if (action != null) {
                                //表示完成了
                                action (null);
                            }
                            try {
                                udpClient.Close ();
                                udpClient = null;
                            } catch (Exception e) { System.Console.WriteLine (e.Message); }
                            break;
                        }
 
                        var sr = new System.IO.StreamReader (new System.IO.MemoryStream (receviceBytes, 0, receviceBytes.Length));
                        string tempLine = null;
                        string ipAddress = null;
                        int port = 0;
                        string uniqueDeviceName = null;
                        //一行一行数据判断,找出需要的信息
                        while ((tempLine = sr.ReadLine ()) != null) {
                            //找出Ip地址相关的信息
                            //System.Console.WriteLine (tempLine);
                            if (tempLine.StartsWith ("LOCATION: http://")) {
                                tempLine = tempLine.Replace ("LOCATION: http://", "").Split ('/') [0];
                                string [] ipAndPort = tempLine.Split (':');
                                ipAddress = ipAndPort [0];
                                port = int.Parse (ipAndPort [1]);
                            } else if (tempLine.StartsWith ("USN: uuid:")) {
                                uniqueDeviceName = tempLine.Replace ("USN: uuid:", "").Split (':') [0];
                            }
                        }
                        //关闭流
                        sr.Close ();
 
                        if (action != null) {
                            if ("AllUniqueDeviceName" == uid) {
                                action (new A31MusicModel { IPAddress = ipAddress, Port = port, Name = getDeviceName (ipAddress, port), UniqueDeviceName = uniqueDeviceName });
                            } else if (uid == uniqueDeviceName) {
                                if (action != null) {
                                    //表示完成了
                                    action (null);
                                }
                                try {
                                    udpClient.Close ();
                                    udpClient = null;
                                } catch (Exception e) { System.Console.WriteLine (e.Message); }
                                break;
                            }
                        }
                    } catch (Exception e) { System.Console.WriteLine (e.Message); }
                }
            });
        }
        ///加载界面
        void addViews (A31MusicModel a31player)
        {
            var BackgroundColorfra = new FrameLayout {
                Width = Application.GetRealWidth (640 - 24),
                Height = Application.GetRealHeight (190 + 20),
                X = Application.GetRealWidth (12),
                Y = verticalScrolViewLayout.ChildrenCount * Application.GetRealHeight (190 + 20),
                Tag = a31player,
            };
            verticalScrolViewLayout.AddChidren (BackgroundColorfra);
 
            var a31frameLayout = new FrameLayout {
                //Y = Application.GetRealHeight (20) + verticalScrolViewLayout.ChildrenCount * Application.GetRealHeight (190 + 20),
                Y = Application.GetRealHeight (20),
                X = Application.GetRealWidth (12),
                Width = Application.GetRealWidth (640 - 24),
                Height = Application.GetRealHeight (190),
                //BackgroundColor = 0xff181818,
                BackgroundColor = SkinStyle.Current.MusicPalyerView,
                //Radius = (uint)Application.GetRealHeight (10),
                Tag = a31player,
            };
            BackgroundColorfra.AddChidren (a31frameLayout);
 
            var a31titelFrameLayout = new FrameLayout {
                Height = Application.GetRealHeight (80),
                Y = Application.GetRealHeight (3),
            };
            a31frameLayout.AddChidren (a31titelFrameLayout);
 
            var a31palyername = new Button {
                Width = Application.GetRealWidth (350),
                Height = Application.GetRealHeight (80),
                Text = a31player.Name,
                TextAlignment = TextAlignment.CenterLeft,
                X = Application.GetRealWidth (29),
                Gravity = Gravity.CenterVertical,
                TextColor = SkinStyle.Current.MusicTextColor,
            };
            a31titelFrameLayout.AddChidren (a31palyername);
 
            var colorBtn = new Button {
                Height = LayoutParams.MatchParent,
                Width = Application.GetRealWidth (5),
                BackgroundColor = 0xffFE5E00,
                //Radius = (uint)Application.GetRealHeight (10),
                Visible = false
            };
            a31frameLayout.AddChidren (colorBtn);
 
            var serverOrClientBtn = new Button {
                Width = Application.GetRealWidth (80),
                Height = Application.GetRealHeight (80),
                X = Application.GetRealWidth (410),
                Gravity = Gravity.CenterVertical,
                Visible = false
            };
            serverOrClientBtn.MouseUpEventHandler += (sender, e) => {
                // clearA31Threads ();
                ///解散所有
                /*
                if (a31player.ServerClientType == 1) {
                    var alert = new Alert (Language.StringByID (MyInternationalizationString.prompt), Language.StringByID (MyInternationalizationString.DissolvedGroup),
                              Language.StringByID (MyInternationalizationString.cancel), Language.StringByID (MyInternationalizationString.confirm));
                    alert.ResultEventHandler += (sender1, e1) => {
                        if (e1) {
                            MainPage.Loading.Start ();
                            System.Threading.Tasks.Task.Run (() => {
                                openWeb ("http://" + a31player.IPAddress + "/httpapi.asp?command=multiroom:Ungroup");
                                seach ((obj) => {
                                    Application.RunOnMainThread (() => {
                                        MainPage.Loading.Hide ();
                                        this.RemoveFromParent ();
                                        MyMusic music = new MyMusic ();
                                        MainPage.MainFrameLayout.AddChidren (music);
                                        music.Show (true);
                                    });
                                }, 5000, a31player.UniqueDeviceName);
                            });
                        } else { }
                    };
                    alert.Show ();
                } else if (a31player.ServerClientType == -1) {
                    var alert = new Alert (Language.StringByID (MyInternationalizationString.prompt), Language.StringByID (MyInternationalizationString.Dissolve),
                              Language.StringByID (MyInternationalizationString.cancel), Language.StringByID (MyInternationalizationString.confirm));
                    alert.ResultEventHandler += (sender1, e1) => {
                        if (e1) {
                            MainPage.Loading.Start ();
                            System.Threading.Tasks.Task.Run (() => {
                                openWeb ("http://" + a31player.ServerIP + "/httpapi.asp?command=multiroom:SlaveKickout:" + a31player.IPAddress);
                                seach ((obj) => {
                                    Application.RunOnMainThread (() => {
                                        MainPage.Loading.Hide ();
                                        this.RemoveFromParent ();
                                        MyMusic music = new MyMusic ();
                                        MainPage.MainFrameLayout.AddChidren (music);
                                        music.Show (true);
                                    });
                                }, 5000, a31player.UniqueDeviceName);
                            });
                        } else { }
                    };
                    alert.Show ();
                }
                */
            };
 
            var a31btnPlayMusic = new Button {
                Width = Application.GetMinRealAverage (80),
                Height = Application.GetMinRealAverage (80),
                X = Application.GetRealWidth (518),
                Gravity = Gravity.CenterVertical,
                UnSelectedImagePath = "MusicIcon/MusicPlay.png",
                SelectedImagePath = "MusicIcon/MusicPlaySelected.png",
            };
            a31titelFrameLayout.AddChidren (a31btnPlayMusic);
            a31btnPlayMusic.MouseUpEventHandler += (sender1, e1) => {
                if (a31btnPlayMusic.IsSelected) {
                    a31btnPlayMusic.IsSelected = false;
                    //sendCommand (a31player, "pause");
                    a31player.Pause ();
                    a31player.A31PlayStatus.status = "pause";
                } else {
                    a31btnPlayMusic.IsSelected = true;
                    //sendCommand (a31player, "resume");
                    a31player.Play ();
                    a31player.A31PlayStatus.status = "play";
                }
            };
 
            var a31image = new ImageView {
                Width = Application.GetRealWidth (80),
                Height = Application.GetRealHeight (80),
                X = Application.GetRealWidth (30),
                Y = Application.GetRealHeight (220 - 130),
                Radius = (uint)Application.GetRealHeight (8),
                ImagePath = "MusicIcon/musicplay1.png",
            };
            a31frameLayout.AddChidren (a31image);
            a31image.MouseLongEventHandler += (sender, e) => {
                var alert = new Alert (Language.StringByID (MyInternationalizationString.prompt), Language.StringByID (MyInternationalizationString.Deletemusicplayer),
                                       Language.StringByID (MyInternationalizationString.cancel), Language.StringByID (MyInternationalizationString.confirm));
                alert.ResultEventHandler += (sender1, e1) => {
                    if (e1) {
                        A31MusicModel.A31MusicModelList.Remove (a31player);
                        a31frameLayout.RemoveFromParent ();
                        A31MusicModel.Save ();
 
                        //RemoveFromParent ();
                        //MyMusic mymusic = new MyMusic ();
                        //MainPage.MainFrameLayout.AddChidren (mymusic);
                        //mymusic.Show (true);
 
 
                        UserMiddle.DevicePageView.PageIndex = 0;
                        var myMusic = new MyMusic ();
                        UserMiddle.DevicePageView.AddChidren (myMusic);
                        myMusic.Show (true);
                        UserMiddle.DevicePageView.PageIndex = 1;
 
 
                    } else { }
                };
                alert.Show ();
            };
 
            var a31currentMusic = new Button {
                Width = Application.GetRealWidth (350),
                Height = Application.GetRealHeight (50),
                X = Application.GetRealWidth (135),
                Y = Application.GetRealHeight (190 - 130),
                TextSize = 12,
                TextAlignment = TextAlignment.CenterLeft,
                Text = "UnKown",
                TextColor = SkinStyle.Current.MusicTextColor,
            };
            a31frameLayout.AddChidren (a31currentMusic);
 
            var a31currentartist = new Button {
                Height = Application.GetRealHeight (50),
                X = Application.GetRealWidth (135),
                Y = Application.GetRealHeight (225 - 130),
                TextSize = 12,
                //TextColor = 0x80ffffff,
                TextAlignment = TextAlignment.CenterLeft,
                Text = "UnKown",
                TextColor = SkinStyle.Current.MusicArtistTextColor,
            };
            a31frameLayout.AddChidren (a31currentartist);
 
            EventHandler<MouseEventArgs> sharing = (sender, e) => {
                if (-1 == a31player.ServerClientType) {
                    return;
                }
                A31MusicModel.Current = a31player;
                A31PlayMusicPage a31playMusic = new A31PlayMusicPage ();
                MainPage.MainFrameLayout.AddChidren (a31playMusic);
                a31playMusic.Show (MusicInfo.MusicInfoList);
            };
            a31palyername.MouseUpEventHandler += sharing;
            a31image.MouseUpEventHandler += sharing;
            a31currentMusic.MouseUpEventHandler += sharing;
            a31currentartist.MouseUpEventHandler += sharing;
 
            var a31voice = new Button {
                Width = Application.GetRealWidth (33),
                Height = Application.GetRealHeight (31),
                X = Application.GetRealWidth (135),
                Y = Application.GetRealHeight (275 - 130),
                UnSelectedImagePath = "MusicIcon/MusicVoice.png",
            };
            a31frameLayout.AddChidren (a31voice);
 
            var a31horizontalSeekBarvol = new HorizontalSeekBar {
                Width = Application.GetRealWidth (380),
                Height = Application.GetRealHeight (50),
                Radius = (uint)Application.GetRealHeight (25),
                Y = Application.GetRealHeight (275 - 140),
                X = Application.GetRealWidth (190),
                SleepTime = 1000,
                ProgressColor = 0xffFE5E00,
                ThumbRadius = 9,
                Max = 100,
                ThumbColor = SkinStyle.Current.HorizontalSeekBarThumbColor,
            };
            a31frameLayout.AddChidren (a31horizontalSeekBarvol);
            ///主从显示效果
            if (a31player.ServerClientType == -1) {
                a31frameLayout.X = Application.GetRealWidth (38);
                a31frameLayout.Width = Application.GetRealWidth (640 - 50);
                serverOrClientBtn.X = Application.GetRealWidth (410 - 26);
                a31btnPlayMusic.X = Application.GetRealWidth (518 - 26);
                a31horizontalSeekBarvol.Width = Application.GetRealWidth (380 - 26);
                if (a31player.IsEnd) {
                    a31player.IsEnd = false;
                    var Line1 = new Button {
                        Height = Application.GetRealHeight (115),
                        Width = Application.GetRealWidth (20 + 6 + 5),
                        X = Application.GetRealWidth (12),
                        //Y = Application.GetRealHeight (115),
                        //TextAlignment = TextAlignment.CenterLeft,
                        UnSelectedImagePath = "MusicIcon/line1.png",
                    };
                    BackgroundColorfra.AddChidren (Line1);
                } else {
                    var Line2 = new Button {
                        Height = Application.GetRealHeight (210),
                        Width = Application.GetRealWidth (20 + 6),
                        X = Application.GetRealWidth (12),
                        //TextAlignment = TextAlignment.CenterLeft,
                        UnSelectedImagePath = "MusicIcon/line.png",
                    };
                    BackgroundColorfra.AddChidren (Line2);
                }
            }
 
            a31horizontalSeekBarvol.ProgressChanged += (sender1, e1) => {
                a31player.ControlVolume (a31horizontalSeekBarvol.Progress);
                a31player.A31PlayStatus.vol = a31horizontalSeekBarvol.Progress.ToString ();
            };
            //a31titelFrameLayout.AddChidren (serverOrClientBtn);
 
 
            refreshUI (a31image, a31player, a31horizontalSeekBarvol, a31btnPlayMusic, a31palyername, a31currentMusic, a31currentartist, serverOrClientBtn, a31frameLayout, colorBtn);
 
            System.Threading.Tasks.Task.Run (() => {
                System.Threading.Thread.CurrentThread.Name = "A31";
                threadLists.Add (System.Threading.Thread.CurrentThread);
                string album = null, artist = null;
                while (true) {
                    System.Threading.Thread.Sleep (1000);
                    if (!a31player.IsOnLine) {
                        continue;
                    }
                    readStatus (a31player);
 
                    Application.RunOnMainThread (() => {
                        try {
                            #region    刷新歌手图片
                            if (a31player.A31PlayStatus.Album != album || a31player.A31PlayStatus.Artist != artist) {
                                album = a31player.A31PlayStatus.Album;
                                artist = a31player.A31PlayStatus.Artist;
                                var path = "MusicImage/AlbumArtistImage_";
                                if (Shared.IO.FileUtils.Exists (path + a31player.A31PlayStatus.Album)) {
                                    a31image.ImagePath = path + a31player.A31PlayStatus.Album;
                                } else if (Shared.IO.FileUtils.Exists (path + a31player.A31PlayStatus.Artist)) {
                                    a31image.ImagePath = path + a31player.A31PlayStatus.Artist;
                                } else {
                                    a31image.ImagePath = "MusicIcon/musicplay1.png";
                                    System.Threading.Tasks.Task.Run (() => {
                                        var filePath = Shared.IO.FileUtils.DownLoadImageFormBaidu (album, artist);
                                        if (filePath != null) {
                                            Application.RunOnMainThread (() => {
                                                a31image.ImagePath = filePath;
                                            });
                                        }
                                    });
                                }
                            }
                            #endregion
                        } catch (Exception e) {
                            System.Console.WriteLine (e.Message);
                        }
                        refreshUI (a31image, a31player, a31horizontalSeekBarvol, a31btnPlayMusic, a31palyername, a31currentMusic, a31currentartist, serverOrClientBtn, a31frameLayout, colorBtn);
                    });
                }
            });
        }
 
        /// <summary>
        /// 读取主从关系
        /// </summary>
        void readServerOrClientMode (bool readType)
        {
            try {
                for (int i = 0; i < A31MusicModel.A31MusicModelList.Count; i++) {
                    var a31player = A31MusicModel.A31MusicModelList [i];
                    if (!a31player.IsOnLine) {
                        continue;
                    }
                    try {
                        if (readType) {
                            readMusicType (a31player);
                        }
                        a31player.ServerClientType = 0;
                        var result = openWeb ("http://" + a31player.IPAddress + "/httpapi.asp?command=multiroom:getSlaveList");
                        if (result == null) {
                            result = openWeb ("http://" + a31player.IPAddress + "/httpapi.asp?command=multiroom:getSlaveList");
                        }
                        if (result != null) {
                            a31player.Slave = Newtonsoft.Json.JsonConvert.DeserializeObject<Slaves> (result);
                        }
                    } catch (Exception e) {
                        var d = e.Message;
                    }
                }
 
                //分析主从关系
                for (int i = 0; i < A31MusicModel.A31MusicModelList.Count; i++) {
                    var a31player = A31MusicModel.A31MusicModelList [i];
 
                    if (!a31player.IsOnLine) {
                        continue;
                    }
                    try {
                        if (a31player.Slave != null && "0" != a31player.Slave.slaves) {
                            a31player.ServerClientType = 1;//主的
                            for (int j = 0; j < a31player.Slave.slave_list.Count; j++) {
                                var slave = a31player.Slave.slave_list [j];
                                var tempA31Player = A31MusicModel.A31MusicModelList.Find ((obj) => slave.uuid.Replace ("uuid:", "") == obj.UniqueDeviceName);
                                if (tempA31Player == null) {
                                    A31MusicModel.A31MusicModelList.Add (new A31MusicModel {
                                        ServerClientType = -1,
                                        IPAddress = slave.ip,
                                        ServerIP = a31player.IPAddress,
                                        UniqueDeviceName = slave.uuid.Replace ("uuid:", ""),
                                        Name = slave.name,
                                        IsCanShow = true,//
                                    });
                                }
                                //如果找到就更新为从的
                                else {
                                    tempA31Player.ServerClientType = -1;//从的
                                    tempA31Player.IPAddress = slave.ip;
                                    tempA31Player.ServerIP = a31player.IPAddress;
                                    tempA31Player.Name = slave.name;//
                                    tempA31Player.UniqueDeviceName = slave.uuid.Replace ("uuid:", "");
                                    tempA31Player.IsCanShow = true;
                                }
                            }
                        }
                    } catch (Exception e) {
                        var ss = e.Message;
                    }
                }
 
                #region   重新排列播放器列表顺序.....
                var MusicList = new List<A31MusicModel> ();
                for (int i = 0; i < A31MusicModel.A31MusicModelList.Count; i++) {
                    var music = A31MusicModel.A31MusicModelList [i];
                    if (!music.IsOnLine) {
                        continue;
                    }
                    ///先找出主播放器的,在从主播放器找出从的播放器;
                    if (music.ServerClientType == 1) {
                        MusicList.Add (music);
                        if (music.Slave != null && "0" != music.Slave.slaves) {
                            for (int j = 0; j < music.Slave.slave_list.Count; j++) {
                                var Slave = music.Slave.slave_list [j];
                                var a31MusicModel = A31MusicModel.A31MusicModelList.Find ((obj) => obj.UniqueDeviceName == Slave.uuid.Replace ("uuid:", ""));
                                if (a31MusicModel != null) {
                                    a31MusicModel.ServerClientType = -1;//从的
                                    a31MusicModel.IPAddress = Slave.ip;
                                    a31MusicModel.ServerIP = music.IPAddress;
                                    a31MusicModel.Name = Slave.name;//
                                    a31MusicModel.UniqueDeviceName = Slave.uuid.Replace ("uuid:", "");
                                    a31MusicModel.IsCanShow = true;
                                    MusicList.Add (a31MusicModel);
 
                                    if (music.Slave.slave_list.Count - 1 == j) {
                                        ///标记从播放器最后那个
                                        a31MusicModel.IsEnd = true;
                                    }
                                } else {
                                    MusicList.Add (new A31MusicModel {
                                        ServerClientType = -1,
                                        IPAddress = Slave.ip,
                                        Name = Slave.name,
                                        UniqueDeviceName = Slave.uuid.Replace ("uuid:", ""),
                                        ServerIP = music.IPAddress,
                                        IsCanShow = true,
                                    });
                                    if (music.Slave.slave_list.Count - 1 == j) {
                                        ///标记从播放器最后那个
                                        a31MusicModel.IsEnd = true;
                                    }
                                }
                            }
                        }
                    }
                }
                if (MusicList.Count != 0) {
                    for (int i = 0; i < A31MusicModel.A31MusicModelList.Count; i++) {
                        var a31player = A31MusicModel.A31MusicModelList [i];
                        if (!a31player.IsOnLine) {
                            continue;
                        }
                        ///找出正常播放器的
                        if (a31player.ServerClientType == 0) {
                            MusicList.Add (A31MusicModel.A31MusicModelList [i]);
                        }
                    }
                    A31MusicModel.A31MusicModelList.Clear ();
                    A31MusicModel.A31MusicModelList = MusicList;
                }
                ///标记从播放器最后那个
 
                //A31MusicModel tempA31MusicModel = null;
                //bool d = false;
                //for (int i = 0; i < A31MusicModel.A31MusicModelList.Count;i++) {
                //    var a31player = A31MusicModel.A31MusicModelList [i];
                //    if(!a31player.IsCanShow){
                //        continue;
                //    }
                //    if(d){
                //        if(a31player.ServerClientType ==-1){
                //            tempA31MusicModel = a31player;
                //            if(i==A31MusicModel.A31MusicModelList.Count-1){
                //                tempA31MusicModel.IsEnd = true;
                //            }
                //        }else{
                //            if(tempA31MusicModel!=null){
                //                tempA31MusicModel.IsEnd = true;
                //            }
                //            if(a31player.ServerClientType == 0){
                //                d = false;
                //            }
                //        }
                //    }
                //    if(a31player.ServerClientType ==1){
                //        d = true;
                //    }
                //}
 
                #endregion
 
            } catch (Exception e) {
                var ss = e.Message;
            }
        }
 
        /// <summary>
        /// 刷新当前音乐的界面
        /// </summary>
        /// <param name="a31image">A31image.</param>
        /// <param name="a31player">A31player.</param>
        /// <param name="a31horizontalSeekBarvol">A31horizontal seek barvol.</param>
        /// <param name="a31btnPlayMusic">A31btn play music.</param>
        /// <param name="a31palyername">A31palyername.</param>
        /// <param name="a31currentMusic">A31current music.</param>
        /// <param name="a31currentartist">A31currentartist.</param>
        void refreshUI (ImageView a31image, A31MusicModel a31player, HorizontalSeekBar a31horizontalSeekBarvol, Button a31btnPlayMusic, Button a31palyername, Button a31currentMusic, Button a31currentartist, Button serverOrClientBtn, FrameLayout a31frameLayout, Button colorBtn)
        {
            try {
                if (a31player.A31PlayStatus.IsMute) {
                    a31horizontalSeekBarvol.Progress = 0;
                } else {
                    a31horizontalSeekBarvol.Progress = int.Parse (a31player.A31PlayStatus.vol);
                }
                a31btnPlayMusic.IsSelected = a31player.A31PlayStatus.status == "play";
                a31palyername.Text = a31player.Name;
                a31currentMusic.Text = a31player.A31PlayStatus.Title;
                a31currentartist.Text = a31player.A31PlayStatus.Artist;
                {
                    a31btnPlayMusic.Alpha = 1.0f;
                    a31btnPlayMusic.Enable = true;
                    a31image.Alpha = 1.0f;
                    a31palyername.Enable = true;
                    a31currentMusic.Alpha = 1.0f;
                    a31currentMusic.Enable = true;
                }
                if (1 == a31player.ServerClientType) {
                    colorBtn.Visible = true;
                    serverOrClientBtn.Visible = true;
                    serverOrClientBtn.UnSelectedImagePath = "MusicIcon/lifeSelected.png";
                } else if (-1 == a31player.ServerClientType) {
                    a31btnPlayMusic.IsSelected = false;
                    a31currentMusic.Text = "";
                    a31currentartist.Text = "";
                    colorBtn.Visible = false;
                    serverOrClientBtn.Visible = true;
                    serverOrClientBtn.UnSelectedImagePath = "MusicIcon/life.png";
                    a31btnPlayMusic.Alpha = 0.5f;
                    a31btnPlayMusic.Enable = false;
                    a31image.Alpha = 0.5f;
                    a31palyername.Enable = false;
                    a31currentMusic.Alpha = 0.5f;
                    a31currentMusic.Enable = false;
                }
            } catch (Exception e) {
                System.Console.WriteLine (e.Message);
            }
        }
 
        //刷新播放器设备列表
        void refreshDevice (MusicVerticalScrolViewLayout verticalScrolViewLayout)
        {
            clearA31Threads ();
            for (int i = 0; i < A31MusicModel.A31MusicModelList.Count; i++) {
                var a31player = A31MusicModel.A31MusicModelList [i];
                a31player.IsCanShow = false;
                a31player.IsOnLine = false;
            }
            MainPage.Loading.Start ();
            seach ((obj) => {
                if (obj == null) {
                    readServerOrClientMode (true);
                    A31MusicModel.Save ();
                    Application.RunOnMainThread (() => {
                        MainPage.Loading.Hide ();
                        for (int i = 0; i < A31MusicModel.A31MusicModelList.Count; i++) {
                            var a31player = A31MusicModel.A31MusicModelList [i];
                            //这个状态是之前保存的,加载完成后要标记为不在线,后面再读取正确的状态
                            if (!a31player.IsCanShow) {
                                continue;
                            }
                            addViews (a31player);
                        }
                    });
                    return;
                }
                var a31MusicModel = A31MusicModel.A31MusicModelList.Find ((music) => { return music.UniqueDeviceName == obj.UniqueDeviceName; });
 
                if (a31MusicModel == null) {
                    //不是我们支持的品牌不支持
                    if (obj.Name != null) {
                        A31MusicModel.A31MusicModelList.Add (obj);
                    }
                } else {
                    a31MusicModel.IPAddress = obj.IPAddress;
                    a31MusicModel.Port = obj.Port;
                    a31MusicModel.Name = obj.Name;
                    a31MusicModel.IsCanShow = true;
                    a31MusicModel.IsOnLine = true;
                }
            });
        }
 
        //标记播放器类型是否有蓝牙功能。
        void readMusicType (A31MusicModel a31player)
        {
            int tempDeviceType = 0;
            Action<byte, byte, int, Command, byte, byte, byte [], System.Net.IPEndPoint> action = (subnetID, deviceId, deviceType, command, targetSubnetID, targetDeviceID, usefullBytes, ipEndPoint) => {
                if (command == Command.ReadRemarkACK && ipEndPoint.Address.ToString () == a31player.IPAddress.ToString ()) {
                    tempDeviceType = deviceType;
                }
            };
            Packet.ReceviceAllDadaAction += action;
 
            DateTime dateTime = DateTime.Now;
            while ((DateTime.Now - dateTime).TotalMilliseconds <= 1000) {
                ///(byte)new Random ().Next (0, 255)表示随机数;
                Control.ControlBytesSend (Command.ReadRemark, 255, 255, new byte [] { (byte)new Random ().Next (0, 255), (byte)new Random ().Next (0, 255) }, SendCount.One, new System.Net.IPEndPoint (System.Net.IPAddress.Parse (a31player.IPAddress), 6000));
                System.Threading.Thread.Sleep (200);
                if (tempDeviceType != 0) {
                    a31player.A31DeviceType = tempDeviceType;
                    break;
                }
            }
            Packet.ReceviceAllDadaAction -= action;
        }
 
        /// <summary>
        /// 更新A31播放器的状态
        /// </summary>
        /// <param name="a31MusicModel"></param>
        void readStatus (A31MusicModel a31MusicModel)
        {
            try {
 
                if (a31MusicModel.ServerClientType == -1) {
                    var result = openWeb ("http://" + a31MusicModel.ServerIP + "/httpapi.asp?command=multiroom:getSlaveList");
                    if (result != null) {
                        var slaves = Newtonsoft.Json.JsonConvert.DeserializeObject<Slaves> (result);
                        if (slaves != null && slaves.slave_list != null) {
                            var slave = slaves.slave_list.Find ((obj) => obj.uuid.Replace ("uuid:", "") == a31MusicModel.UniqueDeviceName);
                            if (slave != null) {
                                a31MusicModel.A31PlayStatus.vol = slave.volume;
                            }
                        }
                    }
                    return;
                }
 
                Shared.Net.MyWebClient webClient = new Shared.Net.MyWebClient (1000);
                webClient.Headers.Add ("Soapaction", "\"urn:schemas-upnp-org:service:AVTransport:1#GetInfoEx\"");
                webClient.Headers.Add ("CONTENT-TYPE", "text/xml; charset=\"utf-8\"");
 
                var recevieBytes = webClient.UploadData (new Uri ("http://" + a31MusicModel.IPAddress + ":" + a31MusicModel.Port + "/upnp/control/rendertransport1"), "POST", System.Text.Encoding.UTF8.GetBytes ("<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?><s:Envelope s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"><s:Body><u:GetInfoEx xmlns:u=\"urn:schemas-upnp-org:service:AVTransport:1\"><InstanceID>0</InstanceID></u:GetInfoEx></s:Body></s:Envelope>"));
                a31MusicModel.LastDateTime = DateTime.Now;
 
                var se = System.Security.SecurityElement.FromString (System.Text.Encoding.UTF8.GetString (recevieBytes)).SearchForChildByTag ("s:Body").SearchForChildByTag ("u:GetInfoExResponse");
 
                if ("PLAYING" == se.SearchForTextOfTag ("CurrentTransportState")) {
                    a31MusicModel.A31PlayStatus.status = "play";
                } else {
                    a31MusicModel.A31PlayStatus.status = "stop";
                }
                a31MusicModel.A31PlayStatus.totlen = (DateTime.Parse (se.SearchForTextOfTag ("TrackDuration")) - DateTime.Parse ("00:00:00")).TotalMilliseconds.ToString ();
 
                var trackMetaData = se.SearchForTextOfTag ("TrackMetaData");
                if (string.IsNullOrEmpty (trackMetaData)) {
                    return;
                }
                if (A31MusicModel.IsJson (trackMetaData)) {
                    var a31QQSong = Newtonsoft.Json.JsonConvert.DeserializeObject<A31QQSong> (trackMetaData);
                    a31MusicModel.A31PlayStatus.Title = a31QQSong.title;
                    a31MusicModel.A31PlayStatus.Album = a31QQSong.album;
                    a31MusicModel.A31PlayStatus.Artist = a31QQSong.creator;
                } else {
                    var metadata = trackMetaData.Replace ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "").Replace ("&", "&amp;amp;");
                    var item = SecurityElement.FromString (metadata).SearchForChildByTag ("item");
                    a31MusicModel.A31PlayStatus.Title = item.SearchForTextOfTag ("dc:title");
                    a31MusicModel.A31PlayStatus.Artist = item.SearchForTextOfTag ("upnp:artist");
                    a31MusicModel.A31PlayStatus.Album = item.SearchForTextOfTag ("upnp:album");
                }
                a31MusicModel.A31PlayStatus.curpos = (DateTime.Parse (se.SearchForTextOfTag ("RelTime")) - DateTime.Parse ("00:00:00")).TotalMilliseconds.ToString ();
                a31MusicModel.A31PlayStatus.vol = se.SearchForTextOfTag ("CurrentVolume");
                a31MusicModel.A31PlayStatus.loop = se.SearchForTextOfTag ("LoopMode");
                a31MusicModel.A31PlayStatus.Source = se.SearchForTextOfTag ("PlayMedium");
                a31MusicModel.A31PlayStatus.playSource = se.SearchForTextOfTag ("TrackSource");
                a31MusicModel.A31PlayStatus.TrackURL = se.SearchForTextOfTag ("TrackURI");
 
            } catch (Exception ex) {
                Console.WriteLine (ex.Message);
            }
        }
 
        /// <summary>
        /// 获取A31的名称
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        /// <returns></returns>
        string getDeviceName (string ip, int port)
        {
            string deviceName = null;
            System.IO.StreamReader sr = null;
            Shared.Net.MyWebClient webClient = new Shared.Net.MyWebClient ();
            try {
                var receviceBytes = webClient.DownloadData (new Uri ("http://" + ip + ":" + port + "/description.xml"));
                sr = new System.IO.StreamReader (new System.IO.MemoryStream (receviceBytes), Encoding.UTF8);
                string line = null;
                string deviceType = null;
 
                while ((line = sr.ReadLine ()) != null) {
                    //System.Console.WriteLine (line);
                    if (line.StartsWith ("<friendlyName>")) {
                        deviceName = line.Replace ("<friendlyName>", "").Replace ("</friendlyName>", "");
                    } else if (line.StartsWith ("<manufacturer>")) {
                        deviceType = line.Replace ("<manufacturer>", "").Replace ("</manufacturer>", "");
                    }
                }
                switch (deviceType) {
                case "iEAST":
                case "Linkplay Technology Inc.":
                    break;
                //不是A31的音乐数据
                default:
                    deviceName = null;
                    break;
                }
 
            } catch (Exception e) {
                System.Console.WriteLine (e.Message);
            } finally {
                if (sr != null) {
                    sr.Close ();
                }
            }
            return deviceName;
        }
 
 
        /// <summary>
        /// 1秒更新一次
        /// </summary>
        public static System.DateTime dateTime = System.DateTime.Now.AddSeconds (-1);
 
        void sendCommand (A31MusicModel a31, string cmd)
        {
            System.Threading.Tasks.Task.Run (() => {
                Shared.Net.MyWebClient webClient = new Shared.Net.MyWebClient ();
                try {
                    byte [] recevieBytes1 = webClient.DownloadData (new Uri ("http://" + a31.IPAddress + "/httpapi.asp?command=setPlayerCmd:" + cmd));
                } catch (Exception e) {
                    System.Console.WriteLine (e.Message);
                }
            });
        }
 
        private void back_MouseDownEventHandler (object sender, MouseEventArgs e)
        {
            this.RemoveFromParent ();
        }
        [System.Serializable]
        class a31wifimessage
        {
            public string res;
            public List<a31message> aplist;
        }
        [System.Serializable]
        class a31message
        {
            public string ssid;
            public string channel;
            public string auth;
            public string encry;
            public string extch;
 
        }
 
    }
 
}