Esempio n. 1
0
        static void Main(string[] args)
        {
            string                ehname     = "<eventhubname>";
            string                connection = "Endpoint=sb://<eventhubnamespace>.servicebus.windows.net/;SharedAccessKeyName=<policy>;SharedAccessKey=<key>;TransportType=Amqp";
            MessagingFactory      factory    = MessagingFactory.CreateFromConnectionString(connection);
            EventHubClient        ehub       = factory.CreateEventHubClient(ehname);
            EventHubConsumerGroup group      = ehub.GetDefaultConsumerGroup();
            EventHubReceiver      reciever   = group.CreateReceiver("0");

            while (true)
            {
                EventData data = reciever.Receive();
                if (data != null)
                {
                    try
                    {
                        string message = Encoding.UTF8.GetString(data.GetBytes());
                        Console.WriteLine(message + " " + DateTime.Now);
                        Console.WriteLine();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.ToString());
                    }
                }
            }
        }
Esempio n. 2
0
        private static void EventHubReceive()
        {
            var ehName     = "davnaeventhub";
            var connection = "Endpoint=sb://alewife.servicebus.windows.net/;SharedAccessKeyName=Receiver;SharedAccessKey=3jaTeykwRu84x93OpW3DftRO1WSHt4oi7QB0FRyHoyg=;TransportType=Amqp";

            MessagingFactory factory = MessagingFactory.CreateFromConnectionString(connection);

            EventHubClient        ehub     = factory.CreateEventHubClient(ehName);
            EventHubConsumerGroup group    = ehub.GetDefaultConsumerGroup();
            EventHubReceiver      receiver = group.CreateReceiver("1");

            while (true)
            {
                EventData data = receiver.Receive();

                if (data != null)
                {
                    var message = Encoding.UTF8.GetString(data.GetBytes());

                    Console.WriteLine("PartitionKey: {0}", data.PartitionKey);
                    Console.WriteLine("SequenceNumber: {0}", data.SequenceNumber);
                    Console.WriteLine(message);
                }
            }
        }
Esempio n. 3
0
 private static void ReceiveDirectFromPartition(
     EventHubClient eventHubClient,
     string partitionId,
     string consumerGroup)
 {
     try
     {
         var group = eventHubClient.GetConsumerGroup(consumerGroup);
         EventHubReceiver receiver = null;
         receiver = group.CreateReceiver(partitionId, DateTime.UtcNow);
         LogEngine.TraceInformation($"Direct Receiver created. Partition {partitionId}");
         while (true)
         {
             var message = receiver?.Receive();
             if (message != null)
             {
                 BubblingObject bubblingObject = BubblingObject.DeserializeMessage(message.GetBytes());
                 MessageIngestor.IngestMessagge(bubblingObject);
             }
         }
     }
     catch (Exception ex)
     {
         LogEngine.TraceError($"Error in {MethodBase.GetCurrentMethod().Name} - Error {ex.Message}");
     }
 }
        protected void ReceiveMessagesFromDeviceAsync(EventHubReceiver receiver)
        {
            while (true)
            {
                var eventData = receiver.Receive(10, new TimeSpan(0, 0, 10));
                if (eventData == null)
                {
                    break;
                }

                List <RowRead> receivedRows = new List <RowRead>();
                int            count        = 0;

                foreach (var ed in eventData)
                {
                    count++;
                    string  data = Encoding.Unicode.GetString(ed.GetBytes());
                    RowRead row  = new RowRead();
                    row.Values = JsonConvert.DeserializeObject <Dictionary <string, object> >(data);
                    receivedRows.Add(row);

                    this.EnqueuedTimeUtc = ed.EnqueuedTimeUtc;
                    this.EnqueuedOffset  = long.Parse(ed.Offset);
                }
                if (count == 0)
                {
                    break;
                }
            }
        }
Esempio n. 5
0
        private static async Task ReceiveMessagesFromDeviceAsync(string partition, Action <string> processEvent, CancellationToken ct)
        {
            DateTime         startingDateTimeUtc = DateTime.Now;
            EventHubReceiver receiver0           = group.CreateReceiver(partition, startingDateTimeUtc);

            receiverList.Add(receiver0);

            while (true)
            {
                if (ct.IsCancellationRequested)
                {
                    break;
                }

                if (!receiver0.IsClosed)
                {
                    EventData data = receiver0.Receive();

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

                    processEvent(theEvent);
                    Debug.WriteLine($"{data.PartitionKey} {data.EnqueuedTimeUtc.ToLocalTime()} {theEvent}");
                }

                await Task.Delay(2000);
            }
        }
