public async Task <MqttClient> ConnectClient(MqttClientOptionsBuilder options, TimeSpan timeout = default) { if (options == null) { throw new ArgumentNullException(nameof(options)); } options = options.WithTcpServer("127.0.0.1", ServerPort); var client = CreateClient(); if (timeout == TimeSpan.Zero) { await client.ConnectAsync(options.Build()).ConfigureAwait(false); } else { using (var timeoutToken = new CancellationTokenSource(timeout)) { await client.ConnectAsync(options.Build(), timeoutToken.Token).ConfigureAwait(false); } } return(client); }
public void Connect(bool force = true) { reconnectOnDisco = force; IMqttClientOptions theOpt = _ClientConfiguration.Build(); _theGameClient.ConnectAsync(theOpt); _logSystem.Info(String.Format("Start connection to '{0}:{1}' ...", _MQTTHostAndPort.Host, _MQTTHostAndPort.Port.ToString())); _logSystem.Info((theOpt.Credentials != null ? "Username : '******', " : "") + "Client ID : " + theOpt.ClientId); }
public async Task <bool> BuildClient() { try { // Create a new MQTT client. var factory = new MqttFactory(); mqttClient = factory.CreateMqttClient(); // Create TCP based options using the builder. var options = new MqttClientOptionsBuilder() .WithClientId(clientID) //.WithTcpServer("test.mosquitto.org") .WithWebSocketServer(mainURL) .WithCleanSession(); mqttClient.UseDisconnectedHandler(async e => { Console.WriteLine("### DISCONNECTED FROM SERVER ###"); await Task.Delay(TimeSpan.FromSeconds(5)); try { await mqttClient.ConnectAsync(options.Build(), System.Threading.CancellationToken.None); // Since 3.0.5 with CancellationToken } catch { Console.WriteLine("### RECONNECTING FAILED ###"); } }); mqttClient.UseApplicationMessageReceivedHandler(e => { Console.WriteLine(System.Text.Encoding.UTF8.GetString(e.ApplicationMessage.Payload)); }); mqttClient.UseConnectedHandler(async e => { Console.WriteLine("### CONNECTED WITH SERVER ###"); //recieves messages via clients own channel, aslo subscribes to a general topic for mass messages. await mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic(Subscription).Build()); await mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic(Subscription + "/" + clientID).Build()); Console.WriteLine("### SUBSCRIBED ###"); }); await mqttClient.ConnectAsync(options.Build(), System.Threading.CancellationToken.None); // Since 3.0.5 with CancellationToken return(true); } catch (Exception e) { Console.WriteLine(e); return(false); } }
/// <summary> /// Constructor responsible for obtaining a <see cref="MQTTConnection"/> through DI. /// </summary> /// <param name="connectionInfo">Valid connection.</param> /// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is null.</exception> /// <exception cref="ArgumentNullException"><see cref="MQTTConnection.Host"/> is null or empty.</exception> public MQTTHandler(MQTTConnection connectionInfo) { if (connectionInfo == null) { throw new ArgumentNullException(paramName: nameof(connectionInfo), message: "Connection info must not be null."); } if (string.IsNullOrWhiteSpace(connectionInfo.Host)) { throw new ArgumentNullException(paramName: nameof(connectionInfo.Host), message: "Host must not be null."); } var factory = new MqttFactory(); Client = factory.CreateMqttClient(); var optsBuilder = new MqttClientOptionsBuilder() .WithTcpServer(opts => { opts.Server = connectionInfo.Host; opts.Port = connectionInfo.Port; opts.TlsOptions = new MqttClientTlsOptions { UseTls = false }; }); if (connectionInfo.IsCredentialsAvailable) { optsBuilder.WithCredentials(connectionInfo.User, connectionInfo.Password); } Options = optsBuilder.Build(); }
protected async Task Connect(string user, string passwd) { var factory = new MqttFactory(); MqttClientOptionsBuilder builder; this.Client = factory.CreateMqttClient(); builder = new MqttClientOptionsBuilder() .WithClientId(Guid.NewGuid().ToString()) .WithTcpServer(this._host, this._port) .WithCleanSession(); if (this._ssl) { builder.WithTls(new MqttClientOptionsBuilderTlsParameters { AllowUntrustedCertificates = true, UseTls = true }); } if (user != null) { builder.WithCredentials(user, passwd); } this.Client.UseDisconnectedHandler(e => { this.OnDisconnect_HandlerAsync(); }); this.Client.UseConnectedHandler(e => { this.OnConnect_Handler(); }); this.Client.UseApplicationMessageReceivedHandler(this.OnMessage_Handler); this._client_options = builder.Build(); await this.Client.ConnectAsync(this._client_options).AwaitBackground(); }
public static async Task ConnectAsync() { var clientId = Guid.NewGuid().ToString(); var mqttURI = "localhost"; var mqttUser = "******"; var mqttPassword = "******"; var mqttPort = 1883; var messageBuilder = new MqttClientOptionsBuilder() .WithClientId(clientId) .WithCredentials(mqttUser, mqttPassword) .WithTcpServer(mqttURI, mqttPort) .WithCleanSession(); var options = messageBuilder .Build(); var managedOptions = new ManagedMqttClientOptionsBuilder() .WithAutoReconnectDelay(TimeSpan.FromSeconds(5)) .WithClientOptions(options) .Build(); await client.StartAsync(managedOptions); client.UseConnectedHandler(e => { Console.WriteLine("Connected successfully with MQTT Brokers."); }); client.UseDisconnectedHandler(e => { Console.WriteLine("Disconnected from MQTT Brokers."); }); }
private async void AttemptConnection() { if (!Client.IsConnected && !IsConnecting) { try { SetStatus("Connecting"); IsConnecting = true; MqttClientOptionsBuilder optionsBuilder = new MqttClientOptionsBuilder() .WithTcpServer(Host, Port) .WithCommunicationTimeout(new TimeSpan(0, 0, 1, 30, 0)) ; ClientOptions = optionsBuilder.Build(); #if HAVE_SYNC if (IsSync) Client.Connect(ClientOptions); else #endif await Client.ConnectAsync(ClientOptions); } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { IsConnecting = false; } } }
private IMqttClientOptions GetMqttOption(string clientId) { var builder = new MqttClientOptionsBuilder() .WithProtocolVersion(MqttProtocolVersion.V311) .WithClientId(clientId); /* * .WithWillMessage(new MqttApplicationMessage() * { * Payload = Encoding.UTF8.GetBytes("Hello World!!!"), * Topic = "/homegenie", * Retain = true, * QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce * }); */ // TODO: ... //.WithKeepAlivePeriod(TimeSpan.FromSeconds(...)) //.WithCommunicationTimeout(TimeSpan.FromSeconds(...)) // .WithTls() //.WithCleanSession(); if (usingWebSockets) { builder.WithWebSocketServer(endPoint.Address + ":" + endPoint.Port + "/mqtt"); } else { builder.WithTcpServer(endPoint.Address, endPoint.Port); } if (networkCredential != null) { builder.WithCredentials(networkCredential.UserName, networkCredential.Password); } return(builder.Build()); }
public MQTTHelper(string clientId, string mqttURI, string mqttUser, string mqttPassword, int mqttPort, string topicSubscribe = "", Action <string> CallBack = null, bool mqttSecure = false) { _CallBack = CallBack; var messageBuilder = new MqttClientOptionsBuilder() .WithClientId(clientId) .WithCredentials(mqttUser, mqttPassword) .WithTcpServer(mqttURI, mqttPort) .WithCleanSession(); var options = mqttSecure ? messageBuilder .WithTls() .Build() : messageBuilder .Build(); var managedOptions = new ManagedMqttClientOptionsBuilder() .WithAutoReconnectDelay(TimeSpan.FromSeconds(5)) .WithClientOptions(options) .Build(); Client = new MqttFactory().CreateManagedMqttClient(); Client.StartAsync(managedOptions); if (!string.IsNullOrEmpty(topicSubscribe)) { var x = this.SubscribeAsync(topicSubscribe).Result; } this.Client.UseApplicationMessageReceivedHandler(e => { string message = Encoding.UTF8.GetString(e.ApplicationMessage.Payload); _CallBack?.Invoke(message); }); }
public async Task ConnectAsync(string clientId) { var messageBuilder = new MqttClientOptionsBuilder() .WithClientId(clientId) .WithCredentials(mqttUser, mqttPassword) .WithTcpServer(mqttURI, mqttPort) .WithCleanSession(); var options = mqttSecure ? messageBuilder .WithTls() .Build() : messageBuilder .Build(); var managedOptions = new ManagedMqttClientOptionsBuilder() .WithAutoReconnectDelay(TimeSpan.FromSeconds(100)) .WithClientOptions(options) .Build(); if (clientMqtt != null) { await clientMqtt.StartAsync(managedOptions); } }
private async Task ConnectMQTT() { string clientId = Guid.NewGuid().ToString(); string mqttURI = "124.107.183.2"; string mqttUser = "******"; string mqttPassword = "******"; int mqttPort = 1883; bool mqttSecure = false; var messageBuilder = new MqttClientOptionsBuilder() .WithClientId(clientId) .WithCredentials(mqttUser, mqttPassword) .WithTcpServer(mqttURI, mqttPort) .WithCleanSession(); var options = mqttSecure ? messageBuilder .WithTls() .Build() : messageBuilder .Build(); var managedOptions = new ManagedMqttClientOptionsBuilder() .WithAutoReconnectDelay(TimeSpan.FromSeconds(5)) .WithClientOptions(options) .Build(); mqttClient = (ManagedMqttClient) new MqttFactory().CreateManagedMqttClient(); await mqttClient.StartAsync(managedOptions); }
public async Task ConnectAsync() { string clientId = Guid.NewGuid().ToString(); string mqttURI = "farmer.cloudmqtt.com"; string mqttUser = "******"; string mqttPassword = "******"; int mqttPort = 22017; bool mqttSecure = true; var messageBuilder = new MqttClientOptionsBuilder() .WithClientId(clientId) .WithCredentials(mqttUser, mqttPassword) .WithTcpServer(mqttURI, mqttPort) .WithCleanSession(); var options = mqttSecure ? messageBuilder .WithTls() .Build() : messageBuilder .Build(); var managedOptions = new ManagedMqttClientOptionsBuilder() .WithAutoReconnectDelay(TimeSpan.FromSeconds(5)) .WithClientOptions(options) .Build(); Client = new MqttFactory().CreateManagedMqttClient(); await Client.StartAsync(managedOptions); }
private IMqttClientOptions ReadConfiguration() { var json = Helpers.MqttConfigJson; if (!string.IsNullOrEmpty(json)) { var config = JsonConvert.DeserializeObject <Config>(json); var builder = new MqttClientOptionsBuilder() .WithClientId(config.BridgeUser.ClientId) .WithTcpServer(config.BridgeUrl, config.BridgePort) .WithCleanSession(); if (config.BridgeTls) { builder = builder.WithTls(); } if (!string.IsNullOrEmpty(config.BridgeUser.UserName) && !string.IsNullOrEmpty(config.BridgeUser.Password)) { builder = builder .WithCredentials(config.BridgeUser.UserName, config.BridgeUser.Password); } return(builder .Build()); } else { throw new FileNotFoundException( $"config.json not found. Assembly location {Helpers.AssemblyDirectory}"); } }
public MqttClient() { Console.WriteLine("Initializing MQTT Client..."); // Create TCP based options using the builder. var optionsBuilder = new MqttClientOptionsBuilder() .WithClientId("FEZ49-Gateway") .WithTcpServer(AMAZON_HOST, 8883) .WithProtocolVersion(MQTTnet.Serializer.MqttProtocolVersion.V311) .WithCommunicationTimeout(new TimeSpan(0, 0, 30)) .WithKeepAlivePeriod(new TimeSpan(0, 0, 10)) .WithCleanSession(); // Get Certificates X509Certificate2 rootCA = new X509Certificate2("Certificates\\Root-CA.pem"); X509Certificate2 clientCert = new X509Certificate2("Certificates\\plcs_certificate.pfx", "fez49"); // Setup TLS connection optionsBuilder.WithTls(false, false, false, rootCA.Export(X509ContentType.SerializedCert), clientCert.Export(X509ContentType.SerializedCert)); clientOptions = optionsBuilder.Build(); mqttClient = new MqttFactory().CreateMqttClient(); mqttClient.Connected += MqttClient_Connected; mqttClient.Disconnected += MqttClient_Disconnected; // Start connection thread keepTrying = true; StartConnectionThread(); }
public MqttService(IHubContext <DevicesHub> hubContext) { #if true _hubContext = hubContext; var messageBuilder = new MqttClientOptionsBuilder().WithClientId(clientId) /*.WithCredentials(mqttUser, mqttPassword)*/.WithTcpServer(mqttURI, mqttPort).WithCleanSession(); var options = mqttSecure ? messageBuilder .WithTls() .Build() : messageBuilder .Build(); var managedOptions = new ManagedMqttClientOptionsBuilder().WithAutoReconnectDelay(TimeSpan.FromSeconds(5)) .WithClientOptions(options) .Build(); client = new MqttFactory().CreateManagedMqttClient(); client.StartAsync(managedOptions); client.UseConnectedHandler(ClientConnectedHandler); //client.UseDisconnectedHandler(ClientDisconnectedHandler); client.ConnectingFailedHandler = new ConnectingFailedHandlerDelegate(OnConnectingFailed); client.UseApplicationMessageReceivedHandler(ClientMessageReceivedHandler); #endif }
public BrixelOpenDoorClient(string clientId, string server, string topic, int port, bool useSSL = true, string username = null, string password = null) { _topic = topic; var optionsBuilder = new MqttClientOptionsBuilder() .WithClientId(clientId) .WithTcpServer(server, port); if (!string.IsNullOrWhiteSpace(username) || !string.IsNullOrWhiteSpace(password)) { optionsBuilder.WithCredentials(username, password); } if (useSSL) { optionsBuilder .WithTls(new MqttClientOptionsBuilderTlsParameters { AllowUntrustedCertificates = true, SslProtocol = SslProtocols.Tls12, IgnoreCertificateChainErrors = true, IgnoreCertificateRevocationErrors = true, UseTls = true }); } _options = optionsBuilder.Build(); }
public MqttSink(MqttSinkOptions options, IManagedMqttClient client) : base(options) { MqttClient = client; Topics = options.Topics.ToList(); Options = options; var builder = new MqttClientOptionsBuilder() .WithTcpServer(options.Server, options.Port); if (options.Password != null && options.Username != null) { builder = builder.WithCredentials(options.Username, options.Password); } var clientOptions = builder.Build(); MqttClientOptions = new ManagedMqttClientOptionsBuilder() .WithPendingMessagesOverflowStrategy(MQTTnet.Server.MqttPendingMessagesOverflowStrategy.DropOldestQueuedMessage) .WithClientOptions(clientOptions) .WithMaxPendingMessages(1).WithAutoReconnectDelay(TimeSpan.FromSeconds(10)).Build(); MqttClient.UseDisconnectedHandler(HandleDisconnected); MqttClient.UseConnectedHandler(HandleConnected); client.StartAsync(MqttClientOptions).Wait(); Next.Subscribe(payload => { Publish(payload).Wait(); }); }
static async Task Main(string[] args) { var deserializer = new DeserializerBuilder() .WithNamingConvention(new CamelCaseNamingConvention()) .Build(); Configuration = deserializer.Deserialize <Configuration>(File.ReadAllText(Path.Combine(Directory.GetCurrentDirectory(), "configuration.yaml"))); var mqttClientOptions = new MqttClientOptionsBuilder().WithClientId(Configuration.ClientId) .WithTcpServer(Configuration.Server, Configuration.Port) .WithCredentials(Configuration.Username, Configuration.Password); if (Configuration.UseSSL) { mqttClientOptions = mqttClientOptions.WithTls(); } var options = new ManagedMqttClientOptionsBuilder().WithAutoReconnectDelay(TimeSpan.FromSeconds(Configuration.ReconnectDelay)) .WithClientOptions(mqttClientOptions.Build()) .Build(); var client = new MqttFactory().CreateManagedMqttClient(); client.ApplicationMessageReceived += Client_ApplicationMessageReceived; client.ConnectingFailed += Client_ConnectingFailed; foreach (var topic in Configuration.Topics) { await client.SubscribeAsync(new TopicFilterBuilder().WithTopic(topic).Build()); } await client.StartAsync(options); Console.ReadLine(); }
public static async Task <IManagedMqttClient> GetClient(MqttOptions mqttOptions) { var clientConnectionOptionsBuilder = new MqttClientOptionsBuilder() .WithClientId(mqttOptions.ClientId) .WithTcpServer(mqttOptions.BrokerHostNameOrIp, mqttOptions.Port); if (!String.IsNullOrEmpty(mqttOptions.UserName) && !String.IsNullOrEmpty(mqttOptions.Password)) { clientConnectionOptionsBuilder = clientConnectionOptionsBuilder .WithCredentials(mqttOptions.UserName, mqttOptions.Password); } if (mqttOptions.EnableTls) { clientConnectionOptionsBuilder = clientConnectionOptionsBuilder .WithTls(); } var managedClientOptions = new ManagedMqttClientOptionsBuilder() .WithAutoReconnectDelay(TimeSpan.FromSeconds(5)) .WithClientOptions(clientConnectionOptionsBuilder.Build()) .Build(); var mqttClient = new MqttFactory().CreateManagedMqttClient(); await mqttClient.StartAsync(managedClientOptions); return(mqttClient); }
private IMqttClientOptions CreateMqttClientOptions() { var options = new MqttClientOptionsBuilder() .WithClientId(_settings.ClientId) .WithCredentials(_settings.Username, _settings.Password); if (_settings.TcpEndPoint.Enabled) { if (_settings.TcpEndPoint.Port > 0) { options.WithTcpServer(_settings.TcpEndPoint.Server, _settings.TcpEndPoint.Port); } else { options.WithTcpServer(_settings.TcpEndPoint.Server); } } else { options.WithTcpServer("localhost"); } if (_settings.CommunicationTimeout > 0) { options.WithCommunicationTimeout(TimeSpan.FromSeconds(_settings.CommunicationTimeout)); } if (_settings.EnableCleanSessions) { options.WithCleanSession(); } return(options.Build()); }
/// <summary> /// Publishes a message to a remote broker that hasn't initially sent the message to the cluster. /// </summary> /// <param name="context">The context.</param> /// <param name="brokerConnectionSettings">The broker connection settings.</param> /// <returns>A <see cref="Task" /> representing asynchronous operation.</returns> private static async Task PublishMessageToBroker(MqttApplicationMessageInterceptorContext context, IBrokerConnectionSettings brokerConnectionSettings) { if (context.ApplicationMessage == null) { return; } // Create a new MQTT client var factory = new MqttFactory(); var mqttClient = factory.CreateMqttClient(); var optionsBuilder = new MqttClientOptionsBuilder().WithClientId(brokerConnectionSettings.ClientId).WithTcpServer(brokerConnectionSettings.HostName, brokerConnectionSettings.Port) .WithCredentials(brokerConnectionSettings.UserName, brokerConnectionSettings.Password).WithCleanSession(brokerConnectionSettings.UseCleanSession); if (brokerConnectionSettings.UseTls) { optionsBuilder.WithTls(); } var options = optionsBuilder.Build(); // Deserialize payload var payloadString = context.ApplicationMessage?.Payload == null ? string.Empty : Encoding.UTF8.GetString(context.ApplicationMessage.Payload); // Connect the MQTT client await mqttClient.ConnectAsync(options, CancellationToken.None); // Send the message var message = new MqttApplicationMessageBuilder().WithTopic(context.ApplicationMessage.Topic).WithPayload(payloadString).WithQualityOfServiceLevel(context.ApplicationMessage.QualityOfServiceLevel) .WithRetainFlag(context.ApplicationMessage.Retain).Build(); await mqttClient.PublishAsync(message, CancellationToken.None); await mqttClient.DisconnectAsync(null, CancellationToken.None); }
/// <summary> /// 重启启动 /// </summary> /// <param name="model"></param> /// <returns></returns> public async Task RestartAsync() { try { await StopAsync(); var model = await FileConfig.GetMqttSetAsync(); MqttClient = new MqttFactory().CreateManagedMqttClient(); var mqttClientOptions = new MqttClientOptionsBuilder() .WithKeepAlivePeriod(TimeSpan.FromSeconds(29)) .WithClientId(model.ClientId) .WithWebSocketServer($"{model.Host}:{model.Port}/mqtt") .WithCredentials(model.UserName, model.Password); if (model.ConnectionMethod == ConnectionMethod.WSS) { mqttClientOptions = mqttClientOptions.WithTls(); } var options = new ManagedMqttClientOptionsBuilder() .WithAutoReconnectDelay(TimeSpan.FromSeconds(5)) .WithClientOptions(mqttClientOptions.Build()) .Build(); await MqttClient.StartAsync(options); } catch (Exception ex) { Log.Logger.Error($"MQTT启动异常,{ex.Message}"); } }
private async void ConnectMirror() { if (_neonConfig.Mqtt.MirrorConfig.IsEnabled) { var mqttMirrorClientOptions = new MqttClientOptionsBuilder() .WithClientId(Guid.NewGuid().ToString()) .WithTcpServer(_neonConfig.Mqtt.MirrorConfig.ClientConfig.HostName, _neonConfig.Mqtt.MirrorConfig.ClientConfig.Port).WithCleanSession(); if (_neonConfig.Mqtt.MirrorConfig.ClientConfig.IsAuth) { mqttMirrorClientOptions = mqttMirrorClientOptions.WithCredentials( _neonConfig.Mqtt.MirrorConfig.ClientConfig.Username, _neonConfig.Mqtt.MirrorConfig.ClientConfig.Password); } _mirrorMqttClient = new MqttFactory().CreateMqttClient(); _mirrorMqttClient.UseApplicationMessageReceivedHandler(async args => { if (_neonConfig.Mqtt.MirrorConfig.ReceiveFromMirror) { await _mqttClient.PublishAsync(args.ApplicationMessage); } }); await _mirrorMqttClient.ConnectAsync(mqttMirrorClientOptions.Build()); _logger.LogInformation($"Mirror MQTT connected"); } }
public void StartClient(string UID, string PWD, string ClientName) { this.ClientName = ClientName; var optionsBuilder = new MqttClientOptionsBuilder() .WithCredentials(UID, PWD) .WithTcpServer("localhost", Program.Port) .WithClientId(ClientName); var factory = new MqttFactory(); client = factory.CreateMqttClient(); // var objSubOptions = new MqttClientSubscribeOptions(); // var topicFilter =new MqttTopicFilter(); // topicFilter.Topic = "brokr/rcv/"; // objSubOptions.TopicFilters.Add(topicFilter); // client.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(e => // { // if (e.ClientId != "MASTER") // OnMsgReceived?.Invoke(e); // }); //client.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(e =>OnReceive(e)); client.ConnectAsync(optionsBuilder.Build()).Wait(); //client.SubscribeAsync(new TopicFilterBuilder().WithTopic("esp/jsondata").Build()).Wait(); Console.WriteLine("MASTER CLIENT STARTED"); }
public async Task ConnectAsync() { string clientId = Guid.NewGuid().ToString(); string mqttURI = "mqtt://*****:*****@farmer.cloudmqtt.com:10472"; string mqttUser = "******"; string mqttPassword = "******"; int mqttPort = 10472; bool mqttSecure = false; var messageBuilder = new MqttClientOptionsBuilder() .WithClientId(clientId) .WithCredentials(mqttUser, mqttPassword) .WithTcpServer(mqttURI, mqttPort) .WithCleanSession(); var options = mqttSecure ? messageBuilder .WithTls() .Build() : messageBuilder .Build(); var managedOptions = new ManagedMqttClientOptionsBuilder() .WithAutoReconnectDelay(TimeSpan.FromSeconds(5)) .WithClientOptions(options) .Build(); await client.StartAsync(managedOptions); }
public async Task HandleServerStartedAsync(EventArgs eventArgs) { lbxMessage.BeginInvoke(this.updateListBoxAction, "Mqtt Server Start..."); if (this.mqttClient != null) { await this.mqttClient.DisconnectAsync(); this.mqttClient = null; } this.mqttClient = new MqttFactory().CreateMqttClient(); this.mqttClient.ConnectedHandler = this; this.mqttClient.DisconnectedHandler = this; var optionsBuilder = new MqttClientOptionsBuilder() .WithClientId($"{Settings.Default.ClientId}_Inner") .WithTcpServer(tbxServer.Text, Convert.ToInt32(tbxPort.Text)) .WithCredentials(Settings.Default.Username, Settings.Default.Password) .WithCleanSession() .WithKeepAlivePeriod(TimeSpan.FromSeconds(100.5)); await this.mqttClient.ConnectAsync(optionsBuilder.Build()); var s = await this.mqttServer.GetClientStatusAsync(); this.sslMessage.Text = $"總連接數:{s.Count}"; }
public async Task ConnectAsync() { string clientId = Guid.NewGuid().ToString(); string mqttURI = "YOUR_MQTT_URI_HERE"; string mqttUser = "******"; string mqttPassword = "******"; int mqttPort = 000000000; bool mqttSecure = false; var messageBuilder = new MqttClientOptionsBuilder() .WithClientId(clientId) .WithCredentials(mqttUser, mqttPassword) .WithTcpServer(mqttURI, mqttPort) .WithCleanSession(); var options = mqttSecure ? messageBuilder.WithTls().Build() : messageBuilder.Build(); var managedOptions = new ManagedMqttClientOptionsBuilder() .WithAutoReconnectDelay(TimeSpan.FromSeconds(5)) .WithClientOptions(options) .Build(); client = new MqttFactory().CreateManagedMqttClient(); await client.StartAsync(managedOptions); }
private void SetupMqttClient() { var solarEdgeSetting = Resolver.CreateConcreteInstanceWithDependencies <SolarEdgeSetting>(); var lwtMessage = new MqttApplicationMessageBuilder() .WithRetainFlag(true) .WithTopic("tele/solaredge/LWT") .WithPayload("offline") .Build(); var clientOptions = new MqttClientOptionsBuilder().WithClientId("SolarEdge") .WithTcpServer(solarEdgeSetting.MqttAddress) .WithWillMessage(lwtMessage); if (!string.IsNullOrWhiteSpace(solarEdgeSetting.MqttUsername)) { clientOptions.WithCredentials(solarEdgeSetting.MqttUsername, solarEdgeSetting.MqttPassword); } var options = new ManagedMqttClientOptionsBuilder().WithAutoReconnectDelay(TimeSpan.FromSeconds(5)) .WithClientOptions(clientOptions.Build()) .Build(); var mqttClient = new MqttFactory().CreateManagedMqttClient(); mqttClient.StartAsync(options).Wait(); ConfigurationResolver.AddRegistration(new SingletonRegistration <IManagedMqttClient>(mqttClient)); }
private async void cloudCred(string di, string ak, string ass) { clientId = di; string mqttURI = "broker.losant.com"; string mqttUser = ak; string mqttPassword = ass; int mqttPort = 1883; bool mqttSecure = false; var messageBuilder = new MqttClientOptionsBuilder() .WithClientId(clientId) .WithCredentials(mqttUser, mqttPassword) .WithTcpServer(mqttURI, mqttPort) .WithCleanSession(); var options = mqttSecure ? messageBuilder .WithTls() .Build() : messageBuilder .Build(); var managedOptions = new ManagedMqttClientOptionsBuilder() .WithAutoReconnectDelay(TimeSpan.FromSeconds(5)) .WithClientOptions(options) .Build(); client = new MqttFactory().CreateManagedMqttClient(); client.ConnectedHandler = new MqttClientConnectedHandlerDelegate(connected); client.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(disconnected); client.UseApplicationMessageReceivedHandler(e => { HandleMessageReceived(e.ApplicationMessage); }); await client.StartAsync(managedOptions); }
public async Task ConnectAsync(string clientId, string username, string password, bool cleanSession, TimeSpan keepAlivePeriod, CancellationToken cancellationToken) { var builder = new MqttClientOptionsBuilder() .WithTcpServer(host, port) .WithClientId(clientId) .WithCredentials(username, password) .WithCleanSession(cleanSession) .WithKeepAlivePeriod(keepAlivePeriod); // default is V311, supports V500 // builder.WithProtocolVersion(MqttProtocolVersion.V500); if (isSsl) { builder.WithTls(); } client.UseConnectedHandler(HandleConnection); client.UseDisconnectedHandler(HandleDisconnection); client.ApplicationMessageReceivedHandler = mqttApplicationMessageReceivedHandler; MqttClientAuthenticateResult connectResult; try { connectResult = await client.ConnectAsync(builder.Build(), cancellationToken); } catch (Exception e) { throw new MqttException(cause: e); } ValidateConnectResult(connectResult); }