Beispiel #1
0
        public static async Task ReadTelemetry(string deviceId, CancellationToken ct)
        {
            EventHubClient   eventHubClient   = null;
            EventHubReceiver eventHubReceiver = null;
            var consumerGroup = ConfigurationManager.AppSettings["ConsumerGroup"];

            try
            {
                var ioTHubConnectionString = ConfigurationManager.AppSettings["IOTHubConnectionString"];
                eventHubClient = EventHubClient.CreateFromConnectionString(ioTHubConnectionString, "messages/events");
                //var ioTHubConnectionString =
                //    "Endpoint=sb://ihsuprodhkres004dednamespace.servicebus.windows.net/;SharedAccessKeyName=iothubowner;SharedAccessKey=Rte+iSJejSjnT4pXbdbGoRd786APJGiX/5pEkk1mAU8=";
                //eventHubClient = EventHubClient.CreateFromConnectionString(ioTHubConnectionString,
                //    "iothub-ehub-raghuhub-1063-f06377c774");
                Console.WriteLine("Receiving events...\r\n");
                var    eventHubPartitionsCount = eventHubClient.GetRuntimeInformation().PartitionCount;
                string partition = EventHubPartitionKeyResolver.ResolveToPartition(deviceId, eventHubPartitionsCount);
                eventHubReceiver = eventHubClient.GetConsumerGroup(consumerGroup).CreateReceiver(partition);

                while (!ct.IsCancellationRequested)
                {
                    EventData eventData = await eventHubReceiver.ReceiveAsync(TimeSpan.FromSeconds(10));

                    if (eventData != null)
                    {
                        Console.WriteLine("Received Message : ");
                        Console.WriteLine(Encoding.UTF8.GetString(eventData.GetBytes()));
                    }
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
            }
        }
Beispiel #2
0
        public async Task Setup(NetworkParameters parameters)
        {
            eventHubClient = EventHubClient.CreateFromConnectionString(parameters.ConnectionString, "messages/events");
            Console.WriteLine("Created client");
            var runtimeinfo = eventHubClient.GetRuntimeInformation();

            partitionsCount = runtimeinfo.PartitionCount;

            var partition = EventHubPartitionKeyResolver.ResolveToPartition(parameters.DeviceName, partitionsCount);

            Console.WriteLine("Got partition");

            if (parameters.StartTime == null)
            {
                parameters.StartTime = DateTime.Now;
            }

            eventHubReceiver = eventHubClient.GetConsumerGroup(parameters.ConsumerGroupName).CreateReceiver(partition, parameters.StartTime);
            Console.WriteLine("Created reciever");

            var pastEvents = await eventHubReceiver.ReceiveAsync(int.MaxValue, TimeSpan.FromSeconds(3));

            int cnt = 0;

            foreach (var ev in pastEvents)
            {
                cnt++;
            }
            Console.WriteLine("Got {0} events from past", cnt);
        }
        private async Task <PartitionReceiver> CreateEventHubReceiver(string deviceName)
        {
            PartitionReceiver eventHubReceiver = null;
            Stopwatch         sw = new Stopwatch();

            sw.Start();

            var builder = new EventHubsConnectionStringBuilder(Configuration.IoTHub.EventHubString)
            {
                EntityPath = Configuration.IoTHub.EventHubCompatibleName
            };

            EventHubClient eventHubClient          = EventHubClient.CreateFromConnectionString(builder.ToString());
            var            eventRuntimeInformation = await eventHubClient.GetRuntimeInformationAsync().ConfigureAwait(false);

            var    eventHubPartitionsCount = eventRuntimeInformation.PartitionCount;
            string partition         = EventHubPartitionKeyResolver.ResolveToPartition(deviceName, eventHubPartitionsCount);
            string consumerGroupName = Configuration.IoTHub.EventHubConsumerGroup;

            while (eventHubReceiver == null && sw.Elapsed.Minutes < 1)
            {
                try
                {
                    eventHubReceiver = eventHubClient.CreateReceiver(consumerGroupName, partition, DateTime.Now.AddMinutes(-5));
                }
                catch (QuotaExceededException ex)
                {
                    Debug.WriteLine(ex);
                }
            }

            sw.Stop();

            return(eventHubReceiver);
        }
        private EventHubReceiver CreateEventHubReceiver(string deviceName, out EventHubClient eventHubClient)
        {
            EventHubReceiver eventHubReceiver = null;
            Stopwatch        sw = new Stopwatch();

            sw.Start();

            eventHubClient = EventHubClient.CreateFromConnectionString(hubConnectionString, "messages/events");
            var    eventHubPartitionsCount = eventHubClient.GetRuntimeInformation().PartitionCount;
            string partition         = EventHubPartitionKeyResolver.ResolveToPartition(deviceName, eventHubPartitionsCount);
            string consumerGroupName = Environment.GetEnvironmentVariable("IOTHUB_EVENTHUB_CONSUMER_GROUP") ?? "$Default";

            while (eventHubReceiver == null && sw.Elapsed.Minutes < 1)
            {
                try
                {
                    eventHubReceiver = eventHubClient.GetConsumerGroup(consumerGroupName).CreateReceiver(partition, DateTime.Now);
                }
                catch (QuotaExceededException ex)
                {
                }
            }

            sw.Stop();

            return(eventHubReceiver);
        }
        public static async Task <EventHubTestListener> CreateListenerPal(string deviceName)
        {
            PartitionReceiver receiver = null;
            Stopwatch         sw       = new Stopwatch();

            sw.Start();

            var builder = new EventHubsConnectionStringBuilder(Configuration.IoTHub.EventHubString)
            {
                EntityPath = Configuration.IoTHub.EventHubCompatibleName
            };

            EventHubClient eventHubClient          = EventHubClient.CreateFromConnectionString(builder.ToString());
            var            eventRuntimeInformation = await eventHubClient.GetRuntimeInformationAsync().ConfigureAwait(false);

            var    eventHubPartitionsCount = eventRuntimeInformation.PartitionCount;
            string partition         = EventHubPartitionKeyResolver.ResolveToPartition(deviceName, eventHubPartitionsCount);
            string consumerGroupName = Configuration.IoTHub.EventHubConsumerGroup;

            while (receiver == null && sw.Elapsed.TotalMinutes < MaximumWaitTimeInMinutes)
            {
                try
                {
                    receiver = eventHubClient.CreateReceiver(consumerGroupName, partition, DateTime.Now.AddMinutes(-5));
                }
                catch (QuotaExceededException ex)
                {
                    s_log.WriteLine($"{nameof(EventHubTestListener)}.{nameof(CreateListener)}: Cannot create receiver: {ex}");
                }
            }

            sw.Stop();

            return(new EventHubTestListener(receiver));
        }
        public static Task <EventHubTestListener> CreateListenerPal(string deviceName)
        {
            EventHubReceiver receiver = null;
            Stopwatch        sw       = new Stopwatch();

            sw.Start();

            EventHubClient eventHubClient          = EventHubClient.CreateFromConnectionString(Configuration.IoTHub.ConnectionString, "messages/events");
            var            eventHubPartitionsCount = eventHubClient.GetRuntimeInformation().PartitionCount;
            string         partition         = EventHubPartitionKeyResolver.ResolveToPartition(deviceName, eventHubPartitionsCount);
            string         consumerGroupName = Configuration.IoTHub.EventHubConsumerGroup;

            while (receiver == null && sw.Elapsed.TotalMinutes < MaximumWaitTimeInMinutes)
            {
                try
                {
                    receiver = eventHubClient.GetConsumerGroup(consumerGroupName).CreateReceiver(partition, DateTime.Now.AddMinutes(-LookbackTimeInMinutes));
                }
                catch (QuotaExceededException ex)
                {
                    s_log.WriteLine($"{nameof(EventHubTestListener)}.{nameof(CreateListener)}: Cannot create receiver: {ex}");
                }
            }

            sw.Stop();

            return(Task.FromResult(new EventHubTestListener(receiver)));
        }
        private EventHubReceiver CreateEventHubReceiver(string deviceName, out EventHubClient eventHubClient)
        {
            EventHubReceiver eventHubReceiver = null;
            Stopwatch        sw = new Stopwatch();

            sw.Start();

            eventHubClient = EventHubClient.CreateFromConnectionString(Configuration.IoTHub.ConnectionString, "messages/events");
            var    eventHubPartitionsCount = eventHubClient.GetRuntimeInformation().PartitionCount;
            string partition         = EventHubPartitionKeyResolver.ResolveToPartition(deviceName, eventHubPartitionsCount);
            string consumerGroupName = Configuration.IoTHub.EventHubConsumerGroup;

            while (eventHubReceiver == null && sw.Elapsed.Minutes < 1)
            {
                try
                {
                    eventHubReceiver = eventHubClient.GetConsumerGroup(consumerGroupName).CreateReceiver(partition, DateTime.Now, FaultInjection.EventHubEpoch++);
                }
                catch (QuotaExceededException ex)
                {
                    Debug.WriteLine(ex);
                }
            }

            sw.Stop();

            return(eventHubReceiver);
        }
Beispiel #8
0
        public async Task <List <EventData> > GetMessagesForDevice(string deviceId, DateTime startTime, int maxPerPartition = 100, int waitTimeSecs = 5)
        {
            var messages = new List <EventData>();

            EventHubClient    eventHubClient    = EventHubClient.CreateFromConnectionString(this.eventHubConnectionString);
            PartitionReceiver partitionReceiver = eventHubClient.CreateReceiver(
                EventHubConsumerGroup,
                EventHubPartitionKeyResolver.ResolveToPartition(deviceId, (await eventHubClient.GetRuntimeInformationAsync()).PartitionCount),
                EventPosition.FromEnqueuedTime(startTime));

            // Retry a few times due to weird behavior with ReceiveAsync() not returning all messages available
            for (int i = 0; i < 3; i++)
            {
                IEnumerable <EventData> events = await partitionReceiver.ReceiveAsync(maxPerPartition, TimeSpan.FromSeconds(waitTimeSecs));

                if (events != null)
                {
                    messages.AddRange(events);
                }

                if (i < 3)
                {
                    await Task.Delay(TimeSpan.FromSeconds(5));
                }
            }

            await partitionReceiver.CloseAsync();

            await eventHubClient.CloseAsync();

            return(messages);
        }
Beispiel #9
0
        private async void MonitorEventHubAsync(DateTime startTime, CancellationToken ct, string consumerGroupName)
        {
            EventHubClient   eventHubClient   = null;
            EventHubReceiver eventHubReceiver = null;

            try
            {
                eventHubClient          = EventHubClient.CreateFromConnectionString(activeIoTHubConnectionString, "messages/events");
                eventHubTextBox.Text    = String.Format("Receiving events...\r\n");
                eventHubPartitionsCount = eventHubClient.GetRuntimeInformation().PartitionCount;
                string partition = EventHubPartitionKeyResolver.ResolveToPartition(deviceIDsComboBoxForEvent.SelectedItem.ToString(), eventHubPartitionsCount);
                eventHubReceiver = eventHubClient.GetConsumerGroup(consumerGroupName).CreateReceiver(partition, startTime);

                while (true)
                {
                    ct.ThrowIfCancellationRequested();

                    EventData eventData = await eventHubReceiver.ReceiveAsync(TimeSpan.FromSeconds(1));

                    if (eventData != null)
                    {
                        string   data         = Encoding.UTF8.GetString(eventData.GetBytes());
                        DateTime enqueuedTime = eventData.EnqueuedTimeUtc.ToLocalTime();
                        eventHubTextBox.Text += String.Format("{0}> Data:[{1}]", enqueuedTime, data);
                        if (eventData.Properties.Count > 0)
                        {
                            eventHubTextBox.Text += "Properties:\r\n";
                            foreach (var property in eventData.Properties)
                            {
                                eventHubTextBox.Text += String.Format("'{0}': '{1}'\r\n", property.Key, property.Value);
                            }
                        }
                        eventHubTextBox.Text += "\r\n";
                    }
                }
            }
            catch (Exception ex)
            {
                if (ct.IsCancellationRequested)
                {
                    eventHubTextBox.Text += String.Format("Stopped Monitoring events. {0}\r\n", ex.Message);
                }
                else
                {
                    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    eventHubTextBox.Text += String.Format("Stopped Monitoring events. {0}\r\n", ex.Message);
                }
                if (eventHubReceiver != null)
                {
                    eventHubReceiver.Close();
                }
                if (eventHubClient != null)
                {
                    eventHubClient.Close();
                }
                dataMonitorButton.Enabled         = true;
                deviceIDsComboBoxForEvent.Enabled = true;
                cancelMonitoringButton.Enabled    = false;
            }
        }
Beispiel #10
0
        async public Task <string> Get(string id)
        {
            var iot = new MessageHub();
            CancellationTokenSource tokenSource = new CancellationTokenSource();
            CancellationToken       token       = tokenSource.Token;
            var context = GlobalHost.ConnectionManager.GetHubContext <MessageHub>();

            string partition        = EventHubPartitionKeyResolver.ResolveToPartition("testDevice180221", eventHubPartitionsCount);
            var    eventHubReceiver = eventHubClient.GetConsumerGroup(consumerGroupName).CreateReceiver(partition, DateTime.UtcNow);

            while (true)
            {
                var eventData = await eventHubReceiver.ReceiveAsync(TimeSpan.FromSeconds(1));

                if (eventData != null)
                {
                    var data         = Encoding.UTF8.GetString(eventData.GetBytes());
                    var enqueuedTime = eventData.EnqueuedTimeUtc.ToLocalTime();

                    // Display only data from the selected device; otherwise, skip.
                    var connectionDeviceId = eventData.SystemProperties["iothub-connection-device-id"].ToString();

                    if (string.CompareOrdinal("testDevice180221", connectionDeviceId) == 0)
                    {
                        context.Clients.Client(id).broadcastMessage(enqueuedTime.ToShortDateString(), connectionDeviceId, data);
                        //context.Clients.Client.Send(enqueuedTime.ToShortDateString(), connectionDeviceId, data);
                    }
                }
            }


            return("");
        }
Beispiel #11
0
        protected async Task VerifyDataOnIoTHub(string moduleId)
        {
            Console.WriteLine($"Verifying data on IoTHub from {moduleId}");

            // First Verify if module is already running.
            await this.bootstrapper.VerifyModuleIsRunning(moduleId);

            var builder = new EventHubsConnectionStringBuilder(this.eventhubCompatibleEndpointWithEntityPath)
            {
                TransportType = this.eventHubClientTransportType
            };

            Console.WriteLine($"Receiving events from device '{this.context.DeviceId}' on Event Hub '{builder.EntityPath}'");

            EventHubClient eventHubClient =
                EventHubClient.CreateFromConnectionString(builder.ToString());

            this.proxy.ForEach(p => eventHubClient.WebProxy = p);

            PartitionReceiver eventHubReceiver = eventHubClient.CreateReceiver(
                "$Default",
                EventHubPartitionKeyResolver.ResolveToPartition(
                    this.context.DeviceId,
                    (await eventHubClient.GetRuntimeInformationAsync()).PartitionCount),
                EventPosition.FromEnd());

            // TODO: [Improvement] should verify test results without using event hub, which introduce latency.
            var result = new TaskCompletionSource <bool>();

            using (var cts = new CancellationTokenSource(TimeSpan.FromMinutes(20))) // This long timeout is needed in case event hub is slow to process messages
            {
                using (cts.Token.Register(() => result.TrySetCanceled()))
                {
                    eventHubReceiver.SetReceiveHandler(
                        new PartitionReceiveHandler(
                            eventData =>
                    {
                        eventData.SystemProperties.TryGetValue("iothub-connection-device-id", out object devId);
                        eventData.SystemProperties.TryGetValue("iothub-connection-module-id", out object modId);

                        if (devId != null && devId.ToString().Equals(this.context.DeviceId) &&
                            modId != null && modId.ToString().Equals(moduleId))
                        {
                            result.TrySetResult(true);
                            return(true);
                        }

                        return(false);
                    }));

                    await result.Task;
                }
            }

            Console.WriteLine("VerifyDataOnIoTHub completed.");
            await eventHubReceiver.CloseAsync();

            await eventHubClient.CloseAsync();
        }
 private async Task<EventHubReceiver> CreateEventHubReceiver(string deviceName)
 {
     EventHubClient eventHubClient = EventHubClient.CreateFromConnectionString(hubConnectionString, "messages/events");
     var eventHubPartitions = await eventHubClient.GetRuntimeInformationAsync();
     var eventHubPartitionsCount = eventHubPartitions.PartitionCount;
     string partition = EventHubPartitionKeyResolver.ResolveToPartition(deviceName, eventHubPartitionsCount);
     string consumerGroupName = Configuration.IoTHub.ConsumerGroup;
     return eventHubClient.GetConsumerGroup(consumerGroupName).CreateReceiver(partition, DateTime.Now, TestUtil.EventHubEpoch++);
 }
Beispiel #13
0
        private EventHubReceiver CreateEventHubReceiver(string deviceName, out EventHubClient eventHubClient)
        {
            eventHubClient = EventHubClient.CreateFromConnectionString(hubConnectionString, "messages/events");
            var    eventHubPartitionsCount = eventHubClient.GetRuntimeInformation().PartitionCount;
            string partition         = EventHubPartitionKeyResolver.ResolveToPartition(deviceName, eventHubPartitionsCount);
            string consumerGroupName = Environment.GetEnvironmentVariable("IOTHUB_EVENTHUB_CONSUMER_GROUP") ?? "$Default";

            return(eventHubClient.GetConsumerGroup(consumerGroupName).CreateReceiver(partition, DateTime.Now));
        }
Beispiel #14
0
        protected async Task VerifyDataOnIoTHubAsync()
        {
            // Leaf device without parent not expected to send messages
            if (!this.edgeDeviceId.HasValue)
            {
                return;
            }

            var builder = new EventHubsConnectionStringBuilder(this.eventhubCompatibleEndpointWithEntityPath)
            {
                TransportType = this.eventHubClientTransportType
            };

            Console.WriteLine($"Receiving events from device '{this.context.Device.Id}' on Event Hub '{builder.EntityPath}'");

            EventHubClient eventHubClient =
                EventHubClient.CreateFromConnectionString(builder.ToString());

            this.proxy.ForEach(p => eventHubClient.WebProxy = p);

            PartitionReceiver eventHubReceiver = eventHubClient.CreateReceiver(
                "$Default",
                EventHubPartitionKeyResolver.ResolveToPartition(
                    this.context.Device.Id,
                    (await eventHubClient.GetRuntimeInformationAsync()).PartitionCount),
                EventPosition.FromEnqueuedTime(DateTime.Now.AddMinutes(-5)));

            var result = new TaskCompletionSource <bool>();

            using (var cts = new CancellationTokenSource(TimeSpan.FromMinutes(3)))
            {
                using (cts.Token.Register(() => result.TrySetCanceled()))
                {
                    eventHubReceiver.SetReceiveHandler(
                        new PartitionReceiveHandler(
                            eventData =>
                    {
                        eventData.SystemProperties.TryGetValue("iothub-connection-device-id", out var devId);

                        if (devId != null && devId.ToString().Equals(this.context.Device.Id, StringComparison.Ordinal) &&
                            Encoding.UTF8.GetString(eventData.Body).Contains(this.context.MessageGuid, StringComparison.Ordinal))
                        {
                            result.TrySetResult(true);
                            return(true);
                        }

                        return(false);
                    }));

                    await result.Task;
                }
            }

            await eventHubReceiver.CloseAsync();

            await eventHubClient.CloseAsync();
        }
Beispiel #15
0
        private async void MonitorEventHubAsync(DateTime startTime, CancellationToken ct, string consumerGroupName)
        {
            EventHubClient   eventHubClient   = null;
            EventHubReceiver eventHubReceiver = null;

            try
            {
                eventHubClient = EventHubClient.CreateFromConnectionString(activeIoTHubConnectionString, "messages/events");
                int    eventHubPartitionsCount = eventHubClient.GetRuntimeInformation().PartitionCount;
                string partition = EventHubPartitionKeyResolver.ResolveToPartition(deviceID, eventHubPartitionsCount);
                eventHubReceiver = eventHubClient.GetConsumerGroup(consumerGroupName).CreateReceiver(partition, startTime);

                //receive the events from startTime until current time in a single call and process them
                var events = await eventHubReceiver.ReceiveAsync(int.MaxValue, TimeSpan.FromSeconds(20));

                foreach (var eventData in events)
                {
                    byte[] rxbuff = eventData.GetBytes();
                    makeCommDataForLogData("Rx", rxbuff);
                }

                //having already received past events, monitor current events in a loop
                while (true)
                {
                    ct.ThrowIfCancellationRequested();

                    var eventData = await eventHubReceiver.ReceiveAsync(TimeSpan.FromSeconds(0.5));

                    if (eventData != null)
                    {
                        byte[] rxbuff = eventData.GetBytes();
                        makeCommDataForLogData("Rx", rxbuff);
                    }
                }
            }
            catch (Exception ex)
            {
                if (ct.IsCancellationRequested)
                {
                    //Stopped Monitoring events by user action.
                }
                else
                {
                    //Something happen.
                }

                if (eventHubReceiver != null)
                {
                    eventHubReceiver.Close();
                }
                if (eventHubClient != null)
                {
                    eventHubClient.Close();
                }
            }
        }
        private async Task <PartitionReceiver> CreateEventHubReceiver(string deviceName)
        {
            string         endpoint        = Configuration.IoTHub.EventHubString;
            EventHubClient eventHubClient  = EventHubClient.CreateFromConnectionString(endpoint);
            var            eventHubRuntime = await eventHubClient.GetRuntimeInformationAsync().ConfigureAwait(false);

            var    eventHubPartitionsCount = eventHubRuntime.PartitionCount;
            string partition         = EventHubPartitionKeyResolver.ResolveToPartition(deviceName, eventHubPartitionsCount);
            string consumerGroupName = Configuration.IoTHub.ConsumerGroup;

            return(eventHubClient.CreateReceiver(consumerGroupName, partition, DateTime.Now.AddMinutes(-5)));
        }
Beispiel #17
0
        protected async Task VerifyDataOnIoTHub(string moduleId)
        {
            var builder = new EventHubsConnectionStringBuilder(this.eventhubCompatibleEndpointWithEntityPath);

            builder.TransportType = this.eventHubClientTransportType;

            Console.WriteLine($"Receiving events from device '{this.context.Device.Id}' on Event Hub '{builder.EntityPath}'");

            EventHubClient eventHubClient =
                EventHubClient.CreateFromConnectionString(builder.ToString());

            PartitionReceiver eventHubReceiver = eventHubClient.CreateReceiver(
                "$Default",
                EventHubPartitionKeyResolver.ResolveToPartition(
                    this.context.Device.Id,
                    (await eventHubClient.GetRuntimeInformationAsync()).PartitionCount),
                EventPosition.FromEnd());

            var result = new TaskCompletionSource <bool>();

            using (var cts = new CancellationTokenSource(TimeSpan.FromMinutes(10)))
            {
                using (cts.Token.Register(() => result.TrySetCanceled()))
                {
                    eventHubReceiver.SetReceiveHandler(
                        new PartitionReceiveHandler(
                            eventData =>
                    {
                        eventData.SystemProperties.TryGetValue("iothub-connection-device-id", out object devId);
                        eventData.SystemProperties.TryGetValue("iothub-connection-module-id", out object modId);

                        if (devId != null && devId.ToString().Equals(this.context.Device.Id) &&
                            modId != null && modId.ToString().Equals(moduleId))
                        {
                            result.TrySetResult(true);
                            return(true);
                        }

                        return(false);
                    }));

                    await result.Task;
                }
            }

            Console.WriteLine("VerifyDataOnIoTHub completed.");
            await eventHubReceiver.CloseAsync();

            await eventHubClient.CloseAsync();
        }
Beispiel #18
0
        private static async Task ReceiveFromIothubAsync()
        {
            eventHubClient = EventHubClient.CreateFromConnectionString(connectionString, iotHubD2cEndpoint);
            var    eventHubPartitionsCount = eventHubClient.GetRuntimeInformation().PartitionCount;
            string partition        = EventHubPartitionKeyResolver.ResolveToPartition("123", eventHubPartitionsCount);
            var    eventHubReceiver = eventHubClient.GetDefaultConsumerGroup().CreateReceiver(partition, DateTime.UtcNow);

            EventData eventData = await eventHubReceiver.ReceiveAsync();

            string data = Encoding.UTF8.GetString(eventData.GetBytes());

            Console.WriteLine("Message received. Partition: {0} Data: '{1}'", partition, data);
            Console.ReadLine();
        }
        static void Main(string[] args)
        {
            Console.WriteLine("Usage: \r\n" +
                              "ConsoleMonitor <iotHubOwner> [<consumerGroup>] [<device>] ");
            string connection = args[0];

            string consumerGroupName = "$Default";

            if (args.Length > 1)
            {
                consumerGroupName = args[1];
            }
            string deviceName = "";

            if (args.Length > 2)
            {
                deviceName = args[2];
            }
            EventHubClient   eventHubClient   = null;
            EventHubReceiver eventHubReceiver = null;

            eventHubClient = EventHubClient.CreateFromConnectionString(connection, "messages/events");
            var ri = eventHubClient.GetRuntimeInformation();

            if (deviceName != "")
            {
                string partition = EventHubPartitionKeyResolver.ResolveToPartition(deviceName, ri.PartitionCount);
                eventHubReceiver = eventHubClient.GetConsumerGroup(consumerGroupName).
                                   CreateReceiver(partition, DateTime.Now);
                Task.Run(() => EventLoopAsync(eventHubReceiver));
            }
            else
            {
                EventHubReceiver[] eventHubReceivers = new EventHubReceiver[ri.PartitionCount];


                int i = 0;
                foreach (var partition in ri.PartitionIds)
                {
                    eventHubReceivers[i] = eventHubClient.GetConsumerGroup(consumerGroupName).CreateReceiver(partition, DateTime.Now);
                    //Task.Run(() => eventLoop(eventHubReceivers[i])); <- very common bug!
                    var r = eventHubReceivers[i];
                    Task.Run(() => EventLoopAsync(r));
                    i++;
                }
            }
            Console.ReadLine();
        }
Beispiel #20
0
        static async Task ReceiveMessagesAsync(DateTime lastReceivedMesssage)
        {
            var builder = new EventHubsConnectionStringBuilder(Settings.Current.EventHubConnectionString);

            Logger.LogInformation($"Receiving events from device '{Settings.Current.DeviceId}' on Event Hub '{builder.EntityPath}' with last received message at {lastReceivedMesssage.ToString()}");

            EventHubClient eventHubClient =
                EventHubClient.CreateFromConnectionString(builder.ToString());

            PartitionReceiver eventHubReceiver = eventHubClient.CreateReceiver(
                Settings.Current.ConsumerGroupId,
                EventHubPartitionKeyResolver.ResolveToPartition(Settings.Current.DeviceId, (await eventHubClient.GetRuntimeInformationAsync()).PartitionCount),
                EventPosition.FromEnqueuedTime(lastReceivedMesssage == DateTime.MinValue ? DateTime.UtcNow : lastReceivedMesssage));

            eventHubReceiver.SetReceiveHandler(new PartitionReceiveHandler(Settings.Current.DeviceId, Settings.Current.ExcludedModuleIds));
        }
Beispiel #21
0
        static async Task ReceiveMessages()
        {
            var builder = new EventHubsConnectionStringBuilder(Settings.Current.EventHubConnectionString);

            Log.LogInformation($"Receiving events from device '{Settings.Current.DeviceId}' on Event Hub '{builder.EntityPath}'");

            EventHubClient eventHubClient =
                EventHubClient.CreateFromConnectionString(builder.ToString());

            PartitionReceiver eventHubReceiver = eventHubClient.CreateReceiver(
                "$Default",
                EventHubPartitionKeyResolver.ResolveToPartition(Settings.Current.DeviceId, (await eventHubClient.GetRuntimeInformationAsync()).PartitionCount),
                EventPosition.FromEnqueuedTime(DateTime.UtcNow));

            eventHubReceiver.SetReceiveHandler(new PartitionReceiveHandler(Settings.Current.DeviceId, Settings.Current.ExcludedModuleIds));
        }
Beispiel #22
0
        async Task sendSingleMessage(Client.TransportType transport)
        {
            Tuple <string, string> deviceInfo     = TestUtil.CreateDevice("E2E_Message_CSharp_", hostName, registryManager);
            EventHubClient         eventHubClient = EventHubClient.CreateFromConnectionString(hubConnectionString, "messages/events");
            var    eventHubPartitionsCount        = eventHubClient.GetRuntimeInformation().PartitionCount;
            string partition         = EventHubPartitionKeyResolver.ResolveToPartition(deviceInfo.Item1, eventHubPartitionsCount);
            string consumerGroupName = Environment.GetEnvironmentVariable("IOTHUB_EVENTHUB_CONSUMER_GROUP");

            if (consumerGroupName == null)
            {
                consumerGroupName = "$Default";
            }
            EventHubReceiver eventHubReceiver = eventHubClient.GetConsumerGroup(consumerGroupName).CreateReceiver(partition, DateTime.Now);

            var deviceClient = DeviceClient.CreateFromConnectionString(deviceInfo.Item2, transport);
            await deviceClient.OpenAsync();

            string dataBuffer    = Guid.NewGuid().ToString();
            string propertyName  = "property1";
            string propertyValue = Guid.NewGuid().ToString();

            Client.Message eventMessage = new Client.Message(Encoding.UTF8.GetBytes(dataBuffer));
            eventMessage.Properties[propertyName] = propertyValue;
            await deviceClient.SendEventAsync(eventMessage);

            var events = await eventHubReceiver.ReceiveAsync(int.MaxValue, TimeSpan.FromSeconds(5));

            foreach (var eventData in events)
            {
                var data = Encoding.UTF8.GetString(eventData.GetBytes());
                Assert.AreEqual(data, dataBuffer);

                var connectionDeviceId = eventData.SystemProperties["iothub-connection-device-id"].ToString();
                Assert.AreEqual(connectionDeviceId.ToUpper(), deviceInfo.Item1.ToUpper());

                Assert.AreEqual(eventData.Properties.Count, 1);
                var property = eventData.Properties.Single();
                Assert.AreEqual(property.Key, propertyName);
                Assert.AreEqual(property.Value, propertyValue);
            }

            await deviceClient.CloseAsync();

            await eventHubClient.CloseAsync();

            TestUtil.RemoveDevice(deviceInfo.Item1, registryManager);
        }
Beispiel #23
0
        private async Task <PartitionReceiver> CreateEventHubReceiver(string deviceName)
        {
            var builder = new EventHubsConnectionStringBuilder(Configuration.IoTHub.EventHubString)
            {
                EntityPath = Configuration.IoTHub.EventHubCompatibleName
            };

            EventHubClient eventHubClient = EventHubClient.CreateFromConnectionString(builder.ToString());

            var eventHubRuntime = await eventHubClient.GetRuntimeInformationAsync().ConfigureAwait(false);

            var    eventHubPartitionsCount = eventHubRuntime.PartitionCount;
            string partition         = EventHubPartitionKeyResolver.ResolveToPartition(deviceName, eventHubPartitionsCount);
            string consumerGroupName = Configuration.IoTHub.EventHubConsumerGroup;

            return(eventHubClient.CreateReceiver(consumerGroupName, partition, DateTime.Now.AddMinutes(-5)));
        }
Beispiel #24
0
        protected async Task VerifyDataOnIoTHub()
        {
            var builder = new EventHubsConnectionStringBuilder(this.eventhubCompatibleEndpointWithEntityPath);

            Console.WriteLine($"Receiving events from device '{this.context.Device.Id}' on Event Hub '{builder.EntityPath}'");

            EventHubClient eventHubClient =
                EventHubClient.CreateFromConnectionString(builder.ToString());

            PartitionReceiver eventHubReceiver = eventHubClient.CreateReceiver(
                "$Default",
                EventHubPartitionKeyResolver.ResolveToPartition(
                    this.context.Device.Id,
                    (await eventHubClient.GetRuntimeInformationAsync()).PartitionCount),
                DateTime.Now.AddMinutes(-5));

            var result = new TaskCompletionSource <bool>();

            using (var cts = new CancellationTokenSource(TimeSpan.FromMinutes(3)))
            {
                using (cts.Token.Register(() => result.TrySetCanceled()))
                {
                    eventHubReceiver.SetReceiveHandler(
                        new PartitionReceiveHandler(
                            eventData =>
                    {
                        eventData.Properties.TryGetValue("iothub-connection-device-id", out object devId);

                        if (devId != null && devId.ToString().Equals(this.context.Device.Id) &&
                            Encoding.UTF8.GetString(eventData.Body).Contains(this.context.MessageGuid))
                        {
                            result.TrySetResult(true);
                            return(true);
                        }

                        return(false);
                    }));

                    await result.Task;
                }
            }

            await eventHubReceiver.CloseAsync();

            await eventHubClient.CloseAsync();
        }
Beispiel #25
0
        protected override async Task ExecuteAsync(CancellationToken cancellationToken)
        {
            this.logger.LogInformation("Test Result Event Receiving Service running.");

            DateTime eventEnqueuedFrom = DateTime.UtcNow;
            var      builder           = new EventHubsConnectionStringBuilder(Settings.Current.EventHubConnectionString);

            this.logger.LogDebug($"Receiving events from device '{Settings.Current.DeviceId}' on Event Hub '{builder.EntityPath}' enqueued on or after {eventEnqueuedFrom}");

            EventHubClient    eventHubClient   = EventHubClient.CreateFromConnectionString(builder.ToString());
            PartitionReceiver eventHubReceiver = eventHubClient.CreateReceiver(
                Settings.Current.ConsumerGroupName,
                EventHubPartitionKeyResolver.ResolveToPartition(Settings.Current.DeviceId, (await eventHubClient.GetRuntimeInformationAsync()).PartitionCount),
                EventPosition.FromEnqueuedTime(eventEnqueuedFrom));

            eventHubReceiver.SetReceiveHandler(new PartitionReceiveHandler(Settings.Current.TrackingId, Settings.Current.DeviceId, this.storage));

            await cancellationToken.WhenCanceled();

            this.logger.LogInformation($"Finish ExecuteAsync method in {nameof(TestResultEventReceivingService)}");
        }
Beispiel #26
0
        static void Main(string[] args)
        {
            string           connection        = ConfigurationManager.AppSettings["ServiceConnection"];
            string           consumerGroupName = "$Default";
            string           deviceName        = "PC";
            EventHubClient   eventHubClient    = null;
            EventHubReceiver eventHubReceiver  = null;

            eventHubClient = EventHubClient.CreateFromConnectionString(connection, "messages/events");
            var ri = eventHubClient.GetRuntimeInformation();

            if (deviceName != "")
            {
                string partition = EventHubPartitionKeyResolver.ResolveToPartition(deviceName, ri.PartitionCount);
                eventHubReceiver = eventHubClient.GetConsumerGroup(consumerGroupName).
                                   CreateReceiver(partition, DateTime.Now);
                Console.WriteLine($"{deviceName} - {partition}");
                Task.Run(() => EventLoopAsync(eventHubReceiver));
            }
            else
            {
                EventHubReceiver[] eventHubReceivers = new EventHubReceiver[ri.PartitionCount];
                Console.WriteLine($"PartitionCount: {ri.PartitionCount}");

                int i = 0;
                foreach (var partition in ri.PartitionIds)
                {
                    Console.WriteLine($"PartitionID: {partition}");
                    eventHubReceivers[i] = eventHubClient.GetConsumerGroup(consumerGroupName).CreateReceiver(partition, DateTime.Now);
                    //Task.Run(() => eventLoop(eventHubReceivers[i])); <- very common bug!
                    var r = eventHubReceivers[i];
                    Task.Run(() => EventLoopAsync(r));
                    i++;
                }
            }
            Console.ReadLine();
        }
Beispiel #27
0
        public async Task Iot()
        {
            string partition        = EventHubPartitionKeyResolver.ResolveToPartition("testDevice180221", eventHubPartitionsCount);
            var    eventHubReceiver = eventHubClient.GetConsumerGroup(consumerGroupName).CreateReceiver(partition, DateTime.UtcNow);

            while (true)
            {
                var eventData = await eventHubReceiver.ReceiveAsync(TimeSpan.FromSeconds(1));

                if (eventData != null)
                {
                    var data         = Encoding.UTF8.GetString(eventData.GetBytes());
                    var enqueuedTime = eventData.EnqueuedTimeUtc.ToLocalTime();

                    // Display only data from the selected device; otherwise, skip.
                    var connectionDeviceId = eventData.SystemProperties["iothub-connection-device-id"].ToString();

                    if (string.CompareOrdinal("testDevice180221", connectionDeviceId) == 0)
                    {
                        Send(enqueuedTime.ToShortDateString(), connectionDeviceId, data);
                    }
                }
            }
        }
Beispiel #28
0
        static void Main(string[] args)
        {
            string           connection        = "HostName=pltkdpepliot2016S1.azure-devices.net;SharedAccessKeyName=service;SharedAccessKey=Q2Lib3zRmGtHYWJMogofGWbhwrBCpGmemnTvXOWj+qE=";
            string           consumerGroupName = "$Default";
            string           deviceName        = "";
            EventHubClient   eventHubClient    = null;
            EventHubReceiver eventHubReceiver  = null;

            eventHubClient = EventHubClient.CreateFromConnectionString(connection, "messages/events");
            var ri = eventHubClient.GetRuntimeInformation();

            if (deviceName != "")
            {
                string partition = EventHubPartitionKeyResolver.ResolveToPartition(deviceName, ri.PartitionCount);
                eventHubReceiver = eventHubClient.GetConsumerGroup(consumerGroupName).
                                   CreateReceiver(partition, DateTime.Now);
                Task.Run(() => EventLoopAsync(eventHubReceiver));
            }
            else
            {
                EventHubReceiver[] eventHubReceivers = new EventHubReceiver[ri.PartitionCount];
                Console.WriteLine($"PartitionCount: {ri.PartitionCount}");

                int i = 0;
                foreach (var partition in ri.PartitionIds)
                {
                    Console.WriteLine($"PartitionID: {partition}");
                    eventHubReceivers[i] = eventHubClient.GetConsumerGroup(consumerGroupName).CreateReceiver(partition, DateTime.Now);
                    //Task.Run(() => eventLoop(eventHubReceivers[i])); <- very common bug!
                    var r = eventHubReceivers[i];
                    Task.Run(() => EventLoopAsync(r));
                    i++;
                }
            }
            Console.ReadLine();
        }
Beispiel #29
0
        private async void MonitorEventHubAsync(DateTime startTime, CancellationToken ct, string consumerGroupName)
        {
            EventHubClient   eventHubClient   = null;
            EventHubReceiver eventHubReceiver = null;

            try
            {
                string selectedDevice = deviceIDsComboBoxForEvent.SelectedItem.ToString();
                eventHubClient          = EventHubClient.CreateFromConnectionString(activeIoTHubConnectionString, "messages/events");
                eventHubTextBox.Text    = "Receiving events...\r\n";
                eventHubPartitionsCount = eventHubClient.GetRuntimeInformation().PartitionCount;
                string partition = EventHubPartitionKeyResolver.ResolveToPartition(selectedDevice, eventHubPartitionsCount);
                eventHubReceiver = eventHubClient.GetConsumerGroup(consumerGroupName).CreateReceiver(partition, startTime);

                //receive the events from startTime until current time in a single call and process them
                var events = await eventHubReceiver.ReceiveAsync(int.MaxValue, TimeSpan.FromSeconds(20));

                foreach (var eventData in events)
                {
                    var data               = Encoding.UTF8.GetString(eventData.GetBytes());
                    var enqueuedTime       = eventData.EnqueuedTimeUtc.ToLocalTime();
                    var connectionDeviceId = eventData.SystemProperties["iothub-connection-device-id"].ToString();

                    if (string.CompareOrdinal(selectedDevice.ToUpper(), connectionDeviceId.ToUpper()) == 0)
                    {
                        eventHubTextBox.Text += $"{enqueuedTime}> Device: [{connectionDeviceId}], Data:[{data}]";

                        if (eventData.Properties.Count > 0)
                        {
                            eventHubTextBox.Text += "Properties:\r\n";
                            foreach (var property in eventData.Properties)
                            {
                                eventHubTextBox.Text += $"'{property.Key}': '{property.Value}'\r\n";
                            }
                        }
                        if (enableSystemProperties.Checked)
                        {
                            if (eventData.Properties.Count == 0)
                            {
                                eventHubTextBox.Text += "\r\n";
                            }
                            foreach (var item in eventData.SystemProperties)
                            {
                                eventHubTextBox.Text += $"SYSTEM>{item.Key}={item.Value}\r\n";
                            }
                        }
                        eventHubTextBox.Text += "\r\n";

                        // scroll text box to last line by moving caret to the end of the text
                        eventHubTextBox.SelectionStart  = eventHubTextBox.Text.Length - 1;
                        eventHubTextBox.SelectionLength = 0;
                        eventHubTextBox.ScrollToCaret();
                    }
                }

                //having already received past events, monitor current events in a loop
                while (true)
                {
                    ct.ThrowIfCancellationRequested();

                    var eventData = await eventHubReceiver.ReceiveAsync(TimeSpan.FromSeconds(1));

                    if (eventData != null)
                    {
                        var data         = Encoding.UTF8.GetString(eventData.GetBytes());
                        var enqueuedTime = eventData.EnqueuedTimeUtc.ToLocalTime();

                        // Display only data from the selected device; otherwise, skip.
                        var connectionDeviceId = eventData.SystemProperties["iothub-connection-device-id"].ToString();

                        if (string.CompareOrdinal(selectedDevice, connectionDeviceId) == 0)
                        {
                            eventHubTextBox.Text += $"{enqueuedTime}> Device: [{connectionDeviceId}], Data:[{data}]";

                            if (eventData.Properties.Count > 0)
                            {
                                eventHubTextBox.Text += "Properties:\r\n";
                                foreach (var property in eventData.Properties)
                                {
                                    eventHubTextBox.Text += $"'{property.Key}': '{property.Value}'\r\n";
                                }
                            }

                            if (enableSystemProperties.Checked)
                            {
                                if (eventData.Properties.Count == 0)
                                {
                                    eventHubTextBox.Text += "\r\n";
                                }
                                foreach (var item in eventData.SystemProperties)
                                {
                                    eventHubTextBox.Text += $"SYSTEM>{item.Key}={item.Value}\r\n";
                                }
                            }

                            eventHubTextBox.Text += "\r\n";
                        }

                        // scroll text box to last line by moving caret to the end of the text
                        eventHubTextBox.SelectionStart  = eventHubTextBox.Text.Length - 1;
                        eventHubTextBox.SelectionLength = 0;
                        eventHubTextBox.ScrollToCaret();
                    }
                }
            }
            catch (Exception ex)
            {
                if (ct.IsCancellationRequested)
                {
                    eventHubTextBox.Text += $"Stopped Monitoring events. {ex.Message}\r\n";
                }
                else
                {
                    using (new CenterDialog(this))
                    {
                        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    eventHubTextBox.Text += $"Stopped Monitoring events. {ex.Message}\r\n";
                }
                if (eventHubReceiver != null)
                {
                    eventHubReceiver.Close();
                }
                if (eventHubClient != null)
                {
                    eventHubClient.Close();
                }
                dataMonitorButton.Enabled         = true;
                deviceIDsComboBoxForEvent.Enabled = true;
                cancelMonitoringButton.Enabled    = false;
            }
        }
Beispiel #30
0
        static async Task MainAsync(CancellationToken token)
        {
            EventHubClient   eventHubClient   = null;
            EventHubReceiver eventHubReceiver = null;

            eventHubClient = EventHubClient.CreateFromConnectionString(Properties.Settings.Default.IoTHubConnectionString, "messages/events");
            int    eventHubPartitionsCount = eventHubClient.GetRuntimeInformation().PartitionCount;
            string partition = EventHubPartitionKeyResolver.ResolveToPartition(Properties.Settings.Default.IoTDeviceId, eventHubPartitionsCount);

            eventHubReceiver = eventHubClient.GetConsumerGroup(Properties.Settings.Default.ConsumerGroupName).CreateReceiver(partition, DateTime.Now);

            while (true)
            {
                try
                {
                    EventData eventData = eventHubReceiver.Receive(TimeSpan.FromSeconds(1));

                    if (eventData != null)
                    {
                        string data = Encoding.UTF8.GetString(eventData.GetBytes());
                        string connectionDeviceId = eventData.SystemProperties["iothub-connection-device-id"].ToString();

                        if (string.CompareOrdinal(Properties.Settings.Default.IoTDeviceId, connectionDeviceId) == 0)
                        {
                            // Get RSSI reading from message
                            int rssi = 0;

                            if (rssi < RANGE)
                            {
                                if ((DateTime.Now - previousEvent).TotalSeconds >= RANGEINTERVAL)
                                {
                                    previousEvent = DateTime.Now;
                                    string cloudToDeviceMessage = "{\"message\":\"flash\"}";

                                    ServiceClient serviceClient  = ServiceClient.CreateFromConnectionString(Properties.Settings.Default.IoTHubConnectionString);
                                    var           serviceMessage = new Microsoft.Azure.Devices.Message(Encoding.ASCII.GetBytes(cloudToDeviceMessage));
                                    serviceMessage.Ack       = DeliveryAcknowledgement.Full;
                                    serviceMessage.MessageId = Guid.NewGuid().ToString();
                                    await serviceClient.SendAsync(Properties.Settings.Default.IoTDeviceId, serviceMessage);

                                    System.Threading.Thread.Sleep(1000);
                                    await serviceClient.CloseAsync();

                                    Console.WriteLine("Sent flash message");

                                    // Send Twilio message
                                    string AccountSid = Properties.Settings.Default.TwilioAccountSid;
                                    string AuthToken  = Properties.Settings.Default.TwilioAuthToken;
                                    var    twilio     = new TwilioRestClient(AccountSid, AuthToken);

                                    var message = twilio.SendMessage(Properties.Settings.Default.TwilioNumber, Properties.Settings.Default.NurseNumber, "Patient arrived in area");
                                    Console.WriteLine("SMS message sent. Sid: " + message.Sid);
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("An error occured. Error was " + ex.Message);
                }
            }
        }