예제 #1
0
        public Client()
        {
            mqttClient = new MqttFactory().CreateManagedMqttClient();

            mqttClient.SynchronizingSubscriptionsFailed += (o, e) => Error?.Invoke(this, e.Exception);
            mqttClient.ConnectingFailed += (o, e) =>
            {
                Debug(this, "NOOOO !!");
                //Error?.Invoke(this, e.Exception);
            };
            mqttClient.Disconnected += (o, e) =>
            {
                if (e.ClientWasConnected)
                {
                    Debug?.Invoke(this, "client already connected");
                }
                else
                {
                    Error?.Invoke(this, e.Exception);
                }
            };
            mqttClient.SynchronizingSubscriptionsFailed += (o, e) => Error?.Invoke(this, e.Exception);
            mqttClient.Connected += (o, e) =>
            {
                ConnectedSucessfully?.Invoke(this, EventArgs.Empty);
                Subscrive("#");
                Debug?.Invoke(this, "Client conencted to server");
                Message m = new Message(Message.AvailableOrders.showup);
                Publish(m.Serialize());
            };
            //mqttClient.ApplicationMessageProcessed += (o, e) => Debug?.Invoke(this, "applicationMEssageProcessed: "+e.Exception.Message);
            mqttClient.ApplicationMessageSkipped += (o, e) => Debug?.Invoke(this, "ApplicationMessageSkipped: " + e.ApplicationMessage);

            mqttClient.ApplicationMessageReceived += MqttClient_ApplicationMessageReceived;
        }
예제 #2
0
        private async void Disconnect(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_mqttClient != null)
                {
                    await _mqttClient.DisconnectAsync();

                    _mqttClient.Dispose();
                    _mqttClient = null;
                }

                if (_managedMqttClient != null)
                {
                    await _managedMqttClient.StopAsync();

                    _managedMqttClient.Dispose();
                    _managedMqttClient = null;
                }
            }
            catch (Exception exception)
            {
                Trace.Text += exception + Environment.NewLine;
            }
        }
        /// <summary>
        /// Opens the MQTT connection.
        /// </summary>
        public async Task StartAsync(IProcesMqttMessage messageHandler)
        {
            try
            {
                lock (startupLock)
                {
                    if (_managedMqttClient != null || ConnectionState == ConnectionState.Connected)
                    {
                        return;
                    }
                    _messageHandler = messageHandler;

                    ConnectionState    = ConnectionState.Connecting;
                    _managedMqttClient = _mqttClientFactory.CreateManagedMqttClient();
                    _managedMqttClient.ApplicationMessageReceivedHandler  = this;
                    _managedMqttClient.ApplicationMessageProcessedHandler = this;
                    _managedMqttClient.ConnectedHandler        = this;
                    _managedMqttClient.ConnectingFailedHandler = this;
                    _managedMqttClient.SynchronizingSubscriptionsFailedHandler = this;
                    _managedMqttClient.DisconnectedHandler = this;
                }
                await _managedMqttClient.StartAsync(_config.Options).ConfigureAwait(false);
            }
            catch (Exception e)
            {
                _logger.LogCritical(new EventId(0), e, $"Exception while setting up the mqttclient to {this}");
                throw new MqttConnectionException($"Exception while setting up the mqttclient to {this}", e);
            }
        }
예제 #4
0
    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);
        });
    }
예제 #5
0
 /// <summary>
 /// Opens the MQTT connection
 /// </summary>
 public async Task StartAsync()
 {
     try
     {
         lock (startupLock)
         {
             if (_managedMqttClient != null || ConnectionState == ConnectionState.Connected)
             {
                 return;
             }
             ConnectionState    = ConnectionState.Connecting;
             _managedMqttClient = _mqttClientFactory.CreateManagedMqttClient();
             _managedMqttClient.ApplicationMessageReceived  += ManagedMqttClientApplicationMessageReceived;
             _managedMqttClient.ApplicationMessageProcessed += ManagedMqttClientApplicationMessageProcessed;
             _managedMqttClient.Connected    += ManagedMqttClientConnected;
             _managedMqttClient.Disconnected += ManagedMqttClientDisconnected;
         }
         await _managedMqttClient.StartAsync(_config.Options).ConfigureAwait(false);
     }
     catch (Exception e)
     {
         _logger.LogCritical($"Exception while setting up the mqttclient to {this}", e);
         throw new MqttConnectionException($"Exception while setting up the mqttclient to {this}", e);
     }
 }
