Ejemplo n.º 1
0
        public static async Task Run(ActionReceivedText OnSvcStatusUpdateD = null, ActionReceivedText OnSvcRecvTextD = null)
        {
            OnSvcStatusUpdate = OnSvcStatusUpdateD;
            OnSvcRecvText     = OnSvcRecvTextD;

            System.Diagnostics.Debug.WriteLine("IoT Hub Telemetry - Read device to cloud messages.");
            OnSvcStatusUpdate?.Invoke("IoT Hub Telemetry - Read device to cloud messages.");
            // Create an EventHubClient instance to connect to the
            // IoT Hub Event Hubs-compatible endpoint.
            //var connectionString1 = new EventHubsConnectionStringBuilder(new Uri(s_eventHubsCompatibleEndpoint), s_eventHubsCompatiblePath, s_iotHubSasKeyName, s_iotHubSasKey);


            //Get some of event cs properties from hub cs

            string iotHubSasKeyName = Azure_IoTHub_Connections.MyConnections.IotHubKeyName;


            EventHubsConnectionStringBuilder EventHubConnectionString = null;

            if (Azure_IoTHub_Connections.MyConnections.EHMethod1)
            {
                EventHubConnectionString = new EventHubsConnectionStringBuilder(Azure_IoTHub_Connections.MyConnections.EventHubsConnectionString);
            }
            else
            {
                EventHubConnectionString = new EventHubsConnectionStringBuilder(
                    new Uri(Azure_IoTHub_Connections.MyConnections.EventHubsCompatibleEndpoint),
                    Azure_IoTHub_Connections.MyConnections.EventHubsCompatiblePath,
                    Azure_IoTHub_Connections.MyConnections.IotHubKeyName,
                    Azure_IoTHub_Connections.MyConnections.EventHubsSasKey);
            }


            s_eventHubClient = EventHubClient.CreateFromConnectionString(EventHubConnectionString.ToString());

            // Create a PartitionReciever for each partition on the hub.
            var runtimeInfo = await s_eventHubClient.GetRuntimeInformationAsync();

            var d2cPartitions = runtimeInfo.PartitionIds;

            cts = new CancellationTokenSource();

            //System.Diagnostics.Debug.CancelKeyPress += (s, e) =>
            //{
            //    e.Cancel = true;
            //    cts.Cancel();
            //    System.Diagnostics.Debug.WriteLine("Exiting...");
            //};

            var tasks = new List <Task>();

            foreach (string partition in d2cPartitions)
            {
                tasks.Add(ReceiveMessagesFromDeviceAsync(partition, cts.Token));
            }

            // Wait for all the PartitionReceivers to finsih.
            Task.WaitAll(tasks.ToArray());
            OnSvcStatusUpdate?.Invoke("Telemetry: All Threads Done.");
        }
        public static async Task Run(int delay, int timeout, int tag, ActionReceivedText setDeviceSentMsg, ActionReceivedText OnDeviceStatusUpdate)
        {
            SetDeviceSentMsg = setDeviceSentMsg;

            if (Azure_IoTHub_Sensors.Weather.CurrentWeather == null)
            {
                Azure_IoTHub_Sensors.Weather.CurrentWeather = new Azure_IoTHub_Sensors.Weather_Random();
            }


            OnDeviceStatusUpdateD = OnDeviceStatusUpdate;
            OnDeviceStatusUpdateD?.Invoke("IoT Hub Telemetry #2 - Simulated device. ");
            // Connect to the IoT hub using the MQTT protocol
            s_deviceClient = DeviceClient.CreateFromConnectionString(s_connectionString, TransportType.Mqtt);

            // Create a handler for the direct method call
            await s_deviceClient.SetMethodHandlerAsync("SetTelemetryInterval", SetTelemetryInterval, null);  //.Wait();

            await s_deviceClient.SetMethodHandlerAsync("SetTelemetryInterval2", SetTelemetryInterval, null); //.Wait();

            await SendDeviceToCloudMessagesAsync();

            //System.Diagnostics.Debug.ReadLine();
            OnDeviceStatusUpdateD?.Invoke("IoT Hub Telemetry #2 - Device done");
        }
Ejemplo n.º 3
0
 public DeviceStreamProxySvc(ServiceClient deviceClient, String deviceId, int localPort, ActionReceivedText onRecvdTextD = null, ActionReceivedText onStatusUpdateD = null)
 {
     sample          = this;
     OnRecvdTextD    = onRecvdTextD;
     OnStatusUpdateD = onStatusUpdateD;
     _serviceClient  = deviceClient;
     _deviceId       = deviceId;
     _localPort      = localPort;
 }
        public DeviceStreamSample(DeviceClient deviceClient, String host, int port, ActionReceivedText onRecvdText, ActionReceivedText onDeviceStatusUpdateD = null)
        {
            sample                = this;
            OnRecvdTextD          = onRecvdText;
            OnDeviceStatusUpdateD = onDeviceStatusUpdateD;

            _deviceClient = deviceClient;
            _host         = host;
            _port         = port;
        }
