HDL Home App 第二版本 旧平台金堂用 正在使用
hxb
2022-08-30 25429f085093d89d543a0b90e30d0d62d1b7dac9
ZigbeeApp/Shared/Phone/UserCenter/CommonBase/Logic/HdlWifiLogic.cs
@@ -1,571 +1,576 @@
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
namespace Shared.Phone.UserCenter
{
    /// <summary>
    /// WiFi的逻辑
    /// </summary>
    public class HdlWifiLogic
    {
        #region ■ 变量声明___________________________
        /// <summary>
        /// WiFi的逻辑
        /// </summary>
        private static HdlWifiLogic m_Current = null;
        /// <summary>
        /// WiFi的逻辑
        /// </summary>
        public static HdlWifiLogic Current
        {
            get
            {
                if (m_Current == null)
                {
                    m_Current = new HdlWifiLogic();
                }
                return m_Current;
            }
        }
        /// <summary>
        /// 当前是否是网关热点
        /// </summary>
        public bool IsGatewayHotspot
        {
            get
            {
                string myId = this.SSID;
                if (myId != null && myId.StartsWith("hdlZigbeeGW") == true)
                {
                    return true;
                }
                return false;
            }
        }
        /// <summary>
        /// 当前是否是Mini网关热点
        /// </summary>
        public bool IsMiniGatewayHotspot
        {
            get
            {
                string myId = this.SSID;
                if (myId != null && myId.StartsWith("hdlZigbeeGW-") == true)
                {
                    return true;
                }
                return false;
            }
        }
        /// <summary>
        /// 当前wifi的SSID,也叫Wifi的名字(取不到时,会返回null)
        /// </summary>
        public string SSID
        {
            get
            {
#if iOS
                string ssiD = Shared.WiimuUPnP.SSID;
                if (string.IsNullOrEmpty(ssiD) == false && ssiD.StartsWith("\"") && ssiD.EndsWith("\""))
                {
                    ssiD = ssiD.Substring(1, ssiD.Length - 2);
                }
                return ssiD;
#endif
#if Android
                string ssiD = null;
                HdlThreadLogic.Current.RunThread(() =>
                {
                    Shared.Net.NetWiFi.GetWIFISSID((strId) =>
                    {
                        ssiD = strId;
                    });
                });
                int count = 0;
                while (ssiD == null)
                {
                    System.Threading.Thread.Sleep(50);
                    count++;
                    if (count == 20)
                    {
                        //1秒超时
                        return null;
                    }
                }
                if (string.IsNullOrEmpty(ssiD) == false && ssiD.StartsWith("\"") && ssiD.EndsWith("\""))
                {
                    ssiD = ssiD.Substring(1, ssiD.Length - 2);
                }
                return ssiD;
#endif
            }
        }
#if Android
        /// <summary>
        /// 定义全局变量
        /// </summary>
        private Com.Mediatek.Elian.ElianNative hdlWiFi = null;
#endif
        /// <summary>
        /// TCP协议
        /// </summary>
        private System.Net.Sockets.TcpClient tcpClient = null;
        /// <summary>
        /// 链接流对象
        /// </summary>
        private System.Net.Sockets.NetworkStream networkStream = null;
        /// <summary>
        /// Ap模式网关返回的秘钥
        /// </summary>
        private string randDesKey = null;
        /// <summary>
        /// 是否已经添加网络变化监听
        /// </summary>
        private bool hadAddListenNetWork = false;
        /// <summary>
        /// 能否访问http
        /// </summary>
        private bool m_CanAccessHttp = true;
        /// <summary>
        /// 上一次访问http的时间
        /// </summary>
        private DateTime oldAccessHttpTime = DateTime.Now;
        /// <summary>
        /// 能否访问http
        /// </summary>
        public bool CanAccessHttp
        {
            set
            {
                m_CanAccessHttp = value;
                oldAccessHttpTime = DateTime.Now;
            }
            get
            {
                //8秒后允许再次访问
                if (m_CanAccessHttp == true || (DateTime.Now - oldAccessHttpTime).TotalMilliseconds > 8 * 1000)
                {
                    oldAccessHttpTime = DateTime.Now;
                    return true;
                }
                return false;
            }
        }
        /// <summary>
        /// 变更网络时的事件
        /// </summary>
        private string changedNetworkTime = string.Empty;
        /// <summary>
        /// 当前 wifi 的
        /// </summary>
        private string oldSsid = string.Empty;
        #endregion
        #region ■ Ap模式的TCP链接____________________
        /// <summary>
        /// 打开Ap模式的TCP链接(有错误时,直接返回错误消息。没有错误时,返回null)
        /// </summary>
        /// <returns></returns>
        public string StartApTcpConnection()
        {
            try
            {
                //TCP连接
                tcpClient = new System.Net.Sockets.TcpClient();
                tcpClient.Connect("192.168.8.1", 5000);
                networkStream = tcpClient.GetStream();
                //加密数据
                string sendDataMsg = "hdl1985.";
                string DefaultdesKey = "hdl1985.";
                //44bytes 加密数据 DES加密 base64密文
                var sendData = Encoding.UTF8.GetBytes(DesEncrypt(sendDataMsg, DefaultdesKey));
                //将数据写入网络流
                networkStream.Write(sendData, 0, sendData.Length);
                System.Threading.Thread.Sleep(500);
                //2.接收状态,长度<1024字节
                byte[] bytes = new Byte[1024];
                int length = networkStream.Read(bytes, 0, bytes.Length);
                if (length == 0)
                {
                    //通信链接失败
                    return Language.StringByID(R.MyInternationalizationString.uCommunicationLinkFail);
                }
                string data = Encoding.UTF8.GetString(bytes, 0, length);
                //网关返回的秘钥
                this.randDesKey = DESDecrypt(data, DefaultdesKey);
                return null;
            }
            catch (Exception ex)
            {
                HdlLogLogic.Current.WriteLog(ex);
                this.CloseApTcpConnection();
                //通信链接失败
                return Language.StringByID(R.MyInternationalizationString.uCommunicationLinkFail);
            }
        }
        /// <summary>
        /// Ap模式 发送密码到家庭的路由器
        /// </summary>
        /// <param name="ssid"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public bool SendApHomeWifiPassword(string ssid, string password)
        {
            try
            {
                //加密数据
                string data2 = "ssid:" + ssid + "," + "pwd:" + password;
                var sendData2 = Encoding.UTF8.GetBytes(DesEncrypt(data2, randDesKey));
                //将数据写入网络流
                networkStream.Write(sendData2, 0, sendData2.Length);
                return true;
            }
            catch (Exception ex)
            {
                HdlLogLogic.Current.WriteLog(ex);
                return false;
            }
        }
        /// <summary>
        /// 关闭Ap模式的tcp链接
        /// </summary>
        public void CloseApTcpConnection()
        {
            try
            {
                //关闭客户端
                tcpClient?.Close();
                tcpClient = null;
                networkStream = null;
                randDesKey = null;
            }
            catch (Exception ex)
            {
                HdlLogLogic.Current.WriteLog(ex);
            }
        }
        #endregion
        #region ■ 加密解密___________________________
        /// <summary>
        /// //加密数据
        /// </summary>
        /// <param name="pToDesEncrypt"></param>
        /// <param name="sKey">DES秘钥</param>
        /// <returns></returns>
        private string DesEncrypt(string pToDesEncrypt, string sKey)
        {
            // 创建des加密没
            using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
            {
                // 得到UTF-8的数据源
                byte[] inputByteArray = Encoding.UTF8.GetBytes(pToDesEncrypt);
                // 设置key和iv密钥
                des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
                des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
                //由于java是使用默认加密模式,C#默认是CBC,需要修改为ECB
                des.Mode = CipherMode.CBC;
                des.Padding = PaddingMode.PKCS7;
                // 创建数据流并进行加密
                var ms = new System.IO.MemoryStream();
                using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(inputByteArray, 0, inputByteArray.Length);
                    cs.FlushFinalBlock();
                    cs.Close();
                }
                // 关闭数据流
                ms.Close();
                return Convert.ToBase64String(ms.ToArray());//base64密文
            }
        }
        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="pToDecrypt"></param>
        /// <param name="key">解密密匙</param>
        /// <returns></returns>
        private string DESDecrypt(string pToDecrypt, string key = null)
        {
            byte[] inputByteArray = Convert.FromBase64String(pToDecrypt);
            using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
            {
                des.Key = ASCIIEncoding.ASCII.GetBytes(key);
                des.IV = ASCIIEncoding.ASCII.GetBytes(key);
                var ms = new System.IO.MemoryStream();
                using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(inputByteArray, 0, inputByteArray.Length);
                    cs.FlushFinalBlock();
                    cs.Close();
                }
                string str = Encoding.UTF8.GetString(ms.ToArray());
                ms.Close();
                return str;
            }
        }
        #endregion
        #region ■ 监听网络变化_______________________
        /// <summary>
        /// 开启监听网络
        /// </summary>
        public void StartListenNetWork()
        {
            if (hadAddListenNetWork == true)
            {
                return;
            }
            hadAddListenNetWork = true;
#if Android
            //开启监听安卓网络变化
            BaseActivity.NetworkStateChanged += (value) =>
            {
                //网络变化
                this.NetworkStateChanged(value);
            };
#endif
#if iOS
            //开启监听IOS网络变化
            GateWay.Ios.Reachability.ReachabilityChanged += (sender, e) =>
            {
                var internetStatus = GateWay.Ios.Reachability.InternetConnectionStatus();
                if (internetStatus == GateWay.Ios.NetworkStatus.NotReachable)//没有网络连接 0
                {
                    //网络变化
                    this.NetworkStateChanged(0);
                }
                else if (internetStatus == GateWay.Ios.NetworkStatus.ReachableViaCarrierDataNetwork)//3,4G的网络连接 1
                {
                    //网络变化
                    this.NetworkStateChanged(1);
                }
                else if (internetStatus == GateWay.Ios.NetworkStatus.ReachableViaWiFiNetwork) //wifi的网络连接 2
                {
                    //网络变化
                    this.NetworkStateChanged(2);
                }
            };
#endif
        }
        /// <summary>
        /// 监听安卓网络变化
        /// </summary>
        /// <param name="value">0:没有网络 1:4G  2:wifi</param>
        public void NetworkStateChanged(int value)
        {
            if (Common.Config.Instance.HomeId == string.Empty)
            {
                //在登录界面不处理
                return;
            }
#if iOS
            var nowSsid = this.SSID;
            if (this.oldSsid == nowSsid)
            {
                //如果当前 wifi 的名字一样,则不处理
                ZigBee.Common.Application.FindGateWaySocket.Start();
                return;
            }
            this.oldSsid = nowSsid;
#endif
            //没有网络
            if (value == 0)
            {
                this.CanAccessHttp = false;
                //关闭Socket
                ZigBee.Common.Application.FindGateWaySocket.Stop();
            }
            //WIFI或者4G时
            if (value == 1 || value == 2)
            {
                //允许联网
                this.CanAccessHttp = true;
                this.changedNetworkTime = DateTime.Now.ToString("yyyyMMdd HH.mm.ss");
                //当前执行此线程的时间
                string thisThreadTime = this.changedNetworkTime;
                HdlThreadLogic.Current.RunThread(() =>
                {
                    //不管如何,都要显示转圈
                    ProgressBar.Show();
                    //检测是否已经完成账号信息初始化
                    if (UserCenterResourse.UserInfo.InitUserInfoSuccess == false
                       && Common.Config.Instance.HomeId != string.Empty)
                    {
                        //重新初始化账号信息
                        UserCenterLogic.ReInitUserAccoutInfo();
                        //因为上面这个东西耗时蛮久的,所以处理完之后进行判断
                        if (thisThreadTime != this.changedNetworkTime)
                        {
                            //在处理的过程中,切换了网络,把下面的处理交给另外的线程
                            return;
                        }
                    }
                    //重新初始化Socket
                    ZigBee.Common.Application.FindGateWaySocket.Stop();
                    System.Threading.Thread.Sleep(100);
                    //断掉本地连接
                    HdlGatewayLogic.Current.ClearAllRealGatewayConection(true);
                    //断掉远程
                    ZigBee.Device.ZbGateway.DisConnectRemoteMqttClient();
                    //如果是wifi
                    if (value == 2)
                    {
                        ZigBee.Common.Application.FindGateWaySocket.Start();
                        //借用一下这个变量(检测能否广播到网关)
                        UserCenterResourse.DicReceiveGatewayTest = new Dictionary<string, ZigBee.Device.ZbGateway>();
                        UserCenterResourse.HideOption.CheckCanReceiveGateway = 1;
                        //固定等个3秒吧
                        System.Threading.Thread.Sleep(2500);
                        if (thisThreadTime != this.changedNetworkTime)
                        {
                            //变更了网络,交由其他线程处理
                            return;
                        }
                        UserCenterResourse.HideOption.CheckCanReceiveGateway = 0;
                        System.Threading.Thread.Sleep(500);
                        bool canReceiveGw = false;
                        foreach (var gateway in UserCenterResourse.DicReceiveGatewayTest.Values)
                        {
                            if (gateway.HomeId == Common.Config.Instance.Home.Id)
                            {
                                //能够搜索得到网关
                                canReceiveGw = true;
                                break;
                            }
                        }
                        UserCenterResourse.DicReceiveGatewayTest = null;
                        //设置远程连接的初始值
                        ZigBee.Device.ZbGateway.IsRemote = canReceiveGw == false;
                        if (canReceiveGw == false)
                        {
                            //如果是远程的话,追加等待时间(总共5秒)
                            System.Threading.Thread.Sleep(2000);
                        }
                    }
                    else if (value == 1)
                    {
                        //如果是4G的话,直接等待
                        System.Threading.Thread.Sleep(4500);
                    }
                    ProgressBar.Close();
                }, ShowErrorMode.NO);
            }
        }
        #endregion
        #region ■ 一般方法___________________________