Esempio n. 6
0
        public async Task ReceiveDataFromCloud()
        {
            startingDateTimeUtc = DateTime.UtcNow - TimeSpan.FromHours(24);

            factory = MessagingFactory.CreateFromConnectionString(ConnectionString);

            client   = factory.CreateEventHubClient(eventHubEntity);
            group    = client.GetDefaultConsumerGroup();
            receiver = group.CreateReceiver(partitionId.ToString(), startingDateTimeUtc);

            try
            {
                while (true)
                {
                    EventData data = receiver.Receive();

                    if (data != null)
                    {
                        var receiveddata = Encoding.UTF8.GetString(data.GetBytes());

                        Debug.WriteLine("{0} {1} {2}", data.SequenceNumber, data.EnqueuedTimeUtc.ToLocalTime(), receiveddata);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Exception {0}", ex);
            }

            receiver.Close();
            client.Close();
            factory.Close();
        }
Esempio n. 7
0
        static int Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine("Proton-DotNet.exe connection_string");
                return(2);
            }

            try
            {
                EventHubClient   ehc      = EventHubClient.CreateFromConnectionString(args[0]);
                EventHubReceiver receiver = ehc.GetDefaultConsumerGroup().CreateReceiver("0");
                while (true)
                {
                    EventData data = receiver.Receive();
                    if (data == null)
                    {
                        break;
                    }

                    string text = Encoding.UTF8.GetString(data.GetBytes());
                    Console.WriteLine(data.SequenceNumber + ":" + text);
                }

                ehc.Close();

                return(0);
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.ToString());
            }

            return(1);
        }
        //code adapted from tutorial https://paolopatierno.wordpress.com/2015/11/02/azure-iot-hub-get-telemetry-data-using-amqp-stack-and-azure-sb-lite/
        public static string GetMessage(string partitionId)
        {
            string result = null;
            ServiceBusConnectionStringBuilder builder = new ServiceBusConnectionStringBuilder(ConnectionString);

            builder.TransportType = TransportType.Amqp;

            MessagingFactory factory = MessagingFactory.CreateFromConnectionString(ConnectionString);

            EventHubClient        client = factory.CreateEventHubClient(eventHubEntity);
            EventHubConsumerGroup group  = client.GetDefaultConsumerGroup();

            var startingDateTimeUtc = DateTime.Now;

            EventHubReceiver receiver = group.CreateReceiver(partitionId, startingDateTimeUtc);

            EventData data = receiver.Receive();

            receiver.Close();
            client.Close();
            factory.Close();
            if (data != null)
            {
                result = Encoding.UTF8.GetString(data.GetBytes());
                return(result);
            }
            else
            {
                return(null);
            }
        }
Esempio n. 9
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="receiverindex"></param>
        /// <param name="r"></param>
        public static void StartReceiver(int receiverindex, EventHubReceiver r)
        {
            var  starttime              = DateTime.Now;
            bool isMessageAvailable     = true;
            var  requestdata            = new WEP.GSP.Data.RequestData();
            EventHubProcessor processor = new EventHubProcessor();

            do
            {
                try
                {
                    var messages = r.Receive(10);
                    if (messages == null || messages.Count() == 0)
                    {
                        isMessageAvailable = false;
                    }
                    else
                    {
                        Task.Factory.StartNew(() => processor.EventMessageHandler(messages));
                        requestdata.UpdatePartitionOffset(Convert.ToString(receiverindex), messages.Last().Offset);
                        requests = requests + messages.Count();
                    }
                }
                catch (Exception exception)
                {
                    Trace.TraceError("exception on receive {0}", exception.Message);
                }
            } while (isMessageAvailable);
            requestdata.UpdateReleasePartitionLock(Convert.ToString(receiverindex));
        }
Esempio n. 10
0
        static void Main(string[] args)
        {
            string                ehname     = "<eventhubname>";
            string                connection = "<eventhubconnectionstring>,TransportType=Amqp";
            MessagingFactory      factory    = MessagingFactory.CreateFromConnectionString(connection);
            EventHubClient        ehub       = factory.CreateEventHubClient(ehname);
            EventHubConsumerGroup group      = ehub.GetDefaultConsumerGroup();
            EventHubReceiver      reciever   = group.CreateReceiver("0");

            while (true)
            {
                EventData data = reciever.Receive();
                if (data != null)
                {
                    try
                    {
                        string message = Encoding.UTF8.GetString(data.GetBytes());
                        //Console.WriteLine("Partition Key: {0}", data.PartitionKey);
                        Console.WriteLine(message);
                        Console.WriteLine();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.ToString());
                    }
                }
            }
        }