예제 #6
0
        private MqttIpcServer(MqttIpcServerConfiguration configuration, IIpcSerializer serializer, IIpcPacketRouter router, IIpcPacketHandlersContainer packetHandlersContainer)
        {
            _serializer = serializer;
            _router     = router;
            _packetHandlersContainer = packetHandlersContainer;
            string clientName = configuration.ClientName;
            string endPoint   = configuration.EndPoint;


            _client        = new MqttFactory().CreateManagedMqttClient(new MqttNetLogger(clientName));
            _packetFactory = new PacketContainerFactory();
            _queues        = new HashSet <string>();
            _packetHandlersContainer.Registered   += (sender, type) => CheckRouting(type).ConfigureAwait(false).GetAwaiter().GetResult();
            _packetHandlersContainer.Unregistered += (sender, type) =>
            {
                IRoutingInformation infos = _router.GetRoutingInformationsAsync(type).ConfigureAwait(false).GetAwaiter().GetResult();
                _client.UnsubscribeAsync(infos.IncomingTopic).ConfigureAwait(false).GetAwaiter().GetResult();
            };
            ManagedMqttClientOptions options = new ManagedMqttClientOptionsBuilder()
                                               .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                                               .WithClientOptions(new MqttClientOptionsBuilder()
                                                                  .WithClientId(clientName)
                                                                  .WithTcpServer(endPoint)
                                                                  .Build())
                                               .Build();

            _client.ApplicationMessageReceived += (sender, args) => OnMessage(args.ClientId, args.ApplicationMessage);
            _client.StartAsync(options).ConfigureAwait(false).GetAwaiter().GetResult();
            _client.Connected    += (sender, args) => _log.Info($"[CONNECTED] {clientName} is connected on MQTT Broker {endPoint}");
            _client.Disconnected += (sender, args) => _log.Info($"[DISCONNECTED] {clientName} has been disconnected on MQTT Broker {endPoint}");
        }
