/// <summary> /// MQTT客户端连接关闭 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MqttClient_Disconnected(object sender, EventArgs e) { DateTime curTime = new DateTime(); curTime = DateTime.UtcNow; UIAction.AppendLog($">> [{curTime.ToLongTimeString()}]"); UIAction.AppendLog("已断开MQTT连接!"); //Reconnecting if (isReconnect) { Task.Run(async() => { UIAction.AppendLog("正在尝试重新连接"); await Task.Delay(TimeSpan.FromSeconds(5)); try { await ConnectMqttServerAsync(); } catch (Exception ex) { UIAction.AppendLog("连接失败:" + ex.ToString()); } }); } else { UIAction.AppendLog("已下线!"); } }
private void MqttClient_ApplicationMessageReceived(object sender, MqttApplicationMessageReceivedEventArgs e) { UIAction.AppendLog($">> ### RECEIVED APPLICATION MESSAGE ###"); UIAction.AppendLog($">> Topic = {e.ApplicationMessage.Topic}"); UIAction.AppendLog($">> Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}"); UIAction.AppendLog($">> QoS = {e.ApplicationMessage.QualityOfServiceLevel}"); UIAction.AppendLog($">> Retain = {e.ApplicationMessage.Retain}"); }
/// <summary> /// 清除缓存 /// </summary> public static void Clear() { string[] files = FileHelper.GetFileNames(CachePath); foreach (string item in files) { FileHelper.DeleteFile(item); } UIAction.AppendLog("缓存已清除"); }
/// <summary> /// 缓存数据 调用 /// </summary> /// <param name="obj"></param> /// <param name="filename"></param> /// <returns></returns> public static bool Save_Cache(object obj, string filename) { try { //对象二进制序列化 BinaryFormatter bf = new BinaryFormatter(); using (FileStream fsWrite = new FileStream(CachePath + filename + ".bin", FileMode.Create)) { bf.Serialize(fsWrite, obj); return(true); } } catch (Exception ex) { UIAction.AppendLog("写入缓存异常:" + ex.Message); return(false); } }
/// <summary> /// 订阅主题 /// </summary> /// <returns></returns> public async Task Subscribe(string topic) { if (string.IsNullOrEmpty(topic)) { UIAction.AppendLog("订阅主题不能为空!"); return; } if (!mqttClient.IsConnected) { UIAction.AppendLog("MQTT客户端尚未连接!"); return; } // Subscribe to a topic await mqttClient.SubscribeAsync(new TopicFilterBuilder() .WithTopic(topic) .WithAtMostOnceQoS() .Build() ); UIAction.AppendLog($"已订阅[{topic}]主题"); }
/// <summary> /// 读取缓存 调用 /// </summary> /// <returns></returns> public static object Read_CacheBin(string filename) { object obj = null; string fullpath = CachePath + filename + ".bin"; try { if (FileHelper.IsExistFile(fullpath)) { //对象二进制序列化 BinaryFormatter bf = new BinaryFormatter(); using (FileStream fsRead = new FileStream(fullpath, FileMode.Open)) { obj = bf.Deserialize(fsRead); } } return(obj); } catch (Exception ex) { UIAction.AppendLog("读取缓存异常:" + ex.Message); return(obj); } }
public async Task ConnectMqttServerAsync() { // Create a new MQTT client. BuldingLoginInfo(); if (mqttClient == null) { MqttFactory factory = new MqttFactory(); mqttClient = factory.CreateMqttClient(); mqttClient.ApplicationMessageReceived += MqttClient_ApplicationMessageReceived; mqttClient.Connected += MqttClient_Connected; mqttClient.Disconnected += MqttClient_Disconnected; } //非托管客户端 try { ////Create TCP based options using the builder. //var options1 = new MqttClientOptionsBuilder() // .WithClientId("client001") // .WithTcpServer("192.168.88.3") // .WithCredentials("bud", "%spencer%") // .WithTls() // .WithCleanSession() // .Build(); //// Use TCP connection. //var options2 = new MqttClientOptionsBuilder() // .WithTcpServer("192.168.88.3", 8222) // Port is optional // .Build(); //// Use secure TCP connection. //var options3 = new MqttClientOptionsBuilder() // .WithTcpServer("192.168.88.3") // .WithTls() // .Build(); //Create TCP based options using the builder. IMqttClientOptions options = new MqttClientOptionsBuilder() .WithClientId(ClientId) .WithTcpServer(TcpServer, TcpServerPort) .WithCredentials(UserName, PassWord) .WithKeepAlivePeriod(TimeSpan.FromSeconds(500)) //.WithTls()//服务器端没有启用加密协议,这里用tls的会提示协议异常 .WithCleanSession() .Build(); //// For .NET Framwork & netstandard apps: //MqttTcpChannel.CustomCertificateValidationCallback = (x509Certificate, x509Chain, sslPolicyErrors, mqttClientTcpOptions) => //{ // if (mqttClientTcpOptions.Server == "server_with_revoked_cert") // { // return true; // } // return false; //}; //2.4.0版本的 //var options0 = new MqttClientTcpOptions //{ // Server = "127.0.0.1", // ClientId = Guid.NewGuid().ToString().Substring(0, 5), // UserName = "******", // Password = "******", // CleanSession = true //}; await mqttClient.ConnectAsync(options); } catch (Exception ex) { //isReconnect = false; UIAction.AppendLog($"连接到MQTT服务器失败:" + ex.ToString()); } //托管客户端 //try //{ //// Setup and start a managed MQTT client. //var options = new ManagedMqttClientOptionsBuilder() // .WithAutoReconnectDelay(TimeSpan.FromSeconds(5)) // .WithClientOptions(new MqttClientOptionsBuilder() // .WithClientId("Client_managed") // .WithTcpServer("192.168.88.3", 8223) // .WithTls() // .Build()) // .Build(); //var mqttClient = new MqttFactory().CreateManagedMqttClient(); //await mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic("my/topic").Build()); //await mqttClient.StartAsync(options); //} //catch (Exception) //{ //} }
/// <summary> /// MQTT客户端连接成功 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MqttClient_Connected(object sender, EventArgs e) { UIAction.AppendLog("已连接到MQTT服务器!"); }