JLChen
2021-01-11 5a5a2b696866f947b6025d26c3302e8ffef46435
Crabtree/SmartHome/UI/SimpleControl/EquipmentPublicClass.cs
@@ -1,144 +1,225 @@
using System;
using System;
using Shared.SimpleControl.Phone;
using System.Collections.Generic;
using System.Text;
using System.Net.NetworkInformation;
namespace Shared.SimpleControl
{
    public class EquipmentPublicClass
    {
        static bool BSaveGateWay = true;
        public void AlertNotOnline ()
        {
            new Alert ("", Language.StringByID (R.MyInternationalizationString.TipEquipmentNotOnline), Language.StringByID (R.MyInternationalizationString.Close)).Show ();
            new Alert (Language.StringByID (R.MyInternationalizationString.Tip), Language.StringByID (R.MyInternationalizationString.TipEquipmentNotOnline), Language.StringByID (R.MyInternationalizationString.Close)).Show ();
        }
        static object lockObj = new object ();
        static bool isConnectiong = false;
        static DateTime mFlagDateTime;
        /// <summary>
        /// 检测/连接远程
        /// </summary>
        /// <returns>The link remote.</returns>
        /// <param name="status">Status.</param>
        public static void CheckLinkRemote (int status)
        public static void CheckLinkRemote (int status, bool IsReconnectRemote = true)
        {
            lock (lockObj) {
                Console.WriteLine ("CheckLinkRemote!!!");
                System.Threading.Tasks.Task.Run (() => {
                    try {
                        if (status == 0) {
                            Application.RunOnMainThread (() => {
                                MainPage.WiFiStatus = "CrabtreeAdd/WiFiUnlink.png";
                                MainPage.AddTip (Language.StringByID (R.MyInternationalizationString.InternetStatusTip));
                                //UserMiddle.LinkStatusTip.BackgroundColor = SkinStyle.Current.DelColor;
                            });
                        } else {
                            MainPage.WiFiStatus = "CrabtreeAdd/WiFi.png";
                            if (MainPage.LoginUser == null || !MainPage.LoginUser.IsLogin) {
                                return;
                            }
                            var localFileList = IO.FileUtils.ReadFiles ();
                            var gateWayList = localFileList.FindAll ((obj) => {
                                return (obj.StartsWith ("Equipment_")) && (
                                 obj.Split ('_') [1].ToString () == DeviceType.OnePortBus.ToString () ||
                                    obj.Split ('_') [1].ToString () == DeviceType.RCU.ToString () ||
                                    obj.Split ('_') [1].ToString () == DeviceType.OnePortWirelessFR.ToString ());
                            });
                            string rmf = "";
                            List<string> linkList = new List<string> ();
                            GatewayBase common = null;
                            string gateWayString = "";
                            if (gateWayList.Count > 1) {
                                foreach (var gatewayFileName in gateWayList) {
                                    var tempStrings = gatewayFileName.Split ('_');
                                    if (tempStrings [1].ToString () == DeviceType.OnePortBus.ToString () || tempStrings [1].ToString () == DeviceType.RCU.ToString () ||
                                        tempStrings [1].ToString () == DeviceType.OnePortWirelessFR.ToString ()) {
                                        gateWayString = CommonPage.MyEncodingUTF8.GetString (IO.FileUtils.ReadFile (gatewayFileName));
                                        common = Newtonsoft.Json.JsonConvert.DeserializeObject<GatewayBase> (gateWayString);
            //20S后强制重置isConnectiong状态,防止isConnectiong一直为true状态
            if (mFlagDateTime.AddSeconds (20).Ticks <= System.DateTime.Now.Ticks) {
                mFlagDateTime = DateTime.Now;
                if (isConnectiong) {
                    Shared.Utlis.WriteLine ("20s》isConnectiong true ");
                    isConnectiong = false;
                }
            }
                                        if (common.MAC.Replace (".", "") == UserConfig.Instance.GatewayMAC.Replace (".", "")) {
                                            rmf = gatewayFileName;
                                            if (!string.IsNullOrEmpty (common.Remote_UserName) && !string.IsNullOrEmpty (common.Remote_Password) &&
                                                !string.IsNullOrEmpty (common.Remote_GroupName) && !string.IsNullOrEmpty (common.Remote_ProjectName)) {
                                                break;
                                            }
                                        }
                                        common = null;
                                    }
                                }
                            } else if (gateWayList.Count == 1) {
                                rmf = gateWayList [0];
                                gateWayString = CommonPage.MyEncodingUTF8.GetString (IO.FileUtils.ReadFile (rmf));
                                common = Newtonsoft.Json.JsonConvert.DeserializeObject<GatewayBase> (gateWayString);
                            } else {
                                return;
                            }
            if (isConnectiong) {
                return;
            }
            isConnectiong = true;
            UserConfig.Instance.internetStatus = status;
            if (MainPage.LoginUser == null || !MainPage.LoginUser.IsLogin) {
                isConnectiong = false;
                return;
            }
#if DEBUG
                            if (common == null) {
                                if (MainPage.LoginUser.AccountString == "464027401@qq.com") {
                                    gateWayString = CommonPage.MyEncodingUTF8.GetString (IO.FileUtils.ReadFile (UserConfig.Instance.RemoteModeFile));
                                    common = Newtonsoft.Json.JsonConvert.DeserializeObject<GatewayBase> (gateWayString);
                                }
                            }
            Shared.Utlis.WriteLine ($"CheckLinkRemote: 开始");
#endif
                            if (common == null || common.Type == DeviceType.UnKown) {
                                return;
                            }
                            Application.RunOnMainThread (() => {
                                MainPage.Loading.Start ("Please wait...");
                            });
                            if (status == 1) {
                                //if (common.Type == DeviceType.OnePortWirelessFR) {
                                //    var gateWay = Newtonsoft.Json.JsonConvert.DeserializeObject<OnePortWirelessFR> (gateWayString);
                                //    var mac = gateWay.MAC.Replace (".", "");
                                //    SystemRemote.LinkRemote (gateWay.Remote_UserName, gateWay.Remote_ProjectName, gateWay.Remote_Password, true, mac);
                                //} else if (common.Type == DeviceType.OnePortBus) {
                                //    var gateWay = Newtonsoft.Json.JsonConvert.DeserializeObject<OnePortBus> (gateWayString);
                                //    var mac = gateWay.MAC.Replace (".", "");
                                //    SystemRemote.LinkRemote (gateWay.Remote_UserName, gateWay.Remote_ProjectName, gateWay.Remote_Password, true, mac);
                                //} else if (common.Type == DeviceType.RCU) {
                                //    var gateWay = Newtonsoft.Json.JsonConvert.DeserializeObject<RCU> (gateWayString);
                                //    var mac = gateWay.MAC.Replace (".", "");
                                //    SystemRemote.LinkRemote (gateWay.Remote_UserName, gateWay.Remote_ProjectName, gateWay.Remote_Password, true, mac);
                                //}
                                var gateWay = Newtonsoft.Json.JsonConvert.DeserializeObject<GatewayBase> (gateWayString);
                                SystemRemote.LinkRemote (gateWay.Remote_UserName, gateWay.Remote_ProjectName, gateWay.Remote_Password, true);
                            } else {
            new System.Threading.Thread (async () => {
                bool IsRemoteLoadingShow = false;
                //Control.IsCanLocal = false;
                try {
                    if (status == 0) {
                        Utlis.ShowAppLinkStatus (AppLinkStatus.CloudOffline);
                        Application.RunOnMainThread (() => {
                            MainPage.AddTip (Language.StringByID (R.MyInternationalizationString.InternetStatusTip));
                        });
                        if (CommonPage.IsRemote) {
                            SmartHome.MqttCommon.DisConnectRemote ("NO net", false);
                        }
                    } else {
                        #region 新方案
                        var mHomeGateway = UserConfig.Instance.HomeGateway;
                        //1.当前住宅云端还没绑定网关
                        if (mHomeGateway == null) {
                            Utlis.ShowAppLinkStatus (AppLinkStatus.WiFiOffline);
                            DisConnectRemoteAsync ();
                        }
                        //2.远程连接情况下,是否需要断开连接重连
                        if (IsReconnectRemote) {
                            if (CommonPage.IsRemote) {
                                CommonPage.IsRemote = false;
                                CommonPage.FindGateway = true;
                                var result = Control.ControlBytesSendHasReturn (Command.ReadDeviceMac, common.SubnetID, common.DeviceID, new byte [] { }, false);
                                CommonPage.FindGateway = false;
                                if (result != null) {
                                    var mac0 = CommonPage.byteToHex16 (result [0]) + "." + CommonPage.byteToHex16 (result [1]) + "." + CommonPage.byteToHex16 (result [2]) + "." + CommonPage.byteToHex16 (result [3]) + "." + CommonPage.byteToHex16 (result [4]) + "." + CommonPage.byteToHex16 (result [5]) + "." + CommonPage.byteToHex16 (result [6]) + "." + CommonPage.byteToHex16 (result [7]);
                                    //if (common.Type == DeviceType.OnePortBus) {
                                    if (common.MAC == mac0) {
                                        Application.RunOnMainThread (() => {
                                            MainPage.WiFiStatus = "CrabtreeAdd/WiFi.png";
                                            //UserMiddle.LinkStatusTip.BackgroundColor = SkinStyle.Current.LinkStatusTipColor;
                                        });
                                        return;
                                    }
                                }
                                var gateWay = Newtonsoft.Json.JsonConvert.DeserializeObject<GatewayBase> (gateWayString);
                                SystemRemote.LinkRemote (gateWay.Remote_UserName, gateWay.Remote_ProjectName, gateWay.Remote_Password, true);
                                Utlis.ShowAppLinkStatus (AppLinkStatus.WiFiOffline);
                                SmartHome.MqttCommon.DisConnectRemote ("IsReconnectRemote");
                            }
                        }
                    } catch (Exception ex) {
                        Console.WriteLine (ex.ToString ());
                    } finally {
                        Application.RunOnMainThread (() => {
                            if (status != 0) {
                                Shared.SimpleControl.Phone.UserMiddle.ReadAllDeviceStatus ();
                        bool canRemote = false;
                        if (CommonPage.IsRemote) {
                            SmartHome.MqttCommon.MqttRemoteSend (new byte [] { }, 3);
                        }
                        //当前住宅云端是否绑定网关,默认没有
                        bool HomeGatewaysExists = false;
                        SmartHome.MqttCommon.GatewayCommon = null;
                        if (mHomeGateway != null) {
                            //(1).当前住宅云端已经绑定网关
                            HomeGatewaysExists = true;
                            //(2).模拟生成一个网关对象
                            SmartHome.MqttCommon.GatewayCommon = new OnePortBus () {
                                SubnetID = (byte)mHomeGateway.subnetId,
                                DeviceID = (byte)mHomeGateway.deviceId,
                                MAC = mHomeGateway.mac,
                                Remote_IP1 = "115.29.251.24",
                                Remote_IP1_Prot = "9999",
                                Name = "OnePortBus",
                                obj1 = 1,
                            };
                            canRemote = true;
                            //(3).当前Wi-Fi连接,参试本地搜索网关
                            if (status == 2) {
                                //var result = Control.ControlBytesSendHasReturn (Command.ReadGateway, common.SubnetID, common.DeviceID, new byte [] { (byte)new Random ().Next (255), (byte)new Random ().Next (255) });
                                #region
                                //开始本地搜索网关...
                                //MainPage.AddTip (Language.StringByID (R.MyInternationalizationString.SearchingGatewayLocally));
                                MainPage.LoadingStart (Language.StringByID (R.MyInternationalizationString.SearchingGatewayLocally));
                                var control = new Control ();
                                control.Send (new Target () {
                                    IPEndPoint = new System.Net.IPEndPoint (System.Net.IPAddress.Parse (new Net.NetWiFi ().BroadcastIpAddress.ToString ()), 6000),
                                    Command = Command.ReadGateway,
                                    SubnetID = SmartHome.MqttCommon.GatewayCommon.SubnetID,
                                    DeviceID = SmartHome.MqttCommon.GatewayCommon.DeviceID,
                                    AddData = new byte [] { (byte)new Random ().Next (255), (byte)new Random ().Next (255) },
                                }, SendCount.Three, true, true);
                                var result = control.UsefulBytes;
                                #endregion
                                if (result != null) {
                                    var mac0 = CommonPage.byteToHex16 (result [5]) + "." + CommonPage.byteToHex16 (result [6]) + "." + CommonPage.byteToHex16 (result [7]) + "." + CommonPage.byteToHex16 (result [8]) + "." + CommonPage.byteToHex16 (result [9]) + "." + CommonPage.byteToHex16 (result [10]) + "." + CommonPage.byteToHex16 (result [11]) + "." + CommonPage.byteToHex16 (result [12]);
                                    if (SmartHome.MqttCommon.GatewayCommon.MAC.Replace (".", "").Replace (":", "").ToUpper () == mac0.Replace (".", "").Replace (":", "").ToUpper ()) {
                                        //搜索成功,启用本地连接
                                        //Control.IsCanLocal = true;//本地搜索成功,允许本地通信
                                        canRemote = false;
                                        Shared.SimpleControl.CommonPage.IsRemote = false;
                                        Application.RunOnMainThread (() => {
                                            Utlis.ShowAppLinkStatus (AppLinkStatus.WiFi);
                                            MainPage.Loading.Hide ();
                                        });
                                        UserMiddle.ReadAllDeviceStatus ();
                                        await SmartHome.MqttCommon.DisConnectRemote ("WIFI", false);
                                        MainPage.AddTip (Language.StringByID (R.MyInternationalizationString.SearchGatewaySuccess));
                                    }
                                } else {
                                    //搜索失败,启用远程连接
                                    MainPage.AddTip (Language.StringByID (R.MyInternationalizationString.SearchGatewayFail));
                                }
                            }
                            UserMiddle.btnLinkStatus.UnSelectedImagePath = MainPage.WiFiStatus;
                            MainPage.Loading.Hide ();
                        });
                            //(3).本地搜索不到网关或者没连接Wi-Fi情况下,检测是否拥有当前住宅的远程权限
                            if (canRemote) {
                                if (!UserConfig.Instance.AllowRemoteControl) {
                                    //没有当前住宅的远程权限
                                    canRemote = false;
                                    MainPage.AddTip (Language.StringByID (R.MyInternationalizationString.NoRemoteControlPermission));
                                }
                            }
                        }
                        //5.能远程
                        if (canRemote) {
                            if (!CommonPage.IsRemote) {
                                if (UserConfig.Instance.CheckHomeGatewaysNotEmpty ()) {
                                    if (!string.IsNullOrEmpty (UserConfig.Instance.GatewayMAC)) {
                                        // 5.1能远程,显示CloudUnlink状态,IsRemote设为true开始远程
                                        //MainPage.AddTip (Language.StringByID (R.MyInternationalizationString.StartEnablingRmote));
                                        MainPage.LoadingTipShow (Language.StringByID (R.MyInternationalizationString.StartEnablingRmote));
                                        Utlis.ShowAppLinkStatus (AppLinkStatus.CloudUnlink);
                                        IsRemoteLoadingShow = true;
                                        CommonPage.IsRemote = true;
                                        SmartHome.MqttCommon.InitState ();
                                    }
                                }
                            }
                        } else {
                            //6.不能远程,如果之前远程模式则断开MQTT连接,显示为未连接
                            if (CommonPage.IsRemote) {
                                Utlis.ShowAppLinkStatus (AppLinkStatus.WiFiOffline);
                                CommonPage.IsRemote = false;
                                await SmartHome.MqttCommon.DisConnectRemote ("", false);
                            }
                            //本地不存在与当前住宅绑定网关的数据
                            if (!HomeGatewaysExists) {
                                Utlis.ShowAppLinkStatus (AppLinkStatus.WiFiOffline);
                            }
                        }
                    }
                });
                    #endregion
                } catch (Exception ex) {
                    Shared.Utlis.WriteLine ("CheckLinkRemote : " + ex.ToString ());
                } finally {
                    isConnectiong = false;
                    //if (!IsRemoteLoadingShow) {
                    //    Application.RunOnMainThread (() => {
                    //        MainPage.Loading.Hide ();
                    //    });
                    //}
                    Application.RunOnMainThread (() => {
                        MainPage.Loading.Hide ();
                    });
                    ////不是远程 并且本地搜索不到匹配的网关就提示禁止本地发送
                    //if (!CommonPage.IsRemote && !Control.IsCanLocal && status != 0) {
                    //    Application.RunOnMainThread (() => {
                    //        Utlis.ShowAppLinkStatus (AppLinkStatus.WiFiUnlink);
                    //        //无法本地通信。当前住宅云端没有绑定网关、或者当前住宅本地没有网关数据!
                    //        //MainPage.AddTip (Language.StringByID (R.MyInternationalizationString.DisableLocalCommunication));
                    //        //new Alert (Language.StringByID (R.MyInternationalizationString.Tip),
                    //        //    Language.StringByID (R.MyInternationalizationString.DisableLocalCommunication),
                    //        //    Language.StringByID (R.MyInternationalizationString.Close)).Show ();
                    //    });
                    //}
#if DEBUG
                    Shared.Utlis.WriteLine ($"CheckLinkRemote: 结束");
#endif
                }
            }) { IsBackground = true }.Start ();
        }
        /// <summary>
        /// 关闭远程连接模式,并断开MQTT
        /// </summary>
        /// <returns></returns>
        static async System.Threading.Tasks.Task DisConnectRemoteAsync ()
        {
            if (CommonPage.IsRemote) {
                CommonPage.IsRemote = false;
                await SmartHome.MqttCommon.DisConnectRemote ();
            }
        }
    }
}
}