예제 #7
0
        public MqttConsumerService(
            IManagedMqttClient mqttClient,
            IMqttApplicationProvider applicationProvider,
            IServiceScopeFactory serviceScopeFactory,
            IManagedMqttClientOptions mqttClientOptions,
            IOptions <TManagedMqttSettings> mqttSettings,
            ILogger <MqttConsumerService <TManagedMqttSettings> > logger)
        {
            MqttClient          = mqttClient;
            ApplicationProvider = applicationProvider;
            ServiceScopeFactory = serviceScopeFactory;
            Options             = mqttClientOptions;
            MqttSettings        = mqttSettings;
            Logger = logger;

            MqttClient.ApplicationMessageProcessedHandler = new ApplicationMessageProcessedHandlerDelegate(OnApplicationMessageProcessed);
            MqttClient.ApplicationMessageReceivedHandler  = new MqttApplicationMessageReceivedHandlerDelegate(OnApplicationMessageReceived);
            MqttClient.ApplicationMessageSkippedHandler   = new ApplicationMessageSkippedHandlerDelegate(OnApplicationMessageSkipped);

            MqttClient.ConnectedHandler        = new MqttClientConnectedHandlerDelegate(OnConnected);
            MqttClient.DisconnectedHandler     = new MqttClientDisconnectedHandlerDelegate(OnDisconnected);
            MqttClient.ConnectingFailedHandler = new ConnectingFailedHandlerDelegate(OnConnectingFailed);

            MqttClient.SynchronizingSubscriptionsFailedHandler = new SynchronizingSubscriptionsFailedHandlerDelegate(OnSynchronizingSubscriptionsFailed);

            ApplicationProvider.ApplicationChanged += OnApplicationChanged;
        }
        public virtual async Task StartMqttClient()
        {
            _logger.Info("Starting MQTT client..");
            _managedMqttClient = new MqttFactory().CreateManagedMqttClient();

            // This is event is hit when we receive a message from the broker.
            _managedMqttClient.ApplicationMessageReceived += (s, a) =>
            {
                var topic         = a.ApplicationMessage.Topic;
                var decodedString = Encoding.UTF8.GetString(a.ApplicationMessage.Payload);
                _logger.Trace($"Message from topic '{topic}' received.");
                _logger.Trace($"Decoded Message: {decodedString}");
                HandleMqttApplicationMessageReceived(topic, decodedString);
            };

            // This just tells us that a message we sent was received successfully by the broker.
            _managedMqttClient.ApplicationMessageProcessed += (s, a) =>
            {
                _logger.Trace("Client Message Processed by Broker", a);
                if (a.HasSucceeded == false)
                {
                    // TODO: What to do here?
                    // Add to a file? And retry later?
                }
            };

            await _managedMqttClient.SubscribeAsync(new List <TopicFilter> {
                new TopicFilterBuilder().WithTopic(_moduleConfiguration.MqttValuePushTopic).WithAtLeastOnceQoS().Build()
            });

            await _managedMqttClient.StartAsync(GetMqttClientOptions());
        }
        private async void StartMessagingClient()
        {
            _mqttClient = new MqttFactory().CreateManagedMqttClient();

            //Build options for the MQTT client based off of config values
            //If running as a Docker container on Ability Edge, the Edge runtime will supply these values to the container
            var options = new ManagedMqttClientOptionsBuilder()
                          .WithClientOptions(
                new MQTTnet.Client.MqttClientOptionsBuilder()
                .WithClientId(this.Configuration.ClientId)
                .WithTcpServer(
                    this.Configuration.ServerUri.Host,
                    this.Configuration.ServerUri.Port)
                .WithCredentials(
                    this.Configuration.Username,
                    this.Configuration.Password)
                .WithKeepAlivePeriod(
                    TimeSpan.FromMilliseconds(
                        DEFAULT_KEEP_ALIVE_PERIOD_MS))
                .WithCleanSession(this.Configuration.CleanSession)
                .Build())
                          .WithAutoReconnectDelay(
                TimeSpan.FromMilliseconds(DEFAULT_AUTO_RECONNECT_DELAY_MS))
                          .Build();

            _mqttClient.ApplicationMessageReceived += OnApplicationMessageReceived;

            await _mqttClient.StartAsync(options);

            Console.WriteLine($"MQTT client created and started.");
        }
예제 #10
0
        public MqttClientFacade(ILogger <MqttClientFacade> logger,
                                IOptions <ConnectionSettings> connectionSettings)
        {
            ConnectionSettings = connectionSettings.Value;
            _logger            = logger;

            // Build LWT message
            _lwtMessage = new MqttApplicationMessageBuilder()
                          .WithPayload(Encoding.UTF8.GetBytes("Offline"))
                          .WithTopic($"stat/{ConnectionSettings.ClientID}/LWT")
                          .WithRetainFlag()
                          .WithAtLeastOnceQoS()
                          .Build();

            // Create Client
            _clientOptions = new ManagedMqttClientOptionsBuilder()
                             .WithAutoReconnectDelay(TimeSpan.FromSeconds(ConnectionSettings.AutoReconnectDelaySeconds))
                             .WithClientOptions(new MqttClientOptionsBuilder()
                                                .WithClientId(ConnectionSettings.ClientID)
                                                .WithTcpServer(ConnectionSettings.BrokerURL)
                                                .WithWillMessage(_lwtMessage)
                                                .WithKeepAlivePeriod(TimeSpan.FromSeconds(10))
                                                .WithCommunicationTimeout(TimeSpan.FromMinutes(5))
                                                .WithCredentials(ConnectionSettings.Username, ConnectionSettings.Password)
                                                .WithCleanSession()
                                                .Build()
                                                ).Build();

            _mqttClient = new MqttFactory().CreateManagedMqttClient();
        }
예제 #11
0
 public MqttClientService(IManagedMqttClientOptions options, IHubContext <BrokerHub, IBrokerEvent> hubContext)
 {
     this.hubContext = hubContext;
     this.options    = options;
     mqttClient      = new MqttFactory().CreateManagedMqttClient();
     ConfigureMqttClient();
 }
