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
using System;
using System.Collections.Generic;
using System.Runtime.Remoting.Contexts;
using System.Text;
using Shared;
using Shared.SimpleControl;
using Shared.SimpleControl.Phone;
using Shared.SimpleControl.Phone.Music;
using Shared.SimpleControl.R;
using SmartHome.UI.SimpleControl.Phone.Music;
 
namespace SmartHome
{
    class A31Wifi : FrameLayout
    {
 
        /// <summary>
        /// 选中
        /// </summary>
        Button beforeClickButton = new Button ();
 
        FrameLayout middle;
        /// <summary>
        /// wifi_密码控件
        /// </summary>
        EditText password;
        /// <summary>
        /// 登陆
        /// </summary>
        Button login;
        public void Show ()
        {
            AddChidren (new Button {
                Height = Application.GetRealHeight (36),
                BackgroundColor = SkinStyle.Current.MusicTopFrameLayout,
            });
 
            var topFrameLayout = new FrameLayout {
                Height = Application.GetRealHeight (100),
                Y = Application.GetRealHeight (36),
                BackgroundColor = SkinStyle.Current.MusicTopFrameLayout,
            };
            AddChidren (topFrameLayout);
 
            var LocallistName = new Button {
                TextID = MyInternationalizationString.Choosenetwork,
                //Text = "选择网络",
                TextColor = SkinStyle.Current.MusicTextColor,
            };
            topFrameLayout.AddChidren (LocallistName);
 
            var hdl = new Button {
                Width = Application.GetRealWidth (154),
                Height = Application.GetRealHeight (90),
                X = Application.GetRealWidth (486),
                Gravity = Gravity.CenterVertical,
                UnSelectedImagePath = MainPage.LogoString,
            };
            topFrameLayout.AddChidren (hdl);
 
            var back = new Button {
                Width = Application.GetRealWidth (82),
                Height = Application.GetRealHeight (89),
                X = Application.GetRealWidth (10),
                Gravity = Gravity.CenterVertical,
                UnSelectedImagePath = "MusicIcon/HomepageBack.png",
            };
            topFrameLayout.AddChidren (back);
            back.MouseDownEventHandler += (sender, e) => {
                RemoveFromParent ();
            };
 
            middle = new FrameLayout ();
            middle.Y = topFrameLayout.Bottom;
            middle.Height = Application.GetRealHeight (Application.DesignHeight - 136);
            middle.BackgroundColor = SkinStyle.Current.MusicVerticalScrolViewLayout;
            AddChidren (middle);
 
            var textrow = new RowLayout {
                Height = Application.GetRealHeight (100),
                BackgroundColor=SkinStyle.Current.MusicMiddleBackgroundColor,
            };
            middle.AddChidren (textrow);
 
            var btntext= new Button {
                Width = Application.GetMinRealAverage (630),
                Height = Application.GetMinRealAverage (100),
                X = Application.GetRealWidth (10),
                TextAlignment = TextAlignment.CenterLeft,
                TextID = MyInternationalizationString.Connectedwirelessnetwork,
                //Text = "选择你将要连接的无线网络",
                TextColor = SkinStyle.Current.MusicTextColor,
 
            };
            textrow.AddChidren (btntext);
 
            var tip1 = new Button {
                Width = Application.GetMinRealAverage (600),
                Height = Application.GetMinRealAverage (40),
                X = Application.GetRealWidth (30),
                Y = Application.GetRealHeight (530),//560
                TextAlignment = TextAlignment.CenterLeft,
                TextColor = SkinStyle.Current.MusicTextColor,
            };
            middle.AddChidren (tip1);
 
            var tip2 = new Button {
                Width = Application.GetMinRealAverage (600),
                Height = Application.GetMinRealAverage (40),
                X = Application.GetRealWidth (100),
                Y = Application.GetRealHeight (570),//560
                TextAlignment = TextAlignment.CenterLeft,
                TextColor = SkinStyle.Current.MusicTextColor,
                //TextID = MyInternationalizationString.thenextstep,
                //Text = "提示:Wi-Fi没有设置密码直接按下一步.",
            };
            middle.AddChidren (tip2);
            if (Language.CurrentLanguage == "English") {
                tip1.Text = "TIPS: There is no password in the Wi-Fi,press the";
                tip2.Text = "next button directly.";
            } else {
                tip2.TextID = MyInternationalizationString.thenextstep;
                tip2.X = Application.GetRealWidth (30);
            }
 
 
            var frameLayout = new FrameLayout {
                Width = Application.GetRealWidth (580),
                Height = Application.GetRealHeight (80),
                X = Application.GetRealWidth (30),
                Y = Application.GetRealHeight (650),
                BackgroundColor = 0xff656565,
            };
            middle.AddChidren (frameLayout);
 
            password = new EditText {
                Width = Application.GetRealWidth (410),
                Height = Application.GetRealHeight (60),
                X = Application.GetRealWidth (30),
                Y = Application.GetRealHeight (10),
                TextAlignment = TextAlignment.Center,
                //BackgroundColor = 0xFF4D4D4D,
                UnSelectedImagePath = "Register/Register_password.png",
                //PlaceholderText = "输入Wi-Fi密码",
                PlaceholderText = Language.StringByID (MyInternationalizationString.theWiFipassword),
                ///不显示密码
                SecureTextEntry = true,
 
            };
            frameLayout.AddChidren (password);
 
            var secureText = new Button {
                X = Application.GetRealWidth (500),
                Width = Application.GetRealWidth (74),
                Height = Application.GetRealHeight (66),
                UnSelectedImagePath = "MusicIcon/hidden.png",
                SelectedImagePath="MusicIcon/selehidden.png",
                Gravity = Gravity.CenterVertical,
            };
            frameLayout.AddChidren (secureText);
            ///是否显示密码的点击事件
            secureText.MouseUpEventHandler += (sender, e) => {
                secureText.IsSelected = !secureText.IsSelected;
                if (secureText.IsSelected) {
                    password.SecureTextEntry = false;
                } else {
                    password.SecureTextEntry = true;
                }
            };
 
            login = new Button {
                Width = Application.GetRealWidth (580),
                Height = Application.GetRealHeight (80),
                TextID = MyInternationalizationString.nextstep,
                TextSize = 20,
                X = Application.GetRealWidth (30),
                Y = Application.GetRealHeight (820),
                BackgroundColor = 0xff656565,
                Radius = (uint)Application.GetRealHeight (16),
            };
            middle.AddChidren (login);
 
        }
 
