コード例 #1
0
 private void OnApplicationMessageReceived(MqttApplicationMessageReceivedEventArgs e)
 {
     OnMessageReceived(new MessageReceivedEventArgs()
     {
         Payload = Encoding.UTF8.GetString(e.ApplicationMessage.Payload),
         Topic   = e.ApplicationMessage.Topic
     });
 }
コード例 #2
0
        /// <summary>
        /// Catches the incomming MQTTMessage and writes it to the MQTTMessageStore
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected override void MqttClient_MessageReceived(object sender, MqttApplicationMessageReceivedEventArgs e)
        {
            MQTTMessage message = new MQTTMessage(e.ApplicationMessage.Topic,
                                                  Encoding.UTF8.GetString(e.ApplicationMessage.Payload),
                                                  DateTime.Now);

            this.WriteLog(message);
        }
コード例 #3
0
 private void MqttClient_ApplicationMessageReceived(object sender, MqttApplicationMessageReceivedEventArgs e)
 {
     UIAction.AppendLog($">> ### RECEIVED APPLICATION MESSAGE ###");
     UIAction.AppendLog($">> Topic = {e.ApplicationMessage.Topic}");
     UIAction.AppendLog($">> Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
     UIAction.AppendLog($">> QoS = {e.ApplicationMessage.QualityOfServiceLevel}");
     UIAction.AppendLog($">> Retain = {e.ApplicationMessage.Retain}");
 }
コード例 #4
0
 private static void OnMessage(object param, MqttApplicationMessageReceivedEventArgs args)
 {
     Console.WriteLine("### MESSAGE RECEIVED FROM DEVICE ###");
     if (args.ApplicationMessage.Topic.Contains("telemetry"))
     {
         producer.ProduceMessage(Literals.KAFKA_TOPIC_TELEMETRY, args.ApplicationMessage.ConvertPayloadToString());
     }
 }
コード例 #5
0
ファイル: Communication.cs プロジェクト: xzsdj/MQTTLearning
 private void MqttClient_ApplicationMessageReceived(object sender, MqttApplicationMessageReceivedEventArgs e)
 {
     ReceiveMsg  = ($">> {"### RECEIVED APPLICATION MESSAGE ###"}{Environment.NewLine}");
     ReceiveMsg += ($">> Topic = {e.ApplicationMessage.Topic}{Environment.NewLine}");
     ReceiveMsg += ($">> Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}{Environment.NewLine}");
     ReceiveMsg += ($">> QoS = {e.ApplicationMessage.QualityOfServiceLevel}{Environment.NewLine}");
     ReceiveMsg += ($">> Retain = {e.ApplicationMessage.Retain}{Environment.NewLine}");
 }
コード例 #6
0
 /// <summary>
 /// 响应消息
 /// </summary>
 protected void Response(MqttApplicationMessageReceivedEventArgs e, string data, MqttQualityOfServiceLevel level)
 {
     if (data == null)
     {
         return;
     }
     Response(e, Encoding.UTF8.GetBytes(data), level);
 }
コード例 #7
0
        private void Client_ApplicationMessageReceivedHandler(MqttApplicationMessageReceivedEventArgs evt)
        {
            var topic        = evt.ApplicationMessage.Topic;
            var payloadBytes = evt.ApplicationMessage.Payload;
            var payload      = payloadBytes != null?Encoding.UTF8.GetString(payloadBytes) : null;

            OnMessageReceived(topic, payload);
        }
コード例 #8
0
        private void MqttClient_ApplicationMessageReceived(MqttApplicationMessageReceivedEventArgs e)
        {
            string message = e.ApplicationMessage.ConvertPayloadToString();
            string topic   = e.ApplicationMessage.Topic;

            logger.Trace($"MQTT Message Received on {name}. Topic:{topic}");
            SendToPipe(message);
        }
コード例 #9
0
ファイル: Client.cs プロジェクト: mqttnettest/Issue432Test
 private void OnMessageReceived(object sender, MqttApplicationMessageReceivedEventArgs e)
 {
     Log.DebugFormat("[{0}] - [{1}]: {2}", GetType().Name, _clientName, string.Format("Message received on topic {0} with payload {1}.", e.ApplicationMessage.Topic, BitConverter.ToString(e.ApplicationMessage.Payload)));
     if (MessageReceived != null)
     {
         MessageReceived(this, null);
     }
 }
コード例 #10
0
 private void MqttClient_ApplicationMessageReceived(MqttApplicationMessageReceivedEventArgs x)
 {
     Invoke(new Action(() =>
     {
         txtReceiveMessage.AppendText(
             $">> {Encoding.UTF8.GetString(x.ApplicationMessage.Payload)}{Environment.NewLine}");
     }));
 }
コード例 #11
0
        public async Task HandleApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs e)
        {
            var json = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);

            Logger.LogDebug($"received topic {e.ApplicationMessage.Topic} with data {json}...");

            if (e.ApplicationMessage.Topic == $"{RemoteTopicConstants.CONFIG_TOPIC}/{_connection.NodeId}")
            {
                if (!await _semaphore.WaitAsync(1000))
                {
                    Logger.LogWarning($"Instance already running, ignoring second call...");
                    return;
                }

                var dto = JsonConvert.DeserializeObject <NodeInstance>(json);

                var context = new DriverContext(dto, _connection.Dispatcher, _connection.NodeTemplateFactory,
                                                new RemoteTelegramMonitor(), new RemoteLicenseState(), Logger, new RemoteLearnMode(_connection),
                                                new RemoteServerCloudApi(), new RemoteLicenseContract(), false);
                _connection.DriverInstance = _connection.Factory.CreateDriver(context);

                await _connection.Loader.LoadDriverFactory(dto, _connection.Factory, context);

                foreach (var driver in _connection.DriverStore.All())
                {
                    await driver.Start();
                }

                await _connection.MqttClient.SubscribeAsync(new TopicFilterBuilder()
                                                            .WithTopic($"{RemoteTopicConstants.ACTION_TOPIC_START}/{_connection.DriverInstance.Id}/+")
                                                            .WithExactlyOnceQoS()
                                                            .Build());
            }
            else if (MqttTopicFilterComparer.IsMatch(e.ApplicationMessage.Topic, $"{RemoteTopicConstants.DISPATCHER_TOPIC}/#"))
            {
                _connection.Dispatcher.MqttDispatch(e.ApplicationMessage.Topic, json);
            }
            else if (_connection.DriverInstance != null && MqttTopicFilterComparer.IsMatch(e.ApplicationMessage.Topic, $"{RemoteTopicConstants.ACTION_TOPIC_START}/{_connection.DriverInstance.Id}/#"))
            {
                var idObject = JsonConvert.DeserializeObject <IdObject>(json);

                var node = _connection.NodeStore.Get(idObject.Id);

                if (node == null)
                {
                    return;
                }

                if (e.ApplicationMessage.Topic.EndsWith(DriverNodeRemoteAction.StartLearnMode.ToString()))
                {
                    await node.EnableLearnMode();
                }
                else if (e.ApplicationMessage.Topic.EndsWith(DriverNodeRemoteAction.StopLearnMode.ToString()))
                {
                    await node.DisableLearnMode();
                }
            }
        }