예제 #12
0
        static async Task Main(string[] args)
        {
            var mqttFactory = new MqttFactory();

            var tlsOptions = new MqttClientTlsOptions
            {
                UseTls = false,
                IgnoreCertificateChainErrors      = true,
                IgnoreCertificateRevocationErrors = true,
                AllowUntrustedCertificates        = true
            };

            var options = new MqttClientOptions
            {
                ClientId        = "Note",
                ProtocolVersion = MqttProtocolVersion.V311,
                ChannelOptions  = new MqttClientTcpOptions
                {
                    Server     = "xx.xx.xx.xx",
                    Port       = 1883,
                    TlsOptions = tlsOptions
                }
            };

            if (options.ChannelOptions == null)
            {
                throw new InvalidOperationException();
            }

            options.Credentials = new MqttClientCredentials
            {
                Username = "******",
                Password = Encoding.UTF8.GetBytes("123456")
            };

            var topicFilter = new MqttTopicFilter {
                Topic = "esp32/dht/temperature"
            };


            options.CleanSession    = true;
            options.KeepAlivePeriod = TimeSpan.FromSeconds(5);

            managedMqttClientSubscriber = mqttFactory.CreateManagedMqttClient();
            managedMqttClientSubscriber.ConnectedHandler    = new MqttClientConnectedHandlerDelegate(OnSubscriberConnected);
            managedMqttClientSubscriber.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(OnSubscriberDisconnected);
            managedMqttClientSubscriber.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(OnSubscriberMessageReceived);

            await managedMqttClientSubscriber.SubscribeAsync(topicFilter);

            await managedMqttClientSubscriber.StartAsync(
                new ManagedMqttClientOptions
            {
                ClientOptions = options
            });

            while (true)
            {
            }
        }
예제 #13
0
    private async Task PublishMessage(IManagedMqttClient mqttClient, string topic, string payload, bool retain,
                                      MqttQualityOfServiceLevel qos)
    {
        var message = new MqttApplicationMessageBuilder().WithTopic(topic)
                      .WithPayload(payload)
                      .WithRetainFlag(retain)
                      .WithQualityOfServiceLevel(qos)
                      .Build();

        _logger.LogDebug("MQTT sending to {Topic}: {Message}", message.Topic, message.ConvertPayloadToString());

        try
        {
            var publishResult = await mqttClient.PublishAsync(message, CancellationToken.None).ConfigureAwait(false);

            if (publishResult.ReasonCode != MqttClientPublishReasonCode.Success)
            {
                throw new MqttPublishException(publishResult.ReasonString);
            }
        }
        catch (Exception e)
        {
            _logger.LogError(e.Message, e);
            throw new MqttPublishException(e.Message, e);
        }
    }
예제 #14
0
        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
        }
예제 #15
0
        private async void MQTTStop()
        {
            await managedMqttClientPublisher.StopAsync();
            managedMqttClientPublisher = null;
            Console.WriteLine("MQTT Connection has been stopped");

        }
예제 #16
0
        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);
        }
예제 #17
0
        private void CreateMQTTClient()
        {
            var clientOptions = new MqttClientOptions()
            {
                ClientId        = _config.RobotName,
                ProtocolVersion = MqttProtocolVersion.V500,
                ChannelOptions  = new MqttClientTcpOptions()
                {
                    Server     = $"{_brokerIP}",
                    Port       = _brokerPort,
                    TlsOptions = _config.TLSOptions
                },
                KeepAlivePeriod = _config.KeepalivePeriod,
                CleanSession    = _config.CleanSession
            };

            _mqttClient = new MqttFactory().CreateManagedMqttClient();
            _mqttClient.ConnectedHandler    = new MqttClientConnectedHandlerDelegate(OnConnected);
            _mqttClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(OnDisconnected);
            _mqttClient.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(OnMessageReceived);

            _mqttClient.StartAsync(new ManagedMqttClientOptions()
            {
                ClientOptions = clientOptions
            }).Wait();
        }