        public void Init ()
        {
            var wifiJsonList = openWeb ("http://10.10.10.254/httpapi.asp?command=wlanGetApList");
            if (wifiJsonList == null) {
                wifiJsonList = openWeb ("http://10.10.10.254/httpapi.asp?command=wlanGetApList");
            }
            if (wifiJsonList == null) {
                new Alert (Language.StringByID (MyInternationalizationString.Tip),
                                      Language.StringByID (MyInternationalizationString.Localconnectedwifi),
                           Language.StringByID (MyInternationalizationString.confirm)).Show ();
                return;
            }
 
            var aplist= Newtonsoft.Json.Linq.JObject.Parse (wifiJsonList) ["aplist"]?.ToString ();
            if(aplist==null){
                return;
            }
            var wifiList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<WifiInfo>> (aplist);
            if (wifiList == null) {
                return;
            }
 
            var wifipass = Newtonsoft.Json.JsonConvert.DeserializeObject<WifiConfig> (System.Text.Encoding.UTF8.GetString (Shared.IO.FileUtils.ReadFile (WifiConfig.FileName)));
 
            //if(wifipass==null){
            //    return;
            //}
            var fra = new FrameLayout {
                Y = Application.GetRealHeight (120),
                X = Application.GetRealWidth (30),
                Height = Application.GetRealHeight (400),
                Width = Application.GetRealWidth (580),
                BackgroundColor = 0xff656565,
            };
            middle.AddChidren (fra);
            var vv = new VerticalScrolViewLayout { };
            fra.AddChidren (vv);
 
           
            string ssid = null, ch = null, auth = null, encry = null;
            foreach (var wifiInfo in wifiList) {
                var ssidrow = new RowLayout {
                    Height = Application.GetRealHeight (100),
                };
                vv.AddChidren (ssidrow);
 
                var btn = new Button {
                    Height = Application.GetRealHeight (100),
                    Width = LayoutParams.MatchParent,
                    SelectedBackgroundColor = 0xfffe5e00,
                };
                ssidrow.AddChidren (btn);
 
                var btnTimelock = new Button {
                    X = Application.GetRealWidth (440),
                    Width = Application.GetRealWidth (51),
                    Height = Application.GetRealHeight (51),
                    UnSelectedImagePath = "MusicIcon/timelock.png",
                    Gravity = Gravity.CenterVertical,
                };
                if (wifiInfo.auth == "WPA2PSK") {
                    ssidrow.AddChidren (btnTimelock);
                }
 
                var wifi = new Button {
                    Width = Application.GetMinRealAverage (50),
                    Height = Application.GetMinRealAverage (50),
                    UnSelectedImagePath = "MusicIcon/wifi.png",
                    X = Application.GetRealWidth (500),
                    Gravity = Gravity.CenterVertical,
                };
                ssidrow.AddChidren (wifi);
 
                var btnssidname = new Button {
                    Width = Application.GetMinRealAverage (400),
                    Height = Application.GetMinRealAverage (100),
                    X = Application.GetRealWidth (30),
                    TextAlignment = TextAlignment.CenterLeft,
                    Text = wifiInfo.ssid,
                };
                ssidrow.AddChidren (btnssidname);
 
                if (wifipass != null) {
                    if (wifipass.UserName != null && wifipass.UserName == wifiInfo.ssid) {
                        password.Text = wifipass.Passwrod.Trim ();
                        beforeClickButton.IsSelected = false;
                        beforeClickButton = btn;
                        btn.IsSelected = true;
                        ssid = wifiInfo.ssid;
                        ch = wifiInfo.channel;
                        auth = wifiInfo.auth;
                        encry = wifiInfo.encry;
                    }
                }
 
                btnssidname.MouseUpEventHandler += (sender, e) => {
                    beforeClickButton.IsSelected = false;
                    beforeClickButton = btn;
                    btn.IsSelected = true;
 
                    ssid = wifiInfo.ssid;
                    ch = wifiInfo.channel;
                    auth = wifiInfo.auth;
                    encry = wifiInfo.encry;
                };
            }
 
            login.MouseUpEventHandler += (sender, e) => {
                var passwordstr = password.Text.Trim ();
                login.BackgroundColor = 0xff656565;
                if (ssid == null || auth == null || encry == null || ch == null) {
                    new Alert (Language.StringByID (MyInternationalizationString.Tip),
                               Language.StringByID (MyInternationalizationString.Connectedwifi),
                               Language.StringByID (MyInternationalizationString.confirm)).Show ();
                    return;
                }
                if (passwordstr == "" && auth == "WPA2PSK") {
                    new Alert (Language.StringByID (MyInternationalizationString.Tip),
                              Language.StringByID (MyInternationalizationString.Passwordisempty),
                    Language.StringByID (MyInternationalizationString.confirm)).Show ();
                    return;
                }
                try {
                    ///密码
                    string tempPassword = "";
                    if (passwordstr != null) {
                        foreach (var c in passwordstr) {
                            var tempStr = System.Convert.ToString ((byte)c, 16).ToUpper ();
                            if (tempStr.Length < 2) {
                                tempStr = "0" + tempStr;
                            }
                            tempPassword += tempStr;
                        }
                    }
                    if (auth == "OPEN") {
                        tempPassword = "NONE";
                    }
                    ///WF-IF:SSID
                    string tempSSID = null;
                    foreach (var c in ssid) {
                        var tempStr = System.Convert.ToString ((byte)c, 16).ToUpper ();
                        if (tempStr.Length < 2) {
                            tempStr = "0" + tempStr;
                        }
                        tempSSID += tempStr;
                    }
 
                    var statusEx = openWeb ("http://10.10.10.254/httpapi.asp?command=getStatusEx");
                    if (statusEx == null) {
                        statusEx = openWeb ("http://10.10.10.254/httpapi.asp?command=getStatusEx");
                    }
                    if (statusEx == null) {
                        new Alert (Language.StringByID (MyInternationalizationString.Tip),
                                   Language.StringByID (MyInternationalizationString.Localconnectedwifi),
                                   Language.StringByID (MyInternationalizationString.confirm)).Show ();
                        return;
                    }
                    var tmpdeviceifon = Newtonsoft.Json.JsonConvert.DeserializeObject<a31wifi> (statusEx);
                    if (null == openWeb ("http://10.10.10.254/httpapi.asp?command=wlanConnectApEx:ssid=" + tempSSID + ":ch=" + ch + ":auth=" + auth + ":encry=" + encry + ":pwd=" + tempPassword + ":chext=1")) {
                        if (null == openWeb ("http://10.10.10.254/httpapi.asp?command=wlanConnectApEx:ssid=" + tempSSID + ":ch=" + ch + ":auth=" + auth + ":encry=" + encry + ":pwd=" + tempPassword + ":chext=1")) {
                            ///TODO请检查手机Wi-Fi是否连接播放器Wi-Fi
                            new Alert (Language.StringByID (MyInternationalizationString.Tip),
                                       Language.StringByID (MyInternationalizationString.Localconnectedwifi),
                            Language.StringByID (MyInternationalizationString.confirm)).Show ();
                            return;
                        }
                    }
 
                    ///搜索查询连接状态
                    MainPage.Loading.Start ();
                    Shared.Net.WifiUtil.Instance.ConnectToWifi ((b) => {
                        if (b) {
                            seach ((obj) => {
                                if (obj == null) {
                                    Application.RunOnMainThread (() => {
                                        MainPage.Loading.Hide ();
                                        ///TODO连接超时
                                        new Alert (Language.StringByID (MyInternationalizationString.Tip),
                                              Language.StringByID (MyInternationalizationString.Connectiontimeout),
                                              Language.StringByID (MyInternationalizationString.confirm)).Show ();
                                    });
                                } else {
                                    if (obj.UniqueDeviceName == tmpdeviceifon.upnp_uuid.Replace ("uuid:", "")) {
                                        ///记录之前的WiFi和密码;
                                        var wifiConfigBytes = System.Text.Encoding.UTF8.GetBytes (Newtonsoft.Json.JsonConvert.SerializeObject (new WifiConfig { UserName = ssid, Passwrod = passwordstr }));
                                        Shared.IO.FileUtils.WriteFileByBytes (WifiConfig.FileName, wifiConfigBytes);
 
                                        Application.RunOnMainThread (() => {
                                            MainPage.Loading.Hide ();
                                            //MainPage.AddTip (Language.StringByID (MyInternationalizationString.connectionissuccessful), 1000);
                                            this.RemoveFromParent ();
                                            UserMiddle.DevicePageView.PageIndex = 0;
                                            var myMusic = new MyMusic ();
                                            UserMiddle.DevicePageView.AddChidren (myMusic);
                                            myMusic.Show (false);
                                            UserMiddle.DevicePageView.PageIndex = 1;
                                        });
                                    }
                                }
 
                            }, 12000, tmpdeviceifon.upnp_uuid.Replace ("uuid:", ""));
                        } else {
                            ///TODO密码不正确
                            Application.RunOnMainThread (() => {
                                MainPage.Loading.Hide ();
                                new Alert (Language.StringByID (MyInternationalizationString.Tip),
                                      Language.StringByID (MyInternationalizationString.Incorrectpassword),
                                      Language.StringByID (MyInternationalizationString.confirm)).Show ();
                            });
                        }
                    }, ssid, passwordstr);
                } catch { }
            };
 
            login.MouseDownEventHandler += (sender, e) => {
                login.BackgroundColor = 0xffFE5E00;
            };
        }
 
