private async Task ConnectMqttServerAsync() { if (mqttClient == null) { mqttClient = new MqttClientFactory().CreateMqttClient() as MqttClient; mqttClient.ApplicationMessageReceived += MqttClient_ApplicationMessageReceived; mqttClient.Connected += MqttClient_Connected; mqttClient.Disconnected += MqttClient_Disconnected; } try { var options = new MqttClientTcpOptions { Server = "10.204.138.7", Port = 1883, ClientId = "claa_001",// Guid.NewGuid().ToString().Substring(0, 5), UserName = "******", Password = "******", CleanSession = true }; await mqttClient.ConnectAsync(options); } catch (Exception ex) { Invoke((new Action(() => { richTextBox_Subscribe.AppendText($"连接到MQTT服务器失败!" + Environment.NewLine + ex.Message + Environment.NewLine); }))); } }
public async Task <bool> ConnectAsync(Uri uri, string username, string password) { if (BrokerUri == null && uri != null) { BrokerUri = uri; } if (BrokerUri != null && uri == null) { uri = BrokerUri; } bool initok = false; try { var factory = new MqttFactory(); Client = factory.CreateMqttClient( ); var clientOptions = new MqttClientOptionsBuilder() .WithClientId(uri.ToString() + Guid.NewGuid().ToString()) .WithTcpServer(uri.Host, uri.Port) .WithCredentials(username, password) .Build(); Client.ApplicationMessageReceivedAsync += Client_ApplicationMessageReceived; Client.ConnectedAsync += e => { Client.SubscribeAsync($"/devices/{DeviceId}/rpc/request/+/+"); Client.SubscribeAsync($"/devices/{DeviceId}/attributes/update/", MqttQualityOfServiceLevel.ExactlyOnce); LogInformation?.Invoke($"CONNECTED WITH SERVER "); return(Task.CompletedTask); }; Client.DisconnectedAsync += async e => { try { await Client.ConnectAsync(clientOptions); } catch (Exception exception) { LogError?.Invoke("CONNECTING FAILED", exception); } }; try { var result = await Client.ConnectAsync(clientOptions); initok = result.ResultCode == MqttClientConnectResultCode.Success; } catch (Exception exception) { LogError?.Invoke("CONNECTING FAILED", exception); } LogInformation?.Invoke("WAITING FOR APPLICATION MESSAGES"); } catch (Exception exception) { LogError?.Invoke("CONNECTING FAILED", exception); } return(initok); }
public MqttContext(IMqttContextOptions options) { Factory = new MqttFactory(); Logger = Factory.DefaultLogger; MqttClient = Factory.CreateMqttClient(); MqttClient.ConnectAsync(options.MqttClientOptions).ConfigureAwait(false).GetAwaiter().GetResult(); }
private async void Btn_conn_Click(object sender, EventArgs e) { var btn = sender as Button; if (btn.Text == "conn") { Make_mqttClientOptions(); try { await mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None); // Since 3.0.5 with CancellationToken } catch (Exception err) { Invoke((new Action(() => { this.textBox_recv.AppendText(Environment.NewLine + err.ToString()); }))); } Console.WriteLine(Environment.NewLine); } else { try { await mqttClient.DisconnectAsync(); } catch (Exception err) { Invoke((new Action(() => { this.textBox_recv.AppendText(Environment.NewLine + err.ToString()); }))); } } }
private static async Task ConnectMqttServerAsync() { if (mqttClient == null) { mqttClient = new MqttClientFactory().CreateMqttClient() as MqttClient; mqttClient.ApplicationMessageReceived += MqttClient_ApplicationMessageReceived; mqttClient.Connected += MqttClient_Connected; mqttClient.Disconnected += MqttClient_Disconnected; } try { var options = new MqttClientTcpOptions { Server = server, ClientId = clientid, UserName = username, Password = password, Port = port, CleanSession = true }; await DisConnectMqttServerAsync(); await mqttClient.ConnectAsync(options); await ReConnectMqttServerAsync(); } catch (Exception ex) { LogHelper.Log(ex.ToString()); } }
public void Setup() { _host = WebHost.CreateDefaultBuilder() .UseKestrel(o => o.ListenAnyIP(1883, l => l.UseMqtt())) .ConfigureServices(services => { services .AddHostedMqttServer(mqttServerOptions => mqttServerOptions.WithoutDefaultEndpoint()) .AddMqttConnectionHandler(); }) .Configure(app => { app.UseMqttServer(s => { }); }) .Build(); var factory = new MqttFactory(); _mqttClient = factory.CreateMqttClient(new MqttNetEventLogger(), new MqttClientConnectionContextFactory()); _host.StartAsync().GetAwaiter().GetResult(); var clientOptions = new MqttClientOptionsBuilder() .WithTcpServer("localhost").Build(); _mqttClient.ConnectAsync(clientOptions).GetAwaiter().GetResult(); _message = new MqttApplicationMessageBuilder() .WithTopic("A") .Build(); }
/// <summary> /// Connects to the MQTT server using the specified port and client identifier and a callback function in case of lost connection. /// </summary> /// <param name="port">MQTT server port.</param> /// <param name="clientId">The client identifier.</param> /// <param name="callback">The name of callback function, like RefreshConnection</param> /// <example>Action RefreshConnection = () => {...}</example> public MqttClientHelper Connect(int port, string clientId, Action callback = null) { endPoint.Port = port; endPoint.ClientId = clientId; Disconnect(); mqttClient = (MqttClient)factory.CreateMqttClient(); mqttClient.UseConnectedHandler(async e => { if (callback != null) { callback(); } foreach (KeyValuePair <string, Action <string, string> > subscription in subscribeTopics) { await mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic(subscription.Key).Build()); } }); mqttClient.UseDisconnectedHandler(async e => { Console.WriteLine(e.Exception.Message); await Task.Delay(TimeSpan.FromSeconds(5)); Connect(endPoint.Port, endPoint.ClientId, null); }); mqttClient.UseApplicationMessageReceivedHandler(e => MessageReceived(e)); mqttClient.ConnectAsync(GetMqttOption(clientId)); return(this); }
/// <summary> /// Connects to the MQTT server using the specified port and client identifier and a callback function in case of lost connection. /// </summary> /// <param name="port">MQTT server port.</param> /// <param name="clientId">The client identifier.</param> /// <param name="callback">The name of callback function, like RefreshConnection</param> /// <example>Action RefreshConnection = () => {...}</example> public MqttClientHelper Connect(int port, string clientId, Action callback) { endPoint.Port = port; endPoint.ClientId = clientId; Disconnect(); mqttClient = (MqttClient)factory.CreateMqttClient(); mqttClient.Connected += (sender, args) => { callback(); if (subscribeTopic != null) { mqttClient.SubscribeAsync(subscribeTopic); } }; mqttClient.Disconnected += (sender, args) => { Console.WriteLine(args.Exception.Message); Disconnect(); Thread.Sleep(5000); Connect(); }; var options = GetMqttOption(clientId); mqttClient.ConnectAsync(options); return(this); }
/// <summary> /// 连接服务器 /// </summary> /// <returns></returns> private async static Task ConnectMqttServerAsync() { if (mqttClient == null) { mqttClient = new MqttClientFactory().CreateMqttClient() as MqttClient; mqttClient.ApplicationMessageReceived += MqttClient_ApplicationMessageReceived; mqttClient.Connected += MqttClient_Connected; mqttClient.Disconnected += MqttClient_Disconnected; } try { var options = new MqttClientTcpOptions { Server = "127.0.0.1", //Server = "172.16.30.77", ClientId = Guid.NewGuid().ToString().Substring(0, 5), UserName = "******", Password = "******", CleanSession = true }; await mqttClient.ConnectAsync(options); Subscribe("IO-LINK"); } catch (Exception ex) { Status = $"连接到MQTT服务器失败!"; } }
private async Task ConnectMqttServerAsync() { if (mqttClient == null) { mqttClient = new MqttClientFactory().CreateMqttClient() as MqttClient; mqttClient.ApplicationMessageReceived += MqttClient_ApplicationMessageReceived; mqttClient.Connected += MqttClient_Connected; mqttClient.Disconnected += MqttClient_Disconnected; } try { var options = 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) { Invoke((new Action(() => { txtReceiveMessage.AppendText($"MQTT service connected failure!" + Environment.NewLine + ex.Message + Environment.NewLine); }))); } }
public async Task <IMqttClient> ConnectTestClient(IMqttServer server, string clientId, MqttApplicationMessage willMessage = null) { var adapterA = new TestMqttCommunicationAdapter(); var adapterB = new TestMqttCommunicationAdapter(); adapterA.Partner = adapterB; adapterB.Partner = adapterA; var client = new MqttClient( new TestMqttCommunicationAdapterFactory(adapterA), new MqttNetLogger()); var connected = WaitForClientToConnect(server, clientId); FireClientAcceptedEvent(adapterB); var options = new MqttClientOptions { ClientId = clientId, WillMessage = willMessage, ChannelOptions = new MqttClientTcpOptions() }; await client.ConnectAsync(options); await connected; return(client); }
private async Task ConnectMqttServerAsync() { if (mqttClient == null) { mqttClient = new MqttClientFactory().CreateMqttClient() as MqttClient; mqttClient.ApplicationMessageReceived += MqttClient_ApplicationMessageReceived; mqttClient.Connected += MqttClient_Connected; mqttClient.Disconnected += MqttClient_Disconnected; } try { var options = new MqttClientTcpOptions { Server = "CN11WPHAN-72", ClientId = Guid.NewGuid().ToString().Substring(0, 5), UserName = "******", Password = "******", CleanSession = true }; await mqttClient.ConnectAsync(options); Subscrebe("user"); } catch (Exception ex) { log.Fatal($"连接到MQTT服务器失败!" + Environment.NewLine + ex.Message + Environment.NewLine, ex); } }
/// <summary> /// MQTT连接服务器 /// </summary> private async Task ConnectMqttServerAsync() { if (mqttClient == null) { mqttClient = new MqttClientFactory().CreateMqttClient() as MqttClient; //mqttClient.ApplicationMessageReceived += MqttClient_ApplicationMessageReceived; mqttClient.Connected += MqttClient_Connected; mqttClient.Disconnected += MqttClient_Disconnected; } try { var options = new MqttClientTcpOptions { Server = "172.17.130.127", ClientId = Guid.NewGuid().ToString().Substring(0, 5), UserName = "******", Password = "", CleanSession = true }; await mqttClient.ConnectAsync(options); } catch (Exception ex) { Invoke((new Action(() => { Common.LogHandler.WriteLog($"连接到MQTT服务器失败!" + Environment.NewLine + ex.Message + Environment.NewLine); }))); } }
private async void Connect(object sender, RoutedEventArgs e) { var options = new MqttClientOptions { Server = Server.Text, UserName = User.Text, Password = Password.Text, ClientId = ClientId.Text }; options.TlsOptions.UseTls = UseTls.IsChecked == true; try { if (_mqttClient != null) { await _mqttClient.DisconnectAsync(); } var factory = new MqttClientFactory(); _mqttClient = factory.CreateMqttClient(options); await _mqttClient.ConnectAsync(); } catch (Exception exception) { Trace.Text += exception + Environment.NewLine; } }
public async Task ClientCleanupOnAuthentificationFails() { var channel = new TestMqttCommunicationAdapter(); var channel2 = new TestMqttCommunicationAdapter(); channel.Partner = channel2; channel2.Partner = channel; Task.Run(async() => { var connect = await channel2.ReceivePacketAsync(TimeSpan.Zero, CancellationToken.None); await channel2.SendPacketAsync(new MqttConnAckPacket() { ConnectReturnCode = Protocol.MqttConnectReturnCode.ConnectionRefusedNotAuthorized }, CancellationToken.None); }); var fake = new TestMqttCommunicationAdapterFactory(channel); var client = new MqttClient(fake, new MqttNetLogger()); try { await client.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("any-server").Build()); } catch (Exception ex) { Assert.IsInstanceOfType(ex, typeof(MqttConnectingFailedException)); } Assert.IsTrue(client._packetReceiverTask == null || client._packetReceiverTask.IsCompleted, "receive loop not completed"); Assert.IsTrue(client._keepAliveMessageSenderTask == null || client._keepAliveMessageSenderTask.IsCompleted, "keepalive loop not completed"); }
public async Task Go() { await MqttClient.ConnectAsync(Options); MqttClient.Disconnected += async(s, e) => { Console.WriteLine("### DISCONNECTED FROM SERVER ###"); await Task.Delay(TimeSpan.FromSeconds(5)); try { await MqttClient.ConnectAsync(Options); } catch { Console.WriteLine("### RECONNECTING FAILED ###"); } }; MqttClient.Connected += async(s, e) => { while (true) { var message = new MqttApplicationMessageBuilder() .WithTopic("MyTopic") .WithPayload("Hello World") .WithExactlyOnceQoS() .WithRetainFlag() .Build(); await MqttClient.PublishAsync(message); } }; }
public async Task StartAsync(CancellationToken cancellationToken) { if (await _client.ConnectAsync() == ConnectReturnCode.ConnectionAccepted) { //var top = "/World"; //_logger.LogInformation("Subscribe:" + top); //try //{ // var subAckPacket = await _client.SubscribeAsync(top, MqttQos.AtMostOnce, CancellationToken.None); // foreach (var rc in subAckPacket.ReturnCodes) // { // Console.WriteLine(rc); // } // for (int i = 1; i < int.MaxValue; i++) // { // await _client.PublishAsync("/World", Encoding.UTF8.GetBytes($"Hello World!: {i}"), MqttQos.AtLeastOnce); // await Task.Delay(1000); // } //} //catch (MqttTimeoutException ex) //{ // _logger.LogError(ex, "Subscribe Timeout"); //} } }
private async Task ConnectMqttServerAsync() { if (mqttClient == null) { mqttClient = new MqttClientFactory().CreateMqttClient() as MqttClient; mqttClient.ApplicationMessageReceived += MqttClient_ApplicationMessageReceived; mqttClient.Connected += MqttClient_Connected; mqttClient.Disconnected += MqttClient_Disconnected; } try { var options = new MqttClientTcpOptions { Server = txt_mqttip.Text, ClientId = "HK", CleanSession = true }; await mqttClient.ConnectAsync(options); mqttstate = 0; } catch (Exception ex) { if (mqttstate == 0) { mqttstate = 1; } txt_log.AppendText(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + " " + "連接到MQTT伺服器失敗!" + ex.Message + Environment.NewLine); } }
private async Task ConnectMqttServerAsync() { if (mqttClient == null) { mqttClient = new MqttClientFactory().CreateMqttClient() as MqttClient; mqttClient.ApplicationMessageReceived += MqttClient_ApplicationMessageReceived; mqttClient.Connected += MqttClient_Connected; mqttClient.Disconnected += MqttClient_Disconnected; } try { var options = new MqttClientTcpOptions { Server = "127.0.0.1", ClientId = "win7-PC", UserName = "******", Password = "******", CleanSession = true }; await mqttClient.ConnectAsync(options); } catch (Exception ex) { Application.Current.Dispatcher.Invoke((new Action(() => { MQTT.AppendText($"连接到MQTT服务器失败!" + Environment.NewLine + ex.Message + Environment.NewLine); }))); } }
/// <summary> /// 发布主题 /// </summary> /// <param name="Message"></param> public void Publish(IotTopic topic, string Message, bool isWait = false) { if (!Enabled) { return; } try { if (mqttClient == null) { return; } if (mqttClient.IsConnected == false) { mqttClient.ConnectAsync(options); } if (mqttClient.IsConnected == false) { Console.WriteLine("Publish >>Connected Failed! "); return; } string tp = topicDeviceId + "/" + Enum.GetName(typeof(IotTopic), topic); Console.WriteLine("Publish >>Message: " + Message); MqttApplicationMessageBuilder mamb = new MqttApplicationMessageBuilder() .WithTopic(tp) .WithPayload(Message) .WithExactlyOnceQoS() .WithRetainFlag(false); if (isWait == true) { mqttClient.PublishAsync(mamb.Build()).Wait(); } else { mqttClient.PublishAsync(mamb.Build()); } } catch (Exception exp) { Console.WriteLine("Publish exception >>" + exp.Message); } }
public override async void ViewDidLoad() { base.ViewDidLoad(); mqttClient.OnTopicRecieved += MqttClient_OnTopicRecieved; await mqttClient.ConnectAsync(); await mqttClient.SubscribeAsync("light/state"); }
/// <summary> /// 发布 /// <paramref name="QoS"/> /// <para>0 - 最多一次</para> /// <para>1 - 至少一次</para> /// <para>2 - 仅一次</para> /// </summary> /// <param name="Topic">发布主题</param> /// <param name="Message">发布内容</param> /// <returns></returns> public string Publish(string Topic, string Message) { try { if (mqttClient == null) { return("失败"); } if (mqttClient.IsConnected == false) { mqttClient.ConnectAsync(options); } if (mqttClient.IsConnected == false) { return("失败"); } // Console.WriteLine("Publish >>Topic: " + Topic + "; QoS: " + QualityOfServiceLevel + "; Retained: " + Retained + ";"); // Console.WriteLine("Publish >>Message: " + Message); MqttApplicationMessageBuilder mamb = new MqttApplicationMessageBuilder() .WithTopic(Topic) .WithPayload(Message).WithRetainFlag(Retained); if (QualityOfServiceLevel == 0) { mamb = mamb.WithAtMostOnceQoS(); } else if (QualityOfServiceLevel == 1) { mamb = mamb.WithAtLeastOnceQoS(); } else if (QualityOfServiceLevel == 2) { mamb = mamb.WithExactlyOnceQoS(); } mqttClient.PublishAsync(mamb.Build()); return("成功"); } catch (Exception exp) { return(exp.Message); } }
public async void TestConnect() { // 连接 var rs = await _client.ConnectAsync(); Assert.NotNull(rs); //Assert.True(rs.SessionPresent); Assert.Equal(ConnectReturnCode.Accepted, rs.ReturnCode); }
/// <summary> /// MQTT 初始化 /// </summary> /// <returns></returns> public bool Initialize(JObject mqttConfig, params IotTopic[] topics) { // 清空原有主题 topicsSubs.Clear(); // 添加主题 foreach (var itm in topics) { topicsSubs.Add(topicDeviceId + "/" + Enum.GetName(typeof(IotTopic), itm)); } if (mqttClient == null) { try { mqttServerUrl = (string)mqttConfig["ServerUrl"]; mqttPort = (int)mqttConfig["Port"]; mqttDeviceApiKey = (string)mqttConfig["ApiKey"]; mqttProductId = (string)mqttConfig["ProductId"]; mqttDeviceId = (string)mqttConfig["DeviceId"]; } catch (Exception ex) { Console.WriteLine("Error: config iot client failed."); return(false); } // 新建 mqtt client 并连接 var factory = new MqttFactory(); mqttClient = factory.CreateMqttClient() as MqttClient; options = new MqttClientOptionsBuilder() .WithTcpServer(mqttServerUrl, mqttPort) .WithCredentials(mqttProductId, mqttDeviceApiKey) .WithClientId(mqttDeviceId) .WithKeepAlivePeriod(mqttTs2) .WithCleanSession(true) .Build(); mqttClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(new Func <MqttClientConnectedEventArgs, Task>(Connected)); mqttClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(new Func <MqttClientDisconnectedEventArgs, Task>(Disconnected)); mqttClient.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(new Action <MqttApplicationMessageReceivedEventArgs>(MqttApplicationMessageReceived)); mqttClient.ConnectAsync(options); _timer.Start(); Enabled = true; return(true); } else { _timer.Start(); return(false); } }
static async void Test3() { _mc = new MqttClient { Log = XTrace.Log, Server = "tcp://127.0.0.1:1883", }; await _mc.ConnectAsync(); }
public void Initialize() { _server.Start(); _server.InjectClient("HA4IoT.Loopback", _clientCommunicationAdapter); _client.ConnectAsync().Wait(); _client.SubscribeAsync(new TopicFilter("#", MqttQualityOfServiceLevel.AtMostOnce)).Wait(); _log.Info("MQTT client (loopback) connected."); }
/// <summary> /// Creates new instance of <see cref="MQTTSink"/> /// </summary> /// <param name="clientOptions">MQTT client options <seealso cref="https://github.com/chkr1011/MQTTnet/wiki/Client"/></param> /// <param name="topic">Topic under which the logs are to be published.</param> /// <param name="qoS">Quality of service level. <see cref="MqttQualityOfServiceLevel"/></param> /// <param name="formatter">Custom log formatter.</param> public MQTTSink(IMqttClientOptions clientOptions, string topic, MqttQualityOfServiceLevel qoS = MqttQualityOfServiceLevel.AtMostOnce, Formatting.ITextFormatter formatter = null) { Topic = topic; QoS = qoS; Formatter = formatter ?? Formatter; MqttClientOptions = clientOptions; MqttClient.ConnectAsync(MqttClientOptions).Wait(); }
public async Task MQTTClientConnect(string URI) { MqttClientOptionsBuilder MQOptions = new MqttClientOptionsBuilder(); MQOptions.WithClientId(MQTT_CLIENT_ID); MQOptions.WithWebSocketServer(URI); MQOptions.WithProtocolVersion(MQTTnet.Formatter.MqttProtocolVersion.V311); MQOptions.WithTls(); await mqClient.ConnectAsync(MQOptions.Build()).ConfigureAwait(false); }
private static async void Connect(MQTTnet.Client.MqttClientOptions options) { try { await mqttClient.ConnectAsync(options, CancellationToken.None); } catch (Exception e) { cumulus.LogMessage("MQTT Error: failed to connect to the host"); cumulus.LogMessage(e.Message); } }
private static MqttClient ConnectTestClient(string clientId, MqttApplicationMessage willMessage, MqttServer server) { var adapterA = new TestMqttCommunicationAdapter(); var adapterB = new TestMqttCommunicationAdapter(); adapterA.Partner = adapterB; adapterB.Partner = adapterA; var client = new MqttClient(new MqttClientOptions(), adapterA); server.InjectClient(clientId, adapterB); client.ConnectAsync(willMessage).Wait(); return(client); }