コード例 #12
0
        protected override async Task OnMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs e)
        {
            byte[] packet = e.ApplicationMessage.Payload;
            string txt    = Encoding.UTF8.GetString(packet);

            try
            {
                EventModel data = JsonConvert.DeserializeObject <EventModel>(txt);
                using (var session = sessionFactory.OpenStatelessSession())
                    using (var transaction = session.BeginTransaction())
                    {
                        EventMap map      = session.Get <EventMap>(data.EventCode);
                        string   redisKey = $"SID{data.SiteId}.EVENT.{data.DeviceId}";
                        Program.logger.Info($"Received Event: {data.EventCode} / Status: {data.Status}");
                        switch (data.Status)
                        {
                        case EventStatus.New:
                            await redisDb.HashSetAsync(redisKey, $"{data.EventCode}", bool.TrueString);

                            // 새로 발생한 이벤트
                            IList <EventRecord> ev = await FindNewRaiseEvent(data.EventCode, session.CreateCriteria <EventRecord>());

                            if (ev.Count > 0)
                            {
                                return;
                            }
                            EventRecord newEventRecode = new EventRecord();
                            newEventRecode.CreateDT = new DateTime(1970, 1, 1).AddSeconds(data.UnixTimestamp).ToLocalTime();
                            newEventRecode.EventId  = data.EventCode;
                            newEventRecode.SiteId   = data.SiteId;
                            newEventRecode.DeviceId = data.DeviceId;
                            await session.InsertAsync(newEventRecode);

                            break;

                        case EventStatus.Recovery:
                            await redisDb.HashSetAsync(redisKey, $"{data.EventCode}", bool.FalseString);

                            var rc_result = await FindNewRaiseEvent(data.EventCode, session.CreateCriteria <EventRecord>());

                            if (rc_result.Count > 0)
                            {
                                foreach (EventRecord exist_record in rc_result)
                                {
                                    exist_record.RecoveryDT = new DateTime(1970, 1, 1).AddSeconds(data.UnixTimestamp).ToLocalTime();
                                    await session.UpdateAsync(exist_record);
                                }
                            }
                            break;
                        }
                        await transaction.CommitAsync();
                    }
            }
            catch (Exception ex)
            {
                Program.logger.Error(ex, ex.Message);
            }
        }