예제 #18
0
        private static int _iLastUpdateThreshold      = 10;    // Minutes

        public static async void StartMQTT(string strMQTTServer, string strClientId, string strUser, string strPassword, MessageHandler messageHandler)
        {
            Logging.WriteDebugLog("MQTT.StartMQTT()");

            if (strMQTTServer == null || strMQTTServer == "")
            {
                return;
            }

            _timerMQTT = new Timer(Update, null, TimeSpan.FromSeconds(10), TimeSpan.FromMinutes(5));

            _strClientId    = strClientId;
            _messageHandler = messageHandler;

            IManagedMqttClientOptions options = new ManagedMqttClientOptionsBuilder().WithAutoReconnectDelay(TimeSpan.FromSeconds(5)).WithClientOptions(new MqttClientOptionsBuilder()
                                                                                                                                                        .WithClientId(_strClientId)
                                                                                                                                                        .WithCredentials(strUser, strPassword)
                                                                                                                                                        .WithTcpServer(strMQTTServer)
                                                                                                                                                        .Build())
                                                .Build();

            _mqtt = new MqttFactory().CreateManagedMqttClient();

            _mqtt.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(MessageProcessor);

            await _mqtt.StartAsync(options);
        }
예제 #19
0
 public HslMqttService(IManagedMqttClient client, ManagedMqttClientOptions options)
 {
     _options = options;
     _client  = client;
     _client.UseApplicationMessageReceivedHandler(MessageReceived);
     _batchTimer = new Timer(BatchTimerTick);
 }
예제 #20
0
        /// <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}");
            }
        }
예제 #21
0
        static async Task Main(string[] args)
        {
            var options = new ManagedMqttClientOptionsBuilder()
                          .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                          .WithClientOptions(new MqttClientOptionsBuilder()
                                             .WithClientId("Ali_Consumer")
                                             .WithCredentials("testuser", "testpass")
                                             .WithTcpServer("www.baltavista.com", 8883)
                                             .WithCleanSession(true)
                                             .Build())
                          .Build();

            _mqttClient = new MqttFactory().CreateManagedMqttClient();
            await _mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic("test1").Build());

            await _mqttClient.StartAsync(options);

            _mqttClient.UseApplicationMessageReceivedHandler(e =>
            {
                Console.WriteLine($"({DateTime.Now}):{Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
            });

            Console.WriteLine("-- MQTT Consumer started ---");
            Console.ReadLine();
        }
예제 #22
0
 //MQTTClient topic cancelling subscription
 public static void ManagedMqttUnsubscribe(IManagedMqttClient managedMqttClient, string mqttTopic)
 {
     managedMqttClient.UseConnectedHandler(async e =>
     {
         await managedMqttClient.UnsubscribeAsync(mqttTopic);
     });
 }
        public MqttService(
            IOptions <MqttOptions> mqttOptions,
            ILogger <MqttService> logger,
            DeviceState deviceState,
            IServiceScopeFactory serviceScopeFactory)
        {
            _mqttOptions = mqttOptions.Value;
            _logger      = logger;
            _deviceState = deviceState;

            _serviceScopeFactory = serviceScopeFactory;
            _client = new MqttFactory().CreateManagedMqttClient();

            _client.UseApplicationMessageReceivedHandler(e =>
            {
                HandleMqttMessage(e);
            });

            _client.UseConnectedHandler(e =>
            {
                HandleMqttConnected(e);
            });

            _client.UseDisconnectedHandler(e =>
            {
                HandleMqttDisconnected(e);
            });
        }
        public static Task EnqueueAsync(
            this IManagedMqttClient managedMqttClient,
            string topic,
            string payload = null,
            MqttQualityOfServiceLevel qualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce,
            bool retain = false)
        {
            if (managedMqttClient == null)
            {
                throw new ArgumentNullException(nameof(managedMqttClient));
            }

            if (topic == null)
            {
                throw new ArgumentNullException(nameof(topic));
            }

            var applicationMessage = new MqttApplicationMessageBuilder().WithTopic(topic)
                                     .WithPayload(payload)
                                     .WithRetainFlag(retain)
                                     .WithQualityOfServiceLevel(qualityOfServiceLevel)
                                     .Build();

            return(managedMqttClient.EnqueueAsync(applicationMessage));
        }
예제 #25
0
        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);
        }
예제 #26
0
        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);
        }