Esempio n. 11
0
        /// <summary>
        /// Receive 10 Event Hub messages
        /// </summary>
        /// <param name="eventHubClient">EventHubClient object</param>
        /// <returns>Task object</returns>
        private async Task Receive10EventHubMessage(EventHubClient eventHubClient)
        {
            int maxMessagesToReceive         = 10;
            int successMessageReceiveCounter = 0;
            int recentPublishedMessageTimeIntervalInMinutes = 10; // Helps to get only the past 10 minutes published messages

            Console.WriteLine($"About to receive [{maxMessagesToReceive}] message published the past [{recentPublishedMessageTimeIntervalInMinutes}] minutes !\n");
            try
            {
                EventHubConsumerGroup   eventHubConsumerGroup = eventHubClient.GetConsumerGroup(ConfigurationManager.AppSettings.Get("EventHubConsumerGroup"));
                EventHubReceiver        eventHubReceiver      = eventHubConsumerGroup.CreateReceiver(PARTITION_ID, DateTime.UtcNow.AddMinutes(-recentPublishedMessageTimeIntervalInMinutes));
                IEnumerable <EventData> eventDatum            = eventHubReceiver.Receive(maxMessagesToReceive);
                if (eventDatum == null)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Error occurred !");
                    Console.WriteLine("Event data is null !");
                }
                else
                {
                    foreach (EventData eventData in eventDatum)
                    {
                        successMessageReceiveCounter++;
                        string offset  = eventData.Offset;
                        string content = Encoding.UTF8.GetString(eventData.GetBytes());
                        if (!string.IsNullOrWhiteSpace(offset) &&
                            !string.IsNullOrWhiteSpace(content))
                        {
                            Console.WriteLine($"\tReceived message offset - [{offset}]");
                            Console.WriteLine($"\tReceived message content - [{content}]\n");
                            Console.WriteLine("Delay 2 seconds to receive the next message !\n");

                            await Task.Delay(2000); // Delay 2 seconds to receive the next message
                        }
                        else
                        {
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine("Event data has no message content !");
                        }
                    }
                    if (successMessageReceiveCounter > 0)
                    {
                        Console.WriteLine($"[{successMessageReceiveCounter}] messages received successfully !\n");
                    }
                    else
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("No message received !");
                    }
                }
            }
            catch (Exception exception)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Error occurred !");
                Console.WriteLine(exception);
            }
        }
Esempio n. 12
0
        static void Main(string[] args)
        {
            // initialization
            SiteState state = StateManager.LoadState();

            Mapper.CreateMap <InventoryTruck, InventoryItem>();

            // obtain the consumer
            EventHubReceiver receiver = GetEventHubReceiver(state);


            bool continueProcessing = true;

            while (continueProcessing)
            {
                // retreive a batch of data
                var data = receiver.Receive(10, TimeSpan.FromSeconds(10));

                // iterate through events
                foreach (EventData item in data)
                {
                    // deserialize the InventoryChangeEvent from the message body
                    var bodyStream = item.GetBodyStream();
                    InventoryChangeEvent changeEvent = SerializationHelper.TryExtractInventoryChangedEvent(bodyStream);

                    // verify that deserialization was successful
                    if (changeEvent != null)
                    {
                        // update inventory depending on type of change
                        if (changeEvent.ChangeType == InventoryChangeType.Refresh)
                        {
                            var mergeTruck = Mapper.Map <InventoryItem>(changeEvent.Truck);
                            MergeInventory(mergeTruck);
                            Console.WriteLine("Merged 1 truck into inventory");
                        }
                        else if (changeEvent.ChangeType == InventoryChangeType.Sold)
                        {
                            RemoveInventory(changeEvent.Truck.Id);
                            Console.WriteLine("Removed 1 truck into inventory");
                        }
                    }

                    // update the saved state with the new offset
                    state.Offset = item.Offset;
                }

                // save state on each round
                StateManager.WriteState(state);

                // management of the console host
                Console.WriteLine("Press any key to continue or 'q' to quit...");
                var keyPress = Console.ReadKey(false);
                continueProcessing = keyPress.KeyChar != 'q';
            }
        }