コード例 #13
0
        private async Task OnMessageReceived(MqttApplicationMessageReceivedEventArgs arg)
        {
            var messageTypeString = arg.ApplicationMessage
                                    .UserProperties?
                                    .FirstOrDefault(p => p.Name == "messageType")?
                                    .Value;

            var responseTypeString = arg.ApplicationMessage
                                     .UserProperties?
                                     .FirstOrDefault(p => p.Name == "responseType")?
                                     .Value;

            // Only if there is a responseType specifed do we do request/response processing
            // Otherwise we treat it as a notification.

            // Notification
            if (responseTypeString == null)
            {
                var    messageType     = MessageTypeMapper(messageTypeString);
                Type[] typeArgs        = { messageType };
                var    generic         = typeof(InboundNotification <>);
                var    constructedType = generic.MakeGenericType(typeArgs);
                var    notifyObject    = Activator.CreateInstance(constructedType);

                var inboundNotification = notifyObject as IInboundNotification;
                inboundNotification.RawMessage = arg.ApplicationMessage;
                inboundNotification.PropertyBag["messageType"] = messageTypeString;

                await _mediator.Publish(notifyObject);
            }
            // Request/Response
            else
            {
                var    messageType     = MessageTypeMapper(messageTypeString);
                Type[] typeArgs        = { messageType };
                var    generic         = typeof(InboundRequest <>);
                var    constructedType = generic.MakeGenericType(typeArgs);
                var    requestObject   = Activator.CreateInstance(constructedType);

                var inboundRequest = requestObject as IInboundRequest;
                inboundRequest.RawMessage = arg.ApplicationMessage;
                inboundRequest.PropertyBag["messageType"]  = messageTypeString;
                inboundRequest.PropertyBag["responseType"] = responseTypeString;
                inboundRequest.ResponseTopic   = arg.ApplicationMessage.ResponseTopic;
                inboundRequest.CorrelationData = arg.ApplicationMessage.CorrelationData;

                var response = await _mediator.Send(requestObject) as InboundResponse;

                arg.ProcessingFailed = !response.Success;
                await Task.Run(async() => await _mqttClient.PublishAsync(builder =>
                                                                         builder
                                                                         .WithTopic(response.Topic)
                                                                         .WithPayload(response.Payload)
                                                                         .WithCorrelationData(response.CorrelationData)
                                                                         .WithUserProperty("messageType", response.MessageType)
                                                                         .WithUserProperty("payloadType", response.PayloadType)));
            }
        }
