示例#1
0
        public async Task Subscribe(CancellationToken cancellationToken)
        {
            var mqttFactory = new MqttFactory();

            var clientOptionsBuilder = new MqttClientOptionsBuilder()
                                       .WithClientId(System.Reflection.Assembly.GetEntryAssembly().FullName)
                                       .WithTcpServer(m_brokerHostName)
                                       .WithCredentials(m_applicationId, m_applicationAccessKey)
                                       .Build();

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

            await m_mqttClientSubscriber.ConnectAsync(clientOptionsBuilder, cancellationToken);

            await m_consoleLogger.AppendMessageAsync($"ConnectAsync IsConnected: {m_mqttClientSubscriber.IsConnected}");
        }
示例#2
0
        private async Task OnSubscriberMessageReceived(MqttApplicationMessageReceivedEventArgs arg)
        {
            var item = $"Timestamp: {DateTime.Now:O} | Topic: {arg.ApplicationMessage.Topic} | Payload: {arg.ApplicationMessage.ConvertPayloadToString()} | QoS: {arg.ApplicationMessage.QualityOfServiceLevel}";

            var loggingStart = DateTime.Now;


            var consoleTask  = m_consoleLogger.AppendMessageAsync(item);
            var fileTask     = m_logger?.AppendMessageAsync(item);
            var pastebinTask = m_pasteBinLogger?.AppendMessageAsync(arg.ApplicationMessage.ConvertPayloadToString());

            await Task.WhenAll(consoleTask, fileTask, pastebinTask);

            await m_consoleLogger.AppendMessageAsync($"Logging completed in {(DateTime.Now - loggingStart).ToString()}");
        }