From 41f9c8837b0551c68f8fd798c06951fa716b7ab8 Mon Sep 17 00:00:00 2001
From: wei <kaede@kaededeMacBook-Air.local>
Date: 星期一, 11 一月 2021 14:05:29 +0800
Subject: [PATCH] Merge branch 'NewFilePath' of http://172.16.1.23:6688/r/~wxr/HDL_APP_Project into NewFilePath
---
HDL_ON/DAL/Mqtt/MqttClient.cs | 241 +++++++++++++++++++++++-------------------------
1 files changed, 116 insertions(+), 125 deletions(-)
diff --git a/HDL_ON/DAL/Mqtt/MqttClient.cs b/HDL_ON/DAL/Mqtt/MqttClient.cs
index 1d130d4..8b725d6 100644
--- a/HDL_ON/DAL/Mqtt/MqttClient.cs
+++ b/HDL_ON/DAL/Mqtt/MqttClient.cs
@@ -1,7 +1,6 @@
锘�/*
鏇存柊浜咵MQ杩炴帴鏂瑰紡
*/
-using System.Collections.Generic;
using System;
using MQTTnet.Client;
using System.Threading.Tasks;
@@ -9,19 +8,20 @@
using MQTTnet;
using System.Text;
using System.Security.Cryptography;
-using System.IO;
using HDL_ON.DriverLayer;
+using HDL_ON.Entity;
+using HDL_ON.UI;
namespace HDL_ON.DAL.Mqtt
{
- public static class MqttCommon
+ public static class MqttClient
{
/// <summary>
/// 鍔犲瘑閫氳KEY
/// </summary>
static string mqttEncryptKey = "";
//static string checkGatewayTopicBase64 = "";
-
+ static bool hadGateway = true;
/// <summary>
/// 鎸や笅绾夸富棰�
/// </summary>
@@ -32,18 +32,18 @@
/// </summary>
static string RandomKey = "";
+ /// <summary>
+ /// 闅忔満鐢熸垚瀛楃
+ /// </summary>
+ /// <returns></returns>
static string GetRandomKey()
{
if (string.IsNullOrEmpty(RandomKey))
{
//闅忔満2浣嶅瓧绗︿覆
- Random random = new Random(Guid.NewGuid().GetHashCode());
- int num = random.Next(65, 91);
- RandomKey = Convert.ToChar(num).ToString();
+ RandomKey = Utlis.CreateRandomString(2);
}
-
return RandomKey;
-
}
/// <summary>
@@ -51,11 +51,10 @@
/// </summary>
public static IMqttClient RemoteMqttClient = new MqttFactory().CreateMqttClient();
-
/// <summary>
/// 鎺ㄩ�佹爣璇�
/// </summary>
- static string PushSignStr = System.DateTime.Now.Ticks.ToString();
+ static string PushSignStr = DateTime.Now.Ticks.ToString();
/// <summary>
/// 鏂紑杩滅▼Mqtt鐨勯摼鎺�
@@ -74,11 +73,7 @@
if (Control.Ins.IsRemote)
{
- //涓嶆槸鏃犵綉缁�
- if (OnAppConfig.Instance.internetStatus != 0)
- {
- Control.Ins.GatewayOnline = false;
- }
+ Control.Ins.GatewayOnline = false;
}
}
}
@@ -95,21 +90,16 @@
{
try
{
- //if (remoteIsConnected) {
remoteIsConnected = false;
isSubscribeSuccess = false;
Utlis.WriteLine($"RemoteStart涓诲姩鏂紑_{s}");
await RemoteMqttClient.DisconnectAsync();
-
- //}
}
catch (Exception e)
{
Utlis.WriteLine($"RemoteStart鏂紑閫氳杩炴帴鍑哄紓甯�:{e.Message}");
}
-
}
-
/// <summary>
/// 鏂紑mqtt杩炴帴
@@ -121,21 +111,18 @@
{
if (reset)
{
- bNeedStartTip = true;
- bNeedConnectTip = true;
MqttInfoConfig.Current.IfGetMqttInfoSuccess = false;
}
await DisConnectRemoteMqttClient(s);
}
- //static DateTime dateTime = DateTime.MinValue;
/// <summary>
/// 澶栫綉鐨凪QTT鏄惁姝e湪杩炴帴
/// </summary>
- public static bool remoteMqttIsConnecting;
+ public static bool RemoteMqttIsConnecting;
static bool remoteIsConnected;
- static MqttCommon()
+ static MqttClient()
{
InitMqtt();
}
@@ -150,13 +137,9 @@
try
{
System.Threading.Thread.Sleep(500);
- //if (!UserInfo.Current.IsLogin) {
- // continue;
- //}
-
if (!Control.Ins.IsRemote) continue;
-
- //if (BusSocket.IsEnterBackground) continue;
+ //杩涘叆鍚庡彴涓嶅鐞�
+ if (MainPage.IsEnterBackground) continue;
await StartCloudMqtt();
await SubscribeTopics();
@@ -177,20 +160,20 @@
}
static bool isSubscribeSuccess;
+ /// <summary>
+ /// 璁㈤槄涓婚
+ /// </summary>
+ /// <returns></returns>
static async Task SubscribeTopics()
{
if (remoteIsConnected && !isSubscribeSuccess)
{
try
{
-
- //var topicFilterPush = new TopicFilter { QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce,
- // Topic = $"/BusGateWayToClient/{MqttInfoConfig.Instance.CurRemoteMACInfo.clientId}/Push/NotifySqueeze" };
-
//2020-05-14 璁㈤槄涓婚璐ㄩ噺鏀逛负0
var topicFilterBusGateWayToClient = new MqttTopicFilter()
{
- Topic = $"/BusGateWayToClient/{MqttInfoConfig.Current.HomeGatewayInfo.id}/#",
+ Topic = $"/BusGateWayToClient/{MqttInfoConfig.Current.HomeGatewayInfo.gatewayId}/#",
QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce
//QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce
};
@@ -202,20 +185,30 @@
//QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce
};
+ var topicAlinkStatus = new MqttTopicFilter()
+ {
+ Topic = $"/user/{MqttInfoConfig.Current.HomeGatewayInfo.gatewayId}/app/thing/property/send",
+ QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce
+ };
+ //var topicBusStatus = new MqttTopicFilter()
+ //{
+ // Topic = $"/BusGateWayToClient/{}/Common",
+ // QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce
+ //};
+
Utlis.WriteLine("寮�濮嬭闃咃紒");
- var result = await RemoteMqttClient.SubscribeAsync(new MqttTopicFilter[] { topicFilterBusGateWayToClient, topicFilterPush2 });
+ var result = await RemoteMqttClient.SubscribeAsync(new MqttTopicFilter[] { topicFilterBusGateWayToClient, topicFilterPush2, topicAlinkStatus });
if (result.Items[0].ResultCode == MQTTnet.Client.Subscribing.MqttClientSubscribeResultCode.GrantedQoS0)
{
+ Control.Ins.GatewayOnline = true;
isSubscribeSuccess = true;
Utlis.WriteLine("璁㈤槄鎴愬姛锛�");
MqttRemoteSend(new byte[] { 0 }, 3);
//杩炴帴鎴愬姛鍚庢娴嬫槸鍚﹂渶瑕侀�氳繃杩滅▼鑾峰彇Key
- CheckIfNeedGetLocalPasswordFromRemote();
+ //CheckIfNeedGetLocalPasswordFromRemote();
}
-
-
}
catch (Exception ex)
{
@@ -224,16 +217,12 @@
}
}
- static DateTime mFlagDateTime;
-
- //static readonly object SendLocker = new object ();
/// <summary>
/// 鍚姩杩滅▼Mqtt
/// </summary>
public static async Task StartCloudMqtt()
{
-
- if (OnAppConfig.Instance.internetStatus == 0)
+ if (MainPage.InternetStatus == 0)
{
return;
}
@@ -244,7 +233,7 @@
}
//杩藉姞锛氭病鏈夎繙绋嬭繛鎺ョ殑鏉冮檺
- if (remoteMqttIsConnecting || remoteIsConnected)
+ if (RemoteMqttIsConnecting || remoteIsConnected)
{
return;
}
@@ -255,13 +244,14 @@
try
{
#region 鍒濆鍖栬繙绋婱qtt
-
+ RemoteMqttIsConnecting = true;
RemoteMqttClient = new MqttFactory().CreateMqttClient();
//(1)褰揫杩炴帴浜戠鐨凪qtt鎴愬姛鍚嶿鎴栬�匸浠ュ強鍚庨潰App閫氳繃浜戠Mqtt杞彂鏁版嵁缁欑綉鍏虫垚鍔熷悗],澶勭悊鎺ユ敹鍒颁簯绔暟鎹寘鍝嶅簲鏃跺湪mqttServerClient_ApplicationMessageReceived杩欎釜鏂规硶澶勭悊
if (RemoteMqttClient.ApplicationMessageReceivedHandler == null)
{
+ //澶勭悊鎺ユ敹鍒扮殑鏁版嵁
RemoteMqttClient.UseApplicationMessageReceivedHandler((e) => {
try
{
@@ -272,37 +262,56 @@
//鏂版尋涓嬬嚎涓婚鏂规 鏀跺埌鎸や笅绾夸富棰�
ReceiveNotifySqueezeAsync(mMes);
}
- else if (topic == $"/BusGateWayToClient/{MqttInfoConfig.Current.HomeGatewayInfo.id}/NotifyBusGateWayInfoChange")
+ else if (topic == $"/BusGateWayToClient/{MqttInfoConfig.Current.HomeGatewayInfo.gatewayId}/NotifyBusGateWayInfoChange")
{//缃戝叧涓婄嚎锛岄渶瑕佹洿鏂癮eskey
//鏀跺埌缃戝叧涓婄嚎娑堟伅涓婚
ReceiveNotifyBusGateWayInfoChange();
}
- else if (topic == $"/BusGateWayToClient/{MqttInfoConfig.Current.HomeGatewayInfo.id}/NotifyGateWayOffline")
- {//缃戝叧鎺夌嚎 //----绗簩姝ワ細璇诲彇璐﹀彿涓嬮潰鐨勭綉鍏冲垪琛�
+ else if (topic == $"/BusGateWayToClient/{MqttInfoConfig.Current.HomeGatewayInfo.gatewayId}/NotifyGateWayOffline")
+ {//缃戝叧鎺夌嚎
+ //----绗簩姝ワ細璇诲彇璐﹀彿涓嬮潰鐨勭綉鍏冲垪琛�
ReceiveNotifyGateWayOffline();
}
- else if (topic == $"/BusGateWayToClient/{MqttInfoConfig.Current.HomeGatewayInfo.id}/Common/CheckGateway")
+ else if (topic == $"/BusGateWayToClient/{MqttInfoConfig.Current.HomeGatewayInfo.gatewayId}/Common/CheckGateway")
{
var ss = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
ReceiveCheckGateway(ss);
}
else
{
-
SetGatewayOnlineResetCheck();
-
- var packet = new Packet();
-
- if (!string.IsNullOrEmpty(mqttEncryptKey))
+ var bytes = Securitys.EncryptionService.AesDecryptPayload(e.ApplicationMessage.Payload, DB_ResidenceData.Instance.HomeGateway.aesKey);
+
+ //bus鏁版嵁瑙f瀽
+ if (DB_ResidenceData.Instance.GatewayType == 0)
{
- packet.Bytes = Securitys.EncryptionService.AesDecryptPayload(e.ApplicationMessage.Payload, mqttEncryptKey);
+ var packet = new Packet();
+
+ if (!string.IsNullOrEmpty(mqttEncryptKey))
+ {
+ packet.Bytes = Securitys.EncryptionService.AesDecryptPayload(e.ApplicationMessage.Payload, mqttEncryptKey);
+ }
+ else
+ {
+ packet.Bytes = e.ApplicationMessage.Payload;
+ }
+#if DEBUG
+ //string ddd = "";
+ //foreach (var bb in packet.Bytes)
+ //{
+ // ddd += bb + ",";
+ //}
+ //MainPage.Log($"mqtt bus data:{ddd}");
+#endif
+ packet.Manager();
}
else
{
- packet.Bytes = e.ApplicationMessage.Payload;
+ MainPage.Log($"mqtt A-Link data");
+ //A鍗忚鏁版嵁澶勭悊
+ var revString = Encoding.UTF8.GetString(bytes);
+ Control.Ins.UpdataFunctionStatus(revString,null);
}
- packet.IsLocal = false;
- packet.Manager();
}
}
catch { }
@@ -316,21 +325,16 @@
Utlis.WriteLine($"杩滅▼杩炴帴鏂紑");
isSubscribeSuccess = false;
await DisConnectRemoteMqttClient("UseDisconnectedHandler");
-
});
}
//(3)ConnectedHandler
if (RemoteMqttClient.ConnectedHandler == null)
{
- RemoteMqttClient.UseConnectedHandler(async (e) => {
+ RemoteMqttClient.UseConnectedHandler(async (e) =>
+ {
IfNeedReadAllDeviceStatus = true;
Utlis.WriteLine($"============>Mqtt杩滅▼杩炴帴鎴愬姛");
SendPushSignOut();
-
- //if (Control.Ins.IsRemote) {
- // //Utlis.ShowAppLinkStatus (AppLinkStatus.CloudLink);
- // MainPage.AddTip (Language.StringByID (SimpleControl.R.MyInternationalizationString.LinkSuccess));
- //}
});
}
#endregion
@@ -357,7 +361,7 @@
finally
{
//鏈�缁堣閲婃斁杩炴帴鐘舵��
- remoteMqttIsConnecting = false;
+ RemoteMqttIsConnecting = false;
Utlis.WriteLine($"StartCloudMqtt: 缁撴潫");
}
@@ -387,7 +391,7 @@
{
try
{
- if (MqttInfoConfig.Current.HomeGatewayInfo != null && MqttInfoConfig.Current.HomeGatewayInfo.mac == Entity.DB_ResidenceData.residenceData.residenceGatewayMAC)
+ if (MqttInfoConfig.Current.HomeGatewayInfo != null && MqttInfoConfig.Current.HomeGatewayInfo.mac == Entity.DB_ResidenceData.Instance.residenceGatewayMAC)
{
await MQTTConnectAsync();
}
@@ -441,12 +445,6 @@
if (MqttInfoConfig.Current.HomeGatewayInfo != null && MqttInfoConfig.Current.mMqttInfo != null)
{
- if (bNeedConnectTip)
- {
- bNeedConnectTip = false;
- MainPage.LoadingTipShow(Language.StringByID(SimpleControl.R.MyInternationalizationString.GetSuccessfullyStartConnecting));
- }
-
try
{
@@ -454,8 +452,7 @@
//url = HttpUtil.GetProxyEMQUrl (url);
//#if DEBUG
- // url = HttpUtil.GetProxyEMQUrl (url);
-
+ //url = HttpUtil.GetProxyEMQUrl (url);
//#endif
var clientId = MqttInfoConfig.Current.mMqttInfo.clientId;
var username = MqttInfoConfig.Current.mMqttInfo.userName;
@@ -485,7 +482,6 @@
{
remoteIsConnected = true;
IsDisConnectingWithSendCatch = false;
- UnsupportedProtocolVersionCount = 0;
}
else
{
@@ -497,22 +493,9 @@
catch (Exception ex)
{
- if (ex.Message == MqttCommunicationTimedOutException)
- {
- Console.WriteLine("Connect error TimedOut: " + ex.Message);
- }
- else
- {
- //閲嶆柊涓績鏈嶅姟鍣ㄨ幏鍙栧弬鏁版爣璁�
- MqttInfoConfig.Current.IfGetMqttInfoSuccess = false;
- Console.WriteLine("Connect error: " + ex.Message);
- }
-
- //Console.WriteLine ("Connect error: " + ex.Message);
- if (IfDEBUG)
- {
- MainPage.ShowAlertOnMainThread("Connect error: " + ex.Message);
- }
+ //閲嶆柊涓績鏈嶅姟鍣ㄨ幏鍙栧弬鏁版爣璁�
+ MqttInfoConfig.Current.IfGetMqttInfoSuccess = false;
+ Console.WriteLine("Connect error: " + ex.Message);
}
finally
{
@@ -561,7 +544,9 @@
/// </summary>
static void ReceiveNotifySqueezeAsync(string mMes)
{
-
+//#if DEBUG
+ return;
+//#endif
if (mMes == PushSignStr) return;//鏄嚜宸辩殑鐧诲綍鎺ㄩ�佷笉澶勭悊
//鏂紑杩滅▼杩炴帴
@@ -573,13 +558,20 @@
DisConnectRemoteMqttClient("鎸や笅绾�");
- UserInfo.Current.LastTime = DateTime.MinValue;
- UserInfo.Current.SaveUserInfo();
-
- Application.RunOnMainThread(() => {
- MainPage.GoLoginPage(UserInfo.Current);
+ Application.RunOnMainThread(() =>
+ {
//寮圭獥鎻愮ず琚尋涓嬬嚎
+ HDLCommon.Current.CheckLogout();
});
+
+
+ //UserInfo.Current.LastTime = DateTime.MinValue;
+ //UserInfo.Current.SaveUserInfo();
+
+ //Application.RunOnMainThread(() => {
+ // MainPage.GoLoginPage(UserInfo.Current);
+ // //寮圭獥鎻愮ず琚尋涓嬬嚎
+ //});
//2020-08-11 鍒犻櫎鎺ㄩ�佹暟鎹�
//HDLRequest.Current.PushserivceSignOut ();
@@ -617,15 +609,13 @@
/// <returns></returns>
public static async Task MqttRemoteSend(byte[] message, int optionType = 0)
{
- //return;
-
try
{
string topicName;
switch (optionType)
{
case 0:
- topicName = $"/ClientToBusGateWay/{MqttInfoConfig.Current.HomeGatewayInfo.id}/Common/ON";
+ topicName = $"/ClientToBusGateWay/{MqttInfoConfig.Current.HomeGatewayInfo.gatewayId}/Common/ON";
if (!string.IsNullOrEmpty(mqttEncryptKey))
{
message = Securitys.EncryptionService.AesEncryptPayload(message, mqttEncryptKey);
@@ -633,7 +623,7 @@
await RemoteMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topicName, Payload = message, Retain = false, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce });
break;
case 3:
- topicName = $"/ClientToBusGateWay/{MqttInfoConfig.Current.HomeGatewayInfo.id}/Common/CheckGateway";
+ topicName = $"/ClientToBusGateWay/{MqttInfoConfig.Current.HomeGatewayInfo.gatewayId}/Common/CheckGateway";
Utlis.WriteLine("CheckGateway");
await RemoteMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topicName, Retain = false, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce });
break;
@@ -664,7 +654,6 @@
/// 鏄惁闇�瑕佽鍙栦竴娆℃墍鏈夎澶囩姸鎬�
/// </summary>
static bool IfNeedReadAllDeviceStatus = true;
- //public static bool IsGatewayOnline = true;
/// <summary>
/// 璁剧疆缃戝叧鍦ㄧ嚎鏍囧織锛屽苟閲嶇疆CheckGateway鍙傛暟
@@ -673,7 +662,18 @@
{
if (Control.Ins.IsRemote)
{
- Control.Ins.GatewayOnline = true;
+ if (!Control.Ins.GatewayOnline)
+ {
+ try
+ {
+ if (DB_ResidenceData.Instance.HomeGateway != null)
+ {
+ DB_ResidenceData.Instance.HomeGateway.gatewayStatus = true;
+ }
+ Control.Ins.GatewayOnline = true;
+ }
+ catch { }
+ }
}
}
@@ -684,35 +684,26 @@
/// <returns></returns>
static async Task GetMqttInfoAndMQTTConnectAsync()
{
- var mqttInfoRequestResult_Obj =new Server.HttpServerRequest().GetMqttRemoteInfo(GetRandomKey());
+ var mqttInfoRequestResult_Obj = new Server.HttpServerRequest().GetMqttRemoteInfo(GetRandomKey());
if (mqttInfoRequestResult_Obj != null)
{
MqttInfoConfig.Current.mMqttInfo = mqttInfoRequestResult_Obj;
- if (UserConfig.Instance.GatewayList != null && UserConfig.Instance.GatewayList.Count > 0)
+ await MQTTConnectAsync();
+ //1.鍒ゆ柇鏄惁缁戝畾浜嗙綉鍏筹紝鑾峰彇缃戝叧杩滅▼杩炴帴鐨勫姞瀵咾EY
+ if (DB_ResidenceData.Instance.CheckWhetherGatewayIsBound())
{
- //----绗簩姝ユ壘鍑烘槸鍚﹀瓨鍦ㄥ尮閰嶅綋鍓嶄綇瀹呯殑mac锛屽瓨鍦ㄥ啀杩涜杩滅▼銆�
- MqttInfoConfig.Current.HomeGatewayInfo = UserConfig.Instance.GatewayList[0];
- if (MqttInfoConfig.Current.HomeGatewayInfo != null)
- {
- //----绗笁姝� 寮�濮嬭繛鎺�
- await MQTTConnectAsync();
- }
+ //2.鎵惧嚭鏄惁瀛樺湪鍖归厤褰撳墠浣忓畢鐨刴ac锛屽瓨鍦ㄥ啀杩涜杩滅▼銆�
+ MqttInfoConfig.Current.HomeGatewayInfo = DB_ResidenceData.Instance.HomeGateway;
+ //3.寮�濮嬭繛鎺�
+ await MQTTConnectAsync();
}
else
{
Utlis.WriteLine("============>杩樻病缁戝畾缃戝叧");
+ hadGateway = false;
}
-
}
- else
- {
- Utlis.WriteLine("============>MqttInfo null");
- }
-
-
-
}
-
}
}
--
Gitblit v1.8.0