/*
|
更新了EMQ连接方式
|
*/
|
using System;
|
using MQTTnet.Client;
|
using System.Threading.Tasks;
|
using Shared;
|
using MQTTnet;
|
using System.Text;
|
using System.Security.Cryptography;
|
using HDL_ON.DriverLayer;
|
using HDL_ON.Entity;
|
using HDL_ON.UI;
|
using HDL_ON.DAL.Server;
|
|
namespace HDL_ON.DAL.Mqtt
|
{
|
public static class MqttClient
|
{
|
/// <summary>
|
/// 加密通讯KEY
|
/// </summary>
|
static string mqttEncryptKey = "";
|
static string tuyaEncryptKey = "";
|
//static string checkGatewayTopicBase64 = "";
|
static bool hadGateway = true;
|
/// <summary>
|
/// 挤下线主题
|
/// </summary>
|
static readonly string PushNotifySqueeze = "/Push/NotifySqueeze";
|
|
/// <summary>
|
/// 随机Key
|
/// </summary>
|
static string RandomKey = "";
|
|
/// <summary>
|
/// 随机生成字符
|
/// </summary>
|
/// <returns></returns>
|
static string GetRandomKey()
|
{
|
if (string.IsNullOrEmpty(RandomKey))
|
{
|
//随机2位字符串
|
RandomKey = Utlis.CreateRandomString(2);
|
}
|
return RandomKey;
|
}
|
|
/// <summary>
|
/// 远程MqttClient
|
/// </summary>
|
public static IMqttClient RemoteMqttClient = new MqttFactory().CreateMqttClient();
|
|
/// <summary>
|
/// 推送标识
|
/// </summary>
|
static string PushSignStr = DateTime.Now.Ticks.ToString();
|
|
/// <summary>
|
/// 断开远程Mqtt的链接
|
/// </summary>
|
static async Task DisConnectRemoteMqttClient(string s = "")
|
{
|
try
|
{
|
if (remoteIsConnected)
|
{
|
remoteIsConnected = false;
|
isSubscribeSuccess = false;
|
Utlis.WriteLine($"Remote主动断开_{s}");
|
//await RemoteMqttClient.DisconnectAsync(new MQTTnet.Client.Disconnecting.MqttClientDisconnectOptions { }, CancellationToken.None);
|
await RemoteMqttClient.DisconnectAsync();
|
}
|
}
|
catch (Exception e)
|
{
|
Utlis.WriteLine($"Remote断开通讯连接出异常:{e.Message}");
|
}
|
}
|
|
/// <summary>
|
/// 断开远程Mqtt的链接
|
/// </summary>
|
static async Task DisConnectRemoteMqttClientWhenStart(string s = "")
|
{
|
try
|
{
|
remoteIsConnected = false;
|
isSubscribeSuccess = false;
|
Utlis.WriteLine($"RemoteStart主动断开_{s}");
|
await RemoteMqttClient.DisconnectAsync();
|
}
|
catch (Exception e)
|
{
|
Utlis.WriteLine($"RemoteStart断开通讯连接出异常:{e.Message}");
|
}
|
}
|
|
/// <summary>
|
/// 断开mqtt连接
|
/// </summary>
|
/// <param name="s">断开原因</param>
|
/// <param name="reset">是否需要去中心服务器 重新获取参数</param>
|
/// <returns></returns>
|
public static async Task DisConnectRemote(string s = "", bool reset = true)
|
{
|
if (reset)
|
{
|
MqttInfoConfig.Current.IfGetMqttInfoSuccess = false;
|
}
|
await DisConnectRemoteMqttClient(s);
|
}
|
|
/// <summary>
|
/// 外网的MQTT是否正在连接
|
/// </summary>
|
public static bool RemoteMqttIsConnecting;
|
static bool remoteIsConnected;
|
|
static MqttClient()
|
{
|
InitMqtt();
|
}
|
|
public static bool IsInitMqtt = false;
|
|
static void InitMqtt()
|
{
|
new System.Threading.Thread(async () => {
|
while (true)
|
{
|
try
|
{
|
System.Threading.Thread.Sleep(2000);
|
//进入后台不处理
|
if (MainPage.IsEnterBackground) continue;
|
if (MqttInfoConfig.Current.HomeGatewayInfo == null)
|
{
|
continue;
|
}
|
|
await StartCloudMqtt();
|
await SubscribeTopics();
|
}
|
catch { }
|
}
|
})
|
{ IsBackground = true }.Start();
|
}
|
|
/// <summary>
|
/// 初始化状态
|
/// </summary>
|
public static void InitState()
|
{
|
IfNeedReadAllDeviceStatus = true;
|
StartCloudMqtt();
|
}
|
|
static bool isSubscribeSuccess;
|
/// <summary>
|
/// 订阅主题
|
/// </summary>
|
/// <returns></returns>
|
static async Task SubscribeTopics()
|
{
|
if (remoteIsConnected && !isSubscribeSuccess)
|
{
|
try
|
{
|
if (DB_ResidenceData.Instance.GatewayType == 0 && !DB_ResidenceData.Instance.CheckWhetherGatewayIdIsNull())
|
{
|
Utlis.WriteLine("开始订阅一端口通用主题!");
|
//2020-05-14 订阅主题质量改为0
|
var topicFilterBusGateWayToClient = new MqttTopicFilter()
|
{
|
Topic = $"/BusGateWayToClient/{MqttInfoConfig.Current.HomeGatewayInfo.gatewayId}/#",
|
QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce
|
};
|
await RemoteMqttClient.SubscribeAsync(topicFilterBusGateWayToClient);
|
}
|
//挤下线主题
|
var topicFilterPush2 = new MqttTopicFilter
|
{
|
Topic = $"/BusGateWayToClient/{UserInfo.Current.ID}/#",
|
QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce,
|
};
|
var topicAlinkStatus = new MqttTopicFilter()
|
{
|
Topic = $"/user/{DB_ResidenceData.Instance.CurrentRegion.id}/app/thing/property/send",
|
QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce
|
};
|
//App订阅红外宝 / 网关遥控器添加成功通知
|
var pirStatus = new MqttTopicFilter()
|
{
|
Topic = $"/user/{DB_ResidenceData.Instance.CurrentRegion.id}/app/thing/topo/found",
|
QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce
|
};
|
//App订阅遥控器自学按键学习成功通知
|
var pirStudy = new MqttTopicFilter()
|
{
|
Topic = $"/user/{DB_ResidenceData.Instance.CurrentRegion.id}/app/thing/event/irCodeStudyDone/up",
|
QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce
|
};
|
|
#region 数据更新推送主题
|
//appHomeRefresh:住宅数据刷新通知--杨涛
|
var appHomeRefresh = new MqttTopicFilter()
|
{
|
Topic = $"/user/{DB_ResidenceData.Instance.CurrentRegion.id}/app/thing/event/appHomeRefresh/up",
|
QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce
|
};
|
//住宅消息变更推送--豆豆
|
var residenceChange = new MqttTopicFilter()
|
{
|
Topic = $"/user/{DB_ResidenceData.Instance.CurrentRegion.id}/app/thing/event/appDeviceRefresh/up",
|
QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce
|
};
|
//appRoomRefresh:房间数据刷新通知
|
var appRoomRefresh = new MqttTopicFilter()
|
{
|
Topic = $"/user/{DB_ResidenceData.Instance.CurrentRegion.id}/app/thing/event/appRoomRefresh/up",
|
QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce
|
};
|
//appDeviceRefresh:设备数据刷新通知
|
var appDeviceRefresh = new MqttTopicFilter()
|
{
|
Topic = $"/user/{MqttInfoConfig.Current.HomeGatewayInfo.gatewayId}/app/thing/event/appHomeRefresh/up",
|
QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce
|
};
|
//一端口密钥更新通知
|
var mqttkeyChange = new MqttTopicFilter()
|
{
|
Topic = $"/user/{MqttInfoConfig.Current.HomeGatewayInfo.gatewayId}/custom/mqtt/secret/change",
|
QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce
|
};
|
|
#endregion
|
|
|
Utlis.WriteLine("开始订阅!");
|
var result = await RemoteMqttClient.SubscribeAsync(new MqttTopicFilter[] {
|
pirStatus,pirStudy,
|
appDeviceRefresh,appHomeRefresh,appRoomRefresh,residenceChange,
|
topicFilterPush2, topicAlinkStatus ,mqttkeyChange});
|
if (result.Items[0].ResultCode == MQTTnet.Client.Subscribing.MqttClientSubscribeResultCode.GrantedQoS0)
|
{
|
isSubscribeSuccess = true;
|
Utlis.WriteLine("订阅成功!");
|
}
|
}
|
catch (Exception ex)
|
{
|
Console.WriteLine("订阅catch:" + ex.Message.ToString());
|
}
|
}
|
}
|
|
/// <summary>
|
/// 启动远程Mqtt
|
/// </summary>
|
public static async Task StartCloudMqtt()
|
{
|
if (MainPage.InternetStatus == 0)
|
{
|
return;
|
}
|
|
if (!UserInfo.Current.IsLogin)
|
{
|
return;
|
}
|
if (DB_ResidenceData.Instance.CurrentRegion == null || DB_ResidenceData.Instance.CurrentRegion.id == null)
|
{
|
return;
|
}
|
|
//追加:没有远程连接的权限
|
if (RemoteMqttIsConnecting || remoteIsConnected)
|
{
|
return;
|
}
|
|
Utlis.WriteLine($"StartCloudMqtt: 开始");
|
|
await Task.Factory.StartNew((Func<Task>)(async () => {
|
try
|
{
|
#region 初始化远程Mqtt
|
RemoteMqttIsConnecting = true;
|
RemoteMqttClient = new MqttFactory().CreateMqttClient();
|
|
|
//(1)当[连接云端的Mqtt成功后]或者[以及后面App通过云端Mqtt转发数据给网关成功后],处理接收到云端数据包响应时在mqttServerClient_ApplicationMessageReceived这个方法处理
|
if (RemoteMqttClient.ApplicationMessageReceivedHandler == null)
|
{
|
//处理接收到的数据
|
RemoteMqttClient.UseApplicationMessageReceivedHandler((Action<MqttApplicationMessageReceivedEventArgs>)((e) => {
|
try
|
{
|
var topic = e.ApplicationMessage.Topic;
|
//MainPage.Log($"收到mqtt主题:{topic}");
|
//一端口主题处理
|
if (DB_ResidenceData.Instance.GatewayType == 0 && !DB_ResidenceData.Instance.CheckWhetherGatewayIdIsNull())
|
{
|
if (topic == $"/BusGateWayToClient/{MqttInfoConfig.Current.HomeGatewayInfo.gatewayId}/NotifyBusGateWayInfoChange")
|
{
|
//网关上线,需要更新aeskey
|
//收到网关上线消息主题
|
ReceiveNotifyBusGateWayInfoChange();
|
return;
|
}
|
else if (topic == $"/BusGateWayToClient/{MqttInfoConfig.Current.HomeGatewayInfo.gatewayId}/NotifyGateWayOffline")
|
{
|
//网关掉线
|
//----第二步:读取账号下面的网关列表
|
ReceiveNotifyGateWayOffline();
|
return;
|
}
|
else if (topic == $"/BusGateWayToClient/{MqttInfoConfig.Current.HomeGatewayInfo.gatewayId}/Common/CheckGateway")
|
{
|
var ss = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
|
//ReceiveCheckGateway(ss);
|
return;
|
}
|
}
|
|
//一些特殊的主题处理(为了执行速度,尽可能的别加耗时的操作 true:执行了特殊处理 false:没有执行特殊处理)
|
if (Stan.HdlCloudReceiveLogic.Current.CloudOverallMsgReceiveEx(topic, e.ApplicationMessage.Payload, mqttEncryptKey, tuyaEncryptKey) == true)
|
{
|
return;
|
}
|
|
if (topic == $"/BusGateWayToClient/{UserInfo.Current.ID}" + PushNotifySqueeze)
|
{
|
var mMes = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
|
//新挤下线主题方案 收到挤下线主题
|
ReceiveNotifySqueezeAsync(mMes);
|
}
|
//App订阅红外宝/网关遥控器添加成功通知
|
else if (topic == $"/user/{DB_ResidenceData.Instance.CurrentRegion.id}/app/thing/topo/found")
|
{
|
var bytes = Securitys.EncryptionService.AesDecryptPayload(e.ApplicationMessage.Payload, tuyaEncryptKey);
|
var revString = Encoding.UTF8.GetString(bytes);
|
HDL_ON.UI.UI2.PersonalCenter.PirDevice.PirMethod.controldata = revString;
|
}
|
//App订阅遥控器自学按键学习成功通知
|
else if (topic == $"/user/{DB_ResidenceData.Instance.CurrentRegion.id}/app/thing/event/irCodeStudyDone/up")
|
{
|
var bytes = Securitys.EncryptionService.AesDecryptPayload(e.ApplicationMessage.Payload, tuyaEncryptKey);
|
var revString = Encoding.UTF8.GetString(bytes);
|
UI.UI2.PersonalCenter.PirDevice.PirMethod.buttondata = revString;
|
}
|
#region 数据更新推送主题
|
//appHomeRefresh:住宅数据刷新通知
|
else if (topic == $"/user/{DB_ResidenceData.Instance.CurrentRegion.id}/app/thing/event/appHomeRefresh/up"
|
|| topic == $"/user/{DB_ResidenceData.Instance.CurrentRegion.id}/app/thing/event/appDeviceRefresh/up")
|
{
|
MainPage.Log("住宅数据刷新通知");
|
new HttpServerRequest().GetHomePager();
|
}
|
//appRoomRefresh:房间数据刷新通知
|
else if (topic == $"/user/{DB_ResidenceData.Instance.CurrentRegion.id}/app/thing/event/appRoomRefresh/up")
|
{
|
MainPage.Log("房间数据刷新通知");
|
var roomResult = new HttpServerRequest().GetRoomList();
|
if (roomResult.Code == StateCode.SUCCESS)
|
{
|
MainPage.Log($"读取房间信息成功");
|
var revData = Newtonsoft.Json.JsonConvert.DeserializeObject<SpatialApiPack>(roomResult.Data.ToString());
|
if (revData == null)
|
{
|
revData = new SpatialApiPack();
|
}
|
{
|
SpatialInfo.CurrentSpatial.UpdateSpatialList(revData.list);
|
}
|
}
|
else
|
{
|
MainPage.Log($"读取房间数据失败:Code:{roomResult.Code}; msg:{roomResult.message}");
|
}
|
}
|
//appDeviceRefresh:设备数据刷新通知
|
else if (topic == $"/user/{DB_ResidenceData.Instance.CurrentRegion.id}/app/thing/event/appDeviceRefresh/up")
|
{
|
MainPage.Log("设备数据刷新通知");
|
var deviceResult = new HttpServerRequest().GetDeviceList();
|
if (deviceResult.Code == StateCode.SUCCESS)
|
{
|
MainPage.Log($"读取设备信息成功");
|
var deviceList = Newtonsoft.Json.JsonConvert.DeserializeObject<DevcieApiPack>(deviceResult.Data.ToString());
|
if (deviceList == null)
|
{
|
deviceList = new DevcieApiPack();
|
}
|
string delFile = "";
|
if (FunctionList.List.GetDeviceFunctionList().Count > 0)
|
{
|
for (int i = 0; i < FunctionList.List.GetDeviceFunctionList().Count;)
|
{
|
var localFunction = FunctionList.List.GetDeviceFunctionList()[i];
|
if (localFunction.Spk_Prefix == FunctionCategory.Music || string.IsNullOrEmpty(localFunction.Spk_Prefix))
|
{
|
i++;
|
continue;
|
}
|
var newFunction = deviceList.list.Find((obj) => obj.deviceId == localFunction.deviceId);
|
|
if (delFile == localFunction.savePath)
|
{
|
i++;
|
continue;
|
}
|
delFile = localFunction.savePath;
|
FunctionList.List.DeleteFunction(localFunction);
|
}
|
}
|
//处理剩下的新增功能
|
foreach (var newFunction in deviceList.list)
|
{
|
newFunction.SaveFunctionFile();
|
FunctionList.List.IniFunctionList(newFunction.savePath);
|
}
|
}
|
else
|
{
|
MainPage.Log($"读取云端设备数据失败:Code:{deviceResult.Code}; Msg:{deviceResult.message}");
|
}
|
}
|
//网关密钥变化
|
else if (topic == $"/user/{DB_ResidenceData.Instance.CurrentRegion.id}/custom/mqtt/secret/change")
|
{
|
var pm = new HttpServerRequest();
|
pm.GetHomeGatewayList();
|
MainPage.Log($"网关密钥变更");
|
MainPage.Log($"旧密钥:{mqttEncryptKey}");
|
mqttEncryptKey = MqttInfoConfig.Current.HomeGatewayInfo.aesKey;
|
MainPage.Log($"新密钥:{mqttEncryptKey}");
|
}
|
|
#endregion
|
//A网关设备状态-包含涂鸦设备
|
else if (topic == $"/user/{DB_ResidenceData.Instance.CurrentRegion.id}/app/thing/property/send")
|
{
|
var bytes = Securitys.EncryptionService.AesDecryptPayload(e.ApplicationMessage.Payload, tuyaEncryptKey);
|
var revString = Encoding.UTF8.GetString(bytes);
|
Control.Ins.UpdataFunctionStatus(revString, null, true);
|
}
|
//一端口数据解析
|
else
|
{
|
//SetGatewayOnlineResetCheck();
|
//var bytes = Securitys.EncryptionService.AesDecryptPayload(e.ApplicationMessage.Payload, mqttEncryptKey);
|
//bus数据解析
|
var packet = new Packet();
|
|
if (!string.IsNullOrEmpty(mqttEncryptKey))
|
{
|
packet.Bytes = Securitys.EncryptionService.AesDecryptPayload(e.ApplicationMessage.Payload, mqttEncryptKey);
|
}
|
else
|
{
|
packet.Bytes = e.ApplicationMessage.Payload;
|
}
|
packet.Manager();
|
}
|
}
|
catch { }
|
}));
|
}
|
|
//(2)DisconnectedHandler
|
if (RemoteMqttClient.DisconnectedHandler == null)
|
{
|
RemoteMqttClient.UseDisconnectedHandler(async (e) => {
|
Utlis.WriteLine($"远程连接断开");
|
isSubscribeSuccess = false;
|
await DisConnectRemoteMqttClient("UseDisconnectedHandler");
|
});
|
}
|
//(3)ConnectedHandler
|
if (RemoteMqttClient.ConnectedHandler == null)
|
{
|
RemoteMqttClient.UseConnectedHandler(async (e) =>
|
{
|
IfNeedReadAllDeviceStatus = true;
|
Control.Ins.GatewayOnline_Cloud = true;
|
Utlis.WriteLine($"============>Mqtt远程连接成功");
|
SendPushSignOut();
|
});
|
}
|
#endregion
|
|
//(4)===========开始连接过程==========
|
|
////一端口每次都要刷新密钥
|
//if (DB_ResidenceData.Instance.HomeGateway != null && DB_ResidenceData.Instance.HomeGateway.gatewayType == "BUSUDPGATEWAY") {
|
// var pm = new HttpServerRequest();
|
// var result = pm.GetHomeGatewayList();
|
// if(result == StateCode.SUCCESS)
|
// {
|
// MainPage.Log($"刷新一端口密钥");
|
// MainPage.Log($"旧密钥:{mqttEncryptKey}");
|
// mqttEncryptKey = MqttInfoConfig.Current.HomeGatewayInfo.aesKey;
|
// MainPage.Log($"新密钥:{mqttEncryptKey}");
|
// }else
|
// {
|
// return;
|
// }
|
//}
|
|
|
|
//之前已经获取参数成功过
|
if (MqttInfoConfig.Current.IfGetMqttInfoSuccess)
|
{
|
//判断是否需要重新获取
|
await CheckMQTTConnectAsync();
|
}
|
else
|
{
|
//开始获取远程连接参数
|
await StartMQTTGetInfo();
|
}
|
|
}
|
catch (Exception ex)
|
{
|
Utlis.WriteLine($"error:" + ex.Message);
|
//mqtt连接异常,清空本地mqtt信息,可能需要重新获取:wxr
|
MqttInfoConfig.Current.Refresh();
|
}
|
finally
|
{
|
//最终要释放连接状态
|
RemoteMqttIsConnecting = false;
|
|
Utlis.WriteLine($"StartCloudMqtt: 结束");
|
}
|
|
}));
|
}
|
|
|
/// <summary>
|
/// 检测是否需要发送刷新获取所有设备的命令
|
/// </summary>
|
static void CheckIfNeedReadAllDeviceStatus()
|
{
|
if (IfNeedReadAllDeviceStatus)
|
{
|
Utlis.WriteLine("ReadAllDeviceStatus");
|
IfNeedReadAllDeviceStatus = false;
|
}
|
}
|
|
|
/// <summary>
|
/// 检测之前获取的Mac与当前住宅MAC是否一致 不一致从新获取
|
/// </summary>
|
/// <returns></returns>
|
static async Task CheckMQTTConnectAsync()
|
{
|
try
|
{
|
if (MqttInfoConfig.Current.HomeGatewayInfo != null && MqttInfoConfig.Current.HomeGatewayInfo.mac == Entity.DB_ResidenceData.Instance.residenceGatewayMAC)
|
{
|
await MQTTConnectAsync();
|
}
|
else
|
{
|
//Mac 变化了重新获取参数
|
await StartMQTTGetInfo();
|
}
|
}
|
catch
|
{
|
MqttInfoConfig.Current.IfGetMqttInfoSuccess = false;
|
}
|
|
}
|
|
/// <summary>
|
/// 开始获取Mqtt 远程参数
|
/// </summary>
|
/// <returns></returns>
|
static async Task StartMQTTGetInfo()
|
{
|
await GetMqttInfoAndMQTTConnectAsync();
|
|
////--判断是当前是否分享的住宅
|
//if (!UserConfig.Instance.CurrentRegion.IsOthreShare) {
|
// //主账号获取MQTT 远程链接信息,并连接
|
// await GetMqttInfoAndMQTTConnectAsync ();
|
//} else {
|
// //如果是分享过来的住宅 走下面流程
|
// //--第一步:获取当前住分享宅网关信息并连接MQTT
|
// await GetSingleHomeGatewayPaggerAndMQTTConnectAsync ();
|
//}
|
}
|
|
/// <summary>
|
/// 连接MQTT
|
/// </summary>
|
static async Task MQTTConnectAsync()
|
{
|
//if (MqttInfoConfig.Current.HomeGatewayInfo != null && MqttInfoConfig.Current.mMqttInfo != null)
|
//没有网关情况下,也需要连接mqtt,涂鸦第三方设备不需要网关
|
if (MqttInfoConfig.Current.mMqttInfo != null)
|
{
|
try
|
{
|
|
var url = MqttInfoConfig.Current.mMqttInfo.url;
|
|
//url = HttpUtil.GetProxyEMQUrl (url);
|
//#if DEBUG
|
//url = HttpUtil.GetProxyEMQUrl (url);
|
//#endif
|
var clientId = MqttInfoConfig.Current.mMqttInfo.clientId;
|
var username = MqttInfoConfig.Current.mMqttInfo.userName;
|
var passwordRemote = MqttInfoConfig.Current.mMqttInfo.passWord;
|
//获取参数成功,保存到本地并标记为true
|
MqttInfoConfig.Current.IfGetMqttInfoSuccess = true;
|
MqttInfoConfig.Current.Save();
|
|
|
|
mqttEncryptKey = MqttInfoConfig.Current.HomeGatewayInfo.aesKey;
|
//解密密钥规则:已现有的住宅ID为基准,从右边一一获取值,最后如果不够16位,则往右补零
|
string aesKey = string.Empty;
|
for (int i = DB_ResidenceData.Instance.CurrentRegion.id.Length - 1; i >= 0; i--)
|
{
|
aesKey += DB_ResidenceData.Instance.CurrentRegion.id[i].ToString();
|
if (aesKey.Length == 16) { break; }
|
}
|
aesKey = aesKey.PadRight(16, '0');
|
tuyaEncryptKey = aesKey;
|
|
var options1 = new MQTTnet.Client.Options.MqttClientOptionsBuilder()
|
.WithClientId(clientId)
|
.WithTcpServer(url.Split(':')[1].Substring("//".Length), int.Parse(url.Split(':')[2]))
|
.WithCredentials(username, passwordRemote)
|
.WithCleanSession()
|
.WithProtocolVersion(MQTTnet.Formatter.MqttProtocolVersion.V311)
|
.WithCommunicationTimeout(new TimeSpan(0, 0, 10))
|
//.WithCommunicationTimeout (new TimeSpan (0, 0, 5))
|
//.WithCommunicationTimeout (new TimeSpan (0, 1, 0))
|
.Build();
|
|
await DisConnectRemoteMqttClient("StartRemoteMqtt");
|
|
var mResult = await RemoteMqttClient.ConnectAsync(options1);
|
|
if (mResult.ResultCode == MQTTnet.Client.Connecting.MqttClientConnectResultCode.Success)
|
{
|
remoteIsConnected = true;
|
IsDisConnectingWithSendCatch = false;
|
}
|
else
|
{
|
//重新中心服务器获取参数标记
|
MqttInfoConfig.Current.IfGetMqttInfoSuccess = false;
|
}
|
|
}
|
catch (Exception ex)
|
{
|
|
//重新中心服务器获取参数标记
|
MqttInfoConfig.Current.IfGetMqttInfoSuccess = false;
|
Console.WriteLine("Connect error: " + ex.Message);
|
//mqtt连接异常,清空本地mqtt信息,可能需要重新获取:wxr
|
MqttInfoConfig.Current.Refresh();
|
}
|
finally
|
{
|
|
}
|
|
}
|
else
|
{
|
MqttInfoConfig.Current.IfGetMqttInfoSuccess = false;
|
}
|
|
}
|
|
/// <summary>
|
/// 收到网关上线消息
|
/// </summary>
|
static void ReceiveNotifyBusGateWayInfoChange()
|
{
|
try
|
{
|
//SetGatewayOnlineResetCheck();
|
if (Control.Ins.GatewayOnline_Cloud)
|
{
|
CheckIfNeedReadAllDeviceStatus();
|
}
|
}
|
catch { }
|
}
|
|
/// <summary>
|
/// 收到网关掉线信息
|
/// </summary>
|
static void ReceiveNotifyGateWayOffline()
|
{
|
Control.Ins.GatewayOnline_Cloud = false;
|
}
|
|
/// <summary>
|
/// 收到挤下线推送
|
/// </summary>
|
static void ReceiveNotifySqueezeAsync(string mMes)
|
{
|
if (mMes == PushSignStr) return;//是自己的登录推送不处理//或者当前不是远程链接状态
|
//测试账号,不挤下线
|
switch (UserInfo.Current.userMobileInfo)
|
{
|
case "13415629083":
|
case "18316120654":
|
case "15622703419":
|
case "18824864143":
|
case "464027401@qq.com":
|
case "2791308028@qq.com":
|
case "13697499568":
|
case "18666455392":
|
case "13375012446":
|
case "13602944661":
|
case "18778381374":
|
case "18316672920":
|
case "15971583093":
|
case "15626203746":
|
case "551775569@qq.com":
|
return;
|
}
|
|
if (!UserInfo.Current.IsLogin)
|
{
|
return;
|
}
|
|
DisConnectRemoteMqttClient("挤下线");
|
|
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 ();
|
}
|
|
///// <summary>
|
///// 收到CheckGateway主题
|
///// </summary>
|
//static void ReceiveCheckGateway(string mMes)
|
//{
|
// if (!Control.Ins.IsRemote) return;
|
|
// Utlis.WriteLine("ReceiveCheckGateway!");
|
|
// //CheckIfNeedReadAllDeviceStatus ();
|
|
// //var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<ResponsePack>(mMes);
|
// Control.Ins.GatewayOnline = true;
|
//}
|
|
/// <summary>
|
/// 推送挤下线主题
|
/// </summary>
|
static void SendPushSignOut()
|
{
|
byte[] message = Encoding.UTF8.GetBytes(PushSignStr);
|
MqttRemoteSend(message, 4);
|
}
|
|
/// <summary>
|
///
|
/// </summary>
|
/// <param name="message">附加数据包</param>
|
/// <param name="optionType">操作类型:0=网关控制;1=订阅网关数据;2=订阅网关上线数据</param>
|
/// <returns></returns>
|
public static async Task MqttRemoteSend(byte[] message, int optionType = 0)
|
{
|
try
|
{
|
string topicName;
|
switch (optionType)
|
{
|
case 0:
|
topicName = $"/ClientToBusGateWay/{MqttInfoConfig.Current.HomeGatewayInfo.gatewayId}/Common/ON";
|
if (!string.IsNullOrEmpty(mqttEncryptKey))
|
{
|
message = Securitys.EncryptionService.AesEncryptPayload(message, mqttEncryptKey);
|
}
|
await RemoteMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topicName, Payload = message, Retain = false, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce });
|
break;
|
case 4://发布新方案的挤下线主题
|
topicName = $"/BusGateWayToClient/{UserInfo.Current.ID}" + PushNotifySqueeze;
|
//message = Encoding.UTF8.GetBytes (PushSignStr);
|
await RemoteMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topicName, Payload = message, Retain = false, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce });
|
break;
|
}
|
}
|
catch (Exception e)
|
{
|
//Utlis.WriteLine ($"============>Mqtt MqttRemoteSend catch");
|
if (!IsDisConnectingWithSendCatch)
|
{
|
IsDisConnectingWithSendCatch = true;
|
await DisConnectRemoteMqttClient("SendCatch");
|
}
|
}
|
}
|
/// <summary>
|
/// SendCatch 后执行一次断开操作
|
/// </summary>
|
static bool IsDisConnectingWithSendCatch = false;
|
|
|
/// <summary>
|
/// 是否需要读取一次所有设备状态
|
/// </summary>
|
static bool IfNeedReadAllDeviceStatus = true;
|
|
///// <summary>
|
///// 设置网关在线标志,并重置CheckGateway参数
|
///// </summary>
|
//static void SetGatewayOnlineResetCheck()
|
//{
|
// if (Control.Ins.IsRemote)
|
// {
|
// if (!Control.Ins.GatewayOnline)
|
// {
|
// try
|
// {
|
// if (DB_ResidenceData.Instance.HomeGateway != null)
|
// {
|
// DB_ResidenceData.Instance.HomeGateway.gatewayStatus = true;
|
// }
|
// Control.Ins.GatewayOnline = true;
|
// }
|
// catch { }
|
// }
|
// }
|
//}
|
|
|
/// <summary>
|
/// 主账号获取MQTT 远程链接信息,并连接
|
/// </summary>
|
/// <returns></returns>
|
static async Task GetMqttInfoAndMQTTConnectAsync()
|
{
|
var mqttInfoRequestResult_Obj = new HttpServerRequest().GetMqttRemoteInfo(GetRandomKey());
|
if (mqttInfoRequestResult_Obj != null)
|
{
|
MainPage.Log($"获取mqtt info 成功 /r/n clientId:{mqttInfoRequestResult_Obj.clientId}/r/n passWord:{mqttInfoRequestResult_Obj.passWord} /r/n url:{mqttInfoRequestResult_Obj.url}/r/n userName:{mqttInfoRequestResult_Obj.userName}");
|
|
|
MqttInfoConfig.Current.mMqttInfo = mqttInfoRequestResult_Obj;
|
await MQTTConnectAsync();
|
//1.判断是否绑定了网关,获取网关远程连接的加密KEY
|
//if (DB_ResidenceData.Instance.CheckWhetherGatewayIsBound())
|
{
|
//2.找出是否存在匹配当前住宅的mac,存在再进行远程。
|
MqttInfoConfig.Current.HomeGatewayInfo = DB_ResidenceData.Instance.HomeGateway;
|
//3.开始连接
|
await MQTTConnectAsync();
|
}
|
//else
|
//{
|
// Utlis.WriteLine("============>还没绑定网关");
|
// hadGateway = false;
|
//}
|
}
|
}
|
|
}
|
}
|
|
|
public class MqttInfo
|
{
|
/// <summary>
|
///
|
/// </summary>
|
public string url;
|
/// <summary>
|
///
|
/// </summary>
|
public string clientId;
|
/// <summary>
|
///
|
/// </summary>
|
public string userName;
|
/// <summary>
|
///
|
/// </summary>
|
public string passWord;
|
}
|
|
|
|
namespace Securitys
|
{
|
public partial class EncryptionService
|
{
|
|
#region 加密
|
/// <summary>
|
/// 加密主题为Base64
|
/// </summary>
|
/// <param name="pToEncrypt"></param>
|
/// <param name="key"></param>
|
/// <returns></returns>
|
public static string AesEncryptTopic(string pToEncrypt, string key)
|
{
|
if (string.IsNullOrEmpty(pToEncrypt)) return null;
|
if (string.IsNullOrEmpty(key)) return pToEncrypt;
|
//需要加密内容的明文流
|
Byte[] toEncryptArray = Encoding.UTF8.GetBytes(pToEncrypt);
|
|
//配置AES加密Key(密钥、向量、模式、填充)
|
RijndaelManaged rm = new RijndaelManaged
|
{
|
Key = Encoding.UTF8.GetBytes(key),
|
IV = Encoding.UTF8.GetBytes(key),
|
Mode = CipherMode.CBC,
|
Padding = PaddingMode.PKCS7
|
};
|
|
//创建AES加密器对象
|
ICryptoTransform cTransform = rm.CreateEncryptor();
|
|
//使用AES将明文流转成密文字节数组
|
Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
|
|
//将AES生成的密文字节数组转成Base64字符串
|
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
|
}
|
|
|
/// <summary>
|
/// 加密负载为二进制流
|
/// </summary>
|
/// <param name="toEncryptArray"></param>
|
/// <param name="key"></param>
|
/// <returns></returns>
|
public static byte[] AesEncryptPayload(byte[] toEncryptArray, string key)
|
{
|
if (string.IsNullOrEmpty(key)) return toEncryptArray;
|
//配置AES加密Key(密钥、向量、模式、填充)
|
var rm = new RijndaelManaged
|
{
|
Key = Encoding.UTF8.GetBytes(key),
|
IV = Encoding.UTF8.GetBytes(key),
|
Mode = CipherMode.CBC,
|
Padding = PaddingMode.PKCS7
|
};
|
|
//创建AES加密器对象
|
var cTransform = rm.CreateEncryptor();
|
//使用AES将明文流转成密文字节数组
|
return cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
|
}
|
#endregion
|
|
|
#region 解密
|
/// <summary>
|
/// 解密主题数据
|
/// </summary>
|
/// <param name="pToDecrypt"></param>
|
/// <param name="key"></param>
|
/// <returns></returns>
|
public static string AesDecryptTopic(string pToDecrypt, string key)
|
{
|
//AES密文Base64转成字符串
|
Byte[] toEncryptArray = Convert.FromBase64String(pToDecrypt);
|
|
//配置AES加密Key(密钥、向量、模式、填充)
|
RijndaelManaged rm = new RijndaelManaged
|
{
|
Key = Encoding.UTF8.GetBytes(key),
|
IV = Encoding.UTF8.GetBytes(key),
|
Mode = CipherMode.CBC,
|
Padding = PaddingMode.PKCS7
|
};
|
|
//创建AES解密器对象
|
ICryptoTransform cTransform = rm.CreateDecryptor();
|
|
//使用AES将密文流转成明文的字节数组
|
Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
|
|
//转成字符串
|
return Encoding.UTF8.GetString(resultArray);
|
}
|
|
/// <summary>
|
/// 采用Aes解密负载数据
|
/// </summary>
|
/// <param name="toEncryptArray"></param>
|
/// <param name="key"></param>
|
/// <returns></returns>
|
public static byte[] AesDecryptPayload(byte[] toEncryptArray, string key)
|
{
|
//配置AES加密Key(密钥、向量、模式、填充)
|
var rm = new RijndaelManaged
|
{
|
Key = Encoding.UTF8.GetBytes(key),
|
IV = Encoding.UTF8.GetBytes(key),
|
Mode = CipherMode.CBC,
|
Padding = PaddingMode.PKCS7
|
};
|
|
//创建AES解密器对象
|
var cTransform = rm.CreateDecryptor();
|
|
//使用AES将密文流转成明文的字节数组
|
return cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
|
}
|
#endregion
|
|
|
|
}
|
}
|