Crabtree/SmartHome/UI/SimpleControl/Phone/Guide/GuideSettingGateway.cs
@@ -6,6 +6,7 @@
{
    public class GuideSettingGateway : FrameLayout
    {
        static byte TYPEStandardMQTT = 5;
        static byte TYPEHdlMQTT = 4;
        static GuideSettingGateway curView;
@@ -35,6 +36,8 @@
                    myLoading.Hide ();
                    btnCloseLoading.RemoveFromParent ();
                    WirelessConfig (new byte [] { 1 });//close
                    //2020-07-02 关闭自动搜索线程
                    StopSearchDeviceThead ();
                    if (needRefresh) {
                        needRefresh = false;
                        SearchDeviceList ();
@@ -49,6 +52,7 @@
            curView = null;
            addedCommon.Clear ();
            BackgroundColor = SkinStyle.Current.MainColor;
            //StopSearchDeviceThead ();
            base.RemoveFromParent ();
        }
@@ -93,8 +97,8 @@
            };
            var btnSearch = new Button () {
                Width = Application.GetRealWidth (75),
                Height = Application.GetRealHeight (75),
                Width = Application.GetMinRealAverage (75),
                Height = Application.GetMinRealAverage (75),
                X = Application.GetRealWidth (520),
                Y = Application.GetRealHeight (10),
                UnSelectedImagePath = "Item/Refresh.png",
@@ -145,11 +149,11 @@
        {
            if (gatewayDeicve.Type == DeviceType.OnePortMqttFR) {
                Console.WriteLine ("Assign OnePortMqttFR,HDL MQTT");
                Utlis.WriteLine ("Assign OnePortMqttFR,HDL MQTT");
                //RemoteSetting ();
                RemoteSettingWithHDLMQTT ();
            } else {
                Console.WriteLine ("Assign OnePortWirelessFR");
                Utlis.WriteLine ("Assign OnePortWirelessFR");
                RemoteSettingWithOldDevice ();
                //RemoteSettingWithMQTT ();
            }
@@ -194,7 +198,7 @@
                    if (common.Type == DeviceType.MusicModel)
                        continue;
                    if (common.isMixBox) {
                        Console.WriteLine ("IsMixBox");
                        Utlis.WriteLine ("IsMixBox");
                        continue;
                    }
                    countDevcie++;
@@ -247,7 +251,12 @@
                            this.AddChidren (myLoading);
                            //myLoading.Start ("点击屏幕关闭配频模式");
                            myLoading.Start ("Searching, Please touch the here to exit the searching mode.");
                            //myLoading.Start ("Waiting for new device, Please touch the here to exit the waiting mode.");
                            this.AddChidren (btnCloseLoading);
                            //2020-07-02 网关配频模式时,开启自动搜索线程
                            StartSearchDeviceThead ();
                        }
                    });
                });
@@ -460,7 +469,7 @@
                                            btnDelDevice.Parent.RemoveFromParent ();
                                        });
                                    } catch (Exception ex) {
                                        Console.WriteLine (ex.Message);
                                        Utlis.WriteLine (ex.Message);
                                    } finally {
                                        Application.RunOnMainThread (() => {
                                            MainPage.Loading.Hide ();
@@ -498,7 +507,7 @@
                        //            }
                        //        }
                        //    } catch (Exception ex) {
                        //        Console.WriteLine ("Cinfig Read Device Loop Info " + ex.Message);
                        //        Utlis.WriteLine ("Cinfig Read Device Loop Info " + ex.Message);
                        //    }
                        //});
                    }
@@ -520,12 +529,17 @@
                    //这里搜索设备,直到完成就退出
                    readDevice ();
                } catch (Exception ex) {
                    Console.WriteLine (ex.Message);
                    Utlis.WriteLine (ex.Message);
                }
                Application.RunOnMainThread (action);
            }) { IsBackground = true }.Start ();
        }
        ///// <summary>
        ///// 2020-02-11
        ///// 搜索重复次数 由4次增加为6次
        ///// </summary>
        //static readonly int READ_COUNT = 6;
        /// <summary>
        /// 读取设备
        /// </summary>