Ejemplo n.º 5
0
        public static void Configure(string device_cs, bool isDeviceStreaming, TransportType transportType, bool loop, ActionReceivedText onDeviceStatusUpdateD = null, int delay = 1000)
        {
            Delay = delay;
            OnDeviceStatusUpdateD = onDeviceStatusUpdateD;
            IsDeviceStreaming     = isDeviceStreaming;

            s_connectionString = device_cs;

            if (!IsDeviceStreaming)
            {
                s_deviceClient = DeviceClient.CreateFromConnectionString(s_connectionString, transportType);
            }
            ContinueLoop = true;
        }
Ejemplo n.º 6
0
 public DeviceStream_Svc(ServiceClient deviceClient, String deviceId, string msgOut, ActionReceivedText onRecvdTextD, int devKeepListening = 2, int devAutoStart = 2,ActionReceivedText onStatusUpdateD = null, bool keepAlive = false, bool responseExpected = true, DeviceAndSvcCurrentSettings svcCurrentSettings = null)
 {
     _serviceClient = deviceClient;
     _deviceId = deviceId;
     OnRecvdTextD = onRecvdTextD;
     OnStatusUpdateD = onStatusUpdateD;
     if (svcCurrentSettings != null)
         SvcCurrentSettings = svcCurrentSettings;
     else
         SvcCurrentSettings = new DeviceAndSvcCurrentSettings();
     SvcCurrentSettings.KeepAlive = keepAlive;
     SvcCurrentSettings.ResponseExpected = responseExpected;
     DevKeepListening = devKeepListening;
     DevAutoStart = devAutoStart;
     MsgOut = msgOut; 
 }
 /// <summary>
 /// The class constructor
 /// </summary>
 /// <param name="deviceClient">Instance of class for Device Steaming from the SDK</param>
 /// <param name="_OnRecvText">Callback to handle received message, post stripping of flags</param>
 /// <param name="deviceCurrentSettings">Optional custom class to handle processing of flags</param>
 public DeviceStream_Device(DeviceClient deviceClient, ActionReceivedTextIO onRecvdText, ActionCommandD actionCommand = null, ActionReceivedText onDeviceStatusUpdateD = null, bool keepDeviceListening = false, DeviceAndSvcCurrentSettings deviceCurrentSettings = null)
 {
     this.deviceClient     = deviceClient;
     OnRecvdTextIO         = onRecvdText;
     OnDeviceStatusUpdateD = onDeviceStatusUpdateD;
     KeepDeviceListening   = keepDeviceListening;
     ActionCmdD            = actionCommand;
     if (deviceCurrentSettings != null)
     {
         DeviceCurrentSettings = deviceCurrentSettings;
     }
     else
     {
         DeviceCurrentSettings = new DeviceAndSvcCurrentSettings();
     }
     DeviceCurrentSettings.KeepDeviceListening = KeepDeviceListening;
 }
        public static async Task  Run(int DelayBetweenTelemetryReadings, int ConnectionTimeout, int MethodTimeout, int MethodTag, ActionReceivedText OnSvcStatusUpdate)
        {
            System.Diagnostics.Debug.WriteLine("1");
            OnDeviceStatusUpdateD = OnSvcStatusUpdate;
            //Azure_IoTHub_Connections.MyConnections.IoTHubConnectionString =
            //        "HostName=MyNewHub2.azure-devices.net;SharedAccessKeyName=service;SharedAccessKey=BuPhIaEYb7S/FK9ojoDqxi8jyUhCttokrcXDTJGwoNI=";
            Azure_IoTHub_Connections.MyConnections.DeviceId = "MyNewDevice2";
            System.Diagnostics.Debug.WriteLine("IoT Hub Quickstarts #2 - Back-end application.\n");
            OnDeviceStatusUpdateD?.Invoke("IoT Hub Quickstarts #2 - Back-end application.");
            //System.Diagnostics.Debug.ReadLine();
            // Create a ServiceClient to communicate with service-facing endpoint on your hub.
            System.Diagnostics.Debug.WriteLine("2");
            s_connectionString =
                Azure_IoTHub_Connections.MyConnections.IoTHubConnectionString;
            s_serviceClient = ServiceClient.CreateFromConnectionString(s_connectionString);
            System.Diagnostics.Debug.WriteLine("3");
            await InvokeMethod(DelayBetweenTelemetryReadings, ConnectionTimeout, MethodTimeout, MethodTag);  //.GetAwaiter().GetResult();

            OnDeviceStatusUpdateD?.Invoke("Backend Done");
            System.Diagnostics.Debug.WriteLine("Press Enter to exit.");
            //System.Diagnostics.Debug.ReadLine();
        }