Esempio n. 13
0
        public void Scenario8_EventHubReceiveFromPartitionDateTimeOffset(string eventHubEntity, string partitionId, DateTime dateTimeOffset)
        {
            ServiceBusConnectionStringBuilder builder = new ServiceBusConnectionStringBuilder(this.ConnectionString);

            builder.TransportType = TransportType.Amqp;

            MessagingFactory factory = MessagingFactory.CreateFromConnectionString(this.ConnectionString);

            EventHubClient        client = factory.CreateEventHubClient(eventHubEntity);
            EventHubConsumerGroup group  = client.GetDefaultConsumerGroup();

            EventHubReceiver receiver = group.CreateReceiver(partitionId, dateTimeOffset);

            while (true)
            {
                EventData data = receiver.Receive();
            }

            receiver.Close();
            client.Close();
            factory.Close();
        }
Esempio n. 14
0
        static void SendReceive(MessagingFactorySettings messagingFactorySettings)
        {
            MessagingFactory messagingFactory = MessagingFactory.Create($"sb://{EventHubNamespace}/",
                                                                        messagingFactorySettings);

            EventHubClient        ehClient      = messagingFactory.CreateEventHubClient(EventHubName);
            EventHubConsumerGroup consumerGroup = ehClient.GetDefaultConsumerGroup();

            var receiveTask = Task.Factory.StartNew(() =>
            {
                string[] partitionIds = { "0", "1" };
                Parallel.ForEach(partitionIds, partitionId =>
                {
                    EventHubReceiver receiver = consumerGroup.CreateReceiver(partitionId, EventHubConsumerGroup.StartOfStream);
                    while (true)
                    {
                        EventData data = receiver.Receive(TimeSpan.FromSeconds(10));
                        if (data == null)
                        {
                            break;
                        }
                        Console.WriteLine($"Received from partition {partitionId} : " + Encoding.UTF8.GetString(data.GetBytes()));
                    }
                    receiver.Close();
                });
            });

            System.Threading.Thread.Sleep(5000);

            ehClient.Send(new EventData(Encoding.UTF8.GetBytes($"{DateTime.UtcNow}")));

            Task.WaitAll(receiveTask);

            ehClient.Close();
            messagingFactory.Close();
            Console.WriteLine("Send / Receive complete. Press enter to exit.");
            Console.ReadLine();
        }
Esempio n. 15
0
        protected void btnReceive_Click(object sender, EventArgs e)
        {
            MessagingFactorySettings messagingFactorySettings = new MessagingFactorySettings
            {
                TokenProvider = TokenProvider.CreateManagedServiceIdentityTokenProvider(ServiceAudience.EventHubsAudience),
                TransportType = TransportType.Amqp
            };

            messagingFactorySettings.AmqpTransportSettings.EnableLinkRedirect = false;

            MessagingFactory messagingFactory = MessagingFactory.Create($"sb://{txtNamespace.Text}.servicebus.windows.net/",
                                                                        messagingFactorySettings);

            EventHubClient        ehClient      = messagingFactory.CreateEventHubClient(txtEventHub.Text);
            EventHubConsumerGroup consumerGroup = ehClient.GetDefaultConsumerGroup();
            int partitions = int.Parse(txtPartitions.Text);

            string[] Offsets = new string[partitions];
            if (!string.IsNullOrEmpty(hiddenStartingOffset.Value))
            {
                Offsets = hiddenStartingOffset.Value.Split(',');
            }
            System.Threading.Tasks.Parallel.ForEach(Enumerable.Range(0, int.Parse(txtPartitions.Text)), partitionId =>
            {
                EventHubReceiver receiver = consumerGroup.CreateReceiver($"{partitionId}", Offsets[partitionId] == null ? "-1" : Offsets[partitionId]);
                EventData data            = receiver.Receive(TimeSpan.FromSeconds(1));
                if (data != null)
                {
                    Offsets[partitionId]  = data.Offset;
                    txtReceivedData.Text += $"PartitionId: {partitionId} Seq#:{data.SequenceNumber} data:{Encoding.UTF8.GetString(data.GetBytes())}{Environment.NewLine}";
                }
                receiver.Close();
            });

            hiddenStartingOffset.Value = string.Join(",", Offsets);
            ehClient.Close();
            messagingFactory.Close();
        }