@@ -539,7 +553,8 @@
            CommonPage.DeviceList.Clear ();
            CommonPage.searchTotal = 0;
            //如果两次都没有数据反馈,就不读取
            int readCount = 4;
            //2020 - 02 - 11搜索重复次数 由4次增加为6次
            int readCount = 6;
            while (0 < readCount) {
                readCount--;
                var ms = new System.IO.MemoryStream ();
@@ -559,7 +574,7 @@
                    ms.WriteByte (common.SubnetID);
                    ms.WriteByte (common.DeviceID);
                }
                Console.WriteLine ("搜索非网关设备,网络地址是:" + CommonPage.EndPoint.ToString ());
                Utlis.WriteLine ("搜索非网关设备,网络地址是:" + CommonPage.EndPoint.ToString ());
                var control = new Control ();
                control.Send (new Target () {
                    IPEndPoint = CommonPage.EndPoint,
@@ -574,7 +589,7 @@
                System.Threading.Thread.Sleep (1000);
                //如果数量不相等,就重置次数
                if (tempCount != CommonPage.DeviceList.Count) {
                    readCount = 4;
                    readCount = 6;
                }
            }
            CommonPage.DeviceList = CommonPage.DeviceList.FindAll ((obj) => { return obj != null && obj.SubnetID == gatewayDeicve.SubnetID; });
@@ -671,7 +686,7 @@
                    var mobytes = Control.ControlBytesSendHasReturn (Command.SetGateWayModelInternetInfo, gatewayDeicve.SubnetID, gatewayDeicve.DeviceID, serverIPBytes);
                    if (mobytes == null) {
                        Application.RunOnMainThread (() => {
                            new Alert ("", Language.StringByID (R.MyInternationalizationString.TipEquipmentNotOnline),
                            new Alert ("", ErrorCode.GatewayNoResponse,
                                       Language.StringByID (R.MyInternationalizationString.Close)).Show ();
                        });
                    } else if (mobytes [0] == 0xF5) {
@@ -684,7 +699,7 @@
                            var bindReginIdStatus = Control.ControlBytesSendHasReturn (Command.Write_APP_Data_STORE_1D5E_CMD, gatewayDeicve.SubnetID, gatewayDeicve.DeviceID, currentRegionIdBytes);
                            if (bindReginIdStatus == null) {
                                Application.RunOnMainThread (() => {
                                    new Alert ("", Language.StringByID (R.MyInternationalizationString.TipEquipmentNotOnline), Language.StringByID (R.MyInternationalizationString.Close)).Show ();
                                    new Alert ("", ErrorCode.GatewayNoResponse, Language.StringByID (R.MyInternationalizationString.Close)).Show ();
                                });
                                return;
                            } else if (bindReginIdStatus [0] != 0xF8) {
@@ -698,7 +713,7 @@
                        BindGatewaysNew ();
                    }
                } catch (Exception ex) {
                    Console.WriteLine (ex.Message);
                    Utlis.WriteLine (ex.Message);
                    Application.RunOnMainThread (() => {
                        new Alert ("", Language.StringByID (R.MyInternationalizationString.OperationFailed), Language.StringByID (R.MyInternationalizationString.Close)).Show ();
                    });
@@ -723,59 +738,29 @@
            byte [] gatewayBytes = null;
            string [] strServerIP = (MainPage.SeviceIP).Split ('.');
            string [] strServerIP1 = (MainPage.SeviceIP).Split ('.');
            MainPage.Loading.Start ("Configuring device...");
            MainPage.Loading.Start ("Configuring gateway...");
            System.Threading.Tasks.Task.Run (() => {
                try {
                    //读取一端口交换机、无线网关的配置信息
                    gatewayBytes = Control.ControlBytesSendHasReturn (Command.ReadGateWayModelInfo, gatewayDeicve.SubnetID, gatewayDeicve.DeviceID, new byte [] { });
                    gatewayDeicve.Remote_GroupName = MainPage.LoginUser.AccountString;//UserConfig.Instance.CurrentRegion.RegionName;
                    gatewayDeicve.Remote_ProjectName = gatewayDeicve.MAC.Replace (".", "");//UserConfig.Instance.CurrentRegion.RegionName;
                    gatewayDeicve.Remote_UserName = "Admin";
                    gatewayDeicve.Remote_Password = "c" + MainPage.LoginUser.ID;
                    //gatewayDeicve.Remote_Password = "85521566";
                    byte [] ggn = new byte [20];
                    byte [] b1 = CommonPage.MyEncodingGB2312.GetBytes (gatewayDeicve.Remote_GroupName);
                    gatewayDeicve.Remote_GroupName = CommonPage.MyEncodingGB2312.GetString (b1);
                    Array.Copy (b1, 0, ggn, 0, 20 < b1.Length ? 20 : b1.Length);
                    byte [] gpn = new byte [20];
                    byte [] b2 = CommonPage.MyEncodingGB2312.GetBytes (gatewayDeicve.Remote_ProjectName);
                    Array.Copy (b2, 0, gpn, 0, 20 < b2.Length ? 20 : b2.Length);
                    byte [] gun = new byte [8];
                    byte [] b3 = CommonPage.MyEncodingGB2312.GetBytes (gatewayDeicve.Remote_UserName);
                    Array.Copy (b3, 0, gun, 0, 8 < b3.Length ? 8 : b3.Length);
                    byte [] gpw = new byte [8];
                    byte [] b4 = CommonPage.MyEncodingGB2312.GetBytes (gatewayDeicve.Remote_Password);
                    Array.Copy (b4, 0, gpw, 0, 8 < b4.Length ? 8 : b4.Length);
                    gatewayBytes [0] = TYPEHdlMQTT;//HDL MQTT
                    Array.Copy (ggn, 0, gatewayBytes, 1, 20);
                    Array.Copy (gpn, 0, gatewayBytes, 21, 20);
                    Array.Copy (gun, 0, gatewayBytes, 41, 8);
                    Array.Copy (gpw, 0, gatewayBytes, 49, 8);
                    //1.修改用户名信息
                    Control.ControlBytesSend (Command.SetGateWayModelInfo, gatewayDeicve.SubnetID, gatewayDeicve.DeviceID, gatewayBytes);
                    ////2.读取一次管理信息
                    //byte [] adminBytes = Control.ControlBytesSendHasReturn (Command.ReadGateWayAdminInfo, gatewayDeicve.SubnetID, gatewayDeicve.DeviceID, new byte [] { });
                    ////3.修改管理信息
                    //if (SetGateWayAdminInfo (adminBytes)) {
                    //    //4.写配置成功后下一步操作
                    //    GatewaySettingSucceeded ();
                    ////读取一端口交换机、无线网关的配置信息
                    //gatewayBytes = Control.ControlBytesSendHasReturn (Command.ReadGateWayModelInfo, gatewayDeicve.SubnetID, gatewayDeicve.DeviceID, new byte [] { });
                    //if (gatewayBytes == null) {
                    //    //读取一端口交换机、无线网关的配置信息失败
                    //    new Alert ("", "Read gateway configuration failed!", "Close").Show ();
                    //    return;
                    //}
                    //2.修改管理信息
                    if (SetGateWayAdminInfo ()) {
                        //3.写配置成功后下一步操作
                        GatewaySettingSucceeded ();
                    //1.修改用户名信息 和修改连接模式
                    if (SetGateWayModelInfo()) {
                        //2.修改管理信息
                        if (SetGateWayAdminInfo ()) {
                            //3.写配置成功后下一步操作
                            GatewaySettingSucceeded ();
                        }
                    }
                } catch (Exception ex) {
                    Console.WriteLine (ex.Message);
                    Utlis.WriteLine (ex.Message);
                    Application.RunOnMainThread (() => {
                        //修改网关连接模式失败
                        new Alert ("", "Failed to modify gateway connection mode!", Language.StringByID (R.MyInternationalizationString.Close)).Show ();
@@ -789,6 +774,40 @@
                }
            });
            //Room.InitAllRoom ();
        }
        bool SetGateWayModelInfo () {
            byte [] gatewayBytes = new byte [60];
            gatewayDeicve.Remote_GroupName = MainPage.LoginUser.AccountString;//UserConfig.Instance.CurrentRegion.RegionName;
            gatewayDeicve.Remote_ProjectName = gatewayDeicve.MAC.Replace (".", "");//UserConfig.Instance.CurrentRegion.RegionName;
            gatewayDeicve.Remote_UserName = "Admin";
            gatewayDeicve.Remote_Password = "c" + MainPage.LoginUser.ID;
            //gatewayDeicve.Remote_Password = "85521566";
            byte [] ggn = new byte [20];
            byte [] b1 = CommonPage.MyEncodingGB2312.GetBytes (gatewayDeicve.Remote_GroupName);
            gatewayDeicve.Remote_GroupName = CommonPage.MyEncodingGB2312.GetString (b1);
            Array.Copy (b1, 0, ggn, 0, 20 < b1.Length ? 20 : b1.Length);
            byte [] gpn = new byte [20];
            byte [] b2 = CommonPage.MyEncodingGB2312.GetBytes (gatewayDeicve.Remote_ProjectName);
            Array.Copy (b2, 0, gpn, 0, 20 < b2.Length ? 20 : b2.Length);
            byte [] gun = new byte [8];
            byte [] b3 = CommonPage.MyEncodingGB2312.GetBytes (gatewayDeicve.Remote_UserName);
            Array.Copy (b3, 0, gun, 0, 8 < b3.Length ? 8 : b3.Length);
            byte [] gpw = new byte [8];
            byte [] b4 = CommonPage.MyEncodingGB2312.GetBytes (gatewayDeicve.Remote_Password);
            Array.Copy (b4, 0, gpw, 0, 8 < b4.Length ? 8 : b4.Length);
            gatewayBytes [0] = TYPEHdlMQTT;//HDL MQTT
            Array.Copy (ggn, 0, gatewayBytes, 1, 20);
            Array.Copy (gpn, 0, gatewayBytes, 21, 20);
            Array.Copy (gun, 0, gatewayBytes, 41, 8);
            Array.Copy (gpw, 0, gatewayBytes, 49, 8);
            byte [] backBytes = Control.ControlBytesSendHasReturn (Command.SetGateWayModelInfo, gatewayDeicve.SubnetID, gatewayDeicve.DeviceID, gatewayBytes);
            return CheckIsSuccessfulWithBytes (backBytes, "Failed to modify gateway connection mode.");
        }
        /// <summary>
@@ -847,7 +866,7 @@
        {
            if (backBytes == null) {
                Application.RunOnMainThread (() => {
                    new Alert ("", Language.StringByID (R.MyInternationalizationString.TipEquipmentNotOnline),
                    new Alert ("", ErrorCode.GatewayNoResponse,
                               Language.StringByID (R.MyInternationalizationString.Close)).Show ();
                });
                return false;
@@ -880,7 +899,7 @@
                var bindReginIdStatus = Control.ControlBytesSendHasReturn (Command.Write_APP_Data_STORE_1D5E_CMD, gatewayDeicve.SubnetID, gatewayDeicve.DeviceID, sendBytes);
                if (bindReginIdStatus == null) {
                    Application.RunOnMainThread (() => {
                        new Alert ("", Language.StringByID (R.MyInternationalizationString.TipEquipmentNotOnline), Language.StringByID (R.MyInternationalizationString.Close)).Show ();
                        new Alert ("", ErrorCode.GatewayNoResponse, Language.StringByID (R.MyInternationalizationString.Close)).Show ();
                    });
                    return;
                } else if (bindReginIdStatus [0] != 0xF8) {
@@ -955,8 +974,13 @@
            MainPage.LoginUser.LastTime = DateTime.Now;
            Application.RunOnMainThread (() => {
                bodyView.RemoveAll ();
                //MainPage.WiFiStatus = "CrabtreeAdd/WiFi.png";
                UserMiddle.Init (true);
                MainPage.WiFiStatus = "CrabtreeAdd/WiFi.png";
                UserMiddle.btnLinkStatus.UnSelectedImagePath = MainPage.WiFiStatus;
            });
            //Utlis.ShowAppLinkStatus (AppLinkStatus.WiFi);
        }
@@ -1077,6 +1101,88 @@
        }
        #region 2020-07-02
        /// <summary>
        /// 定时搜索设备线程
        /// </summary>
        Thread searchDeviceThead;
        bool bStartSearch;
        /// <summary>
        /// 2020-07-02
        /// 网关配频模式时,开启自动搜索线程
        /// </summary>
        void StartSearchDeviceThead ()
        {
            StopSearchDeviceThead ();
            CommonPage.LocalPhoneFindDevice = true;
            CommonPage.FindGatewayChilren = true;
            CommonPage.RandomHigh = (byte)new Random ().Next (255);
            CommonPage.RandomLow = (byte)new Random ().Next (255);
            bStartSearch = true;
            searchDeviceThead = new Thread ((obj) => {
                while (bStartSearch) {
                    try {
                        //定时4S
                        Thread.Sleep (4000);
                        var ms = new System.IO.MemoryStream ();
                        ms.WriteByte (CommonPage.RandomHigh);
                        ms.WriteByte (CommonPage.RandomLow);
                        var list = CommonPage.DeviceList;
                        int tempCount = list.Count;
                        string s = ";";
                        for (int i = 0; i < list.Count; i++) {
                            Common common = list [i];
                            if (common.SubnetID != gatewayDeicve.SubnetID)
                                continue;
                            if (s.Contains (";" + common.SubnetID.ToString () + ":" + common.DeviceID.ToString ()))
                                continue;
                            s += common.SubnetID.ToString () + ":" + common.DeviceID.ToString () + ";";
                            ms.WriteByte (common.SubnetID);
                            ms.WriteByte (common.DeviceID);
                        }
                        Utlis.WriteLine ("SearchDeviceThead搜索非网关设备,网络地址是:" + CommonPage.EndPoint.ToString ());
                        var control = new Control ();
                        control.Send (new Target () {
                            IPEndPoint = CommonPage.EndPoint,
                            Command = Command.ReadDeviceModul,
                            SubnetID = gatewayDeicve.SubnetID,
                            DeviceID = 0xFF,
                            AddData = ms.ToArray ()
                        }, SendCount.Zero, false);
                        ms.Close ();
                    } catch {
                    }
                }
            });
            searchDeviceThead.Start ();
            Utlis.WriteLine ("----StartSearchDeviceThead----");
        }
        /// <summary>
        /// 暂停搜索设备线程
        /// </summary>
        void StopSearchDeviceThead ()
        {
            CommonPage.LocalPhoneFindDevice = false;
            CommonPage.FindGatewayChilren = false;
            bStartSearch = false;
            if (searchDeviceThead != null)
                searchDeviceThead.Abort ();
            Utlis.WriteLine ("----StopSearchDeviceThead----");
        }
        #endregion
        ///// <summary>
        ///// 查询当前住宅 网关列表
@@ -1202,7 +1308,7 @@
        //            }
        //        } catch (Exception ex) {
        //            Console.WriteLine (ex.Message);
        //            Utlis.WriteLine (ex.Message);
        //            Application.RunOnMainThread (() => {
        //                new Alert ("", Language.StringByID (R.MyInternationalizationString.OperationFailed), Language.StringByID (R.MyInternationalizationString.Close)).Show ();
        //            });
@@ -1217,7 +1323,7 @@
        //    //Room.InitAllRoom ();
        //}
        ///// <summary>
        ///// 修改URL