private static IMqttClientOptions UnwrapOptions(IClientOptions wrappedOptions, IWillMessage willMessage) { var optionsBuilder = new MqttClientOptionsBuilder(); if (wrappedOptions.ConnectionType == ConnectionType.Tcp) { optionsBuilder.WithTcpServer(wrappedOptions.Uri.Host); } else { optionsBuilder.WithWebSocketServer(wrappedOptions.Uri.AbsoluteUri); } return(optionsBuilder .WithWillMessage(WrapWillMessage(willMessage)) .WithCleanSession(wrappedOptions.CleanSession) .WithClientId(wrappedOptions.ClientId ?? Guid.NewGuid().ToString().Replace("-", string.Empty)) .WithTls(wrappedOptions.AllowUntrustedCertificates, wrappedOptions.IgnoreCertificateChainErrors, wrappedOptions.IgnoreCertificateChainErrors, UnwrapCertificates(wrappedOptions.Certificates)) .WithProtocolVersion(UnwrapProtocolVersion(wrappedOptions.ProtocolVersion)) .WithCommunicationTimeout(wrappedOptions.DefaultCommunicationTimeout == default(TimeSpan) ? TimeSpan.FromSeconds(10) : wrappedOptions.DefaultCommunicationTimeout) .WithKeepAlivePeriod(wrappedOptions.KeepAlivePeriod == default(TimeSpan) ? TimeSpan.FromSeconds(5) : wrappedOptions.KeepAlivePeriod) .WithCredentials(wrappedOptions.UserName, wrappedOptions.Password) .Build()); }
public static MqttClientOptionsBuilder ConfigureHassConnectedEntityServiceLastWill(this MqttClientOptionsBuilder builder, IServiceProvider provider) { HassMqttTopicBuilder topicBuilder = provider.GetRequiredService <HassMqttTopicBuilder>(); HassConnectedEntityServiceConfig config = provider.GetRequiredService <IOptions <HassConnectedEntityServiceConfig> >().Value; return(builder.WithWillMessage(new MqttApplicationMessage { Topic = topicBuilder.GetServiceTopic(config.DeviceId, config.EntityId, "state"), Payload = Encoding.UTF8.GetBytes(config.ProblemMessage), Retain = true })); }
public static IServiceCollection AddMqttServices <TMqttSettings>(this IServiceCollection services, IConfiguration mqttConfiguration) where TMqttSettings : MqttSettings, new() { services.AddOptions <TMqttSettings>() .Bind(mqttConfiguration) .ValidateDataAnnotations(); services.AddSingleton(sp => { var mqttSettings = sp.GetRequiredService <IOptions <TMqttSettings> >().Value; var mqttClientOptionsBuilder = new MqttClientOptionsBuilder() .WithTcpServer(mqttSettings.Host, mqttSettings.Port) .WithProtocolVersion(mqttSettings.MqttProtocolVersion ?? MqttProtocolVersion.V500); if (mqttSettings.ClientId != null) { mqttClientOptionsBuilder = mqttClientOptionsBuilder.WithClientId(mqttSettings.ClientId); } if (mqttSettings.CommunicationTimeout.HasValue) { mqttClientOptionsBuilder = mqttClientOptionsBuilder.WithCommunicationTimeout(mqttSettings.CommunicationTimeout.Value); } mqttClientOptionsBuilder = mqttSettings.KeepAliveInterval.HasValue ? mqttClientOptionsBuilder.WithKeepAlivePeriod(mqttSettings.KeepAliveInterval.Value) : mqttClientOptionsBuilder.WithNoKeepAlive(); var lastWillAndTestamentMessage = mqttSettings.GetLastWillAndTestamentApplicationMessage(); if (lastWillAndTestamentMessage != null) { mqttClientOptionsBuilder = mqttClientOptionsBuilder.WithWillMessage(lastWillAndTestamentMessage); } return(mqttClientOptionsBuilder.Build()); }); services.AddSingleton <IMqttFactory, MqttFactory>(); services.AddTransient(sp => { var factory = sp.GetRequiredService <IMqttFactory>(); var client = factory.CreateMqttClient(); return(client); }); return(services); }
public Mqtt( ILogger <Mqtt> logger, string clientId, string serverUri, int port, bool cleanSession, string?brokerUsername, string?brokerPassword, MqttChannelConfig?lastWill) { this.logger = logger; this.serverUri = serverUri; this.clientId = clientId; var factory = new MqttFactory(); client = factory.CreateMqttClient(); client.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(DisconnectedHandler); client.ConnectedHandler = new MqttClientConnectedHandlerDelegate(ConnectedHandler); client.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(MessageReceivedHandler); var clientOptionsBuilder = new MqttClientOptionsBuilder() .WithTcpServer(serverUri, port) .WithClientId(clientId) .WithCleanSession(cleanSession); if (lastWill is not null) { clientOptionsBuilder.WithWillMessage( new MqttApplicationMessageBuilder() .WithTopic(lastWill.Topic) .WithPayload(lastWill.Payload) .WithRetainFlag(lastWill.Retain) .WithQualityOfServiceLevel(lastWill.GetQualityOfServiceAsEnum().ToMqttNet()) .Build()); } if (brokerUsername is not null && brokerPassword is not null) { clientOptionsBuilder.WithCredentials(brokerUsername, brokerPassword); } clientOptions = clientOptionsBuilder.Build(); }
/// <summary> /// Connects the Sparkplug node to the MQTT broker. /// </summary> /// <param name="options">The configuration option.</param> /// <returns>A <see cref="Task"/> representing any asynchronous operation.</returns> private async Task ConnectInternal(SparkplugNodeOptions options) { options.CancellationToken ??= CancellationToken.None; var builder = new MqttClientOptionsBuilder() .WithClientId(options.ClientId) .WithCredentials(options.UserName, options.Password) .WithCleanSession(false) .WithProtocolVersion(MqttProtocolVersion.V311); if (options.UseTls) { builder.WithTls(); } if (options.WebSocketParameters is null) { builder.WithTcpServer(options.BrokerAddress, options.Port); } else { builder.WithWebSocketServer(options.BrokerAddress, options.WebSocketParameters); } if (options.ProxyOptions != null) { builder.WithProxy( options.ProxyOptions.Address, options.ProxyOptions.Username, options.ProxyOptions.Password, options.ProxyOptions.Domain, options.ProxyOptions.BypassOnLocal); } if (this.willMessage != null) { builder.WithWillMessage(this.willMessage); } this.ClientOptions = builder.Build(); await this.Client.ConnectAsync(this.ClientOptions, options.CancellationToken.Value); }
private async Task ConnectAsync() { try { if (client == null) { client = new MqttFactory().CreateMqttClient(); client.ApplicationMessageReceived += Client_ApplicationMessageReceived; client.Connected += Client_Connected; client.Disconnected += Client_Disconnected; } if (!client.IsConnected) { var option = new MqttClientOptionsBuilder() .WithCleanSession(Convert.ToBoolean(cob_CleanSession.SelectedItem)) .WithClientId(tb_ClientId.Text.Trim()) .WithCommunicationTimeout(TimeSpan.FromSeconds(5)) .WithCredentials(tb_UserName.Text.Trim(), tb_Password.Text.Trim()) .WithKeepAlivePeriod(TimeSpan.FromSeconds(5)) .WithProtocolVersion(MqttProtocolVersion.V311) .WithTcpServer(tb_Server.Text.Trim(), Convert.ToInt32(nud_Port.Value)); if (!string.IsNullOrWhiteSpace(tb_WillTopic.Text)) { var msg = new MqttApplicationMessageBuilder() .WithTopic(tb_WillTopic.Text.Trim()) .WithQualityOfServiceLevel((MqttQualityOfServiceLevel)Convert.ToInt32(cob_WillQos.SelectedItem)) .WithRetainFlag(Convert.ToBoolean(cob_WillRetain.SelectedItem)) .WithPayload(tb_WillMessage.Text.Trim()) .Build(); option = option.WithWillMessage(msg); } await client.ConnectAsync(option.Build()); } } catch (Exception ex) { } }
/// <summary> /// Connects the Sparkplug node to the MQTT broker. /// </summary> /// <exception cref="ArgumentNullException">The options are null.</exception> /// <returns>A <see cref="Task"/> representing any asynchronous operation.</returns> private async Task ConnectInternal() { if (this.options is null) { throw new ArgumentNullException(nameof(this.options)); } // Increment the session number. this.IncrementLastSessionNumber(); // Reset the sequence number. this.ResetLastSequenceNumber(); // Get the will message. var willMessage = this.MessageGenerator.GetSparkPlugNodeDeathMessage( this.NameSpace, this.options.GroupIdentifier, this.options.EdgeNodeIdentifier, this.LastSessionNumber); // Build up the MQTT client and connect. this.options.CancellationToken ??= CancellationToken.None; var builder = new MqttClientOptionsBuilder() .WithClientId(this.options.ClientId) .WithCredentials(this.options.UserName, this.options.Password) .WithCleanSession(false) .WithProtocolVersion(MqttProtocolVersion.V311); if (this.options.UseTls) { builder.WithTls(); } if (this.options.WebSocketParameters is null) { builder.WithTcpServer(this.options.BrokerAddress, this.options.Port); } else { builder.WithWebSocketServer(this.options.BrokerAddress, this.options.WebSocketParameters); } if (this.options.ProxyOptions != null) { builder.WithProxy( this.options.ProxyOptions.Address, this.options.ProxyOptions.Username, this.options.ProxyOptions.Password, this.options.ProxyOptions.Domain, this.options.ProxyOptions.BypassOnLocal); } builder.WithWillMessage(willMessage); this.ClientOptions = builder.Build(); // Debug output. this.Logger?.Debug("CONNECT Message: {@ClientOptions}", this.ClientOptions); await this.Client.ConnectAsync(this.ClientOptions, this.options.CancellationToken.Value); }
private async void Connect_Click(object sender, EventArgs e) { if (mqttClient == null) { mqttClient = new MqttFactory().CreateMqttClient(); mqttClient.UseApplicationMessageReceivedHandler(new Action <MqttApplicationMessageReceivedEventArgs>(MqttClient_ApplicationMessageReceived)); mqttClient.UseDisconnectedHandler(new Action <MqttClientDisconnectedEventArgs>(MqttClient_Disconnected)); mqttClient.UseConnectedHandler(new Action <MqttClientConnectedEventArgs>(MqttClient_Connected)); } if (mqttClient.IsConnected) { return; } status.Text = "Connecting..."; var clientOptionsBuilder = new MqttClientOptionsBuilder(); clientOptionsBuilder.WithProtocolVersion((MqttProtocolVersion)version.SelectedValue); if (!string.IsNullOrWhiteSpace(username.Text)) { if (!string.IsNullOrWhiteSpace(password.Text)) { clientOptionsBuilder.WithCredentials(username.Text, password.Text); } else { clientOptionsBuilder.WithCredentials(username.Text); } } if (!string.IsNullOrWhiteSpace(clientId.Text)) { clientOptionsBuilder.WithClientId(clientId.Text); } if (useTls.Checked) { clientOptionsBuilder.WithTls(); } if (useWebSocket.Checked) { clientOptionsBuilder.WithWebSocketServer(host.Text); } else { clientOptionsBuilder.WithTcpServer(host.Text, int.Parse(port.Text)); } if (cleanSession.Checked) { clientOptionsBuilder.WithCleanSession(true); } else { clientOptionsBuilder.WithCleanSession(false); } if (setWill.Checked && !string.IsNullOrWhiteSpace(input.TextValue)) { clientOptionsBuilder.WithWillMessage(BuildMessage()); } try { await mqttClient.ConnectAsync(clientOptionsBuilder.Build()); clientId.Text = mqttClient.Options.ClientId; } catch (Exception ex) { MessageBox.Show(this, ex.Message); } }