コード例 #1
0
        private static Message CreateMessageBody(ConnectedDeviceItem connectedDeviceItem)
        {
            var eventJson      = JsonConvert.SerializeObject(connectedDeviceItem.InitialState);
            var eventJsonBytes = Encoding.UTF8.GetBytes(eventJson);
            var message        = new Message(eventJsonBytes);

            IDictionary <string, string> messageProperties = message.Properties;

            messageProperties.Add("messageType", connectedDeviceItem.MessageType);
            messageProperties.Add("correlationId", Guid.NewGuid().ToString());
            messageProperties.Add("parentCorrelationId", Guid.NewGuid().ToString());
            messageProperties.Add("createdDateTime", DateTime.UtcNow.ToString("u", DateTimeFormatInfo.InvariantInfo));
            messageProperties.Add("deviceId", connectedDeviceItem.Name);

            var properties = connectedDeviceItem.Properties;

            if (properties != null)
            {
                foreach (var property in properties)
                {
                    messageProperties.Add(property.Key, property.Value);
                }
            }

            return(message);
        }
コード例 #2
0
        public static async Task Run([EventGridTrigger] EventGridEvent eventGridEvent, TraceWriter log)
        {
            var iotHubConnectionString = Environment.GetEnvironmentVariable("IoTHubConnectionString");
            var deviceItem             = JsonConvert.DeserializeObject <DeviceItem>(eventGridEvent.Data.ToString());

            var registryManager = RegistryManager.CreateFromConnectionString(iotHubConnectionString);

            await AddDeviceAsync(registryManager, deviceItem, log);
            await UpdateTwinAsync(registryManager, deviceItem, log);

            var deviceConnectionString = await BuildConnectionStringAsync(registryManager, deviceItem, log);

            var deviceClient = DeviceClient.CreateFromConnectionString(deviceConnectionString);
            await deviceClient.OpenAsync();

            var connectedDeviceItem = new ConnectedDeviceItem(deviceItem)
            {
                DeviceConnectionString = deviceConnectionString
            };

            var sendEventGridEvent = new EventGridEvent()
            {
                Id          = Guid.NewGuid().ToString(),
                EventTime   = DateTime.UtcNow,
                Data        = JsonConvert.SerializeObject(connectedDeviceItem),
                EventType   = "sendEvent",
                Subject     = "simulation/devices/event",
                DataVersion = "1.0",
            };

            await SendEventGridEvents(new List <EventGridEvent>(1) { sendEventGridEvent });
        }