コード例 #14
0
 public static void HandleMessage(MqttApplicationMessageReceivedEventArgs args)
 {
     if (args.ApplicationMessage.Topic == Topics.CODE_CHANGE)
     {
         var json = args.ApplicationMessage.ConvertPayloadToString();
         var codeChangeMessage = Serializer.DeserializeJson <CodeChangeMessage>(json);
         NewCodeChangeFound?.Invoke(codeChangeMessage);
     }
 }
コード例 #15
0
ファイル: MainForm.cs プロジェクト: urbanoanderson/net-tools
 private void MqttClient_ApplicationMessageReceived(MqttApplicationMessageReceivedEventArgs e)
 {
     BeginInvoke(new MethodInvoker(() => {
         output.AppendText($"Topic {e.ApplicationMessage.Topic} on {DateTime.Now}:{Environment.NewLine}");
         output.AppendBinary(e.ApplicationMessage.Payload, e.ApplicationMessage.Payload.Length);
         output.AppendText(Environment.NewLine);
         output.AppendText(Environment.NewLine);
     }));
 }
コード例 #16
0
 private void OnSubscriberMessageReceived(MqttApplicationMessageReceivedEventArgs obj)
 {
     index++;
     if (IsShowInput)
     {
         Console.WriteLine($"{obj.ApplicationMessage.Topic}-{Encoding.UTF8.GetString(obj.ApplicationMessage.Payload)}-total received : {index}");
     }
     OnReceivedMessage?.Invoke(obj);
 }
コード例 #17
0
 public static void printApplicationMessageInfo(MqttApplicationMessageReceivedEventArgs e)
 {
     Console.WriteLine("### RECEIVED APPLICATION MESSAGE ###");
     Console.WriteLine($"+ Topic = {e.ApplicationMessage.Topic}");
     Console.WriteLine($"+ Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
     Console.WriteLine($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}");
     Console.WriteLine($"+ Retain = {e.ApplicationMessage.Retain}");
     Console.WriteLine();
 }
コード例 #18
0
            public Task HandleApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs eventArgs)
            {
                var items = _mqttServer.GetClientStatusAsync();

                Console.WriteLine(eventArgs.ApplicationMessage);
                Console.WriteLine(eventArgs.ClientId);
                Console.WriteLine(eventArgs.ProcessingFailed);
                return(Task.FromResult(0));
            }
コード例 #19
0
 public Task HandleApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs e)
 {
     if (e.ApplicationMessage.Payload != null)
     {
         String msg = DefaultMessageEncoding.GetString(e.ApplicationMessage.Payload);
         return(Task.Run(() => ReceivedHandler.OnReceived(msg)));
     }
     return(Task.Run(() => { }));
 }
コード例 #20
0
 /// <summary>
 /// 响应消息
 /// </summary>
 protected void Response(MqttApplicationMessageReceivedEventArgs e, byte[] buffer, MqttQualityOfServiceLevel level)
 {
     if (buffer == null)
     {
         return;
     }
     e.ApplicationMessage.Payload = buffer;
     e.ApplicationMessage.QualityOfServiceLevel = level;
 }
コード例 #21
0
 public void Visualize(MqttApplicationMessageReceivedEventArgs e)
 {
     lstv_log.Items.Add("        ----------------------      ");
     lstv_log.Items.Add("+ Topic = " + e.ApplicationMessage.Topic);
     lstv_log.Items.Add("+ Payload = " + Encoding.UTF8.GetString(e.ApplicationMessage.Payload));
     // lstv_log.Items.Add($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}");
     //lstv_log.Items.Add($"+ Retain = {e.ApplicationMessage.Retain}");
     lstv_log.Items.Add("        ----------------------      ");
 }