#if Android
        /// <summary>
        /// 开始Wi-Fi配网
        /// </summary>
        /// <param name="wifiName">wifi名字</param>
        /// <param name="wifiPsw">wifi密码</param>
        /// <param name="p2">我也不知道这个是什么东西</param>
        /// <returns></returns>
        public bool StartSmartConnection(string wifiName, string wifiPsw, string p2 = "")
        {
            if (hdlWiFi == null)
            {
                var result2 = Com.Mediatek.Elian.ElianNative.LoadLib();
                //初始化Wi-Fi配网
                this.hdlWiFi = new Com.Mediatek.Elian.ElianNative();
                var value = hdlWiFi.InitSmartConnection(null, 1, 1);
            }
            //开始Wi-Fi配网
            var result = hdlWiFi.StartSmartConnection(wifiName, wifiPsw, p2);
            return true;
        }
        /// <summary>
        /// 停止Wi-Fi配网
        /// </summary>
        public void StopSmartConnection()
        {
            if (hdlWiFi != null)
            {
                //停止Wi-Fi配网
                var result = hdlWiFi.StopSmartConnection();
                hdlWiFi = null;
            }
        }
#endif
#if iOS
        /// <summary>
        /// 开始Wi-Fi配网
        /// </summary>
        /// <param name="wifiName">wifi名字</param>
        /// <param name="wifiPsw">wifi密码</param>
        /// <param name="p2">我也不知道这个是什么东西</param>
        /// <returns></returns>
        public bool StartSmartConnection(string wifiName, string wifiPsw, string p2 = "")
        {
            //初始化Wi-Fi连接
            Com.Mediatek.Elian.ElianNative.InitSmartConnection("1", 1, 1);
            //开始Wi-Fi连接
            var result = Com.Mediatek.Elian.ElianNative.StartSmartConnection(wifiName, wifiPsw, p2);
            return true;
        }
        /// <summary>
        /// 停止Wi-Fi配网
        /// </summary>
        public void StopSmartConnection()
        {
            //停止Wi-Fi配网
            Com.Mediatek.Elian.ElianNative.StopSmartConnection();
        }