Ejemplo n.º 9
0
        public static async Task <string> Run(ActionReceivedText onDeviceStatusUpdateD = null, ActionReceivedText setDeviceSentMsg = null)
        {
            SetDeviceSentMsg     = setDeviceSentMsg;
            OnDeviceStatusUpdate = onDeviceStatusUpdateD;

            if (Azure_IoTHub_Sensors.Weather.CurrentWeather == null)
            {
                Azure_IoTHub_Sensors.Weather.CurrentWeather = new Azure_IoTHub_Sensors.Weather_Random();
            }
            MessageString = "";
            System.Diagnostics.Debug.WriteLine("IoT Hub Telemetry - Simulated device started.");
            OnDeviceStatusUpdate?.Invoke("IoT Hub Telemetry - Simulated device started.");
            // Connect to the IoT hub using the MQTT protocol
            if (ControlDeviceMode)
            {
                // Create a handler for the direct method call
                try
                {
                    await s_deviceClient.SetMethodHandlerAsync("SetTelemetryInterval", SetTelemetryInterval, null);//.Wait();
                } catch (Exception ex)
                {
                }
            }
            await SendDeviceToCloudMessagesAsync();

            if (!IsDeviceStreaming)
            {
                System.Diagnostics.Debug.WriteLine("IoT Hub Telemetry - Device done");
                OnDeviceStatusUpdate?.Invoke("IoT Hub Telemetry - Device done");
                await s_deviceClient.CloseAsync();

                MessageString = "";
            }

            return(MessageString);
        }
        public static async Task RunSvc(string s_connectionString, String deviceId, string msgOut, ActionReceivedText onRecvdTextD, int devKeepListening = 2, int devAutoStart = 2, ActionReceivedText oOnStatusUpdate = null, bool keepAlive = false, bool responseExpected = true, DeviceAndSvcCurrentSettings deviceAndSvcCurrentSettings = null)
        {
            if (deviceStream_Svc != null)
            {
                System.Diagnostics.Debug.WriteLine("Svc Socket is already open!");
                return;
            }
            else
            {
                try
                {
                    using (ServiceClient serviceClient = ServiceClient.CreateFromConnectionString(s_connectionString, DeviceStreamingCommon.s_transportType))
                    {
                        if (serviceClient == null)
                        {
                            System.Diagnostics.Debug.WriteLine("Failed to create SericeClient!");
                            //return null;
                        }

                        //Attach keepalive and respond info if set

                        deviceStream_Svc = new DeviceStream_Svc(serviceClient, deviceId, msgOut, onRecvdTextD, devKeepListening, devAutoStart, oOnStatusUpdate, keepAlive, responseExpected, deviceAndSvcCurrentSettings);
                        if (deviceStream_Svc == null)
                        {
                            System.Diagnostics.Debug.WriteLine("Failed to create DeviceStreamSvc!");
                        }
                        else
                        {
                            try
                            {
                                await deviceStream_Svc.RunSvcAsync();//.GetAwaiter().GetResult();
                            }
                            catch (Microsoft.Azure.Devices.Client.Exceptions.IotHubCommunicationException)
                            {
                                System.Diagnostics.Debug.WriteLine("3 Error RunSvc(): Hub connection failure");
                            }
                            catch (Microsoft.Azure.Devices.Common.Exceptions.DeviceNotFoundException)
                            {
                                System.Diagnostics.Debug.WriteLine("3 Error RunSvc(): Device not found");
                            }
                            catch (TaskCanceledException)
                            {
                                System.Diagnostics.Debug.WriteLine("3 Error RunSvc(): Task canceled");
                            }
                            catch (OperationCanceledException)
                            {
                                System.Diagnostics.Debug.WriteLine("3 Error RunSvc(): Operation canceled");
                            }
                            catch (Exception ex)
                            {
                                if (!ex.Message.Contains("Timed out"))
                                {
                                    System.Diagnostics.Debug.WriteLine("3 Error RunSvc(): " + ex.Message);
                                }
                                else
                                {
                                    System.Diagnostics.Debug.WriteLine("3 Error RunSvc(): Timeout");
                                }
                            }
                        }
                    }
                }
                catch (Microsoft.Azure.Devices.Client.Exceptions.IotHubCommunicationException)
                {
                    System.Diagnostics.Debug.WriteLine("4 Error RunSvc(): Hub connection failure");
                }
                catch (Microsoft.Azure.Devices.Common.Exceptions.DeviceNotFoundException)
                {
                    System.Diagnostics.Debug.WriteLine("4 Error RunSvc(): Device not found");
                }
                catch (TaskCanceledException)
                {
                    System.Diagnostics.Debug.WriteLine("4 Error RunSvc(): Task canceled");
                }
                catch (OperationCanceledException)
                {
                    System.Diagnostics.Debug.WriteLine("4 Error RunSvc(): Operation canceled");
                }
                catch (Exception ex)
                {
                    if (!ex.Message.Contains("Timeout"))
                    {
                        System.Diagnostics.Debug.WriteLine("4 Error RunSvc(): " + ex.Message);
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine("4 Error RunSvc(): Timeout");
                    }
                }
            }
        }
        /// <summary>
        /// Method called from app to instantiate this class and start Device Streaming on Device.
        /// </summary>
        /// <param name="device_cs">Device Id eg "MyDevice"</param>
        /// <param name="onRecvdTextD">Callback to handle received message, post stripping of flags</param>
        /// <param name="deviceCurrentSettings">Optional custom class to handle processing of flags</param>
        /// <returns>The running task</returns>
        public static async Task RunDevice(string device_cs, ActionReceivedTextIO onRecvdTextD, ActionReceivedText onDeviceStatusUpdateD = null, ActionCommandD actionCommandD = null, bool keepDeviceListening = false, DeviceAndSvcCurrentSettings deviceCurrentSettings = null)
        {
            bool __keepDeviceListening = false;

            do
            {
                TransportType device_hubTransportTryp = DeviceStreamingCommon.device_transportType;
                try
                {
                    using (DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(device_cs, device_hubTransportTryp))
                    {
                        if (deviceClient == null)
                        {
                            System.Diagnostics.Debug.WriteLine("Failed to create DeviceClient!");
                            //return null;
                        }

                        deviceStream_Device = new DeviceStream_Device(deviceClient, onRecvdTextD, actionCommandD, onDeviceStatusUpdateD, keepDeviceListening, deviceCurrentSettings);

                        if (deviceStream_Device == null)
                        {
                            System.Diagnostics.Debug.WriteLine("Failed to create DeviceStreamClient!");
                            //return null;
                        }

                        try
                        {
                            await deviceStream_Device.RunDeviceAsync();//.GetAwaiter().GetResult();
                        }
                        catch (Microsoft.Azure.Devices.Client.Exceptions.IotHubCommunicationException)
                        {
                            System.Diagnostics.Debug.WriteLine("3 Error RunDevice(): Hub connection failure");
                        }
                        catch (Microsoft.Azure.Devices.Common.Exceptions.DeviceNotFoundException)
                        {
                            System.Diagnostics.Debug.WriteLine("3 Error RunDevice(): Device not found");
                        }
                        catch (TaskCanceledException)
                        {
                            System.Diagnostics.Debug.WriteLine("3 Error RunDevice(): Task canceled");
                        }
                        catch (OperationCanceledException)
                        {
                            System.Diagnostics.Debug.WriteLine("3 Error RunDevice(): Operation canceled");
                        }
                        catch (Exception ex)
                        {
                            if (!ex.Message.Contains("Timed out"))
                            {
                                System.Diagnostics.Debug.WriteLine("3 Error RunDevice(): " + ex.Message);
                            }
                            else
                            {
                                System.Diagnostics.Debug.WriteLine("3 Error RunDevice(): Timeout");
                            }
                        }
                    }
                    //return null;
                }
                catch (Microsoft.Azure.Devices.Client.Exceptions.IotHubCommunicationException)
                {
                    System.Diagnostics.Debug.WriteLine("4 Error RunDevice(): Hub connection failure");
                }
                catch (Microsoft.Azure.Devices.Common.Exceptions.DeviceNotFoundException)
                {
                    System.Diagnostics.Debug.WriteLine("4 Error RunDevice(): Device not found");
                }
                catch (TaskCanceledException)
                {
                    System.Diagnostics.Debug.WriteLine("4 Error RunDevice(): Task canceled");
                }
                catch (OperationCanceledException eex)
                {
                    System.Diagnostics.Debug.WriteLine("4 Error RunDevice(): Operation canceled \r\n" + eex.Message);
                }
                catch (Exception ex)
                {
                    if (!ex.Message.Contains("Timeout"))
                    {
                        System.Diagnostics.Debug.WriteLine("4 Error RunDevice(): " + ex.Message);
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine("4 Error RunDevice(): Timeout");
                    }
                }
                __keepDeviceListening = deviceStream_Device.DeviceCurrentSettings.KeepDeviceListening;
                if (__keepDeviceListening)
                {
                    deviceStream_Device.UpdateStatus("Continuing to listen");
                }
                else
                {
                    deviceStream_Device.UpdateStatus("Not listening");
                }
                //Nb: deviceStream_Device is disposed here.
            } while (__keepDeviceListening);
        }