예제 #27
0
        public void Start()
        {
            var optionsBuilder = new ManagedMqttClientOptionsBuilder();

            optionsBuilder = optionsBuilder.WithClientOptions(
                o => o
                .WithTcpServer(_parameters.Server, _parameters.Port)
                .WithCredentials(_parameters.Username, _parameters.Password)
                .WithClientId(_parameters.ClientId)
                .WithTls(new MqttClientOptionsBuilderTlsParameters
            {
                UseTls = _parameters.UseTls
            }));

            if (!string.IsNullOrEmpty(_parameters.ClientId))
            {
                optionsBuilder = optionsBuilder.WithClientOptions(o => o.WithClientId(_parameters.ClientId));
            }

            var options = optionsBuilder.Build();

            _mqttClient = new MqttFactory().CreateManagedMqttClient(new LoggerAdapter(_logger));
            _mqttClient.SubscribeAsync(_parameters.Topic, _parameters.QualityOfServiceLevel).GetAwaiter().GetResult();
            _mqttClient.UseApplicationMessageReceivedHandler(e => OnApplicationMessageReceived(e));
            _mqttClient.StartAsync(options).GetAwaiter().GetResult();
        }
예제 #28
0
        private async void button1_Click(object sender, EventArgs e)
        {
            var factory = new MqttFactory();

            _mqttClient = factory.CreateManagedMqttClient();

            _mqttClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(OnSubscriberConnected);

            _mqttClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(OnSubscriberDisconnected);

            _mqttClient.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(OnSubscriberMessageReceived);

            await _mqttClient
            .SubscribeAsync(new TopicFilterBuilder()
                            .WithTopic($"devices/{IdentifierBox.Text}/config")
                            .WithAtMostOnceQoS()
                            .Build());

            var options = new ManagedMqttClientOptionsBuilder()
                          .WithClientOptions(new MqttClientOptionsBuilder()
                                             .WithKeepAlivePeriod(TimeSpan.FromSeconds(5))
                                             .WithClientId(IdentifierBox.Text)
                                             .WithCredentials(UserName.Text, Password.Text)
                                             .WithTcpServer(IpAddressBox.Text, int.Parse(ServerPort.Text))
                                             .WithCleanSession())
                          .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                          .Build();

            await _mqttClient.StartAsync(options);
        }
예제 #29
0
        public MessageSender(MessageSenderConfiguration messageSenderConfiguration)
        {
            _messageSenderConfiguration = messageSenderConfiguration;

            if (!_messageSenderConfiguration.Enabled)
            {
                return;
            }

            var messageBuilder = new MqttClientOptionsBuilder()
                                 .WithClientId(messageSenderConfiguration.ClientId)
                                 .WithTcpServer(messageSenderConfiguration.Uri, messageSenderConfiguration.PortNumber)
                                 .WithCleanSession();

            var options = messageSenderConfiguration.Secure? messageBuilder.WithTls().Build() : messageBuilder.Build();

            var managedOptions = new ManagedMqttClientOptionsBuilder()
                                 .WithAutoReconnectDelay(TimeSpan.FromSeconds(messageSenderConfiguration.AutoConnectDelaySeconds))
                                 .WithClientOptions(options)
                                 .Build();

            var clientFactory = new MqttFactory();

            _messageClient = clientFactory.CreateManagedMqttClient();

            _messageClient.StartAsync(managedOptions);
        }
예제 #30
0
        public async Task Start()
        {
            var optionsBuilder = new ManagedMqttClientOptionsBuilder();

            optionsBuilder = optionsBuilder.WithClientOptions(
                o => o
                .WithTcpServer(_parameters.Server, _parameters.Port)
                .WithCredentials(_parameters.Username, _parameters.Password)
                .WithClientId(_parameters.ClientId)
                .WithTls(new MqttClientOptionsBuilderTlsParameters
            {
                UseTls = _parameters.UseTls
            }));

            if (!string.IsNullOrEmpty(_parameters.ClientId))
            {
                optionsBuilder = optionsBuilder.WithClientOptions(o => o.WithClientId(_parameters.ClientId));
            }

            var options = optionsBuilder.Build();

            if (_mqttService.IsLowLevelMqttLoggingEnabled)
            {
                _mqttClient = new MqttFactory().CreateManagedMqttClient(); //new LoggerAdapter(_logger));
            }
            else
            {
                _mqttClient = new MqttFactory().CreateManagedMqttClient();
            }

            await _mqttClient.SubscribeAsync(_parameters.Topic, _parameters.QualityOfServiceLevel).ConfigureAwait(false);

            _mqttClient.UseApplicationMessageReceivedHandler(e => OnApplicationMessageReceived(e));
            await _mqttClient.StartAsync(options).ConfigureAwait(false);
        }