예제 #1
0
        private void OnMqttMessageReceived(object sender, MQTTnet.MqttApplicationMessageReceivedEventArgs e)
        {
            Console.WriteLine($"{DateTime.Now} Received MQTT message. Topic: {e.ApplicationMessage.Topic} Payload: {e.ApplicationMessage.ConvertPayloadToString()}");
            try
            {
                string   parm    = null;
                string[] tokens  = e.ApplicationMessage.Topic.Split('/');
                string   payload = e.ApplicationMessage.ConvertPayloadToString();

                if (tokens.Length != 4)
                {
                    throw new InvalidMqttTopicException();
                }

                GenericDevice device = _hub.GetDeviceByLabel <GenericDevice>(tokens[2]) as GenericDevice;
                if (!string.IsNullOrEmpty(payload))
                {
                    parm = payload;
                }

                device.DoAction(tokens[3], parm);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"{DateTime.Now} {ex}");
            }
        }
예제 #2
0
        private async void OnMqttMessageReceived(object sender, MQTTnet.MqttApplicationMessageReceivedEventArgs e)
        {
            Console.WriteLine($"{DateTime.Now} Received MQTT message. Topic: {e.ApplicationMessage.Topic} Payload: {e.ApplicationMessage.ConvertPayloadToString()}");
            using (var operation =
                       _telemetryClient.StartOperation <RequestTelemetry>($"{this.ToString()}: Message Received"))
            {
                _telemetryClient.TrackEvent("MQTT Message Received",
                                            new Dictionary <string, string>()
                {
                    { "Topic", e.ApplicationMessage.Topic },
                    { "Payload", e.ApplicationMessage.ConvertPayloadToString() },
                });
                try
                {
                    string   parm    = null;
                    string[] tokens  = e.ApplicationMessage.Topic.Split('/');
                    string   payload = e.ApplicationMessage.ConvertPayloadToString();

                    if (tokens.Length != 4)
                    {
                        throw new InvalidMqttTopicException();
                    }

                    GenericDevice device = await _hub.GetDeviceByLabel <GenericDevice>(tokens[2]);

                    if (!string.IsNullOrEmpty(payload))
                    {
                        parm = payload;
                    }

                    await device.DoAction(tokens[3], parm);
                }
                catch (Exception ex)
                {
                    operation.Telemetry.Success = false;
                    _telemetryClient.TrackException(ex);
                    Console.WriteLine($"{DateTime.Now} {ex}");
                }
            }
        }