| | |
| | | /// <summary> |
| | | /// 主网关 |
| | | /// </summary> |
| | | /// <value>The main gate way.</value> |
| | | [Newtonsoft.Json.JsonIgnore] |
| | | public static ZbGateway MainGateWay |
| | | { |
| | | get |
| | |
| | | /// <summary> |
| | | /// 是否使用远程连接模式 |
| | | /// </summary> |
| | | /// <value><c>true</c> if is remote; otherwise, <c>false</c>.</value> |
| | | public static bool IsRemote; |
| | | |
| | | /// <summary>
|
| | | /// 是否拥有远程连接的权限
|
| | | /// </summary> |
| | | [Newtonsoft.Json.JsonIgnore] |
| | | public static bool AllowRemoteCtrl = true; |
| | | public static bool IsRemote; |
| | | |
| | | /// <summary> |
| | | /// 网关保存路径 |
| | |
| | | return password; |
| | | } |
| | | } |
| | |
|
| | | /// <summary> |
| | | /// 网关远程连接的一个标识ID,获取到了就不再改变 |
| | | /// </summary> |
| | | [Newtonsoft.Json.JsonIgnore] |
| | | private static string RemoteClientId = new Random().Next(10, 99).ToString(); |
| | | |
| | | /// <summary> |
| | | /// 网关是否加密 |
| | |
| | | string accountId = string.Empty; |
| | | if (homeId != string.Empty)
|
| | | {
|
| | | if (Shared.Phone.UserCenter.UserCenterResourse.UserInfo.AuthorityNo == 1)
|
| | | {
|
| | | //主账号
|
| | | accountId = Config.Instance.Guid;
|
| | | }
|
| | | else
|
| | | {
|
| | | accountId = Config.Instance.Home.MainUserDistributedMark;
|
| | | }
|
| | | } |
| | | var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 82 } }; |
| | | var data = new JObject { { "HomeId", homeId }, { "AccountId", accountId } }; |
| | |
| | | /// </summary> |
| | | public async System.Threading.Tasks.Task<Panel.PanelSwitchLevelInfo> ClientDataPassthroughBytesAsync(string deviceAddr, int devicePoint, long dataLength, byte[] passData) |
| | | { |
| | | var myDevice = Shared.Common.LocalDevice.Current.GetDevice(deviceAddr, devicePoint); |
| | | var myDevice = Shared.Phone.HdlDeviceCommonLogic.Current.GetDevice(deviceAddr, devicePoint); |
| | | |
| | | Panel.PanelSwitchLevelInfo result = null; |
| | | |
| | |
| | | }
|
| | | #endregion |
| | | |
| | | #region 通讯连接 |
| | | #region 本地通讯连接 |
| | | /// <summary>
|
| | | /// 本地连接是否连接成功
|
| | | /// </summary> |
| | | [Newtonsoft.Json.JsonIgnore] |
| | | public bool LocalIsConnected; |
| | | /// <summary> |
| | | /// 局域网的MQTT |
| | | /// </summary> |
| | | IMqttClient localMqttClient = new MqttFactory().CreateMqttClient(); |
| | | bool localMqttIsConnecting; |
| | | [Newtonsoft.Json.JsonIgnore] |
| | | public bool localIsConnected; |
| | | private IMqttClient localMqttClient = new MqttFactory().CreateMqttClient(); |
| | | /// <summary> |
| | | /// 手机标识 |
| | | /// 本地mqtt是否正在连接中
|
| | | /// </summary> |
| | | static Guid currentGuid = Guid.NewGuid(); |
| | | private bool localMqttIsConnecting; |
| | | /// <summary> |
| | | /// 本地连接的一个客户端ID(app启动之后就不变了) |
| | | /// </summary> |
| | | private static Guid LocalConnectGuid = Guid.NewGuid(); |
| | | |
| | | public async Task SendAesKey()
|
| | | {
|
| | |
| | | {
|
| | | if (localMqttIsConnecting
|
| | | || Shared.Common.Config.Instance.HomeId == ""
|
| | | || localIsConnected)
|
| | | || LocalIsConnected) |
| | | {
|
| | | return;
|
| | | } |
| | | await System.Threading.Tasks.Task.Factory.StartNew(async () => |
| | | await Task.Factory.StartNew(async () => |
| | | { |
| | | try |
| | | { |
| | |
| | | DebugPrintLog($" 本地连接成功_网关IP:{brokerName}_网关是否加:{IsEncry}_当前密码:{Password}");
|
| | | IsRemote = false;
|
| | | //Log写入(调试用)
|
| | | if (Shared.Phone.UserCenter.UserCenterResourse.HideOption.WriteSendAndReceveDataToFile == 1)
|
| | | if (Shared.Phone.HdlUserCenterResourse.HideOption.WriteSendAndReceveDataToFile == 1) |
| | | {
|
| | | Shared.Phone.UserCenter.HdlLogLogic.Current.WriteLog(2, "本地连接成功");
|
| | | Shared.Phone.HdlLogLogic.Current.WriteLog(2, "本地连接成功"); |
| | | }
|
| | | }); |
| | | }
|
| | |
| | | if (localMqttClient.Options == null)
|
| | | {
|
| | | var options = new MQTTnet.Client.Options.MqttClientOptionsBuilder()//MQTT连接参数填充
|
| | | .WithClientId(currentGuid.ToString())//客户端ID
|
| | | .WithClientId(LocalConnectGuid.ToString())//客户端ID |
| | | .WithTcpServer(brokerName, 1883)//TCP服务端 1883 ,即MQTT服务端
|
| | | .WithCredentials("", "")//"", "")//凭证 帐号 密码
|
| | | .WithCommunicationTimeout(new TimeSpan(0, 0, 60)) //重连超时时间,默认5s
|
| | |
| | | await DisConnectLocalMqttClient("StartLocalMqtt");
|
| | | await localMqttClient.ReconnectAsync();
|
| | | }
|
| | | localIsConnected = true;
|
| | | LocalIsConnected = true; |
| | | await SendAesKey();
|
| | | }
|
| | | catch { }
|
| | |
| | | catch (Exception ex) |
| | | {
|
| | | //Log写入(调试用)
|
| | | if (Shared.Phone.UserCenter.UserCenterResourse.HideOption.WriteSendAndReceveDataToFile == 1)
|
| | | if (Shared.Phone.HdlUserCenterResourse.HideOption.WriteSendAndReceveDataToFile == 1) |
| | | {
|
| | | Shared.Phone.UserCenter.HdlLogLogic.Current.WriteLog(2, "本地连接异常:\r\n" + ex.Message);
|
| | | Shared.Phone.HdlLogLogic.Current.WriteLog(2, "本地连接异常:\r\n" + ex.Message); |
| | | } |
| | | DebugPrintLog($"局域网通讯连接出异常:{ex.Message}"); |
| | | } |
| | |
| | | } |
| | | |
| | | /// <summary> |
| | | /// 当前有帐号下所有的网关列表及信息 |
| | | /// 断开服务器连接 |
| | | /// </summary> |
| | | public static Dictionary<string, Shared.Phone.UserCenter.GatewayResult> GateWayBaseInfomations = new Dictionary<string, Shared.Phone.UserCenter.GatewayResult> { }; |
| | | /// <summary> |
| | | /// 获取当前帐号所有的网关信息 |
| | | /// </summary> |
| | | /// <returns></returns> |
| | | static async Task initGateWayBaseInfomation() |
| | | public async Task DisConnectLocalMqttClient(string s) |
| | | {
|
| | | if (AllowRemoteCtrl == false)
|
| | | {
|
| | | //没有远程连接的权限
|
| | | return;
|
| | | }
|
| | | string loginToken = Config.Instance.Token;
|
| | | if (Config.Instance.Home.IsOthreShare == true)
|
| | | {
|
| | | //获取成员的特殊Token
|
| | | var pra = new
|
| | | {
|
| | | CommonPage.RequestVersion,
|
| | | LoginAccessToken = Config.Instance.Token,
|
| | | MainAccountId = Config.Instance.Home.MainUserDistributedMark,
|
| | | SharedHid = Config.Instance.Home.Id
|
| | | };
|
| | | var resultData = Shared.Phone.UserCenter.UserCenterLogic.GetByteResponseDataByRequestHttps("App/GetSharedHomeApiControl", false, pra, new List<string> { "NotCheck" });
|
| | | if (resultData == null)
|
| | | {
|
| | | return;
|
| | | }
|
| | | var revertObj = Newtonsoft.Json.JsonConvert.DeserializeObject<Shared.Common.ResponseEntity.ResponsePack>(Encoding.UTF8.GetString(resultData));
|
| | | //分享链接
|
| | | var info = Newtonsoft.Json.JsonConvert.DeserializeObject<Shared.Phone.UserCenter.MemberAdministratorResult>(revertObj.ResponseData.ToString());
|
| | | loginToken = info.RequestToken;
|
| | | }
|
| | |
|
| | | try |
| | | { |
| | | //设置访问接口的参数
|
| | | var pra2 = new Shared.Phone.UserCenter.GetGatewayPra();
|
| | | pra2.IsOtherAccountCtrl = Config.Instance.Home.IsOthreShare;
|
| | | pra2.ReqDto.PageSetting.Page = 1;
|
| | | pra2.ReqDto.PageSetting.PageSize = 20;
|
| | | pra2.ReqDto.LoginAccessToken = loginToken; |
| | | var bytes = System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(pra2)); |
| | | |
| | | var result = CommonPage.Instance.DoRequestZigbeeHttpsInterface("https://global.hdlcontrol.com/HangZhouHdlCloudApi/App/GetSingleHomeGatewayPagger", bytes, loginToken);
|
| | | if (result != null)
|
| | | if (LocalIsConnected) |
| | | {
|
| | | var jobject = Newtonsoft.Json.Linq.JObject.Parse(Encoding.UTF8.GetString(result));
|
| | |
|
| | | var statuCode = jobject["StateCode"].ToString();
|
| | | if (statuCode != "Success")
|
| | | {
|
| | | //序列化对象
|
| | | var requestJson = Newtonsoft.Json.JsonConvert.SerializeObject(pra2);
|
| | | //Log出力
|
| | | string errorMsg = "接口访问失败★:App/GetSingleHomeGatewayPagger " + statuCode + "\r\n";
|
| | | errorMsg += "参数:\r\n" + requestJson;
|
| | | Shared.Phone.UserCenter.HdlLogLogic.Current.WriteLog(-1, errorMsg);
|
| | | return;
|
| | | }
|
| | |
|
| | | var responseData = jobject["ResponseData"];
|
| | | if (responseData != null)
|
| | | {
|
| | | if (responseData["PageData"] != null)
|
| | | {
|
| | | var list = JArray.Parse(responseData["PageData"].ToString());
|
| | | foreach (var v in list)
|
| | | {
|
| | | GateWayBaseInfomations[v["GatewayUniqueId"].ToString()] = new Shared.Phone.UserCenter.GatewayResult { AesKey = v["AesKey"].ToString(), MacMark = v["MacMark"].ToString(), MqttOnlineStatus = bool.Parse(v["MqttOnlineStatus"].ToString()) };
|
| | | //if (RemoteMqttClient.IsConnected)
|
| | | {
|
| | | await RemoteMqttClient.SubscribeAsync($"/ZigbeeGateWayToClient/{v["MacMark"].ToString()}/#", MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce);
|
| | | }
|
| | | }
|
| | | }
|
| | | }
|
| | | LocalIsConnected = false; |
| | | //这个东西也要弄 |
| | | localMqttIsConnecting = false; |
| | | DebugPrintLog($"Local主动断开_{s}"); |
| | | //await localMqttClient.DisconnectAsync(new MQTTnet.Client.Disconnecting.MqttClientDisconnectOptions { }, CancellationToken.None); |
| | | await localMqttClient.DisconnectAsync(); |
| | | } |
| | | } |
| | | catch (Exception ex)
|
| | | { |
| | | Shared.Phone.UserCenter.HdlLogLogic.Current.WriteLog(ex); |
| | | DebugPrintLog($"Local断开通讯连接出异常:{ex.Message}"); |
| | | } |
| | | } |
| | | |
| | | /// <summary> |
| | | /// 强制断开本地的网关连接 |
| | | /// </summary> |
| | | public async Task CloseLocalConnectionOnForce() |
| | | { |
| | | try |
| | | { |
| | | await localMqttClient.DisconnectAsync(); |
| | | } |
| | | catch { } |
| | | finally |
| | | { |
| | | LocalIsConnected = false; |
| | | //这个东西也要弄 |
| | | localMqttIsConnecting = false; |
| | | } |
| | | } |
| | |
|
| | | #endregion |
| | |
|
| | | #region 远程通讯连接 |
| | |
|
| | | /// <summary> |
| | | /// 当前有帐号下所有的云端网关列表及信息 |
| | | /// </summary> |
| | | public static Dictionary<string, Shared.Phone.GatewayResult> DicGatewayBaseInfo = new Dictionary<string, Shared.Phone.GatewayResult> { };
|
| | | /// <summary> |
| | | /// 外网的MQTT是否正在连接 |
| | | /// </summary> |
| | | static bool remoteMqttIsConnecting; |
| | | |
| | | private static bool remoteMqttIsConnecting; |
| | | /// <summary> |
| | | /// 远程MqttClient |
| | | /// </summary> |
| | | public static IMqttClient RemoteMqttClient = new MqttFactory().CreateMqttClient(); |
| | | static bool remoteIsConnected; |
| | | |
| | | /// <summary>
|
| | | /// 远程连接是否完成
|
| | | /// </summary> |
| | | private static bool remoteIsConnected; |
| | | /// <summary>
|
| | | /// 远程开始连接的时间点
|
| | | /// </summary> |
| | | private static DateTime RemoteConnectTime = DateTime.Now; |
| | | |
| | | /// <summary> |
| | | /// 启动远程Mqtt |
| | | /// </summary> |
| | | /// <returns>The start.</returns> |
| | | /// <param name="brokerName">Broker name.</param> |
| | | public static async Task StartRemoteMqtt() |
| | | {
|
| | | //追加:没有远程连接的权限
|
| | | if (AllowRemoteCtrl == false
|
| | | || Shared.Common.Config.Instance.HomeId == ""
|
| | | if (Config.Instance.Home.IsRemoteControl == false |
| | | || Config.Instance.Home.Id == "" |
| | | || remoteIsConnected)
|
| | | {
|
| | | return;
|
| | |
| | | //记录起这次远程连接的时间点 |
| | | RemoteConnectTime = DateTime.Now; |
| | | |
| | | await Task.Factory.StartNew(async () => |
| | | { |
| | | //初始化远程mqtt事件
|
| | | InitRemoteMqttEvent();
|
| | |
|
| | | try |
| | | {
|
| | | //获取远程mqtt链接信息
|
| | | var pra = new { attachClientId = RemoteClientId, homeType = "ZIGBEE" };
|
| | | var result = Shared.Phone.HdlHttpLogic.Current.RequestResponseFromZigbeeHttps("home-wisdom/mqtt/getRemoteInfo", RestSharp.Method.POST, pra);
|
| | | if (result != null && result.Code == Shared.Phone.HttpMessageEnum.A成功)
|
| | | {
|
| | | var jobject = JObject.Parse(result.Data.ToString());
|
| | |
|
| | | var connEmqClientId = jobject["clientId"]?.ToString();
|
| | | var connEmqUserName = jobject["userName"]?.ToString();
|
| | | var connEmqPwd = jobject["passWord"]?.ToString();
|
| | | //记录起当前的客户端ID
|
| | | Config.Instance.ConnEmqClientId = connEmqClientId;
|
| | |
|
| | | var connEmqDomainPorts = jobject["url"].ToString().Replace("//", "").Split(':');
|
| | | var domain = connEmqDomainPorts[1];
|
| | | var port = connEmqDomainPorts[2];
|
| | |
|
| | | var options = new MQTTnet.Client.Options.MqttClientOptionsBuilder()
|
| | | .WithClientId(connEmqClientId)
|
| | | .WithTcpServer(domain, int.Parse(port))
|
| | | .WithCredentials(connEmqUserName, connEmqPwd)
|
| | | .WithKeepAlivePeriod(TimeSpan.FromSeconds(20))
|
| | | .WithCleanSession()
|
| | | .Build();
|
| | | await DisConnectRemoteMqttClient("StartRemoteMqtt");
|
| | | await RemoteMqttClient.ConnectAsync(options, CancellationToken.None);
|
| | |
|
| | | remoteIsConnected = true;
|
| | | }
|
| | | }
|
| | | catch { }
|
| | | finally
|
| | | {
|
| | | //最终要释放连接状态
|
| | | remoteMqttIsConnecting = false;
|
| | | } |
| | | }
|
| | |
|
| | | /// <summary>
|
| | | /// 初始化远程mqtt事件
|
| | | /// </summary>
|
| | | private static void InitRemoteMqttEvent()
|
| | | { |
| | | lock (RemoteMqttClient) |
| | | { |
| | | //表示后面将进行连接 |
| | | remoteMqttIsConnecting = true; |
| | | |
| | | #region 初始化远程Mqtt |
| | | //(3)当[连接云端的Mqtt成功后]或者[以及后面App通过云端Mqtt转发数据给网关成功后],处理接收到云端数据包响应时在mqttServerClient_ApplicationMessageReceived这个方法处理 |
| | | if (RemoteMqttClient.ApplicationMessageReceivedHandler == null) |
| | | { |
| | |
| | | { |
| | | DebugPrintLog($"远程连接断开"); |
| | | await DisConnectRemoteMqttClient("StartRemoteMqtt.DisconnectedHandler"); |
| | | //await StartRemoteMqtt(); |
| | | }); |
| | | } |
| | |
|
| | | if (RemoteMqttClient.ConnectedHandler == null) |
| | | { |
| | | RemoteMqttClient.UseConnectedHandler(async (e) =>
|
| | | {
|
| | | DebugPrintLog($"远程连接成功");
|
| | |
|
| | | if (Config.Instance.Home.IsOthreShare == true)
|
| | | if (Config.Instance.Home.IsOtherShare == true)
|
| | | {
|
| | | //订阅一个成员被删除的主题
|
| | | string myGuid = Config.Instance.Guid;
|
| | |
| | | await RemoteMqttClient.SubscribeAsync("/ZigbeeGateWayToClient/" + Config.Instance.ConnEmqClientId + "/Push/NotifySqueeze");
|
| | |
|
| | | //如果这个函数卡久了的话,会接收到云端推送的挤下线主题,不知道为什么
|
| | | new Thread(async () =>
|
| | | new System.Threading.Thread(async () =>
|
| | | {
|
| | | await initGateWayBaseInfomation();
|
| | | await InitGateWayBaseInfomation();
|
| | |
|
| | | //没有主网关时主动读取,获取主网关信息
|
| | | var gateWayList = GateWayList.FindAll(obj => obj.HomeId == Shared.Common.Config.Instance.HomeId);
|
| | |
| | | }
|
| | | })
|
| | | { IsBackground = true }.Start();
|
| | | |
| | | }); |
| | | } |
| | | #endregion |
| | | }
|
| | | } |
| | | |
| | | try |
| | | /// <summary> |
| | | /// 初始化当前帐号所有的云端网关信息 |
| | | /// </summary> |
| | | /// <returns></returns> |
| | | private static async Task InitGateWayBaseInfomation() |
| | | {
|
| | | byte[] result = null;
|
| | | if (Config.Instance.Home.IsOthreShare == false)
|
| | | {
|
| | | //主人
|
| | | var jsonData = new Dictionary<string, object>
|
| | | {
|
| | | ["RequestVersion"] = CommonPage.RequestVersion,
|
| | | ["RequestSource"] = 0,
|
| | | ["LoginAccessToken"] = Config.Instance.Token,
|
| | | ["RequestProtocolType"] = 0,
|
| | | ["PlatformStr"] = "h",//这两个值如果不设置,则云端不发布主题
|
| | | ["PublishPayloadJsonStr"] = "1"
|
| | | };
|
| | | var bytes = System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(jsonData));
|
| | | result = CommonPage.Instance.DoRequestZigbeeHttpsInterface("https://global.hdlcontrol.com/HangZhouHdlCloudApi/EmqMqtt/GetConnMqttInfo", bytes, Config.Instance.Token);
|
| | | } |
| | | else
|
| | | {
|
| | | //分享的
|
| | | var jsonData = new Dictionary<string, object>
|
| | | {
|
| | | ["RequestVersion"] = CommonPage.RequestVersion,
|
| | | ["RequestSource"] = 0,
|
| | | ["LoginAccessToken"] = Config.Instance.Token,
|
| | | ["RequestProtocolType"] = 0,
|
| | | ["MainUserDistributedMark"] = Config.Instance.Home.MainUserDistributedMark,
|
| | | ["HomeId"] = Config.Instance.Home.Id,
|
| | | ["PlatformStr"] = "h",//这两个值如果不设置,则云端不发布主题
|
| | | ["PublishPayloadJsonStr"] = "1"
|
| | | };
|
| | | var bytes = System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(jsonData));
|
| | | result = CommonPage.Instance.DoRequestZigbeeHttpsInterface("https://global.hdlcontrol.com/HangZhouHdlCloudApi/EmqMqtt/ShareMemberConnMqttInfo", bytes, Config.Instance.Token);
|
| | | } |
| | | if (result != null) |
| | | { |
| | | var jobject = Newtonsoft.Json.Linq.JObject.Parse(Encoding.UTF8.GetString(result)); |
| | | if (jobject["StateCode"].ToString() == "NotAllowRemoteCtrl")
|
| | | if (Config.Instance.Home.IsRemoteControl == false) |
| | | {
|
| | | //没有远程连接的权限
|
| | | AllowRemoteCtrl = false;
|
| | | return;
|
| | | } |
| | | //获取云端网关信息 |
| | | var listGatewayInfo = Shared.Phone.HdlGatewayLogic.Current.GetGateWayListFromDataBase(Config.Instance.Home.Id); |
| | | if (listGatewayInfo == null) { return; } |
| | | |
| | | var responseData = jobject["ResponseData"]; |
| | | if (responseData != null) |
| | | { |
| | | var connEmqDomainPort = responseData["ConnEmqDomainPort"]?.ToString(); |
| | | var connEmqClientId = responseData["ConnEmqClientId"]?.ToString(); |
| | | var connEmqUserName = responseData["ConnEmqUserName"]?.ToString(); |
| | | var connEmqPwd = responseData["ConnEmqPwd"]?.ToString(); |
| | | //记录起当前的客户端ID |
| | | Config.Instance.ConnEmqClientId = connEmqClientId; |
| | | |
| | | var connEmqDomainPorts = connEmqDomainPort.Replace("//", "").Split(':'); |
| | | var domain = connEmqDomainPorts[1]; |
| | | var port = connEmqDomainPorts[2];
|
| | |
|
| | | var options = new MQTTnet.Client.Options.MqttClientOptionsBuilder()
|
| | | .WithClientId(connEmqClientId)
|
| | | .WithTcpServer(domain, int.Parse(port))
|
| | | .WithCredentials(connEmqUserName, connEmqPwd)
|
| | | .WithKeepAlivePeriod(TimeSpan.FromSeconds(20))
|
| | | .WithCleanSession()
|
| | | //.WithCommunicationTimeout(TimeSpan.FromSeconds(10))
|
| | | .Build();
|
| | | await DisConnectRemoteMqttClient("StartRemoteMqtt");
|
| | | await RemoteMqttClient.ConnectAsync(options, CancellationToken.None);
|
| | |
|
| | | remoteIsConnected = true; |
| | | } |
| | | } |
| | | } |
| | | catch { } |
| | | finally |
| | | { |
| | | //最终要释放连接状态 |
| | | remoteMqttIsConnecting = false;
|
| | | } |
| | | } |
| | | catch (Exception ex) |
| | | { |
| | | DebugPrintLog($"远程连接通讯连接出异常:{ex.Message}"); |
| | | } |
| | | }); |
| | | } |
| | | |
| | | /// <summary> |
| | | /// 断开服务器连接 |
| | | /// </summary> |
| | | public async Task DisConnectLocalMqttClient(string s) |
| | | foreach (var info in listGatewayInfo.Values)
|
| | | { |
| | | try |
| | | { |
| | | if (localIsConnected)
|
| | | {
|
| | | localIsConnected = false;
|
| | | //这个东西也要弄
|
| | | localMqttIsConnecting = false;
|
| | | DebugPrintLog($"Local主动断开_{s}");
|
| | | //await localMqttClient.DisconnectAsync(new MQTTnet.Client.Disconnecting.MqttClientDisconnectOptions { }, CancellationToken.None);
|
| | | await localMqttClient.DisconnectAsync();
|
| | | }
|
| | | //有可能云端是这么处理:如果没有远程权限,则不给AesKey
|
| | | if (string.IsNullOrEmpty(info.AesKey) == true) { continue; }
|
| | | //保存缓存
|
| | | DicGatewayBaseInfo[info.Mac] = info;
|
| | | //我也不知道这个是干嘛的
|
| | | await RemoteMqttClient.SubscribeAsync($"/ZigbeeGateWayToClient/" + info.Id + "/#", MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce);
|
| | | } |
| | | catch (Exception ex) |
| | | { |
| | | DebugPrintLog($"Local断开通讯连接出异常:{ex.Message}"); |
| | | Shared.Phone.HdlLogLogic.Current.WriteLog(ex);
|
| | | } |
| | | }
|
| | |
|
| | | /// <summary> |
| | | /// 强制断开本地的网关连接 |
| | | /// </summary> |
| | | public async Task CloseLocalConnectionOnForce() |
| | | { |
| | | try |
| | | {
|
| | | await localMqttClient.DisconnectAsync();
|
| | | } |
| | | catch { } |
| | | finally |
| | | {
|
| | | localIsConnected = false;
|
| | | //这个东西也要弄
|
| | | localMqttIsConnecting = false;
|
| | | } |
| | | } |
| | | |
| | |
| | | {
|
| | | try
|
| | | {
|
| | | await RemoteMqttClient.DisconnectAsync();
|
| | | await RemoteMqttClient?.DisconnectAsync(); |
| | | }
|
| | | catch { }
|
| | | finally
|
| | |
| | | { |
| | | try
|
| | | {
|
| | | if (this.GwId == string.Empty || !GateWayBaseInfomations.ContainsKey(this.GwId))
|
| | | if (this.GwId == string.Empty || !DicGatewayBaseInfo.ContainsKey(this.GwId)) |
| | | {
|
| | | return;
|
| | | }
|
| | | var gateWayBaseInfomation = GateWayBaseInfomations[this.GwId];
|
| | | var gateWayBaseInfomation = DicGatewayBaseInfo[this.GwId]; |
| | | message = SecuritySet.AesEncryptBytes(message, gateWayBaseInfomation.AesKey);
|
| | | var topicEncStr = $"/ClientToZigbeeGateWay/{gateWayBaseInfomation.MacMark}/Common/{topicName}";
|
| | | var topicEncStr = $"/ClientToZigbeeGateWay/{gateWayBaseInfomation.Id}/Common/{topicName}"; |
| | | //(6)构建Mqtt需要发布的数据包,发布给云端的MqttBroker
|
| | | if (remoteIsConnected)
|
| | | {
|
| | |
| | | }
|
| | |
|
| | | //Log写入(调试用)
|
| | | if (Shared.Phone.UserCenter.UserCenterResourse.HideOption.WriteSendAndReceveDataToFile == 1)
|
| | | if (Shared.Phone.HdlUserCenterResourse.HideOption.WriteSendAndReceveDataToFile == 1) |
| | | {
|
| | | string text = "远程发送:";
|
| | | if (IsRemote == false) { text = "本地发送:"; }
|
| | | text += topic + "\r\n";
|
| | | text += Encoding.UTF8.GetString(message) + "\r\n";
|
| | | Shared.Phone.UserCenter.HdlLogLogic.Current.WriteLog(2, text);
|
| | | Shared.Phone.HdlLogLogic.Current.WriteLog(2, text); |
| | | } |
| | | |
| | | if (IsRemote) |
| | |
| | | message = SecuritySet.AesEncryptBytes(message, password); |
| | | } |
| | | }
|
| | | if (localIsConnected) |
| | | if (LocalIsConnected) |
| | | {
|
| | | try
|
| | | {
|
| | |
| | | DebugPrintLog($"Local主动断开_{e.Message}");
|
| | | await DisConnectLocalMqttClient(e.Message); |
| | | await StartLocalMqtt("ReConnect");
|
| | | if (localIsConnected)
|
| | | if (LocalIsConnected) |
| | | {
|
| | | DebugPrintLog($"局域网——二次发送到网关的主题:{topic}_发送到网关的数据:{System.Text.Encoding.UTF8.GetString(message)}_是否加密:{IsEncry}");
|
| | | await localMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topic, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce, Retain = retain });
|
| | | }
|
| | | //Log写入(调试用)
|
| | | if (Shared.Phone.UserCenter.UserCenterResourse.HideOption.WriteSendAndReceveDataToFile == 1)
|
| | | if (Shared.Phone.HdlUserCenterResourse.HideOption.WriteSendAndReceveDataToFile == 1) |
| | | {
|
| | | Shared.Phone.UserCenter.HdlLogLogic.Current.WriteLog(2, "本地连接异常断开");
|
| | | Shared.Phone.HdlLogLogic.Current.WriteLog(2, "本地连接异常断开"); |
| | | } |
| | | }
|
| | | }
|
| | |
| | | message = SecuritySet.AesEncryptBytes(message, password);
|
| | | }
|
| | | }
|
| | | if (localIsConnected)
|
| | | if (LocalIsConnected) |
| | | {
|
| | | try
|
| | | {
|
| | |
| | | DebugPrintLog($"Local主动断开_{e.Message}");
|
| | | await DisConnectLocalMqttClient(e.Message);
|
| | | await StartLocalMqtt("ReConnect");
|
| | | if (localIsConnected)
|
| | | if (LocalIsConnected) |
| | | {
|
| | | DebugPrintLog($"局域网——二次发送到网关的主题:{topic}_发送到网关的数据:{System.Text.Encoding.UTF8.GetString(message)}_是否加密:{IsEncry}");
|
| | | await localMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topic, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce, Retain = retain });
|
| | |
| | | } |
| | | if (topics[2] == "NotifyGateWayInfoChange") |
| | | { |
| | | initGateWayBaseInfomation(); |
| | | InitGateWayBaseInfomation(); |
| | | return; |
| | | } |
| | | if (topics[2] == "Common") |
| | |
| | | } |
| | | else |
| | | { |
| | | foreach (var key in GateWayBaseInfomations.Keys) |
| | | foreach (var key in DicGatewayBaseInfo.Keys) |
| | | { |
| | | var value = GateWayBaseInfomations[key]; |
| | | if (value.MacMark == macMark) |
| | | var value = DicGatewayBaseInfo[key]; |
| | | if (value.Id == macMark) |
| | | { |
| | | topic = $"{key}/{topic}"; |
| | | message = System.Text.Encoding.UTF8.GetString(ZigBee.Common.SecuritySet.AesDecryptBytes(e.ApplicationMessage.Payload, value.AesKey)); |
| | |
| | | }
|
| | |
|
| | | //Log写入(调试用)
|
| | | if (Shared.Phone.UserCenter.UserCenterResourse.HideOption.WriteSendAndReceveDataToFile == 1)
|
| | | if (Shared.Phone.HdlUserCenterResourse.HideOption.WriteSendAndReceveDataToFile == 1) |
| | | {
|
| | | string text = "网关回复:" + topic + "\r\n";
|
| | | text += message + "\r\n";
|
| | | Shared.Phone.UserCenter.HdlLogLogic.Current.WriteLog(2, text);
|
| | | Shared.Phone.HdlLogLogic.Current.WriteLog(2, text); |
| | | }
|
| | |
|
| | | //全局接收网关推送的的逻辑(为了执行速度,尽可能的别加耗时的操作)
|
| | | Shared.Phone.UserCenter.HdlGatewayReceiveLogic.Current.GatewayOverallMsgReceive(gatewayID, topic, reportStatus, message); |
| | | Shared.Phone.HdlGatewayReceiveLogic.Current.GatewayOverallMsgReceive(gatewayID, topic, reportStatus, message); |
| | | |
| | | var gwa = GateWayList.Find(obj => obj.GwId == gatewayID); |
| | | if (gwa == null) |