public async Task Connect(string host) { try { var options = new MqttClientOptionsBuilder() .WithClientId("TestClient_Sub") .WithTcpServer(host) .WithCleanSession() .Build(); var test = await _mqttClient.ConnectAsync(options); Console.WriteLine("Is Connected : {0} ", _mqttClient.IsConnected); } catch (Exception ex) { throw ex; } }
private async Task <ReconnectionResult> ReconnectIfRequiredAsync() { if (_mqttClient.IsConnected) { return(ReconnectionResult.StillConnected); } try { await _mqttClient.ConnectAsync(_options.ClientOptions).ConfigureAwait(false); return(ReconnectionResult.Reconnected); } catch (Exception) { return(ReconnectionResult.NotConnected); } }
private async static void SendCommandToDevice(string ipAddress, string port, string topic, string command) { if (client != null && client.IsConnected) { await client.DisconnectAsync(); } configuration = new MqttConfiguration { Port = Convert.ToInt32(port) }; client = await MqttClient.CreateAsync(ipAddress, configuration); var sessionState = await client.ConnectAsync(new MqttClientCredentials(clientId : "mrpclient")); await client.SubscribeAsync(topic + "_client", MqttQualityOfService.AtLeastOnce); client.MessageStream.Subscribe(msg => OnMessageReceived(msg.Topic, System.Text.Encoding.UTF8.GetString(msg.Payload))); await client.PublishAsync(new MqttApplicationMessage(topic, Encoding.UTF8.GetBytes(command)), MqttQualityOfService.AtLeastOnce); }
public async Task mqttClientConnectAsync() { var options = new MqttClientOptions { ClientId = ClientId, Credentials = new MqttClientCredentials { Username = Username, Password = Password, }, ChannelOptions = new MqttClientTcpOptions { Server = MqttServer, Port = MqttPort, } }; await mqttClient.ConnectAsync(options); }
public async Task Run() { var clientOptions = new MqttClientOptionsBuilder() .WithClientId("VoiceCommand") .WithTcpServer(Settings.Default.MqttServer) .WithCredentials(Settings.Default.MqttUser, Settings.Default.MqttPassword) .WithCleanSession() .Build(); try { await _client.ConnectAsync(clientOptions).ConfigureAwait(false); } catch (Exception e) { Console.WriteLine(e); } }
/// <summary> /// Connect the client to the AR. The given options suit the testcases but have to be reviewed for a production environment regarding reconnecting for example. /// </summary> /// <param name="mqttClient">-</param> /// <param name="onboardResponse">-</param> /// <returns>No dedicated response.</returns> public static async Task ConnectMqttClient(IMqttClient mqttClient, OnboardResponse onboardResponse) { var tlsParameters = new MqttClientOptionsBuilderTlsParameters { Certificates = new[] { ReadRootCertificates(), ReadClientCertificate(onboardResponse) }, UseTls = true }; var options = new MqttClientOptionsBuilder() .WithClientId(onboardResponse.ConnectionCriteria.ClientId) .WithTcpServer(onboardResponse.ConnectionCriteria.Host, int.Parse(onboardResponse.ConnectionCriteria.Port)) .WithTls(tlsParameters) .WithCommunicationTimeout(TimeSpan.FromSeconds(20)) .Build(); await mqttClient.ConnectAsync(options); }
public async Task when_disconnect_clients_then_succeeds(int count) { List <IMqttClient> clients = new List <IMqttClient>(); List <string> clientIds = new List <string>(); for (int i = 1; i <= count; i++) { IMqttClient client = await GetClientAsync(); string clientId = MqttTestHelper.GetClientId(); await client.ConnectAsync(new MqttClientCredentials( clientId )); clients.Add(client); clientIds.Add(clientId); } int initialConnectedClients = Server.ActiveClients.Where(c => clientIds.Contains(c)).Count(); foreach (IMqttClient client in clients) { await client.DisconnectAsync(); } ManualResetEventSlim disconnectedSignal = new ManualResetEventSlim(initialState: false); while (!disconnectedSignal.IsSet) { if (Server.ActiveClients.Where(c => clientIds.Contains(c)).Count() == 0 && clients.All(c => !c.IsConnected)) { disconnectedSignal.Set(); } } initialConnectedClients.Should().Be(clients.Count); Server.ActiveClients.Where(c => clientIds.Contains(c)).Should().BeEmpty(); Assert.True(clients.All(c => !c.IsConnected)); Assert.True(clients.All(c => string.IsNullOrEmpty(c.Id))); foreach (IMqttClient client in clients) { client.Dispose(); } }
async void Start() { var factory = new MqttFactory(); mqttClient = factory.CreateMqttClient(); var options = new MqttClientOptionsBuilder() .WithTcpServer(mqttHost, 1883) .WithClientId("Unity.client.subscriber") //Guid.NewGuid ().ToString ()) //.WithCredentials ("your_MQTT_username", "your_MQTT_password") //.WithTls () .Build(); mqttClient.Connected += async(s, e) => { Debug.Log("MQTTブローカに接続しました"); await mqttClient.SubscribeAsync( new TopicFilterBuilder() .WithTopic ("itoyuNineAxis") .Build()); Debug.Log("指定したトピックをSubscribeしました"); }; mqttClient.Disconnected += async(s, e) => { if (e.Exception == null) { Debug.Log("サーバとの通信を切断しました"); return; } Debug.Log("サーバから切断されました。"); }; mqttClient.ApplicationMessageReceived += (s, e) => { var message = System.Text.Encoding.UTF8.GetString(e.ApplicationMessage.Payload); //Debug.Log ($"メッセージ受信 : {message}"); OnMessageReceived.OnNext(message); }; await mqttClient.ConnectAsync(options); }
private static async Task ConnectClient(String address) { try { IMqttClientOptions mqttClientOptions = new MqttClientOptionsBuilder() .WithClientId("RealClient") .WithTcpServer(address, 1883) .WithCleanSession(false) .WithKeepAlivePeriod(TimeSpan.FromMilliseconds(-1)) .WithCommunicationTimeout(TimeSpan.FromSeconds(20)) .Build(); await MqttClient.ConnectAsync(mqttClientOptions); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }
public void Setup() { TopicGenerator.Generate(NumPublishers, NumTopicsPerPublisher, out var topicsByPublisher, out var singleWildcardTopicsByPublisher, out var multiWildcardTopicsByPublisher); _topics = topicsByPublisher.Values.First(); var serverOptions = new MqttServerOptionsBuilder().WithDefaultEndpoint().Build(); var factory = new MqttFactory(); _mqttServer = factory.CreateMqttServer(serverOptions); _mqttClient = factory.CreateMqttClient(); _mqttServer.StartAsync().GetAwaiter().GetResult(); var clientOptions = new MqttClientOptionsBuilder() .WithTcpServer("localhost").Build(); _mqttClient.ConnectAsync(clientOptions).GetAwaiter().GetResult(); }
public async Task when_connecting_client_to_non_existing_server_then_fails() { try { Server.Dispose(); IMqttClient client = await GetClientAsync(); await client.ConnectAsync(new MqttClientCredentials( MqttTestHelper.GetClientId())); } catch (Exception ex) { Assert.True(ex is MqttClientException); Assert.NotNull(ex.InnerException); //Assert.True( ex.InnerException is MqttException );//Not throwing this with SSL. //Assert.NotNull( ex.InnerException.InnerException ); //Assert.True( ex.InnerException.InnerException is SocketException ); } }
public void Connect(string clientName, string channel) { if (_mqttClient.IsConnected) { return; } _clientName = clientName; _mqttClient = _factory.CreateMqttClient(new CustomMqttNetLogger(_clientName)); _mqttClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(new Action <MqttClientConnectedEventArgs>(OnConnected)); _mqttClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(new Action <MqttClientDisconnectedEventArgs>(OnDisconnected)); _mqttClient.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(new Action <MqttApplicationMessageReceivedEventArgs>(OnMessageReceived)); IMqttClientOptions options = new MqttClientOptionsBuilder() .WithTcpServer("127.0.0.1", 1883) .WithClientId(clientName) /*.WithWillMessage(new MqttApplicationMessage * { * Topic = "will/message/topic", * QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce, * Payload = new byte[] { }, * Retain = true * })*/ .WithKeepAlivePeriod(new TimeSpan(0, 0, 15)) .WithCommunicationTimeout(new TimeSpan(0, 0, 10)) .WithCleanSession() .Build(); try { Log.InfoFormat("[{0}] - [{1}]: {2}", GetType().Name, _clientName, string.Format("Connecting to broker at {0}:{1}.", "127.0.0.1", "1883")); _mqttClient.ConnectAsync(options).Wait(); } catch (Exception e) { _mqttClient.ConnectedHandler = null; _mqttClient.DisconnectedHandler = null; _mqttClient.ApplicationMessageReceivedHandler = null; Log.Error("Connection error:", e); } }
private async Task <ReconnectionResult> ReconnectIfRequiredAsync() { if (_mqttClient.IsConnected) { return(ReconnectionResult.StillConnected); } try { await _mqttClient.ConnectAsync(Options.ClientOptions).ConfigureAwait(false); return(ReconnectionResult.Reconnected); } catch (Exception exception) { ConnectingFailed?.Invoke(this, new MqttManagedProcessFailedEventArgs(exception)); return(ReconnectionResult.NotConnected); } }
/// <summary> /// Attempt to connect and subscribe to the MQTT broker. /// </summary> /// <param name="entities"></param> public async Task Connect() { if (string.IsNullOrEmpty(SettingsControl.MqttUsername)) { throw new ArgumentNullException(nameof(SettingsControl.MqttUsername)); } if (string.IsNullOrEmpty(SettingsControl.MqttPassword)) { throw new ArgumentNullException(nameof(SettingsControl.MqttPassword)); } if (string.IsNullOrEmpty(SettingsControl.MqttBrokerHostname)) { throw new ArgumentNullException(nameof(SettingsControl.MqttBrokerHostname)); } // Create TCP-based connection options IMqttClientOptions mqttClientOptions = new MqttClientOptionsBuilder() .WithTcpServer(SettingsControl.MqttBrokerHostname) .WithCredentials(SettingsControl.MqttUsername, SettingsControl.MqttPassword) .WithCleanSession() .Build(); await WebRequests.WaitForNetworkAvailable(); // If we disconnect for any reason, attempt to reconnect AttemptReconnectOnDisconnect = true; while (!MqttClient.IsConnected) { try { await MqttClient.ConnectAsync(mqttClientOptions); } catch (Exception e) { Telemetry.TrackException(nameof(Connect), e); await Task.Delay(TimeSpan.FromSeconds(1)); } } }
/// <summary> /// Attempt to connect and subscribe to the MQTT broker. /// </summary> /// <param name="entities"></param> public void Connect() { if (string.IsNullOrEmpty(MqttConfig.BrokerHostname)) { throw new ArgumentNullException(nameof(MqttConfig.BrokerHostname)); } if (string.IsNullOrEmpty(MqttConfig.Username)) { throw new ArgumentNullException(nameof(MqttConfig.Username)); } if (string.IsNullOrEmpty(MqttConfig.Password)) { throw new ArgumentNullException(nameof(MqttConfig.Password)); } // Create TCP-based connection options IMqttClientOptions mqttClientOptions = new MqttClientOptionsBuilder() .WithTcpServer(MqttConfig.BrokerHostname) .WithCredentials(MqttConfig.Username, MqttConfig.Password) .WithCleanSession() .Build(); // Fire and forget to ensure windows service is not blocked on initialization // pending successful connection to the MQTT subscription. Task task = Task.Factory.StartNew(async() => { await Task.Delay(TimeSpan.FromSeconds(1)); while (!MqttClient.IsConnected) { try { await MqttClient.ConnectAsync(mqttClientOptions); } catch (Exception) { await Task.Delay(TimeSpan.FromSeconds(1)); } } }); }
/// <summary> /// Call this method to (re)connect /// </summary> public async Task Connect(string username, string password, string brokerUrl = "mqtt.ardich.com", int serverport = 8883) { ctSource = new CancellationTokenSource(); // Setup and start a managed MQTT client. var options = new MqttClientOptionsBuilder() .WithClientId(ClientId) .WithTcpServer(brokerUrl, serverport) .WithCredentials(username, password) .WithTls() .Build(); mqttClient = new MqttFactory().CreateMqttClient(); ConnectionStatus = (await mqttClient.ConnectAsync(options, ctSource.Token)).ResultCode; if (ConnectionStatus == MqttClientConnectResultCode.Success) { Listen(); } }
/// <summary> /// Establish a connection with a TCP client at the given address and port. /// This connection is made with *no* KeepAlive timeout. /// There is a short delay (100 ms) after the connection. /// </summary> /// <param name="client"></param> /// <param name="serverAddress"></param> /// <param name="port"></param> /// <returns></returns> public static async Task ConnectClient(IMqttClient client, string serverAddress, int port) { try { var connectOptions = new MqttClientOptionsBuilder() .WithTcpServer(serverAddress, port) .WithNoKeepAlive() .Build(); CancellationToken cancellationToken; await client.ConnectAsync(connectOptions, cancellationToken); await Task.Delay(100); } catch (Exception ex) { throw new ApplicationException($"Start Client: Server={serverAddress}:{port} Err={ex.Message}"); } }
public async Task Subscribe(CancellationToken cancellationToken) { var mqttFactory = new MqttFactory(); var clientOptionsBuilder = new MqttClientOptionsBuilder() .WithClientId(System.Reflection.Assembly.GetEntryAssembly().FullName) .WithTcpServer(m_brokerHostName) .WithCredentials(m_applicationId, m_applicationAccessKey) .Build(); m_mqttClientSubscriber = mqttFactory.CreateMqttClient(); m_mqttClientSubscriber.ConnectedHandler = new MqttClientConnectedHandlerDelegate(OnSubscriberConnected); m_mqttClientSubscriber.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(OnSubscriberDisconnected); m_mqttClientSubscriber.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(OnSubscriberMessageReceived); await m_mqttClientSubscriber.ConnectAsync(clientOptionsBuilder, cancellationToken); await m_consoleLogger.AppendMessageAsync($"ConnectAsync IsConnected: {m_mqttClientSubscriber.IsConnected}"); }
public async Task Connect() { var certificate = new X509Certificate("C:\\Users\\Andre\\Desktop\\ESAMI\\Broker_Anto\\Resource\\certificate.pfx", "Guido2018", X509KeyStorageFlags.Exportable); //var certificate = new X509Certificate("C:\\Users\\Andre\\Desktop\\ESAMI\\Broker_Anto\\Resource\\esame.pfx", "Guido2018", X509KeyStorageFlags.Exportable); ///idilio var caRoot = X509Certificate2.CreateFromSignedFile("C:\\Users\\Andre\\Desktop\\ESAMI\\Broker_Anto\\Resource\\CAroot.crt"); MqttClientOptionsBuilder optionsBuilder = new MqttClientOptionsBuilder(); var fact = new MqttFactory(); client = fact.CreateMqttClient(); client.ApplicationMessageReceived += Client_ApplicationMessageReceived; client.Connected += Client_Connected; optionsBuilder .WithClientId("pc-broker") .WithTcpServer(IoTEndPoint, 8883) .WithTls(true, true, true, certificate.Export(X509ContentType.Pfx), caRoot.Export(X509ContentType.Cert)) .WithCleanSession() .WithProtocolVersion(MQTTnet.Serializer.MqttProtocolVersion.V311) .WithKeepAlivePeriod(new TimeSpan(0, 0, 5)); try { await client.ConnectAsync(optionsBuilder.Build()); } catch (Exception e) { w.Dispatcher.Invoke(v, "impossibile connect " + e.Message.ToString()); } try { await client.SubscribeAsync("aws/misure"); } catch (Exception e) { w.Dispatcher.Invoke(v, "impossibile subscribe " + e.Message.ToString()); } while (!client.IsConnected) { } }
/// <summary> /// MQTT Brokerへ接続 /// </summary> /// <returns></returns> public async Task Connect() { if (string.IsNullOrEmpty(_mqttConfig.BrokerHostname)) { throw new ArgumentNullException(nameof(MqttConfig.BrokerHostname)); } if (_mqttConfig.BrokerHostPort == 0) { throw new ArgumentNullException(nameof(MqttConfig.BrokerHostPort)); } if (string.IsNullOrEmpty(_mqttConfig.AccountId)) { throw new ArgumentNullException(nameof(MqttConfig.AccountId)); } var mqttClientOptions = new MqttClientOptionsBuilder() .WithTcpServer(_mqttConfig.BrokerHostname, _mqttConfig.BrokerHostPort) .WithCredentials(_mqttConfig.AccountId, _mqttConfig.AccountPassword) .WithTls() .WithCleanSession() .Build(); var retry = 0; while (!_mqttClient.IsConnected && retry < 10) { try { await _mqttClient.ConnectAsync(mqttClientOptions); _logger.LogInformation("Connected."); } catch (Exception e) { _logger.LogWarning($"接続失敗 {retry + 1}回目:{e.Message}"); await Task.Delay(TimeSpan.FromSeconds(1)); } retry++; } }
private async void Button_Connect_Click(object sender, RoutedEventArgs e) { if (mqttClient.IsConnected) { await mqttClient.DisconnectAsync(); return; } if (InputServerName.Text.Trim().Length == 0) { MessageBox.Show("服务器地址不能为空!", "ERROR"); return; } var portText = InputServerPort.Text; var port = 1883; if (portText.Length > 0) { port = int.Parse(portText); } var willMessage = new MqttApplicationMessage(); willMessage.Topic = "tamefire/tf5156/offline/TF0001"; willMessage.Payload = new byte[] { 0x01 }; // Create TCP based options using the builder. var options = new MqttClientOptionsBuilder() .WithClientId("tf5156" + System.DateTime.Now) .WithTcpServer(InputServerName.Text) .WithCredentials(InputUsername.Text, InputPassword.Text) .WithCleanSession() .WithWillMessage(willMessage) .Build(); PrintLog("开始连接:" + InputServerName.Text); await mqttClient.ConnectAsync(options); PrintLog("成功连接到:" + InputServerName.Text); }
public void Setup() { var factory = new MqttFactory(); _mqttServer = factory.CreateMqttServer(); _mqttClient = factory.CreateMqttClient(); var serverOptions = new MqttServerOptionsBuilder().Build(); _mqttServer.StartAsync(serverOptions).GetAwaiter().GetResult(); var clientOptions = new MqttClientOptionsBuilder() .WithTcpServer("localhost").Build(); _mqttClient.ConnectAsync(clientOptions).GetAwaiter().GetResult(); _message = new MqttApplicationMessageBuilder() .WithTopic("A") .Build(); }
public static async void init() { var factory = new MqttFactory(); client = factory.CreateMqttClient(); var options = new MqttClientOptionsBuilder() .WithTcpServer("localhost", 1883); await client.ConnectAsync(options.Build()); client.UseConnectedHandler(e => { Console.WriteLine("Producer is connected to server"); }); client.UseDisconnectedHandler(e => { Console.WriteLine("Producer has been disconnected from the server"); }); }
public async void ReplaceMqttClient(IMqttClientOptions options) { this._logger.LogInformation($"Replacing Mqtt client with new config"); await _mqttClient.DisconnectAsync(); try { await _mqttClient.ConnectAsync(options); } catch (MqttConnectingFailedException ex) { this._mqttClientMessage = ex.ResultCode.ToString(); Log.Logger.Error("Could not connect to broker: " + ex.ResultCode.ToString()); } catch (MqttCommunicationException ex) { this._mqttClientMessage = ex.ToString(); Log.Logger.Error("Could not connect to broker: " + ex.Message); } }
public Task ConnectAsync() { lock (synclock) { if (_client != null) { return(Task.CompletedTask); } _client = new MQTTnet.MqttFactory().CreateMqttClient(); _client.Connected += OnConnected; _client.Disconnected += OnDisconnected; _client.ApplicationMessageReceived += OnMessageReceieved; var connected = new TaskCompletionSource <object>(); _client.ConnectAsync(_options) .ContinueWith(task => DispatchTask <object>(task, connected)); return(connected.Task); } }
public async Task ConnectBrokerAsync() { // Create a new MQTT client. factory = new MqttFactory(); mqttClient = factory.CreateMqttClient(); // Create TCP based options using the builder. options = new MqttClientOptionsBuilder() .WithTcpServer(_config.BROKER_URL, _config.BROKER_PORT) .WithCredentials(_config.BROKER_USERNAME, _config.BROKER_PASSWORD) .WithCleanSession() .Build(); mqttClient.UseConnectedHandler(MqttConnectedHandlerAsync); mqttClient.UseDisconnectedHandler(MqttDisconnectedHandler); mqttClient.UseApplicationMessageReceivedHandler(MqttOnMessagesReceived); await mqttClient.ConnectAsync(options, CancellationToken.None); // Since 3.0.5 with CancellationToken }
/// <summary> /// 连接服务器 /// </summary> /// <returns></returns> private async Task ConnectMqttServerAsync() { try { //实例化 创建客户端对象 mqttClient = new MqttFactory().CreateMqttClient(); mqttClient.ApplicationMessageReceived += MqttClient_ApplicationMessageReceived; mqttClient.Connected += MqttClient_Connected; mqttClient.Disconnected += MqttClient_Disconnected; await mqttClient.ConnectAsync(option()); } catch (Exception ex) { Invoke((new Action(() => { txtReceiveMessage.AppendText($"连接到MQTT服务器失败!" + Environment.NewLine + ex.Message + Environment.NewLine); }))); } }
/// <summary> /// Start the input - consuming and processing messages from MQTT and send to input stream on runtime /// </summary> public void Start() { Task.Run(async() => { var channel = new Channel(_configuration.RuntimeEndpoint, ChannelCredentials.Insecure); var streamClient = new InputStreamClient(channel); var inputStream = streamClient.Open(); _mqttClient.UseConnectedHandler(async e => { _logger.Information($"Connected to MQTT broker"); var wildcard = _configuration.InputTopicPrefix.Wildcard; _logger.Information($"Subscribe to '{wildcard}'"); await _mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic(wildcard).Build()); }); _mqttClient.UseApplicationMessageReceivedHandler(async e => await ProcessMessage(e, inputStream)); await _mqttClient.ConnectAsync(_mqttClientOptions, CancellationToken.None); }); }
public async Task SendMessage(string message, string topic) { var options = new MqttClientOptionsBuilder() .WithTcpServer(_settings.MqttClientSettings.Server, _settings.MqttClientSettings.Port) .WithCredentials(_settings.MqttClientSettings.User, _settings.MqttClientSettings.Password) .Build(); CancellationToken cancellationToken; await _mqttClient.ConnectAsync(options, cancellationToken); var payload = new MqttApplicationMessageBuilder() .WithTopic(topic) .WithPayload(message) .WithExactlyOnceQoS() .Build(); await _mqttClient.PublishAsync(payload, cancellationToken); await _mqttClient.DisconnectAsync(); }
public async Task PublishAsync(Presence presence) { try { if (!_mqttClient.IsConnected) { await _mqttClient.ConnectAsync(_mqttClientOptions, CancellationToken.None); } string topic = _options.Topic; await _mqttClient.PublishAsync(topic + "/activity", presence.Activity, true); await _mqttClient.PublishAsync(topic + "/availability", presence.Availability, true); } catch (Exception) { //TODO: add logging } }