#endif
        /// <summary>
        /// 打开手机wifi设置界面
        /// </summary>
        public void OpenAppWifiSettion()
        {
            if (Application.DeviceType == Shared.Device.Android)
            {
                ///打开WI-IF界面
                CommonClass.OpenAction("android.settings.WIFI_SETTINGS");
            }
            else
            {
                CommonClass.OpenAction("App-Prefs:root=WIFI");
            }
        }
        #endregion
    }
}
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
namespace Shared.Phone.UserCenter
{
    /// <summary>
    /// WiFi的逻辑
    /// </summary>
    public class HdlWifiLogic
    {
        #region ■ 变量声明___________________________
        /// <summary>
        /// WiFi的逻辑
        /// </summary>
        private static HdlWifiLogic m_Current = null;
        /// <summary>
        /// WiFi的逻辑
        /// </summary>
        public static HdlWifiLogic Current
        {
            get
            {
                if (m_Current == null)
                {
                    m_Current = new HdlWifiLogic();
                }
                return m_Current;
            }
        }
        /// <summary>
        /// 当前是否是网关热点
        /// </summary>
        public bool IsGatewayHotspot
        {
            get
            {
                //string myId = this.SSID;
                //if (myId != null && myId.StartsWith("hdlZigbeeGW") == true)
                //{
                //    return true;
                //}
                //2021.03.22 个人决定,不再检测这个东西
                return true;
            }
        }
        /// <summary>
        /// 当前是否是Mini网关热点
        /// </summary>
        public bool IsMiniGatewayHotspot
        {
            get
            {
                //string myId = this.SSID;
                //if (myId != null && myId.StartsWith("hdlZigbeeGW-") == true)
                //{
                //    return true;
                //}
                //2021.03.22 个人决定,不再检测这个东西
                return true;
            }
        }
        /// <summary>
        /// 当前wifi的SSID,也叫Wifi的名字(取不到时,会返回null)
        /// </summary>
        public string SSID
        {
            get
            {
#if iOS
                string ssiD = Shared.WiimuUPnP.SSID;
                if (string.IsNullOrEmpty(ssiD) == false && ssiD.StartsWith("\"") && ssiD.EndsWith("\""))
                {
                    ssiD = ssiD.Substring(1, ssiD.Length - 2);
                }
                return ssiD;
#endif
#if Android
                string ssiD = null;
                HdlThreadLogic.Current.RunThread(() =>
                {
                    Shared.Net.NetWiFi.GetWIFISSID((strId) =>
                    {
                        ssiD = strId;
                    });
                });
                int count = 0;
                while (ssiD == null)
                {
                    System.Threading.Thread.Sleep(50);
                    count++;
                    if (count == 20)
                    {
                        //1秒超时
                        return null;
                    }
                }
                if (string.IsNullOrEmpty(ssiD) == false && ssiD.StartsWith("\"") && ssiD.EndsWith("\""))
                {
                    ssiD = ssiD.Substring(1, ssiD.Length - 2);
                }
                return ssiD;
#endif
            }
        }
#if Android
        /// <summary>
        /// 定义全局变量
        /// </summary>
        private Com.Mediatek.Elian.ElianNative hdlWiFi = null;
#endif
        /// <summary>
        /// TCP协议
        /// </summary>
        private System.Net.Sockets.TcpClient tcpClient = null;
        /// <summary>
        /// 链接流对象
        /// </summary>
        private System.Net.Sockets.NetworkStream networkStream = null;
        /// <summary>
        /// Ap模式网关返回的秘钥
        /// </summary>
        private string randDesKey = null;
        /// <summary>
        /// 是否已经添加网络变化监听
        /// </summary>
        private bool hadAddListenNetWork = false;
        /// <summary>
        /// 能否访问http
        /// </summary>
        private bool m_CanAccessHttp = true;
        /// <summary>
        /// 上一次访问http的时间
        /// </summary>
        private DateTime oldAccessHttpTime = DateTime.Now;
        /// <summary>
        /// 能否访问http
        /// </summary>
        public bool CanAccessHttp
        {
            set
            {
                m_CanAccessHttp = value;
                oldAccessHttpTime = DateTime.Now;
            }
            get
            {
                //8秒后允许再次访问
                if (m_CanAccessHttp == true || (DateTime.Now - oldAccessHttpTime).TotalMilliseconds > 8 * 1000)
                {
                    oldAccessHttpTime = DateTime.Now;
                    return true;
                }
                return false;
            }
        }
        /// <summary>
        /// 变更网络时的事件
        /// </summary>
        private string changedNetworkTime = string.Empty;
        /// <summary>
        /// 当前 wifi 的
        /// </summary>
        private string oldSsid = string.Empty;
        #endregion
        #region ■ Ap模式的TCP链接____________________
        /// <summary>
        /// 打开Ap模式的TCP链接(有错误时,直接返回错误消息。没有错误时,返回null)
        /// </summary>
        /// <returns></returns>
        public string StartApTcpConnection()
        {
            try
            {
                //TCP连接
                tcpClient = new System.Net.Sockets.TcpClient();
                tcpClient.Connect("192.168.8.1", 5000);
                networkStream = tcpClient.GetStream();
                networkStream.ReadTimeout = 1000;
                //加密数据
                string sendDataMsg = "hdl1985.";
                string DefaultdesKey = "hdl1985.";
                //44bytes 加密数据 DES加密 base64密文
                var sendData = Encoding.UTF8.GetBytes(DesEncrypt(sendDataMsg, DefaultdesKey));
                //将数据写入网络流
                networkStream.Write(sendData, 0, sendData.Length);
                System.Threading.Thread.Sleep(500);
                //2.接收状态,长度<1024字节
                byte[] bytes = new Byte[1024];
                int length = networkStream.Read(bytes, 0, bytes.Length);
                if (length == 0)
                {
                    //通信链接失败
                    return Language.StringByID(R.MyInternationalizationString.uCommunicationLinkFail);
                }
                string data = Encoding.UTF8.GetString(bytes, 0, length);
                //网关返回的秘钥
                this.randDesKey = DESDecrypt(data, DefaultdesKey);
                return null;
            }
            catch (Exception ex)
            {
                HdlLogLogic.Current.WriteLog(ex);
                this.CloseApTcpConnection();
                //通信链接失败
                return Language.StringByID(R.MyInternationalizationString.uCommunicationLinkFail);
            }
        }
        /// <summary>
        /// Ap模式 发送密码到家庭的路由器
        /// </summary>
        /// <param name="ssid"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public bool SendApHomeWifiPassword(string ssid, string password)
        {
            try
            {
                //加密数据
                string data2 = "ssid:" + ssid + "," + "pwd:" + password;
                var sendData2 = Encoding.UTF8.GetBytes(DesEncrypt(data2, randDesKey));
                //将数据写入网络流
                networkStream.Write(sendData2, 0, sendData2.Length);
                return true;
            }
            catch (Exception ex)
            {
                HdlLogLogic.Current.WriteLog(ex);
                return false;
            }
        }
        /// <summary>
        /// 关闭Ap模式的tcp链接
        /// </summary>
        public void CloseApTcpConnection()
        {
            try
            {
                //关闭客户端
                tcpClient?.Close();
                tcpClient = null;
                networkStream = null;
                randDesKey = null;
            }
            catch (Exception ex)
            {
                HdlLogLogic.Current.WriteLog(ex);
            }
        }
        #endregion
        #region ■ 加密解密___________________________
        /// <summary>
        /// //加密数据
        /// </summary>
        /// <param name="pToDesEncrypt"></param>
        /// <param name="sKey">DES秘钥</param>
        /// <returns></returns>
        private string DesEncrypt(string pToDesEncrypt, string sKey)
        {
            // 创建des加密没
            using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
            {
                // 得到UTF-8的数据源
                byte[] inputByteArray = Encoding.UTF8.GetBytes(pToDesEncrypt);
                // 设置key和iv密钥
                des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
                des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
                //由于java是使用默认加密模式,C#默认是CBC,需要修改为ECB
                des.Mode = CipherMode.CBC;
                des.Padding = PaddingMode.PKCS7;
                // 创建数据流并进行加密
                var ms = new System.IO.MemoryStream();
                using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(inputByteArray, 0, inputByteArray.Length);
                    cs.FlushFinalBlock();
                    cs.Close();
                }
                // 关闭数据流
                ms.Close();
                return Convert.ToBase64String(ms.ToArray());//base64密文
            }
        }
        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="pToDecrypt"></param>
        /// <param name="key">解密密匙</param>
        /// <returns></returns>
        private string DESDecrypt(string pToDecrypt, string key = null)
        {
            byte[] inputByteArray = Convert.FromBase64String(pToDecrypt);
            using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
            {
                des.Key = ASCIIEncoding.ASCII.GetBytes(key);
                des.IV = ASCIIEncoding.ASCII.GetBytes(key);
                var ms = new System.IO.MemoryStream();
                using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(inputByteArray, 0, inputByteArray.Length);
                    cs.FlushFinalBlock();
                    cs.Close();
                }
                string str = Encoding.UTF8.GetString(ms.ToArray());
                ms.Close();
                return str;
            }
        }
        #endregion
        #region ■ 监听网络变化_______________________
        /// <summary>
        /// 开启监听网络
        /// </summary>
        public void StartListenNetWork()
        {
            if (hadAddListenNetWork == true)
            {
                return;
            }
            hadAddListenNetWork = true;
#if Android
            //开启监听安卓网络变化
            BaseActivity.NetworkStateChanged += (value) =>
            {
                //网络变化
                this.NetworkStateChanged(value);
            };
#endif
#if iOS
            //开启监听IOS网络变化
            GateWay.Ios.Reachability.ReachabilityChanged += (sender, e) =>
            {
                var internetStatus = GateWay.Ios.Reachability.InternetConnectionStatus();
                if (internetStatus == GateWay.Ios.NetworkStatus.NotReachable)//没有网络连接 0
                {
                    //网络变化
                    this.NetworkStateChanged(0);
                }
                else if (internetStatus == GateWay.Ios.NetworkStatus.ReachableViaCarrierDataNetwork)//3,4G的网络连接 1
                {
                    //网络变化
                    this.NetworkStateChanged(1);
                }
                else if (internetStatus == GateWay.Ios.NetworkStatus.ReachableViaWiFiNetwork) //wifi的网络连接 2
                {
                    //网络变化
                    this.NetworkStateChanged(2);
                }
            };
#endif
        }
        /// <summary>
        /// 监听安卓网络变化
        /// </summary>
        /// <param name="value">0:没有网络 1:4G  2:wifi</param>
        public void NetworkStateChanged(int value)
        {
            if (Common.Config.Instance.HomeId == string.Empty)
            {
                //在登录界面不处理
                return;
            }
#if iOS
            var nowSsid = this.SSID;
            if (this.oldSsid == nowSsid)
            {
                //如果当前 wifi 的名字一样,则不处理
                ZigBee.Common.Application.FindGateWaySocket.Start();
                return;
            }
            this.oldSsid = nowSsid;
#endif
            //没有网络
            if (value == 0)
            {
                this.CanAccessHttp = false;
                //关闭Socket
                ZigBee.Common.Application.FindGateWaySocket.Stop();
            }
            //WIFI或者4G时
            if (value == 1 || value == 2)
            {
                //允许联网
                this.CanAccessHttp = true;
                this.changedNetworkTime = DateTime.Now.ToString("yyyyMMdd HH.mm.ss");
                //当前执行此线程的时间
                string thisThreadTime = this.changedNetworkTime;
                HdlThreadLogic.Current.RunThread(() =>
                {
                    //不管如何,都要显示转圈
                    ProgressBar.Show();
                    //检测是否已经完成账号信息初始化
                    if (UserCenterResourse.UserInfo.InitUserInfoSuccess == false
                       && Common.Config.Instance.HomeId != string.Empty)
                    {
                        //重新初始化账号信息
                        UserCenterLogic.ReInitUserAccoutInfo();
                        //因为上面这个东西耗时蛮久的,所以处理完之后进行判断
                        if (thisThreadTime != this.changedNetworkTime)
                        {
                            //在处理的过程中,切换了网络,把下面的处理交给另外的线程
                            return;
                        }
                    }
                    //重新初始化Socket
                    ZigBee.Common.Application.FindGateWaySocket.Stop();
                    System.Threading.Thread.Sleep(100);
                    //断掉本地连接
                    HdlGatewayLogic.Current.ClearAllRealGatewayConection(true);
                    //断掉远程
                    ZigBee.Device.ZbGateway.CloseRemoteConnectionOnForce();
                    //如果是wifi
                    if (value == 2)
                    {
                        ZigBee.Common.Application.FindGateWaySocket.Start();
                        //借用一下这个变量(检测能否广播到网关)
                        UserCenterResourse.DicReceiveGatewayTest = new Dictionary<string, ZigBee.Device.ZbGateway>();
                        UserCenterResourse.HideOption.CheckCanReceiveGateway = 1;
                        //固定等个3秒吧
                        System.Threading.Thread.Sleep(2500);
                        if (thisThreadTime != this.changedNetworkTime)
                        {
                            //变更了网络,交由其他线程处理
                            return;
                        }
                        UserCenterResourse.HideOption.CheckCanReceiveGateway = 0;
                        System.Threading.Thread.Sleep(500);
                        bool canReceiveGw = false;
                        foreach (var gateway in UserCenterResourse.DicReceiveGatewayTest.Values)
                        {
                            if (gateway.HomeId == Common.Config.Instance.Home.Id)
                            {
                                //能够搜索得到网关
                                canReceiveGw = true;
                                break;
                            }
                        }
                        UserCenterResourse.DicReceiveGatewayTest = null;
                        //设置远程连接的初始值
                        ZigBee.Device.ZbGateway.IsRemote = canReceiveGw == false;
                        if (canReceiveGw == false)
                        {
                            //如果是远程的话,追加等待时间(总共5秒)
                            System.Threading.Thread.Sleep(2000);
                        }
                    }
                    else if (value == 1)
                    {
                        //如果是4G的话,直接等待
                        System.Threading.Thread.Sleep(4500);
                    }
                    ProgressBar.Close();
                }, ShowErrorMode.NO);
            }
        }
        #endregion
        #region ■ 一般方法___________________________