Esempio n. 16
0
        private async Task <IEnumerable <EventData> > GetEventData()
        {
            EventHubRuntimeInformation runtimeInformation = _eventHubClient.GetRuntimeInformation();
            List <EventData>           dataRecieved       = new List <EventData>();

            foreach (string partitionId in runtimeInformation.PartitionIds)
            {
                string partitionOffset = await _stateHandler.GetOffset(partitionId);

                //EventHubReceiver eventReceiver = _eventHubClient.GetDefaultConsumerGroup().CreateReceiver(partitionId, partitionOffset);
                EventHubReceiver eventReceiver = _eventHubClient.GetConsumerGroup("mojo").CreateReceiver(partitionId, partitionOffset);

                EventData eventData = eventReceiver.Receive();

                await _stateHandler.SetOffset(eventData.Offset, partitionId);

                await eventReceiver.CloseAsync();

                dataRecieved.Add(eventData);
            }

            return(dataRecieved);
        }
Esempio n. 17
0
        static void Main(string[] args)
        {
            /* Get event hub name and service bus connection string from user input. Basic use is to ask user:
             * Which Event Hub are we listening for a message from? (where is the AverageSentiment number coming from?)
             */

            //string ehName = "";
            //string connection = "";

            //Console.WriteLine("Enter Event Hub Name: ");
            //ehName = Console.ReadLine();
            //Console.WriteLine("Enter Service Bus Connection String: ");
            //connection = Console.ReadLine() + ";TransportType=Amqp";

            //Console.WriteLine("START\n");


            //Comment out these two string if using the user input code above
            string ehName     = "EVENT HUB NAME";
            string connection = "Endpoint=sb://SERVICEBUSNAMESPACE.servicebus.windows.net/;SharedAccessKeyName=ACCESSKEYNAME;SharedAccessKey=ACCESSKEY;TransportType=Amqp";

            MessagingFactory      factory  = MessagingFactory.CreateFromConnectionString(connection);
            EventHubClient        ehub     = factory.CreateEventHubClient(ehName);
            EventHubConsumerGroup group    = ehub.GetDefaultConsumerGroup();
            EventHubReceiver      reciever = group.CreateReceiver("0");


            while (true)
            {
                EventData data = reciever.Receive();
                if (data != null)
                {
                    try
                    {
                        var     result     = Encoding.UTF8.GetString(data.GetBytes());
                        dynamic resultJson = JObject.Parse(result);
                        var     avgScore   = resultJson.avgsentiment;

                        Console.WriteLine(result);
                        Console.WriteLine("Average Score: " + avgScore + "\n");

                        //create sentimentdata object
                        var sentimentData = new SentimentData()
                        {
                            AverageSentiment = avgScore, EventHubName = ehName
                        };

                        //post sentimentdata to api
                        using (var client = new HttpClient())
                        {
                            client.BaseAddress = new Uri("CLIENT BASE ADDRESS FOR WEB API FOR SENTIMENT DATA");
                            var response = client.PostAsJsonAsync("/api/sentimentdata", sentimentData).Result;
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.ToString());
                    }
                }
            }
        }
        private static void ReceiveDirectFromPartition(
            EventHubClient eventHubClient,
            string partitionId,
            string consumerGroup)
        {
            try
            {
                var group = eventHubClient.GetConsumerGroup(consumerGroup);

                var eventHubsStartingDateTimeReceiving =
                    DateTime.Parse(
                        ConfigurationBag.Configuration.EventHubsStartingDateTimeReceiving == "0"
                        // ReSharper disable once SpecifyACultureInStringConversionExplicitly
                            ? DateTime.UtcNow.ToString()
                            : ConfigurationBag.Configuration.EventHubsStartingDateTimeReceiving);
                var eventHubsEpoch = ConfigurationBag.Configuration.EventHubsEpoch;

                EventHubReceiver receiver = null;

                switch (ConfigurationBag.Configuration.EventHubsCheckPointPattern)
                {
                case EventHubsCheckPointPattern.CheckPoint:
                    //Receiving from the last valid receiving point
                    receiver = group.CreateReceiver(partitionId, DateTime.UtcNow);
                    break;

                case EventHubsCheckPointPattern.Dt:

                    receiver = group.CreateReceiver(partitionId, eventHubsStartingDateTimeReceiving);
                    break;

                case EventHubsCheckPointPattern.Dtepoch:
                    receiver = group.CreateReceiver(partitionId, eventHubsStartingDateTimeReceiving, eventHubsEpoch);
                    break;

                case EventHubsCheckPointPattern.Dtutcnow:
                    receiver = group.CreateReceiver(partitionId, DateTime.UtcNow);
                    break;

                case EventHubsCheckPointPattern.Dtnow:
                    receiver = group.CreateReceiver(partitionId, DateTime.Now);
                    break;

                case EventHubsCheckPointPattern.Dtutcnowepoch:
                    receiver = group.CreateReceiver(partitionId, DateTime.UtcNow, eventHubsEpoch);
                    break;

                case EventHubsCheckPointPattern.Dtnowepoch:
                    receiver = group.CreateReceiver(partitionId, DateTime.Now, eventHubsEpoch);
                    break;
                }
                Debug.WriteLine(
                    $"Direct Receiver created. Partition {partitionId}",
                    ConsoleColor.Yellow);
                while (true)
                {
                    var message = receiver?.Receive();
                    if (message != null)
                    {
                        BubblingObject bubblingObject = BubblingObject.DeserializeMessage(message.GetBytes());
                        SetEventOnRampMessageReceived(bubblingObject);
                    }
                }
            }
            catch (Exception ex)
            {
                LogEngine.WriteLog(
                    ConfigurationBag.EngineName,
                    $"Error in {MethodBase.GetCurrentMethod().Name}",
                    Constant.LogLevelError,
                    Constant.TaskCategoriesError,
                    ex,
                    Constant.LogLevelError);
            }
        }
