/// <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}]主题");
        }
Beispiel #2
0
        /// <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服务器!");
 }