Example #1
0
        static string PopulateMessagePropertiesFromMessage(string topicName, Message message)
        {
            var systemProperties = new Dictionary <string, string>();

            foreach (KeyValuePair <string, object> property in message.SystemProperties)
            {
                string propertyName;
                if (FromSystemPropertiesMap.TryGetValue(property.Key, out propertyName))
                {
                    systemProperties[propertyName] = ConvertFromSystemProperties(property.Value);
                }
            }
            string properties = UrlEncodedDictionarySerializer.Serialize(new ReadOnlyMergeDictionary <string, string>(systemProperties, message.Properties));

            string msg;

            if (properties != string.Empty)
            {
                msg = topicName.EndsWith(SegmentSeparator, StringComparison.Ordinal) ? topicName + properties + SegmentSeparator : topicName + SegmentSeparator + properties;
            }
            else
            {
                msg = topicName;
            }

            return(msg);
        }
        static string GetPropertyBag(IMessage message)
        {
            var properties = new Dictionary <string, string>(message.Properties);

            foreach (KeyValuePair <string, string> systemProperty in message.SystemProperties)
            {
                if (SystemProperties.OutgoingSystemPropertiesMap.TryGetValue(systemProperty.Key, out string onWirePropertyName))
                {
                    properties[onWirePropertyName] = systemProperty.Value;
                }
            }

            return(UrlEncodedDictionarySerializer.Serialize(properties));
        }
Example #3
0
        public async Task SendUpstreamMessage(string payload, IDictionary <string, string> propertyBag, CancellationToken stopToken)
        {
            var propertyUrlString = "";

            if (propertyBag != null)
            {
                propertyUrlString = UrlEncodedDictionarySerializer.Serialize(propertyBag);
            }
            var topic = $"devices/{upstreamClientCredentials.DeviceId}/messages/events/{propertyUrlString}";

            logger.LogInformation($"SendMessage: Topic {topic} with Payload {payload}");
            var msg = new MqttApplicationMessageBuilder()
                      .WithTopic(topic)
                      .WithPayload(payload)
                      .WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtLeastOnce) // qos = 1
                      .Build();

            await upstreamClient.PublishAsync(msg, stopToken);
        }
Example #4
0
        public async Task PublishLeafDeviceMessage(LocalDeviceMqttPublicationCategory category, string topicName, string payload, IDictionary <string, string> propertyBag, CancellationToken stopToken)
        {
            var propertyUrlString = "";

            if (propertyBag != null)
            {
                propertyUrlString = UrlEncodedDictionarySerializer.Serialize(propertyBag);
            }


            if (category == LocalDeviceMqttPublicationCategory.Twin)
            {
                // if topic name is null send to all topics
                foreach (var t in device.LocalDeviceMqttPublications.Twin)
                {
                    var t1 = t.Topic.Trim('/') + "/" + propertyUrlString;  // Ensure topic ends with a forward slash /

                    if (topicName == null)
                    {
                        // send to all topics
                        logger.LogInformation($"SendMessage: Topic {t1} with Payload {payload}");
                        var msg = new MqttApplicationMessageBuilder()
                                  .WithTopic(t1)
                                  .WithPayload(payload)
                                  .WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtLeastOnce) // qos = 1
                                  .Build();

                        await downstreamClient.PublishAsync(msg, stopToken);
                    }
                    else if (topicName == t.Name)
                    {
                        logger.LogInformation($"SendMessage: Topic {t1} with Payload {payload}");
                        var msg = new MqttApplicationMessageBuilder()
                                  .WithTopic(t1)
                                  .WithPayload(payload)
                                  .WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtLeastOnce) // qos = 1
                                  .Build();

                        await downstreamClient.PublishAsync(msg, stopToken);
                    }
                }
            }
        }
Example #5
0
        public async Task PublishMessage(IMqttClient client, string topic, string payload, IDictionary <string, string> propertyBag, CancellationToken stopToken)
        {
            var t = $"{topic.TrimEnd('/')}/";

            if (propertyBag != null)
            {
                var propertyUrlString = UrlEncodedDictionarySerializer.Serialize(propertyBag);

                t = $"{topic.TrimEnd('/')}/{propertyUrlString}";
            }

            logger.LogInformation($"SendMessage: Topic {topic} with Payload {payload}");
            var msg = new MqttApplicationMessageBuilder()
                      .WithTopic(topic)
                      .WithPayload(payload)
                      .WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtLeastOnce) // qos = 1
                      .Build();

            await client.PublishAsync(msg, stopToken);
        }
        /// <summary>
        /// This method takes an endpoint reference (<paramref name="endPointUri"/>) and an
        /// Edge Hub <see cref="IMessage"/> object (<paramref name="message"/>) and builds
        /// an MQTT topic name. The <paramref name="endPointUri"/> refers to a template endpoint
        /// name. A cloud-to-device (C2D) endpoint for example might look like this -
        /// <c>devices/{deviceId}/messages/devicebound</c> where <c>{deviceId}</c> is a place
        /// holder for the identifier of the device that is receiving the C2D message.
        /// </summary>
        public bool TryBuildProtocolAddressFromEdgeHubMessage(string endPointUri, IMessage message, IDictionary <string, string> messagePropertiesToSend, out string address)
        {
            address = null;
            if (this.outboundTemplateMap.TryGetValue(endPointUri, out UriPathTemplate template))
            {
                try
                {
                    address = template.Bind(message.SystemProperties);
                    if (!string.IsNullOrWhiteSpace(address) && messagePropertiesToSend != null && messagePropertiesToSend.Count > 0)
                    {
                        address = Invariant($"{address.TrimEnd('/')}/{UrlEncodedDictionarySerializer.Serialize(messagePropertiesToSend)}");
                    }
                }
                catch (InvalidOperationException ex)
                {
                    // An InvalidOperationException exception means that one of the required
                    // template fields was not supplied in the "properties" dictionary. We
                    // handle that by simply returning false.
                    this.logger.LogWarning($"Applying properties ${message.SystemProperties.ToLogString()} on endpoint URI {endPointUri} failed with error {ex}.");
                }
            }

            return(!string.IsNullOrEmpty(address));
        }