        string openWeb (string url)
        {
            try {
                return new Shared.Net.MyWebClient (5 * 1000).DownloadString (url);
            } catch {
                return null;
            }
        }
 
        [System.Serializable]
        class WifiInfo
        {
            public string ssid;
            public string channel;
            public string auth;
            public string encry;
            public string extch;
 
        }
               
        void seach (Action<A31MusicModel> action, int time = 5 * 1000, string uid = "AllUniqueDeviceName")
        {
            System.Threading.Tasks.Task.Run (() => {
                var socket = new System.Net.Sockets.Socket (System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
                for (int i = 10000; i < 65535; i++) {
                    try {
                        //绑定本地端口
                        socket.Bind (new System.Net.IPEndPoint (System.Net.IPAddress.Any, i));//57404
                        break;
                    } catch { }
                }
                A31MusicModel music = null;
               System.Threading.Tasks.Task.Run (() => {
                    var tempDateTime = DateTime.Now;
                    while ((DateTime.Now - tempDateTime).TotalMilliseconds < time && socket != null) {
                        try {
                            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 ();
 
                            //请求获取A31服务器信息
                            socket.SendTo (System.Text.Encoding.ASCII.GetBytes (stringBuilder.ToString ()), System.Net.Sockets.SocketFlags.None, new System.Net.IPEndPoint (System.Net.IPAddress.Parse ("239.255.255.250"), 1900));
                            socket.SendTo (System.Text.Encoding.ASCII.GetBytes (stringBuilder.ToString ()), System.Net.Sockets.SocketFlags.None, new System.Net.IPEndPoint (System.Net.IPAddress.Parse ("239.255.255.250"), 1900));
                                                    
                            System.Threading.Thread.Sleep (1000);
                        } catch { }
                    }
                   
                    try {
                        if (socket != null) {
                            socket.Close ();
                            socket = null;
 
                        }
                    } catch { } finally {
                       //表示完成了
                       action?.Invoke (music);
                   }
                });
 
                while (socket != null) {
                    try {
                        //接收回来的数据
                        var receviceBytes = new byte [1024];
                        System.Net.EndPoint remoteIpEndPoint = new System.Net.IPEndPoint (0, 0);
                        //开始在这里等待接收数据,
                        var len = socket.ReceiveFrom (receviceBytes, ref remoteIpEndPoint);
                        var ms = new System.IO.MemoryStream (receviceBytes, 0, len);
 
                        var sr = new System.IO.StreamReader (ms);
                        string tempLine = "";
                        string ipAddress = "";
                        int port = 0;
                        string uniqueDeviceName = "";
                        //一行一行数据判断,找出需要的信息
                        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 ();
                        ms.Close ();
                        if (action != null) {
                            if ("AllUniqueDeviceName" == uid) {
                                action (new A31MusicModel { IPAddress = ipAddress, Port = port, Name = getDeviceName (ipAddress, port), UniqueDeviceName = uniqueDeviceName });
                            } else if (uid == uniqueDeviceName) {
                                music = new A31MusicModel { IPAddress = ipAddress, Port = port, Name = getDeviceName (ipAddress, port), UniqueDeviceName = uniqueDeviceName };
                               if (socket != null) {
                                    socket.Close ();
                                    socket = null;
                                }
                            }
                        }
                    } catch { }
                }
            });
        }
 
        /// <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 { } finally {
                if (sr != null) {
                    sr.Close ();
                }
            }
            return deviceName;
        }
 
 
 
    }
}