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");
        }
示例#2
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.");
        }
        //"HostName=MyNewHub2.azure-devices.net;SharedAccessKeyName=service;SharedAccessKey=BuPhIaEYb7S/FK9ojoDqxi8jyUhCttokrcXDTJGwoNI=";
        //"HostName=MyNewHub2.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=7KZtl2QDsaiS7of40G56f7Ib27SQ5gx3XAmQkAN0Kks=";
        //"{Your service connection string here}";

        // Invoke the direct method on the device, passing the payload
        private static async Task InvokeMethod(int DelayBetweenTelemetryReadings, int ConnectionTimeout, int MethodTimeout, int MethodTag)
        {
            CloudToDeviceMethod methodInvocation = null;

            switch (MethodTag)
            {
            case 1:
                methodInvocation = new CloudToDeviceMethod("SetTelemetryInterval")
                {
                };
                //Method timeout
                methodInvocation.ResponseTimeout = TimeSpan.FromSeconds(MethodTimeout);
                //Timeout for device to come online
                methodInvocation.ConnectionTimeout = TimeSpan.FromSeconds(ConnectionTimeout);
                methodInvocation.SetPayloadJson(string.Format("{0}", DelayBetweenTelemetryReadings));
                break;

            case 2:
                methodInvocation = new CloudToDeviceMethod("SetTelemetryInterval2")
                {
                };
                //Method timeout
                methodInvocation.ResponseTimeout = TimeSpan.FromSeconds(MethodTimeout);
                //Timeout for device to come online
                methodInvocation.ConnectionTimeout = TimeSpan.FromSeconds(ConnectionTimeout);
                methodInvocation.SetPayloadJson(string.Format("{0}", DelayBetweenTelemetryReadings));
                break;

            default:
                break;
            }
            if (methodInvocation != null)
            {
                System.Diagnostics.Debug.WriteLine(" s_serviceClient.InvokeDeviceMethodAsync");
                // Invoke the direct method asynchronously and get the response from the simulated device.
                var response = await s_serviceClient.InvokeDeviceMethodAsync(Azure_IoTHub_Connections.MyConnections.DeviceId, methodInvocation);

                OnDeviceStatusUpdateD?.Invoke(string.Format("Svc Control Set Response status: {0}, payload:", response.Status));
                System.Diagnostics.Debug.WriteLine("Svc Control Set Response status: {0}, payload:", response.Status);
                string resp = response.GetPayloadAsJson();
                System.Diagnostics.Debug.WriteLine(string.Format("Svc Control Set Response: {0}", resp));
                OnDeviceStatusUpdateD?.Invoke(string.Format("Svc Control SetResponse: {0}", resp));
            }
        }
        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();
        }
示例#5
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);
        }