コード例 #22
0
ファイル: Program.cs プロジェクト: nappo95/Termostato-
        public Task HandleApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs eventArgs)
        {
            var tt = eventArgs.ApplicationMessage.Payload;

            string result = System.Text.Encoding.UTF8.GetString(tt);


            return(Task.FromResult(0));
        }
コード例 #23
0
ファイル: MessageHandler.cs プロジェクト: wesback/fluksocore
        public static async void ConsoleHandler(object sender, MqttApplicationMessageReceivedEventArgs e)
        {
            SensorData sensorData = await ParseMessage(e.ApplicationMessage.Payload, e.ApplicationMessage.Topic);

            if ((sensorData.type == "W" || sensorData.type == "L/s") && sensorData.value > 0)
            {
                Console.WriteLine($"{sensorData.Name} | {sensorData.TopicName} | {sensorData.timeStamp} - {sensorData.type} - {sensorData.value}");
            }
        }
コード例 #24
0
 private void MqttClient_ApplicationMessageReceived(object sender, MqttApplicationMessageReceivedEventArgs e)
 {
     Invoke((new Action(() =>
     {
         richTextBox_Subscribe.AppendText($">> {e.ApplicationMessage.Topic}{Environment.NewLine}");
         richTextBox_Subscribe.AppendText($">> {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}{Environment.NewLine}");
         richTextBox_Subscribe.ScrollToCaret();
     })));
 }
コード例 #25
0
        private async Task ManagedClient_ApplicationMessageReceived(MqttApplicationMessageReceivedEventArgs e)
        {
            await OnApplicationMessageReceived(e.ClientId, e.ApplicationMessage.Topic, e.ApplicationMessage.ContentType, (uint)e.ApplicationMessage.QualityOfServiceLevel, e.ApplicationMessage.Payload);

            if (ApplicationMessageReceived != null)
            {
                await ApplicationMessageReceived.Invoke(e.ClientId, e.ApplicationMessage.Topic, e.ApplicationMessage.ContentType, (uint)e.ApplicationMessage.QualityOfServiceLevel, e.ApplicationMessage.Payload);
            }
        }
コード例 #26
0
        private async void OnMessageReceived(object sender, MqttApplicationMessageReceivedEventArgs e)
        {
            var triggerData = new TriggeredFunctionData
            {
                TriggerValue = e.ApplicationMessage
            };

            await Executor.TryExecuteAsync(triggerData, CancellationToken.None);
        }
コード例 #27
0
        private static void MessageProcessor(MqttApplicationMessageReceivedEventArgs e)
        {
            Logging.WriteDebugLog("MQTT.MessageProcessor() {0}", e.ApplicationMessage.Topic);

            if (_messageHandler != null)
            {
                _messageHandler.Invoke(e.ApplicationMessage.Topic, ASCIIEncoding.ASCII.GetString(e.ApplicationMessage.Payload));
            }
        }
コード例 #28
0
        public Task HandleApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs eventArgs)
        {
            lock (_messageReceivedEventArgs)
            {
                _messageReceivedEventArgs.Add(eventArgs.ApplicationMessage);
            }

            return(PlatformAbstractionLayer.CompletedTask);
        }
コード例 #29
0
        public void Notify(MqttApplicationMessageReceivedEventArgs eventArgs)
        {
            if (eventArgs == null)
            {
                throw new ArgumentNullException(nameof(eventArgs));
            }

            _callback(eventArgs);
        }
コード例 #30
0
        private void HandleReceivedApplicationMessage(MqttApplicationMessageReceivedEventArgs x)
        {
            var item = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff")} | Topic: {x.ApplicationMessage.Topic} | QoS: {x.ApplicationMessage.QualityOfServiceLevel} | Payload: {x.ApplicationMessage.ConvertPayloadToString()} ";

            //this.BeginInvoke((MethodInvoker)delegate { txt_subscribe.AppendText(item + Environment.NewLine); });
            txt_subscribe.BeginInvoke(new Action(() => {
                txt_subscribe.AppendText(item + Environment.NewLine);
            }));
        }