Esempio n. 19
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);
                }
            }
        }
Esempio n. 20
0
        //For demo purpose we have taken two devices/rooms and
        //updating the collection based on the data received
        public async Task ReceiveDataFromCloud()
        {
            startingDateTimeUtc = DateTime.UtcNow;
            ServiceBusConnectionStringBuilder builder = new ServiceBusConnectionStringBuilder(ConnectionString);

            builder.TransportType = ppatierno.AzureSBLite.Messaging.TransportType.Amqp;

            factory = MessagingFactory.CreateFromConnectionString(ConnectionString);

            client   = factory.CreateEventHubClient(eventHubEntity);
            group    = client.GetDefaultConsumerGroup();
            receiver = group.CreateReceiver(partitionId.ToString(), startingDateTimeUtc);//startingDateTimeUtc
            while (true)
            {
                EventData data = receiver.Receive();

                if (data != null)
                {
                    var receiveddata = Encoding.UTF8.GetString(data.GetBytes());

                    var messageString = JsonConvert.DeserializeObject <ConferenceRoomDataPoint>(receiveddata);

                    if (messageString.DeviceId == "device1")
                    {
                        conferenceRoomDataPointList[0].DeviceId    = messageString.DeviceId;
                        conferenceRoomDataPointList[0].RoomTemp    = messageString.RoomTemp;
                        conferenceRoomDataPointList[0].RoomStatus  = messageString.RoomStatus;
                        conferenceRoomDataPointList[0].Color       = messageString.Color;
                        conferenceRoomDataPointList[0].LightStatus = messageString.LightStatus;
                        DateTime localDateTime = DateTime.Parse(messageString.Time);
                        DateTime utcDateTime   = localDateTime.ToLocalTime();
                        conferenceRoomDataPointList[0].Time         = utcDateTime.ToString();
                        conferenceRoomDataPointList[0].RoomPressure = messageString.RoomPressure;
                        conferenceRoomDataPointList[0].RoomAlt      = messageString.RoomAlt;
                    }
                    if (messageString.DeviceId == "device2")
                    {
                        conferenceRoomDataPointList[1].DeviceId    = messageString.DeviceId;
                        conferenceRoomDataPointList[1].RoomTemp    = messageString.RoomTemp;
                        conferenceRoomDataPointList[1].RoomStatus  = messageString.RoomStatus;
                        conferenceRoomDataPointList[1].Color       = messageString.Color;
                        conferenceRoomDataPointList[1].LightStatus = messageString.LightStatus;
                        DateTime localDateTime = DateTime.Parse(messageString.Time);
                        DateTime utcDateTime   = localDateTime.ToLocalTime();
                        conferenceRoomDataPointList[1].Time         = utcDateTime.ToString();
                        conferenceRoomDataPointList[1].RoomPressure = messageString.RoomPressure;
                        conferenceRoomDataPointList[1].RoomAlt      = messageString.RoomAlt;
                    }


                    //var message = new ConferenceRooms(Encoding.ASCII.GetBytes(receiveddata));

                    Debug.WriteLine("{0} {1} {2}", data.SequenceNumber, data.EnqueuedTimeUtc.ToLocalTime(), Encoding.UTF8.GetString(data.GetBytes()));
                }
                else
                {
                    break;
                }

                await Task.Delay(2000);
            }

            receiver.Close();
            client.Close();
            factory.Close();
        }