private static async Task ExecuteTestAsync(string name, IMqttClientOptions options) { try { Write("Testing '" + name + "'... ", ConsoleColor.Gray); var factory = new MqttFactory(); var client = factory.CreateMqttClient(); var topic = Guid.NewGuid().ToString(); MqttMessage receivedMessage = null; client.ApplicationMessageReceived += (s, e) => receivedMessage = e.ApplicationMessage; await client.ConnectAsync(options); await client.SubscribeAsync(topic, MqttQualityOfServiceLevel.AtLeastOnce); await client.PublishAsync(topic, "Hello_World", MqttQualityOfServiceLevel.AtLeastOnce); SpinWait.SpinUntil(() => receivedMessage != null, 5000); if (receivedMessage?.Topic != topic || receivedMessage?.ConvertPayloadToString() != "Hello_World") { throw new Exception("Message invalid."); } await client.UnsubscribeAsync("test"); await client.DisconnectAsync(); Write("[OK]\n", ConsoleColor.Green); } catch (Exception e) { Write("[FAILED] " + e.Message + "\n", ConsoleColor.Red); } }
/// <inheritdoc cref="IMqttClient.ConnectAsync" /> public async Task <MqttClientAuthenticateResult> ConnectAsync( IMqttClientOptions options, CancellationToken cancellationToken) { Check.NotNull(options, nameof(options)); if (_connecting) { throw new InvalidOperationException("ConnectAsync shouldn't be called concurrently."); } _connecting = true; Options = options; _broker.Connect(options, this); await Task.Delay(_mockOptions.ConnectionDelay, cancellationToken).ConfigureAwait(false); IsConnected = true; _connecting = false; return(new MqttClientAuthenticateResult()); }
public void Init(string clientId, IMqttClientOptions mqttClientOptions) { try { this.mqttClientOptions = mqttClientOptions; var factory = new MqttFactory(); _mqttClient = factory.CreateMqttClient(); _mqttClient.ConnectedHandler = new MqttConnectedHandler(mqttClientConnectedEventArgs => { Connected?.Invoke(this, mqttClientConnectedEventArgs); }); _mqttClient.DisconnectedHandler = new MqttDisconnectedHandler(disconnectEventArgs => { Disconnected?.Invoke(this, disconnectEventArgs); }); _mqttClient.ApplicationMessageReceivedHandler = new MqttMessageReceivedHandler(messageReceivedArgs => { MessageReceived?.Invoke(this, messageReceivedArgs); }); } catch (Exception ex) { } }
public MqttProvider() { try { // Create a new MQTT client. var factory = new MqttFactory(); _client = factory.CreateMqttClient(); //configure options _options = new MqttClientOptionsBuilder() .WithClientId("ProxyModule") .WithTcpServer("localhost", 1884) // 127.0.0.1 .WithCredentials("sanjay", "%Welcome@123%") .WithCleanSession() .Build(); //connect _client.ConnectAsync(_options).Wait(); } catch (Exception e) { Console.WriteLine(e.Message); } }
public MqttConnectPacket CreateConnectPacket(MqttApplicationMessage willApplicationMessage, IMqttClientOptions options) { if (options == null) { throw new ArgumentNullException(nameof(options)); } return(new MqttConnectPacket { ClientId = options.ClientId, Username = options.Credentials?.Username, Password = options.Credentials?.Password, CleanSession = options.CleanSession, KeepAlivePeriod = (ushort)options.KeepAlivePeriod.TotalSeconds, WillMessage = willApplicationMessage, Properties = new MqttConnectPacketProperties { AuthenticationMethod = options.AuthenticationMethod, AuthenticationData = options.AuthenticationData, WillDelayInterval = options.WillDelayInterval, MaximumPacketSize = options.MaximumPacketSize, ReceiveMaximum = options.ReceiveMaximum, RequestProblemInformation = options.RequestProblemInformation, RequestResponseInformation = options.RequestResponseInformation, SessionExpiryInterval = options.SessionExpiryInterval, TopicAliasMaximum = options.TopicAliasMaximum, UserProperties = options.UserProperties } }); }
public static Task <MqttClientAuthenticateResult> ConnectAsync(this IMqttClient client, IMqttClientOptions options) { if (client == null) { throw new ArgumentNullException(nameof(client)); } return(client.ConnectAsync(options, CancellationToken.None)); }
private static bool CertificateValidationCallback(X509Certificate cert, X509Chain chain, SslPolicyErrors errors, IMqttClientOptions opts) { try { if (errors == SslPolicyErrors.None) { return(true); } if (errors == SslPolicyErrors.RemoteCertificateChainErrors) { chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; chain.ChainPolicy.VerificationFlags = X509VerificationFlags.NoFlag; chain.ChainPolicy.ExtraStore.Add(rootCrt); chain.Build((X509Certificate2)rootCrt); var res = chain.ChainElements.Cast <X509ChainElement>().Any(a => a.Certificate.Thumbprint == rootCrt.Thumbprint); return(res); } } catch { } return(false); }
public ManagedMqttClientOptionsBuilder WithClientOptions(IMqttClientOptions value) { _options.ClientOptions = value ?? throw new ArgumentNullException(nameof(value)); return(this); }
private static string GetBrokerIdentifier(IMqttClientOptions clientOptions) => clientOptions.ChannelOptions switch {
public bool IsMatch(string topic, IMqttClientOptions clientOptions) => Regex.IsMatch(GetFullTopicName(topic, clientOptions));
public MqttClientService(IMqttClientOptions options, IDistributedCache cache) { this.client = new AspMqttClient(options, cache); }
public async Task <bool> Connect() { using var Trace = new Trace(); //This c# 8.0 using feature will auto dispose when the function is done. bool ret = false; try { this.server = AppSettings.Settings.mqtt_serverandport.GetWord("", ":"); this.port = AppSettings.Settings.mqtt_serverandport.GetWord(":", "/"); this.portint = 0; if (!string.IsNullOrEmpty(this.port)) { this.portint = Convert.ToInt32(this.port); } if (this.portint == 0 && AppSettings.Settings.mqtt_UseTLS) { this.portint = 8883; } else if (this.portint == 0) { this.portint = 1883; } bool IsWebSocket = (AppSettings.Settings.mqtt_serverandport.IndexOf("ws://", StringComparison.OrdinalIgnoreCase) >= 0 || AppSettings.Settings.mqtt_serverandport.IndexOf("/mqtt", StringComparison.OrdinalIgnoreCase) >= 0 || AppSettings.Settings.mqtt_serverandport.IndexOf("wss://", StringComparison.OrdinalIgnoreCase) >= 0); bool UseTLS = (AppSettings.Settings.mqtt_UseTLS || portint == 8883 || AppSettings.Settings.mqtt_serverandport.IndexOf("wss://", StringComparison.OrdinalIgnoreCase) >= 0); //bool UseCreds = (!string.IsNullOrWhiteSpace(AppSettings.Settings.mqtt_username)); //===================================================================== //Seems like there should be a better way here with this Options builder... //I dont see an obvious way to directly modify options without the builder //and I cant seem to put IF statements around each part of the option builder //parameters. //===================================================================== var lw = new MqttApplicationMessage() { Topic = AppSettings.Settings.mqtt_LastWillTopic, Payload = Encoding.UTF8.GetBytes(AppSettings.Settings.mqtt_LastWillPayload), QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce, Retain = true }; if (UseTLS) { if (IsWebSocket) { options = new MqttClientOptionsBuilder() .WithClientId(AppSettings.Settings.mqtt_clientid) .WithWebSocketServer(AppSettings.Settings.mqtt_serverandport) .WithCredentials(AppSettings.Settings.mqtt_username, AppSettings.Settings.mqtt_password) .WithTls() .WithWillMessage(lw) .WithCleanSession() .Build(); } else { options = new MqttClientOptionsBuilder() .WithClientId(AppSettings.Settings.mqtt_clientid) .WithTcpServer(server, portint) .WithCredentials(AppSettings.Settings.mqtt_username, AppSettings.Settings.mqtt_password) .WithTls() .WithWillMessage(lw) .WithCleanSession() .Build(); } } else { if (IsWebSocket) { options = new MqttClientOptionsBuilder() .WithClientId(AppSettings.Settings.mqtt_clientid) .WithWebSocketServer(AppSettings.Settings.mqtt_serverandport) .WithCredentials(AppSettings.Settings.mqtt_username, AppSettings.Settings.mqtt_password) .WithWillMessage(lw) .WithCleanSession() .Build(); } else { options = new MqttClientOptionsBuilder() .WithClientId(AppSettings.Settings.mqtt_clientid) .WithTcpServer(server, portint) .WithCredentials(AppSettings.Settings.mqtt_username, AppSettings.Settings.mqtt_password) .WithWillMessage(lw) .WithCleanSession() .Build(); } } mqttClient.UseDisconnectedHandler(async e => { IsConnected = false; string excp = ""; if (e.Exception != null) { excp = e.Exception.Message; } Log($"Debug: MQTT: ### DISCONNECTED FROM SERVER ### - Reason: {e.Reason}, ClientWasDisconnected: {e.ClientWasConnected}, {excp}"); //reconnect here if needed? }); mqttClient.UseApplicationMessageReceivedHandler(async e => { Log($"Debug: MQTT: ### RECEIVED APPLICATION MESSAGE ###"); Log($"Debug: MQTT: + Topic = {e.ApplicationMessage.Topic}"); Log($"Debug: MQTT: + Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload).Truncate(128, true)}"); Log($"Debug: MQTT: + QoS = {e.ApplicationMessage.QualityOfServiceLevel}"); Log($"Debug: MQTT: + Retain = {e.ApplicationMessage.Retain}"); Log(""); }); mqttClient.UseConnectedHandler(async e => { IsConnected = true; Log($"Debug: MQTT: ### CONNECTED WITH SERVER '{AppSettings.Settings.mqtt_serverandport}' ### - Result: {e.AuthenticateResult.ResultCode}, '{e.AuthenticateResult.ReasonString}'"); MqttApplicationMessage ma = new MqttApplicationMessageBuilder() .WithTopic(AppSettings.Settings.mqtt_LastWillTopic) .WithPayload(AppSettings.Settings.mqtt_OnlinePayload) .WithAtLeastOnceQoS() .WithRetainFlag(true) .Build(); Log($"Debug: MQTT: Sending '{AppSettings.Settings.mqtt_OnlinePayload}' message..."); MqttClientPublishResult res = await mqttClient.PublishAsync(ma, CancellationToken.None); //if (!string.IsNullOrWhiteSpace(this.LastTopic)) //{ // // Subscribe to the topic // MqttClientSubscribeResult res = await mqttClient.SubscribeAsync(this.LastTopic, MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce); // IsSubscribed = true; // Log($"Debug: MQTT: ### SUBSCRIBED to topic '{this.LastTopic}'"); //} }); Log($"Debug: MQTT: Connecting to server '{this.server}:{this.portint}' with ClientID '{AppSettings.Settings.mqtt_clientid}', Username '{AppSettings.Settings.mqtt_username}', Password '{AppSettings.Settings.mqtt_username.ReplaceChars('*')}'..."); cres = await mqttClient.ConnectAsync(options, CancellationToken.None); } catch (Exception ex) { Log($"Error: {ex.Msg()}"); } return(ret); }
public MQTTTranData(string ClientId, string MQTTerver, int MQTTPort, string MQTTUsr, string MQTTPsw) { MyClientID = ClientId; MqttClientOptions options = new MqttClientOptions() { ClientId = ClientId //ClientId = "shop1002" }; options.ChannelOptions = new MqttClientTcpOptions() { Server = MQTTerver, Port = MQTTPort }; options.Credentials = new MqttClientCredentials() { Username = MQTTUsr, Password = System.Text.Encoding.UTF8.GetBytes(MQTTPsw) }; options.CleanSession = true; options.KeepAlivePeriod = TimeSpan.FromSeconds(100); //options.aliv = TimeSpan.FromSeconds(10000); _IMqttClientOptions = options; mtqqClient = new MQTTnet.MqttFactory().CreateMqttClient(); mtqqClient.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(e => { try { if (OnGetData != null) { OnGetData(this, e.ClientId, e.ApplicationMessage.Topic, Encoding.UTF8.GetString(e.ApplicationMessage.Payload)); } } catch (Exception ex) { } }); mtqqClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(async e => { for (int i = 0; i <= Topic.GetUpperBound(0); i++) { await mtqqClient.SubscribeAsync(new TopicFilter { Topic = Topic[i], QualityOfServiceLevel = MqttQualityOfServiceLevel.ExactlyOnce }); } }); mtqqClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(async e => { if (IsRun == true) { await Task.Delay(TimeSpan.FromSeconds(5)); try { Connect(); } catch { } } }); }
public MqttClientService(IMqttClientOptions options) { this.options = options; mqttClient = new MqttFactory().CreateMqttClient(); ConfigureMqttClient(); }
public IMqttCommunicationAdapter CreateClientCommunicationAdapter(IMqttClientOptions options) { var logger = _serviceProvider.GetRequiredService <ILogger <MqttChannelCommunicationAdapter> >(); return(new MqttChannelCommunicationAdapter(CreateCommunicationChannel(options.ChannelOptions), CreateSerializer(options.ProtocolVersion), logger)); }
public RpcClient(IMqttClientOptions mqtt) : this(new MQTTnet.MqttFactory().CreateMqttClient()) { _mqtt = mqtt; }
public Subscription(IMqttClientOptions clientOptions, string topic) { Topic = topic; Regex = GetSubscriptionRegex(topic, clientOptions); }
public MqttTcpChannel(IMqttClientOptions clientOptions) { _options = (MqttClientTcpOptions)clientOptions.ChannelOptions; _bufferSize = _options.BufferSize; }
private static string GetFullTopicName(string topic, IMqttClientOptions clientOptions) => $"{GetBrokerIdentifier(clientOptions)}|{topic}";
public FizzMQTTConnection(string username, string password, string clientId, bool retry, bool cleanSession, IFizzActionDispatcher dispatcher) { if (string.IsNullOrEmpty(clientId)) { throw ERROR_INVALID_CLIENT_ID; } if (string.IsNullOrEmpty(username)) { throw ERROR_INVALID_USERNAME; } if (string.IsNullOrEmpty(password)) { throw ERROR_INVALID_PASSWORD; } if (dispatcher == null) { throw ERROR_INVALID_DISPATCHER; } _clientOptions = new MqttClientOptionsBuilder() .WithClientId(clientId) .WithTcpServer(FizzConfig.MQTT_HOST_ENDPOINT) .WithCredentials(username, password) .WithTls() .WithCleanSession(cleanSession) .WithKeepAlivePeriod(TimeSpan.FromSeconds(30)) .Build(); _retry = retry; _dispatcher = dispatcher; var clientFactory = new MqttFactory(); _client = clientFactory.CreateMqttClient(); _client.UseDisconnectedHandler(discArgs => { if (discArgs.Exception is MqttConnectingFailedException failedException) { if (failedException.ResultCode == MqttClientConnectResultCode.BadUserNameOrPassword || failedException.ResultCode == MqttClientConnectResultCode.NotAuthorized) { OnDisconnected(discArgs.ClientWasConnected, new FizzMqttAuthException()); } } else if (discArgs.Exception != null) { OnDisconnected(discArgs.ClientWasConnected, discArgs.Exception); } else { OnDisconnected(discArgs.ClientWasConnected, null); } }); _client.UseConnectedHandler(conArgs => { if (_manualDisconnect) { return; } if (Connected != null) { _dispatcher.Post(() => Connected.Invoke(this, conArgs.AuthenticateResult.IsSessionPresent)); } }); _client.UseApplicationMessageReceivedHandler(OnMqttMessageReceived); }
static void Main(string[] args) { Console.WriteLine("Starting Publisher...."); try { // Create a new MQTT client. var factory = new MqttFactory(); _client = factory.CreateMqttClient(); //configure options _options = new MqttClientOptionsBuilder() .WithClientId("PublisherId") .WithTcpServer("dotnetbroker", 1884) .WithCredentials("bud", "%spencer%") .WithCleanSession() .Build(); //handlers _client.UseConnectedHandler(e => { Console.WriteLine("Connected successfully with MQTT Brokers."); }); _client.UseDisconnectedHandler(e => { Console.WriteLine("Disconnected from MQTT Brokers."); }); _client.UseApplicationMessageReceivedHandler(e => { try { string topic = e.ApplicationMessage.Topic; if (string.IsNullOrWhiteSpace(topic) == false) { string payload = Encoding.UTF8.GetString(e.ApplicationMessage.Payload); Console.WriteLine($"Topic: {topic}. Message Received: {payload}"); } } catch (Exception ex) { Console.WriteLine(ex.Message, ex); } }); //connect _client.ConnectAsync(_options).Wait(); Console.WriteLine("Press key to publish message."); Console.ReadLine(); //simulating publish SimulatePublish(); Console.WriteLine("Simulation ended! press any key to exit."); Console.ReadLine(); //To keep the app running in container //https://stackoverflow.com/questions/38549006/docker-container-exits-immediately-even-with-console-readline-in-a-net-core-c Task.Run(() => Thread.Sleep(Timeout.Infinite)).Wait(); _client.DisconnectAsync().Wait(); } catch (Exception e) { Console.WriteLine(e); throw; } }
public static IServiceCollection AddMqttEventBus(this IServiceCollection services, IMqttClientOptions mqttClientOptions, int retryCount = 5) { services.AddSingleton <IEventBus, MqttEventBus>(sp => { var rabbitMQPersistentConnection = sp.GetRequiredService <IMqttPersisterConnection>(); var iLifetimeScope = sp.GetRequiredService <IServiceScopeFactory>(); var logger = sp.GetRequiredService <ILogger <MqttEventBus> >(); var eventBusSubcriptionsManager = sp.GetRequiredService <IEventBusSubscriptionsManager>(); return(new MqttEventBus(rabbitMQPersistentConnection, logger, iLifetimeScope, eventBusSubcriptionsManager, retryCount)); }); services.AddSingleton <IMqttPersisterConnection, DefaultMqttPersisterConnection>(sp => { var logger = sp.GetRequiredService <ILogger <DefaultMqttPersisterConnection> >(); return(new DefaultMqttPersisterConnection(mqttClientOptions, logger)); }); services.AddSingleton <IEventBusSubscriptionsManager, InMemoryEventBusSubscriptionsManager>(); return(services); }
public DevicesController(ApplicationDbContext context, IMqttClientOptions mqtt) { _context = context; _mqtt = mqtt; }
static async Task Main(string[] args) { Console.WriteLine("Starting Publisher...."); try { // Create a new MQTT client. var factory = new MqttFactory(); _client = factory.CreateMqttClient(); string pclientId = Guid.NewGuid().ToString(); //configure options _options = new MqttClientOptionsBuilder() .WithClientId(pclientId) //"PublisherId" .WithTcpServer("localhost", 1884) .WithCredentials("suhel", "%suhel@786%") .WithCleanSession() .Build(); //handlers _client.UseConnectedHandler(e => { Console.WriteLine("Connected successfully with MQTT Brokers."); }); _client.UseDisconnectedHandler(e => { Console.WriteLine("Disconnected from MQTT Brokers."); }); _client.UseApplicationMessageReceivedHandler(e => { try { string topic = e.ApplicationMessage.Topic; if (string.IsNullOrWhiteSpace(topic) == false) { string payload = Encoding.UTF8.GetString(e.ApplicationMessage.Payload); Console.WriteLine($"Topic: {topic}. Message Received: {payload}"); } } catch (Exception ex) { Console.WriteLine(ex.Message, ex); } }); //connect // _client.ConnectAsync(_options).Wait(); await _client.ConnectAsync(_options); Console.WriteLine("Press key to publish message."); Console.ReadLine(); //simulating publish SimulatePublish(); Console.WriteLine("Simulation ended! press any key to exit."); Console.ReadLine(); _client.DisconnectAsync().Wait(); } catch (Exception e) { Console.WriteLine(e); throw; } }
public Task <MqttClientConnectResult> ConnectAsync(IMqttClientOptions options) { IsConnected = true; Connected?.Invoke(this, new MqttClientConnectedEventArgs(false)); return(Task.FromResult(new MqttClientConnectResult(false))); }
public IndexModel(IMqttClient mqttClient, IMqttClientOptions mqttClientOptions) { this.mqttClient = mqttClient; this.mqttClientOptions = mqttClientOptions; }
/// <summary> /// called on client sockets are created in connect /// </summary> public MqttTcpChannel(IMqttClientOptions clientOptions) { _clientOptions = clientOptions ?? throw new ArgumentNullException(nameof(clientOptions)); _options = (MqttClientTcpOptions)clientOptions.ChannelOptions; }
static public async void connect(IMqttClient mqttClient, IMqttClientOptions options) { await mqttClient.ConnectAsync(options); }
public async Task <MqttClientAuthenticateResult> ConnectAsync(IMqttClientOptions options, CancellationToken cancellationToken) { if (options == null) { throw new ArgumentNullException(nameof(options)); } if (options.ChannelOptions == null) { throw new ArgumentException("ChannelOptions are not set."); } ThrowIfConnected("It is not allowed to connect with a server after the connection is established."); ThrowIfDisposed(); MqttClientAuthenticateResult authenticateResult = null; try { Options = options; _packetIdentifierProvider.Reset(); _packetDispatcher.Reset(); _backgroundCancellationTokenSource = new CancellationTokenSource(); var backgroundCancellationToken = _backgroundCancellationTokenSource.Token; _isDisconnectPending = 0; var adapter = _adapterFactory.CreateClientAdapter(options); _adapter = adapter; using (var combined = CancellationTokenSource.CreateLinkedTokenSource(backgroundCancellationToken, cancellationToken)) { _logger.Verbose($"Trying to connect with server '{options.ChannelOptions}' (Timeout={options.CommunicationTimeout})."); await _adapter.ConnectAsync(options.CommunicationTimeout, combined.Token).ConfigureAwait(false); _logger.Verbose("Connection with server established."); _publishPacketReceiverQueue = new AsyncQueue <MqttPublishPacket>(); _publishPacketReceiverTask = Task.Run(() => ProcessReceivedPublishPackets(backgroundCancellationToken), backgroundCancellationToken); _packetReceiverTask = Task.Run(() => TryReceivePacketsAsync(backgroundCancellationToken), backgroundCancellationToken); authenticateResult = await AuthenticateAsync(adapter, options.WillMessage, combined.Token).ConfigureAwait(false); } _sendTracker.Restart(); _receiveTracker.Restart(); if (Options.KeepAlivePeriod != TimeSpan.Zero) { _keepAlivePacketsSenderTask = Task.Run(() => TrySendKeepAliveMessagesAsync(backgroundCancellationToken), backgroundCancellationToken); } _isConnected = true; _logger.Info("Connected."); var connectedHandler = ConnectedHandler; if (connectedHandler != null) { await connectedHandler.HandleConnectedAsync(new MqttClientConnectedEventArgs(authenticateResult)).ConfigureAwait(false); } return(authenticateResult); } catch (Exception exception) { _logger.Error(exception, "Error while connecting with server."); if (!DisconnectIsPending()) { await DisconnectInternalAsync(null, exception, authenticateResult).ConfigureAwait(false); } throw; } }
public DevicesController(UserManager <IdentityUser> userManager, SignInManager <IdentityUser> signInManager, ILogger <DevicesController> logger, IMqttServerEx serverEx, ApplicationDbContext context, IMqttClientOptions mqtt, IStorage storage) { _context = context; _mqtt = mqtt; _userManager = userManager; _signInManager = signInManager; _logger = logger; _storage = storage; _serverEx = serverEx; }