#if Android
        /// <summary>
        /// 开始Wi-Fi配网
        /// </summary>
        /// <param name="wifiName">wifi名字</param>
        /// <param name="wifiPsw">wifi密码</param>
        /// <param name="p2">我也不知道这个是什么东西</param>
        /// <returns></returns>
        public bool StartSmartConnection(string wifiName, string wifiPsw, string p2 = "")
        {
            if (hdlWiFi == null)
            {
                var result2 = Com.Mediatek.Elian.ElianNative.LoadLib();
                //初始化Wi-Fi配网
                this.hdlWiFi = new Com.Mediatek.Elian.ElianNative();
                var value = hdlWiFi.InitSmartConnection(null, 1, 1);
            }
            //开始Wi-Fi配网
            var result = hdlWiFi.StartSmartConnection(wifiName, wifiPsw, p2);
            return true;
        }
        /// <summary>
        /// 停止Wi-Fi配网
        /// </summary>
        public void StopSmartConnection()
        {
            if (hdlWiFi != null)
            {
                //停止Wi-Fi配网
                var result = hdlWiFi.StopSmartConnection();
                hdlWiFi = null;
            }
        }
#endif
#if iOS
        /// <summary>
        /// 开始Wi-Fi配网
        /// </summary>
        /// <param name="wifiName">wifi名字</param>
        /// <param name="wifiPsw">wifi密码</param>
        /// <param name="p2">我也不知道这个是什么东西</param>
        /// <returns></returns>
        public bool StartSmartConnection(string wifiName, string wifiPsw, string p2 = "")
        {
            //初始化Wi-Fi连接
            //Com.Mediatek.Elian.ElianNative.InitSmartConnection("1", 1, 1);
            Com.Mediatek.Elian.ElianNative.InitSmartConnection( 1, 1);
            //开始Wi-Fi连接
            var result = Com.Mediatek.Elian.ElianNative.StartSmartConnection(wifiName, wifiPsw, p2);
            return true;
        }
        /// <summary>
        /// 停止Wi-Fi配网
        /// </summary>
        public void StopSmartConnection()
        {
            //停止Wi-Fi配网
            Com.Mediatek.Elian.ElianNative.StopSmartConnection();
        }
#endif
        /// <summary>
        /// 打开手机wifi设置界面
        /// </summary>
        public void OpenAppWifiSettion()
        {
            if (Application.DeviceType == Shared.Device.Android)
            {
                ///打开WI-IF界面
                CommonClass.OpenAction("android.settings.WIFI_SETTINGS");
            }
            else
            {
                CommonClass.OpenAction("App-Prefs:root=WIFI");
            }
        }
        #endregion
    }
}