/// <summary> /// Provides the MQTT client options to create an authenticated MQTT /// over WebSocket connection to an AWS IoT Device Gateway endpoint. /// </summary> /// <param name="client">The authenticated AWS IoT Device Gateway client.</param> /// <param name="iotEndpointAddress">The AWS account-specific AWS IoT endpoint address.</param> /// <param name="cancelToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> public static async Task <IMqttClientOptions> CreateMqttWebSocketClientOptionsAsync(this AmazonIoTDeviceGatewayClient client, string iotEndpointAddress, CancellationToken cancelToken = default) { if (client is null) { throw new ArgumentNullException(nameof(client)); } var uriDetails = await client.CreateMqttWebSocketUriAsync(new Model.CreateMqttWebSocketUriRequest { EndpointAddress = iotEndpointAddress }, cancelToken).ConfigureAwait(continueOnCapturedContext: false); var optionsBuilder = new MqttClientOptionsBuilder(); optionsBuilder = optionsBuilder.WithTls(); optionsBuilder = optionsBuilder.WithWebSocketServer(uriDetails.RequestUri?.ToString()); IWebProxy iProxy = client.Config.GetWebProxy(); if (!(iProxy is null)) { Uri proxyUri; if (iProxy is Amazon.Runtime.Internal.Util.WebProxy awssdkProxy) { proxyUri = awssdkProxy.ProxyUri; } else { proxyUri = new Uri("http://" + client.Config.ProxyHost + ":" + client.Config.ProxyPort); } var iCreds = iProxy.Credentials ?? client.Config.ProxyCredentials; var netCreds = iCreds?.GetCredential(proxyUri, default); optionsBuilder = optionsBuilder.WithProxy(proxyUri.ToString(), username: netCreds?.UserName, password: netCreds?.Password, domain: netCreds?.Domain, bypassOnLocal: iProxy.IsBypassed(localhostUri) ); } var options = optionsBuilder.Build(); if (options.ChannelOptions is MqttClientWebSocketOptions webSocketOptions) { webSocketOptions.RequestHeaders = uriDetails.Headers; } return(options); }
public async Task <ILowLevelMqttClient> ConnectLowLevelClient(Action <MqttClientOptionsBuilder> optionsBuilder) { if (optionsBuilder == null) { throw new ArgumentNullException(nameof(optionsBuilder)); } var options = new MqttClientOptionsBuilder(); options = options.WithTcpServer("127.0.0.1", ServerPort); optionsBuilder.Invoke(options); var client = CreateLowLevelClient(); await client.ConnectAsync(options.Build(), CancellationToken.None).ConfigureAwait(false); return(client); }
public async Task <bool> IsRunning() { try { var client = new MqttFactory().CreateMqttClient(); var clientOptions = new MqttClientOptionsBuilder() .WithTcpServer("127.0.0.1", port) .Build(); var result = await client.ConnectAsync(clientOptions); return(true); } catch (Exception ex) { return(false); } }
public static async Task RunAsync() { var logger = new MqttNetEventLogger(); MqttNetConsoleLogger.ForwardToConsole(logger); var factory = new MqttFactory(logger); var server = factory.CreateMqttServer(new MqttServerOptionsBuilder().Build()); var client = factory.CreateMqttClient(); await server.StartAsync(); var clientOptions = new MqttClientOptionsBuilder().WithTcpServer("localhost").Build(); await client.ConnectAsync(clientOptions); await Task.Delay(Timeout.Infinite); }
public async Task Connect() { if (IsConnected) { Disconnect(); } if (!(this.BrokerAddress.StartsWith("ws://") || this.BrokerAddress.StartsWith("wss://"))) { Logger.Error("Invalid protocol in '{0}'", this.BrokerAddress); return; } string useTls = null; var options = new MqttClientOptionsBuilder() .WithWebSocketServer(this.BrokerAddress) .WithClientId(Guid.NewGuid().ToString() + "-PDI-team01"); if (this.BrokerAddress.StartsWith("wss://")) { options = options.WithTls(); useTls = "with"; } else { useTls = "without"; } Logger.Info("Trying to connect to '{0}' {1} TLS", this.BrokerAddress, useTls); try { await this._Client.ConnectAsync(options.Build()); } catch (Exception e) { Logger.Error("Failed to connect to {0} {1} TLS", this.BrokerAddress, useTls); Logger.Error(e.Message); Logger.Error(e.StackTrace); } ReinitializeSubscriptions(); Logger.Info(this.IsConnected ? "Connected" : "Not connected"); }
private void Connect() { var clientoptions = new MqttClientOptionsBuilder() .WithTcpServer(Globals.G_ServerWorkerIP, 1884) // Port is optional .Build(); mqtc = new MqttFactory().CreateMqttClient(); mqtc.ConnectAsync(clientoptions); mqtc.Connected += mqtc_Connected; //mqtc.Connected += async (s, evt) => //{ // SetText("### CONNECTED WITH SERVER ###" + Environment.NewLine); // await mqtc.SubscribeAsync(new TopicFilterBuilder().WithTopic("Server/Status").Build()); // SetText("### SUBSCRIBED ###" + Environment.NewLine); //}; mqtc.Disconnected += mqtc_Disconnected; //mqtc.Disconnected += async (s, evtdisconnected) => //{ // SetText("### DISCONNECTED FROM SERVER ###" + Environment.NewLine); // await Task.Delay(TimeSpan.FromSeconds(5)); // try // { // await mqtc.ConnectAsync(clientoptions); // } // catch // { // SetText("### RECONNECTING FAILED ### PLEASE CONTACT SERVER ADMINISTRATOR" + Environment.NewLine); // } //}; mqtc.ApplicationMessageReceived += mqtc_MsgEventHandler; //mqtc.ApplicationMessageReceived += (s, msgreceived) => //{ // //SetText("### RECEIVED APPLICATION MESSAGE ###" + Environment.NewLine); // SetText(string.Format("{0} Received : {1}", pcname, Encoding.UTF8.GetString(msgreceived.ApplicationMessage.Payload))); //}; }
private async Task ConnectMqttServerAsync() { if (mqttClient == null) { mqttClient = new MqttFactory().CreateMqttClient(); mqttClient.ApplicationMessageReceived += MqttClient_ApplicationMessageReceived; mqttClient.Connected += MqttClient_Connected; mqttClient.Disconnected += MqttClient_Disconnected; } try { var index = this.CombServer.InvokeRequired ? (int)this.CombServer.EndInvoke(this.CombServer.BeginInvoke(new Func <int>(() => { return(this.CombServer.SelectedIndex); }))): this.CombServer.SelectedIndex; if (index == 1) { var options = new MqttClientOptionsBuilder() .WithClientId(Guid.NewGuid().ToString().Substring(0, 5)) .WithTcpServer(ConfigurationManager.AppSettings["MqttUrl"], Convert.ToInt32(ConfigurationManager.AppSettings["MqttPort"])) .WithCredentials(ConfigurationManager.AppSettings["MqttUserName"], ConfigurationManager.AppSettings["MqttPassWord"]) .WithKeepAlivePeriod(TimeSpan.FromSeconds(60)) .WithCommunicationTimeout(TimeSpan.FromSeconds(30)) .Build(); await mqttClient.ConnectAsync(options); } else { var options = new MqttClientOptionsBuilder() .WithClientId(Guid.NewGuid().ToString().Substring(0, 5)) .WithTcpServer(ConfigurationManager.AppSettings["local_MqttUrl"]) .WithCredentials(ConfigurationManager.AppSettings["local_MqttUserName"], ConfigurationManager.AppSettings["local_MqttPassWord"]) .WithKeepAlivePeriod(TimeSpan.FromSeconds(60)) .WithCommunicationTimeout(TimeSpan.FromSeconds(30)) .Build(); await mqttClient.ConnectAsync(options); } } catch (Exception ex) { Invoke((new Action(() => { txtReceiveMessage.AppendText($"连接到MQTT服务器失败!" + Environment.NewLine + ex.Message + Environment.NewLine); }))); } }
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> /// Service Start action. Do not call this directly. /// </summary> /// <param name="cancellationToken">Cancelation token.</param> /// <returns>Awaitable <see cref="Task" />.</returns> public async Task StartAsync(CancellationToken cancellationToken = default(CancellationToken)) { _serviceLog.LogInformation("Service start initiated"); _stopping = false; // MQTT will message var willMessage = new MqttApplicationMessageBuilder() .WithTopic($"{TopicRoot}/connected") .WithPayload(((int)ConnectionStatus.Disconnected).ToString()) .WithAtLeastOnceQoS() .WithRetainFlag() .Build(); // MQTT client options var optionsBuilder = new MqttClientOptionsBuilder() .WithTcpServer(_brokerSettings.BrokerIp, _brokerSettings.BrokerPort) .WithClientId(MqttClientId.ToString()) .WithCleanSession() .WithWillMessage(willMessage); // MQTT credentials if (!string.IsNullOrEmpty(_brokerSettings.BrokerUsername) && !string.IsNullOrEmpty(_brokerSettings.BrokerPassword)) { optionsBuilder.WithCredentials(_brokerSettings.BrokerUsername, _brokerSettings.BrokerPassword); } var managedOptions = new ManagedMqttClientOptionsBuilder() .WithAutoReconnectDelay(TimeSpan.FromSeconds(_brokerSettings.BrokerReconnectDelay)) .WithClientOptions(optionsBuilder.Build()) .Build(); // Subscribe to MQTT messages await SubscribeAsync(cancellationToken) .ConfigureAwait(false); // Connect to MQTT await MqttClient.StartAsync(managedOptions) .ConfigureAwait(false); // Call startup on inheriting service class await StartServiceAsync(cancellationToken) .ConfigureAwait(false); _serviceLog.LogInformation("Service started successfully"); }
public virtual IChannel CreateGreenChannel(string gatewayId) { var options = new MqttClientOptionsBuilder() .WithTcpServer("greenqueue.prod.iotnxt.io", 8883) .WithClientId($"{gatewayId}.GREEN.{DateTime.Now.Ticks}") .WithCredentials("green1:public1", "publicpassword1") .WithTls(new MqttClientOptionsBuilderTlsParameters { AllowUntrustedCertificates = true, IgnoreCertificateChainErrors = true, IgnoreCertificateRevocationErrors = true, UseTls = true, }) .WithCleanSession() .Build(); return(new MqttClientChannel(options)); }
// PM> Install-Package MQTTnet.AspNetCore public static async Task ClientTestAsync() { var factory = new MqttFactory(); var client = factory.CreateMqttClient(); // await client.SubscribeAsync("house#"); var options = new MqttClientOptionsBuilder() .WithTcpServer("10.0.75.1", 1883) // Port is optional .Build(); client.ApplicationMessageReceived += Client_ApplicationMessageReceived; client.Connected += Client_Connected; client.Disconnected += Client_Disconnected; await client.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); } }
public async Task SendMQTT() { //Create a new MQTT client. var factory = new MqttFactory(); var mqttClient = factory.CreateMqttClient(); var options = new MqttClientOptionsBuilder() .WithTcpServer("localhost", 1889) .Build(); await mqttClient.ConnectAsync(options); mqttClient.UseApplicationMessageReceivedHandler(_ => { }); await mqttClient.SubscribeAsync("device/+/#"); }
public async void ConnectAsync(string ip, string username, string password, List <string> topics) { var factory = new MqttFactory(); mqttClient = factory.CreateMqttClient(); var options = new MqttClientOptionsBuilder() .WithTcpServer(ip) .WithCredentials(username, password) .Build(); mainOptions = options; await mqttClient.ConnectAsync(options, CancellationToken.None); foreach (var t in topics) { await mqttClient.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic(t).Build()); } }
public Task ConnectAsync(string ipAddress, int port) { string clientId = Guid.NewGuid().ToString(); IMqttClientOptions options = new MqttClientOptionsBuilder() .WithClientId(clientId) .WithTcpServer(ipAddress, port) .WithCleanSession().Build(); ManagedMqttClientOptions managedOptions = new ManagedMqttClientOptionsBuilder() .WithAutoReconnectDelay(TimeSpan.FromSeconds(5)) .WithClientOptions(options) .Build(); this.Client = new MqttFactory().CreateManagedMqttClient(); return(this.Client.StartAsync(managedOptions)); }
public async Task Manage_Session_MaxParallel() { using (var testEnvironment = new TestEnvironment(TestContext)) { testEnvironment.IgnoreClientLogErrors = true; var serverOptions = new MqttServerOptionsBuilder(); await testEnvironment.StartServer(serverOptions); var options = new MqttClientOptionsBuilder().WithClientId("1"); var clients = await Task.WhenAll(Enumerable.Range(0, 10) .Select(i => TryConnect(testEnvironment, options))); var connectedClients = clients.Where(c => c?.IsConnected ?? false).ToList(); Assert.AreEqual(1, connectedClients.Count); } }
/// <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 Connect(string host) { try { var options = new MqttClientOptionsBuilder() .WithClientId("TestClient_pub") .WithTcpServer(host) .WithCleanSession() .Build(); var test = await _mqttClient.ConnectAsync(options); Console.WriteLine("Is Connected : {0} ", _mqttClient.IsConnected); } catch (Exception ex) { throw ex; } }
public async Task MqttServer_ConnectionDenied() { var server = new MqttFactory().CreateMqttServer(); var client = new MqttFactory().CreateMqttClient(); try { var options = new MqttServerOptionsBuilder().WithConnectionValidator(context => { context.ReturnCode = MqttConnectReturnCode.ConnectionRefusedNotAuthorized; }).Build(); await server.StartAsync(options); var clientOptions = new MqttClientOptionsBuilder() .WithTcpServer("localhost").Build(); try { await client.ConnectAsync(clientOptions); Assert.Fail("An exception should be raised."); } catch (Exception exception) { if (exception is MqttConnectingFailedException) { } else { Assert.Fail("Wrong exception."); } } } finally { await client.DisconnectAsync(); await server.StopAsync(); client.Dispose(); } }
public async Task MqttServer_Client_Disconnect_Without_Errors() { var errors = 0; MqttNetGlobalLogger.LogMessagePublished += (_, e) => { System.Diagnostics.Debug.WriteLine($"[{e.TraceMessage.Timestamp:s}] {e.TraceMessage.Source} {e.TraceMessage.Message}"); if (e.TraceMessage.Level == MqttNetLogLevel.Error) { errors++; } }; bool clientWasConnected; var server = new MqttFactory().CreateMqttServer(); try { var options = new MqttServerOptionsBuilder().Build(); await server.StartAsync(options); var client = new MqttFactory().CreateMqttClient(); var clientOptions = new MqttClientOptionsBuilder() .WithTcpServer("localhost") .Build(); await client.ConnectAsync(clientOptions); clientWasConnected = true; await client.DisconnectAsync(); await Task.Delay(500); } finally { await server.StopAsync(); } Assert.IsTrue(clientWasConnected); Assert.AreEqual(0, errors); }
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureServices(async(hostContext, services) => { services.AddTransient <IMqttApplicationMessageReceivedHandler, MqttApplicationMessageReceivedHandler>(); var factory = new MqttFactory(); var mqttClient = factory.CreateMqttClient(); var options = new MqttClientOptionsBuilder() .WithClientId("Device Enactor") .WithTcpServer("iot.mqtt.broker", 1884) .WithCredentials("DeviceEnactor", "u@'xSQjBM&6~nMEd") .Build(); mqttClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(async e => { await mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic("temperature/#").Build()); await mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic("soilmoisture/#").Build()); await mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic("connected/#").Build()); await mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic("disconnected/#").Build()); await mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic("led/#").Build()); }); mqttClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(async e => { await Task.Delay(TimeSpan.FromSeconds(5)); try { await mqttClient.ConnectAsync(options, CancellationToken.None); } catch { } }); services.AddSingleton(mqttClient); services.AddSingleton(options); var provider = services.AddNServiceBus("IoT.DeviceEnactor"); var mqttApplicationMessageReceivedHandler = provider.GetService <IMqttApplicationMessageReceivedHandler>(); mqttClient.UseApplicationMessageReceivedHandler(mqttApplicationMessageReceivedHandler); try { await mqttClient.ConnectAsync(options, CancellationToken.None); } catch { } });
public static async Task RunClientTaskAsync() { MyTrueWriteLine("Creating a new client....."); var mqttclient = new MqttFactory().CreateMqttClient(); MqttClientTcpOptions mqttClientTcpOptions = new MqttClientTcpOptions() { Server = "127.0.0.1", Port = 1883, }; var optionbuilder = new MqttClientOptionsBuilder() .WithWillMessage(BuildMessage()) .WithTcpServer("127.0.0.1", 1883) .WithClientId("Test1") .WithCredentials("user", "password") .WithTls() .WithCommunicationTimeout(new TimeSpan(0, 0, 20)) .WithKeepAlivePeriod(new TimeSpan(0, 0, 20)) .WithCleanSession(true); var options = optionbuilder.Build(); MyTrueWriteLine("Client starting to connect the server......"); try { MqttClientConnectResult clientConnectResult = await mqttclient.ConnectAsync(options); MyTrueWriteLine("The result of action:" + clientConnectResult.ToString()); } catch (Exception e) { MyTrueWriteLine("Failed:" + Environment.NewLine + e); } mqttclient.Connected += (s, e) => { MyTrueWriteLine("Client has connected to server successfully!"); MyTrueWriteLine($"Detail:{e.ConnectResult.ToString()}"); }; mqttclient.Disconnected += (s, e) => { MyTrueWriteLine("Client has disconnected from the server"); }; }
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); }
static void Main(string[] args) { Console.WriteLine("Hello World!"); var options = new MqttClientOptionsBuilder() .WithTcpServer("localhost", 5002) // Port is optional .Build(); var client = new MqttFactory().CreateMqttClient(); Console.WriteLine("Ready to Connect"); Console.ReadLine(); Console.WriteLine("Connecting"); var task = client.ConnectAsync(options); task.ContinueWith(t => { Console.WriteLine("Subscribing"); client.SubscribeAsync("my/amazing/topic"); client.SubscribeAsync("my/+/stuff"); return(true); }) .ContinueWith(t => { if (t.Result) { Task.Delay(10000).Wait(); Console.WriteLine("Sending Data"); client.PublishAsync("my/dance/stuff", "{ \"DanceMove\":\"Break Dancing\" }"); } }); Console.WriteLine("Hit Enter to Disconnect"); Console.ReadLine(); client.DisconnectAsync().Wait(); Console.WriteLine("Disconnected"); Console.WriteLine("Hit Enter to Shutdown"); Console.ReadLine(); }
public async Task InitializeAsync() { Logger = new TestableLogger(); LoggerFactory = Microsoft.Extensions.Logging.LoggerFactory.Create(c => c.ConfigureTestableLogger(Logger)); LogoHardwareMock = new LogoHardwareMock(); var brokerIpAddress = IPAddress.Loopback; var brokerPort = 1889; var mqttFactory = new MqttFactory(); mqttServer = mqttFactory.CreateMqttServer(); MqttClient = mqttFactory.CreateMqttClient(); MqttClient.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(args => MqttMessageReceived?.Invoke(this, args)); var mqttServerOptions = new MqttServerOptionsBuilder() .WithClientId(nameof(IntegrationTestEnvironment) + "Broker") .WithDefaultEndpointBoundIPAddress(brokerIpAddress) .WithDefaultEndpointPort(brokerPort) .Build(); var mqttClientOptions = new MqttClientOptionsBuilder() .WithClientId(nameof(IntegrationTestEnvironment) + "Client") .WithTcpServer(brokerIpAddress.ToString(), brokerPort) .Build(); await mqttServer .StartAsync(mqttServerOptions) .ConfigureAwait(false); await MqttClient .ConnectAsync(mqttClientOptions) .ConfigureAwait(false); var config = IntegrationTests.GetConfig(brokerIpAddress.ToString(), brokerPort); config.Validate(); appContext = Logic .Initialize(LoggerFactory, config); await appContext .Connect() .ConfigureAwait(false); }
public static async Task RunAsync() { try { var logger = new MqttNetLogger(); MqttNetConsoleLogger.ForwardToConsole(logger); var factory = new MqttFactory(logger); var client = factory.CreateMqttClient(); var options = new MqttClientOptionsBuilder() .WithTcpServer("localhost") .Build(); Console.WriteLine("BEFORE CONNECT"); await client.ConnectAsync(options); Console.WriteLine("AFTER CONNECT"); Console.WriteLine("BEFORE SUBSCRIBE"); await client.SubscribeAsync("test/topic"); Console.WriteLine("AFTER SUBSCRIBE"); Console.WriteLine("BEFORE PUBLISH"); await client.PublishAsync("test/topic", "payload"); Console.WriteLine("AFTER PUBLISH"); await Task.Delay(1000); Console.WriteLine("BEFORE DISCONNECT"); await client.DisconnectAsync(); Console.WriteLine("AFTER DISCONNECT"); Console.WriteLine("FINISHED"); } catch (Exception ex) { Console.WriteLine(ex); } }
public async Task MqttSendTest() { var jsonEventFormatter = new JsonEventFormatter(); var cloudEvent = new CloudEvent { Type = "com.github.pull.create", Source = new Uri("https://github.com/cloudevents/spec/pull/123"), Id = "A234-1234-1234", Time = new DateTimeOffset(2018, 4, 5, 17, 31, 0, TimeSpan.Zero), DataContentType = MediaTypeNames.Text.Xml, Data = "<much wow=\"xml\"/>", ["comexampleextension1"] = "value" }; var client = new MqttFactory().CreateMqttClient(); var options = new MqttClientOptionsBuilder() .WithClientId("Client1") .WithTcpServer("localhost", 52355) .WithCleanSession() .Build(); TaskCompletionSource <CloudEvent> tcs = new TaskCompletionSource <CloudEvent>(); await client.ConnectAsync(options); client.ApplicationMessageReceived += (sender, args) => tcs.SetResult(args.ApplicationMessage.ToCloudEvent(jsonEventFormatter)); var result = await client.SubscribeAsync("abc"); await client.PublishAsync(cloudEvent.ToMqttApplicationMessage(ContentMode.Structured, new JsonEventFormatter(), topic: "abc")); var receivedCloudEvent = await tcs.Task; Assert.Equal(CloudEventsSpecVersion.Default, receivedCloudEvent.SpecVersion); Assert.Equal("com.github.pull.create", receivedCloudEvent.Type); Assert.Equal(new Uri("https://github.com/cloudevents/spec/pull/123"), receivedCloudEvent.Source); Assert.Equal("A234-1234-1234", receivedCloudEvent.Id); AssertTimestampsEqual("2018-04-05T17:31:00Z", receivedCloudEvent.Time.Value); Assert.Equal(MediaTypeNames.Text.Xml, receivedCloudEvent.DataContentType); Assert.Equal("<much wow=\"xml\"/>", receivedCloudEvent.Data); Assert.Equal("value", (string)receivedCloudEvent["comexampleextension1"]); }
public static void SendDataTask(string mqttServer, string mqttTopic) { Task.Run(async() => { Console.WriteLine("Creating MQTT client"); var options = new MqttClientOptionsBuilder().WithClientId("NetworkSpeedMonitor") .WithTcpServer(mqttServer) .WithCleanSession() .Build(); var factory = new MqttFactory(); var mqttClient = factory.CreateMqttClient(); var i = 0; while (true) { i++; var value = await buffer.ReceiveAsync(); Console.WriteLine($"down: {value.Down} MB/s, up: {value.Up} MB/s"); if (!mqttClient.IsConnected) { Console.WriteLine("Connecting to mqtt server"); await mqttClient.ConnectAsync(options); Console.WriteLine("Connected to mqtt server"); } if (mqttClient.IsConnected) { await mqttClient.PublishAsync(new MqttApplicationMessage() { Topic = mqttTopic + "/Up", Payload = Encoding.UTF8.GetBytes(value.Up.ToString("0.00")) }, new MqttApplicationMessage() { Topic = mqttTopic + "/Down", Payload = Encoding.UTF8.GetBytes(value.Down.ToString("0.00")) }); //Console.WriteLine("Mqtt message sent"); } else { Console.WriteLine("Failed to connect, dumping message!"); } } }); }
public async Task StartAsync(CancellationToken cancellationToken) { disconnecting = false; MqttFactory factory = new MqttFactory(); _mqttClient = factory.CreateMqttClient(); var options = new MqttClientOptionsBuilder() .WithClientId("IotRouter") .WithTcpServer(Server) .WithCredentials(Username, Password) .WithTls() .WithCleanSession() .Build(); _mqttClient.UseConnectedHandler(async e => { _logger.LogInformation($"MqttListener {Name}: Connected"); await _mqttClient.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic(Topic).Build()); _logger.LogInformation($"MqttListener {Name}: Subscribed"); }); _mqttClient.UseDisconnectedHandler(async e => { if (!disconnecting) { _logger.LogWarning($"MqttListener {Name}: Disconnected, trying to reconnect"); await Task.Delay(TimeSpan.FromSeconds(5)); await _mqttClient.ConnectAsync(options, CancellationToken.None); } }); _mqttClient.UseApplicationMessageReceivedHandler(e => { _logger.LogInformation($"MqttListener {Name}: Message received\n" + $"+ Topic = {e.ApplicationMessage.Topic}\n" + $"+ Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}\n" + $"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}\n" + $"+ Retain = {e.ApplicationMessage.Retain}"); MessageReceived?.Invoke(this, new MessageReceivedEventArgs(e.ApplicationMessage.Topic, e.ApplicationMessage.Payload)); }); await _mqttClient.ConnectAsync(options, cancellationToken); }
public async Task <ActionResult> ToggleFromUser(Guid uuid, bool state) { var user = HttpContext.User.Identity?.Name; if (user == null) { return(NotFound("User Not Found")); } var count = await Db.Users .Include(x => x.Device) .CountAsync(x => x.Aud == user && uuid == x.Device.DeviceId); if (count == 0) { return(NotFound("No such device")); } var factory = new MqttFactory(); var mqttClient = factory.CreateMqttClient(); var options = new MqttClientOptionsBuilder() .WithClientId("Backend_Server") .WithTcpServer("node02.myqtthub.com") .WithCredentials("server", "password") .WithCleanSession() .Build(); mqttClient.UseConnectedHandler(async e => { var message = new MqttApplicationMessageBuilder() .WithTopic("esp32/update") .WithPayload($"{uuid}:{state}") .WithExactlyOnceQoS() .WithRetainFlag() .Build(); await mqttClient.PublishAsync(message, CancellationToken.None); await mqttClient.DisconnectAsync(); }); await mqttClient.ConnectAsync(options, CancellationToken.None); return(NoContent()); }