static async Task ReceiveCommands(DeviceClient deviceClient) { Console.WriteLine("\nDevice waiting for commands from IoTHub...\n"); Message receivedMessage = null; while (true) { try { receivedMessage = await deviceClient.ReceiveAsync(TimeSpan.FromSeconds(1)); if (receivedMessage != null) { string messageData = Encoding.ASCII.GetString(receivedMessage.GetBytes()); Console.WriteLine("\t{0}> Received message: {1}", DateTime.Now.ToLocalTime(), messageData); int propCount = 0; foreach (var prop in receivedMessage.Properties) { Console.WriteLine("\t\tProperty[{0}> Key={1} : Value={2}", propCount++, prop.Key, prop.Value); } await deviceClient.CompleteAsync(receivedMessage); } } finally { if (receivedMessage != null) { receivedMessage.Dispose(); } } } }
static async Task ReceiveCommands(DeviceClient deviceClient) { Debug.WriteLine("\nDevice waiting for commands from IoTHub...\n"); Message receivedMessage; string messageData; while (true) { receivedMessage = await deviceClient.ReceiveAsync(); if (receivedMessage != null) { messageData = Encoding.ASCII.GetString(receivedMessage.GetBytes()); Debug.WriteLine("\t{0}> Received message: {1}", DateTime.Now.ToLocalTime(), messageData); await deviceClient.CompleteAsync(receivedMessage); } // Note: In this sample, the polling interval is set to // 10 seconds to enable you to see messages as they are sent. // To enable an IoT solution to scale, you should extend this // interval. For example, to scale to 1 million devices, set // the polling interval to 25 minutes. // For further information, see // https://azure.microsoft.com/documentation/articles/iot-hub-devguide/#messaging await Task.Delay(TimeSpan.FromSeconds(10)); } }
static async Task ReceiveCommands(DeviceClient deviceClient) { Console.WriteLine("\nDevice waiting for commands from IoTHub...\n"); Message receivedMessage; string messageData; while (true) { receivedMessage = await deviceClient.ReceiveAsync(); if (receivedMessage != null) { messageData = Encoding.ASCII.GetString(receivedMessage.GetBytes()); Console.WriteLine("\t{0}> Received message: {1}", DateTime.Now.ToLocalTime(), messageData); int propCount = 0; foreach (var prop in receivedMessage.Properties) { Console.WriteLine("\t\tProperty[{0}> Key={1} : Value={2}", propCount++, prop.Key, prop.Value); } await deviceClient.CompleteAsync(receivedMessage); } // Note: In this sample, the polling interval is set to // 10 seconds to enable you to see messages as they are sent. // To enable an IoT solution to scale, you should extend this // interval. For example, to scale to 1 million devices, set // the polling interval to 25 minutes. // For further information, see // https://azure.microsoft.com/documentation/articles/iot-hub-devguide/#messaging Thread.Sleep(10000); } }
//------------------------------------------------------------------------------------------------------------------------ #endregion #region Constructor //------------------------------------------------------------------------------------------------------------------------ public DevClient(string organization, string devtype, string devid, string authmethod, string authtoken) { // a device has already been registered in the IOTF deviceClient = new DeviceClient(organization, devtype, devid, authmethod, authtoken); //connect the device to the mqtt broker deviceClient.connect(); }
/// <summary> /// 带两个参数的构造函数,该状态下,ApnsProduction默认为false /// </summary> /// <param name="app_key">Portal上产生的app_key</param> /// <param name="masterSecret">你的API MasterSecret</param> public JPushClient(String app_key, String masterSecret) { _pushClient = new PushClient(app_key, masterSecret); _reportClient = new ReportClient(app_key, masterSecret); _deviceClient = new DeviceClient(app_key, masterSecret); }
public void Open() { if (string.IsNullOrWhiteSpace(_device.DeviceID)) { throw new ArgumentException("DeviceID value cannot be missing, null, or whitespace"); } _deviceClient = DeviceClient.CreateFromConnectionString(GetConnectionString()); }
static void Main(string[] args) { log4net.Config.XmlConfigurator.Configure(); ILog log = log4net.LogManager.GetLogger(typeof(SampleDeviceClient)); DeviceClient deviceClient = new DeviceClient("j82zgk", "TestType", "9663155111", "token", "y1&_!98TlxScdk?hqP"); deviceClient.connect(); deviceClient.publishEvent("temp", "json", "{\"temp\":\"23\"}", 2); deviceClient.subscribeCommand("testcmd","json",0); deviceClient.commandCallback += processCommand; deviceClient.disconnect(); }
static async Task SendEvent(DeviceClient deviceClient) { string dataBuffer; Console.WriteLine("Device sending {0} messages to IoTHub...\n", MESSAGE_COUNT); for (int count = 0; count < MESSAGE_COUNT; count++) { dataBuffer = Guid.NewGuid().ToString(); Message eventMessage = new Message(Encoding.UTF8.GetBytes(dataBuffer)); Console.WriteLine("\t{0}> Sending message: {1}, Data: [{2}]", DateTime.Now.ToLocalTime(), count, dataBuffer); await deviceClient.SendEventAsync(eventMessage); } }
static void Main(string[] args) { log4net.Config.XmlConfigurator.Configure(); ILog log = log4net.LogManager.GetLogger(typeof(SampleDeviceClientAutoData)); DeviceClient deviceClient = new DeviceClient("j82zgk", "TestType", "9663155111", "token", "y1&_!98TlxScdk?hqP"); deviceClient.connect(); deviceClient.subscribeCommand("testcmd","json",0); deviceClient.commandCallback += processCommand; for (int i = 0; i < 10; i++) { String data = "{time:" + DateTime.Now.ToString() + "}"; deviceClient.publishEvent("temp", "json", data, 2); Thread.Sleep(1000); } deviceClient.disconnect(); }
static async Task ReceiveCommands(DeviceClient deviceClient) { Console.WriteLine("\nDevice waiting for commands from IoTHub...\n"); Message receivedMessage; string messageData; while (true) { receivedMessage = await deviceClient.ReceiveAsync(TimeSpan.FromSeconds(1)); if (receivedMessage != null) { messageData = Encoding.ASCII.GetString(receivedMessage.GetBytes()); Console.WriteLine("\t{0}> Received message: {1}", DateTime.Now.ToLocalTime(), messageData); await deviceClient.CompleteAsync(receivedMessage); } } }
/// <summary> /// Initializes the DeviceClient and sets up the callback to receive /// messages containing temperature information /// </summary> static async Task Init(string connectionString, bool bypassCertVerification = false) { Console.WriteLine("Connection String {0}", connectionString); MqttTransportSettings mqttSetting = new MqttTransportSettings(TransportType.Mqtt_Tcp_Only); // During dev you might want to bypass the cert verification. It is highly recommended to verify certs systematically in production if (bypassCertVerification) { mqttSetting.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true; } ITransportSettings[] settings = { mqttSetting }; // Open a connection to the Edge runtime DeviceClient ioTHubModuleClient = DeviceClient.CreateFromConnectionString(connectionString, settings); await ioTHubModuleClient.OpenAsync(); Console.WriteLine("IoT Hub module client initialized."); // Read DataSentInterval from Module Twin Desired Properties var moduleTwin = await ioTHubModuleClient.GetTwinAsync(); var moduleTwinCollection = moduleTwin.Properties.Desired; try { dataSentInterval = moduleTwinCollection["DataSentInterval"]; } catch (ArgumentOutOfRangeException e) { Console.WriteLine("Property DataSentInterval not exist"); } // Attach callback for Twin desired properties updates await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(onDesiredPropertiesUpdate, null); // as this runs in a loop we don't await SendDataAsync(ioTHubModuleClient); }
public static async Task SendBatchMessagesAsync(DeviceClient deviceClient, string deviceId, MsTestLogger logger) { var messagesToBeSent = new Dictionary <Client.Message, Tuple <string, string> >(); try { var props = new List <Tuple <string, string> >(); for (int i = 0; i < MessageBatchCount; i++) { (Client.Message testMessage, string payload, string p1Value) = ComposeD2cTestMessage(logger); messagesToBeSent.Add(testMessage, Tuple.Create(payload, p1Value)); } await deviceClient.SendEventBatchAsync(messagesToBeSent.Keys.ToList()).ConfigureAwait(false); } finally { foreach (KeyValuePair <Client.Message, Tuple <string, string> > messageEntry in messagesToBeSent) { Client.Message message = messageEntry.Key; message.Dispose(); } } }
public bool Init() { if (deviceClient == null) { try { var localSettings = ApplicationData.Current.LocalSettings; deviceId = localSettings.Values[DEVICEID_TAG] as string; string deviceKey = localSettings.Values[IOTHUBKEY_TAG] as string; string receiverConnectionString = localSettings.Values[IOTHUBRECVCONN_TAG] as string; //char[] separators = { '=', ';' }; //string[] receiverArgs = receiverConnectionString.Split(separators); //string iotHubUri = (receiverArgs.Length >= 2) ? receiverArgs[1] : null; //deviceClient = DeviceClient.Create(iotHubUri, // AuthenticationMethodFactory.CreateAuthenticationWithRegistrySymmetricKey(deviceId, deviceKey), // TransportType.Http1); deviceClient = DeviceClient.CreateFromConnectionString( receiverConnectionString, deviceId, TransportType.Amqp_WebSocket_Only); return(true); } catch (Exception ex) { Debug.WriteLine("IoTHubMessageSender.Init: " + ex.Message); } return(false); } else { return(true); } }
public async Task RunAsync(string connectionString, ILogger logger, CancellationToken quitSignal) { this.logger = logger; deviceClient = DeviceClient.CreateFromConnectionString(connectionString, TransportType.Mqtt, new ClientOptions { ModelId = modelId }); tempSensor = new TemperatureSensor(deviceClient, "tempSensor1", logger); diag = new DiagnosticsInterface(deviceClient, "diag"); deviceInfo = new DeviceInformation(deviceClient, "deviceInfo"); sdkInfo = new SdkInformation(deviceClient, "sdkInfo"); await deviceInfo.ReportDeviceInfoPropertiesAsync(DeviceInfo.ThisDeviceInfo); await sdkInfo.ReportSdkInfoPropertiesAsync(); diag.OnRebootCommand += Diag_OnRebootCommand; tempSensor.OnTargetTempReceived += TempSensor_OnTargetTempReceived; await tempSensor.InitAsync(); await Task.Run(async() => { logger.LogWarning("Entering Device Loop"); while (!quitSignal.IsCancellationRequested) { await tempSensor.SendTemperatureTelemetryValueAsync(CurrentTemperature); await diag.SendWorkingTelemetryAsync(Environment.WorkingSet); logger.LogInformation("Sending workingset and temp " + CurrentTemperature); await Task.Delay(5000); } }); }
public static DeviceClient GetClient(string ip, int port, string username = "", string password = "") { EndpointAddress serviceAddress = new EndpointAddress(string.Format("", ip, port)); HttpTransportBindingElement httpBindingElement = new HttpTransportBindingElement(); httpBindingElement.AuthenticationScheme = AuthenticationSchemes.Digest; var messageElement = new TextMessageEncodingBindingElement(); messageElement.MessageVersion = MessageVersion.CreateVersion(EnvelopeVersion.Soap12, AddressingVersion.None); System.ServiceModel.Channels.CustomBinding customBinding = new System.ServiceModel.Channels.CustomBinding(messageElement, httpBindingElement); DeviceClient deviceClient = new DeviceClient(customBinding, serviceAddress); if (username != string.Empty) { // Handles adding of SOAP Security header containing User Token (user, nonce, pwd digest) PasswordDigestBehavior behavior = new PasswordDigestBehavior(username, password); deviceClient.Endpoint.Behaviors.Add(behavior); } return(deviceClient); }
// Tests_SRS_DEVICECLIENT_10_001: [ The SetMethodHandler shall lazy-initialize the deviceMethods property. ] // Tests_SRS_DEVICECLIENT_10_003: [ The given delegate will only be added if it is not null. ] public async Task DeviceClient_SetMethodHandler_SetFirstMethodHandler() { string connectionString = "HostName=acme.azure-devices.net;SharedAccessKeyName=AllAccessKey;DeviceId=dumpy;SharedAccessKey=CQN2K33r45/0WeIjpqmErV5EIvX8JZrozt3NEHCEkG8="; DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(connectionString); var innerHandler = Substitute.For <IDelegatingHandler>(); deviceClient.InnerHandler = innerHandler; bool methodCallbackCalled = false; string actualMethodName = string.Empty; string actualMethodBody = string.Empty; object actualMethodUserContext = null; MethodCallback methodCallback = (methodRequest, userContext) => { actualMethodName = methodRequest.Name; actualMethodBody = methodRequest.DataAsJson; actualMethodUserContext = userContext; methodCallbackCalled = true; return(Task.FromResult(new MethodResponse(new byte[0], 200))); }; string methodName = "TestMethodName"; string methodUserContext = "UserContext"; string methodBody = "{\"grade\":\"good\"}"; deviceClient.SetMethodHandler(methodName, methodCallback, methodUserContext); await deviceClient.OnMethodCalled(new MethodRequestInternal(methodName, "fakeRequestId", new MemoryStream(Encoding.UTF8.GetBytes(methodBody)))); await innerHandler.Received().EnableMethodsAsync(Arg.Any <CancellationToken>()); Assert.IsTrue(methodCallbackCalled); Assert.AreEqual(methodName, actualMethodName); Assert.AreEqual(methodBody, actualMethodBody); Assert.AreEqual(methodUserContext, actualMethodUserContext); }
private async Task SendSingleMessage(DeviceClient deviceClient, string deviceId) { EventHubTestListener testListener = await EventHubTestListener.CreateListener(deviceId).ConfigureAwait(false); try { await deviceClient.OpenAsync().ConfigureAwait(false); string payload; string p1Value; Client.Message testMessage = ComposeD2CTestMessage(out payload, out p1Value); await deviceClient.SendEventAsync(testMessage).ConfigureAwait(false); bool isReceived = await testListener.WaitForMessage(deviceId, payload, p1Value).ConfigureAwait(false); Assert.IsTrue(isReceived, "Message is not received."); } finally { await deviceClient.CloseAsync().ConfigureAwait(false); await testListener.CloseAsync().ConfigureAwait(false); } }
private async Task sendMethodAndRespondWithObseletedSetMethodHandler(Client.TransportType transport) { Tuple <string, string> deviceInfo = TestUtil.CreateDevice(DevicePrefix, hostName, registryManager); var assertResult = new TaskCompletionSource <Tuple <bool, bool> >(); var deviceClient = DeviceClient.CreateFromConnectionString(deviceInfo.Item2, transport); #pragma warning disable CS0618 deviceClient?.SetMethodHandler(MethodName, (request, context) => { assertResult.TrySetResult(new Tuple <bool, bool>(request.Name.Equals(MethodName), request.DataAsJson.Equals(ServiceRequestJson))); return(Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes(DeviceResponseJson), 200))); }, null); #pragma warning restore CS0618 // sleep to ensure async tasks started in SetMethodHandler has completed Thread.Sleep(5000); await ServiceSendMethodAndVerifyResponse(deviceInfo.Item1, MethodName, DeviceResponseJson, ServiceRequestJson, assertResult); await deviceClient.CloseAsync(); await TestUtil.RemoveDeviceAsync(deviceInfo.Item1, registryManager); }
private async Task initialzation(string certificatePath) { _restfulAPIHelper = new RestfulAPIHelper(_hwProductKey.email, _hwProductKey.password); // Get the Device Model string resp = await _restfulAPIHelper.callDeviceAPIService("GET", _hwProductKey.email, null); _deviceModels = DeviceModels.CreateDeviceModels(resp); verifyAndAppendIoTHubAuthCertificatePath(_deviceModels, _certificatePath); // Get the Message Schema of Device resp = await _restfulAPIHelper.getDeviceMessageSchemaAPIService(_hwProductKey.email); _messageCatalogSchemaList = MessageCatalogSchema.CreateMessageCatalogSchemaList(resp); _deviceClient = getAzureIoTDeviceSDKClient(_deviceModels); // Get SfTwin Properties Helper _sfTwinPropertiesHelper = new SfTwinPropertiesHelper(_deviceClient); // Sync System Config of Twin await _sfTwinPropertiesHelper.SyncAndUpdateSfTwinPropertiesFromTwin(); }
private DeviceClient getAzureIoTDeviceSDKClient(DeviceModels deviceModels) { if (deviceModels.IoTHubAuthenticationType.ToLower().Equals(DeviceModels.IOTHUB_AUTH_TYPE_KEY)) { string connectionString = combineIoTHubDeviceConnectionString(deviceModels.IoTHubName, deviceModels.DeviceId, deviceModels.DeviceKey); Logger.showDebug(TAG, "IoTHubName={0}, DeviceId={1}, DeviceKey={2}".FormatInvariant(deviceModels.IoTHubName, deviceModels.DeviceId, deviceModels.DeviceKey)); Logger.showDebug(TAG, "IoTHubProtocol={0}".FormatInvariant(deviceModels.IoTHubProtocol)); DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(connectionString, getTransportType(deviceModels.IoTHubProtocol.ToLower())); return(deviceClient); } else if (deviceModels.IoTHubAuthenticationType.ToLower().Equals(DeviceModels.IOTHUB_AUTH_TYPE_CERTIFICATE)) { // x509 certificate var x509Certificate = new X509Certificate2(deviceModels.CertificateFileName, deviceModels.CertificatePassword); Logger.showDebug(TAG, "CertificateFileName={0}, CertificatePassword={1}".FormatInvariant(deviceModels.CertificateFileName, deviceModels.CertificatePassword)); Logger.showDebug(TAG, "IoTHubProtocol={0}".FormatInvariant(deviceModels.IoTHubProtocol)); var authMethod = new DeviceAuthenticationWithX509Certificate(deviceModels.DeviceId, x509Certificate); DeviceClient deviceClient = DeviceClient.Create( deviceModels.IoTHubName, authMethod, getTransportType(deviceModels.IoTHubProtocol.ToLower())); return(deviceClient); } else { Logger.showError(TAG, "Unsupported IoTHub Authentication Type {0}".FormatInvariant(deviceModels.IoTHubAuthenticationType)); throw new InvalidOperationException("Unsupported IoTHub Authentication Type {0}".FormatInvariant(deviceModels.IoTHubAuthenticationType)); } }
private static async Task Main(string[] args) { Console.WriteLine("IoT Hub #1 - Simulated device."); //ValidateConnectionString(args); s_deviceClient = DeviceClient.CreateFromConnectionString(s_connectionString, s_transportType); Console.WriteLine("Press control-C to exit."); using var cts = new CancellationTokenSource(); Console.CancelKeyPress += (sender, eventArgs) => { eventArgs.Cancel = true; cts.Cancel(); Console.WriteLine("Exiting..."); }; await SendDeviceToCloudMessagesAsync(cts.Token); await s_deviceClient.CloseAsync(); s_deviceClient.Dispose(); Console.WriteLine("Device simulator finished."); }
public static DeviceClient GetOnvifDeviceClient(string ip, int port, double deviceTimeOffset, string username = "", string password = "") { EndpointAddress serviceAddress = new EndpointAddress(string.Format("http://{0}:{1}/onvif/device_service", ip, port)); HttpTransportBindingElement httpBinding = new HttpTransportBindingElement(); httpBinding.AuthenticationScheme = AuthenticationSchemes.Digest; var messageElement = new TextMessageEncodingBindingElement(); messageElement.MessageVersion = MessageVersion.CreateVersion(EnvelopeVersion.Soap12, AddressingVersion.None); CustomBinding bind = new CustomBinding(messageElement, httpBinding); DeviceClient deviceClient = new DeviceClient(bind, serviceAddress); if (username != string.Empty) { // Handles adding of SOAP Security header containing User Token (user, nonce, pwd digest) PasswordDigestBehavior behavior = new PasswordDigestBehavior(username, password, deviceTimeOffset); deviceClient.Endpoint.Behaviors.Add(behavior); } return(deviceClient); }
private static async Task SendDeviceToCloudMessageAsyc() { Console.WriteLine("Sending Data To Hub"); Console.WriteLine("Please enter the connection string"); var connectionString = Console.ReadLine(); if (string.IsNullOrWhiteSpace(connectionString)) { connectionString = defaultConnectionString; } try { var deviceClient = DeviceClient.CreateFromConnectionString(connectionString, TransportType.Mqtt); while (true) { var data = JsonConvert.SerializeObject(new { ticketId = Guid.NewGuid(), entryTime = DateTime.UtcNow }); var message = new Message(Encoding.ASCII.GetBytes(data)); await deviceClient.SendEventAsync(message); Console.WriteLine("{0} > Sending Message: {1}", DateTime.UtcNow, data); await Task.Delay(1000); } } catch (Exception ex) { Console.WriteLine(ex); } }
private static async Task RunSimulatedGeneratorDataAsync(DeviceClient device, CancellationToken ct) { var rand = new Random(); const int anomalyTimeinterval = 20; var nextAnomalousEvent = DateTime.Now.AddSeconds(anomalyTimeinterval); while (!ct.IsCancellationRequested) { var measurement = new MeasurementMessage { TemperatureUnit = "Temperature", Temperature = (rand.Next(200, 209) / 10f), HumidityUnit = "%", Humidity = rand.Next(480, 520) / 10f, PressureUnit = "hPa", Pressure = rand.Next(9400, 9500) / 10f }; if (nextAnomalousEvent < DateTime.Now) { Console.WriteLine("**GENERATING ANOMALY**"); measurement.Temperature = rand.Next(300, 350) / 10f; measurement.Humidity = rand.Next(800, 1000) / 10f; nextAnomalousEvent = DateTime.Now.AddSeconds(anomalyTimeinterval); } else { Console.WriteLine("Sending measurement..."); } await SendMessage(device, measurement); await Task.Delay(1000, ct); } }
static async Task MainAsync() { try { deviceClient = DeviceClient.CreateFromConnectionString(DeviceConnectionString); //await SendEvent(deviceClient).ConfigureAwait(false); await ReceiveCommands(deviceClient).ConfigureAwait(false); } catch (UnauthorizedException ex) { Console.WriteLine("UnauthorizedExpception:\n" + ex.Message); if (!isRollOverInvoked) { isRollOverInvoked = true; DeviceConnectionString = DeviceConnectionString2; await MainAsync().ConfigureAwait(false); } else { throw ex; } } }
private DeviceClient CreateDeviceClient() { DeviceClient client = null; if (!string.IsNullOrEmpty(_iotHub) && _auth != null) { Console.WriteLine($"CreateDeviceClient::{_iotHub}"); client = DeviceClient.Create(_iotHub, _auth, TransportType.Mqtt_WebSocket_Only); } else if (!string.IsNullOrEmpty(_connectionString)) { Console.WriteLine($"CreateDeviceClient::{_connectionString}"); client = DeviceClient.CreateFromConnectionString(_connectionString); } else { throw new ArgumentNullException("Connection information"); } // TODO: Should handle reprovision ? If so, then should switch to // DeviceProvisioningClient instead of DeviceClient to create IoT hub connection //client.SetMethodHandlerAsync("Reprovision", ReprovisionHandler, null).GetAwaiter().GetResult(); client.SetDesiredPropertyUpdateCallbackAsync(DesiredPropertyUpdated, null).GetAwaiter().GetResult(); return(client); }
public static async Task SendMessageAsync(DeviceClient deviceClient) { while (true) { double temp = 10 + rnd.NextDouble() * 15; double hum = 40 + rnd.NextDouble() * 20; var data = new { temperature = temp, humidity = hum }; var json = JsonConvert.SerializeObject(data); var payload = new Message(Encoding.UTF8.GetBytes(json)); payload.Properties.Add("temperatureAlert", (temp > 30) ? "true" : "false"); await deviceClient.SendEventAsync(payload); Console.WriteLine($"Message sent: {json}"); await Task.Delay(telemetryInterval * 1000); } }
public static async Task <float> ReceiveCloudToDeviceMessageAsync() { try { var deviceClient = DeviceClient.CreateFromConnectionString(deviceConnectionString, TransportType.Http1); while (true) { var receivedMessage = await deviceClient.ReceiveAsync(); if (receivedMessage != null) { var messageData = Encoding.ASCII.GetString(receivedMessage.GetBytes()); await deviceClient.CompleteAsync(receivedMessage); dynamic dataObject = JsonConvert.DeserializeObject(messageData); deviceClient.CompleteAsync(receivedMessage); return(dataObject.ThresholdReached); } // Note: In this sample, the polling interval is set to // 10 seconds to enable you to see messages as they are sent. // To enable an IoT solution to scale, you should extend this // interval. For example, to scale to 1 million devices, set // the polling interval to 25 minutes. // For further information, see // https://azure.microsoft.com/documentation/articles/iot-hub-devguide/#messaging await Task.Delay(TimeSpan.FromMilliseconds(500)); } } catch (Exception e) { // Add your own log tracing here return(100); } }
async Task uploadFile(Client.TransportType transport, string filename, bool x509auth = false) { DeviceClient deviceClient; Tuple <string, string> deviceInfo; if (x509auth) { deviceInfo = TestUtil.CreateDeviceWithX509(DevicePrefix, hostName, registryManager); X509Certificate2 cert = Configuration.IoTHub.GetCertificateWithPrivateKey(); var auth = new DeviceAuthenticationWithX509Certificate(deviceInfo.Item1, cert); deviceClient = DeviceClient.Create(deviceInfo.Item2, auth, transport); } else { deviceInfo = TestUtil.CreateDevice(DevicePrefix, hostName, registryManager); deviceClient = DeviceClient.CreateFromConnectionString(deviceInfo.Item2, transport); } using (FileStream fileStreamSource = new FileStream(filename, FileMode.Open, FileAccess.Read)) { await deviceClient.UploadToBlobAsync(filename, fileStreamSource).ConfigureAwait(false); } FileNotification fileNotification = await VerifyFileNotification(deviceInfo).ConfigureAwait(false); Assert.IsNotNull(fileNotification, "FileNotification is not received."); Assert.AreEqual(deviceInfo.Item1 + "/" + filename, fileNotification.BlobName, "Uploaded file name mismatch in notifications"); Assert.AreEqual(new FileInfo(filename).Length, fileNotification.BlobSizeInBytes, "Uploaded file size mismatch in notifications"); Assert.IsFalse(string.IsNullOrEmpty(fileNotification.BlobUri), "File notification blob uri is null or empty"); await deviceClient.CloseAsync().ConfigureAwait(false); await TestUtil.RemoveDeviceAsync(deviceInfo.Item1, registryManager).ConfigureAwait(false); }
public Temperature() { var pin = GpioController.GetDefault().OpenPin(4, GpioSharingMode.Exclusive); Dht = new Dht11(pin, GpioPinDriveMode.Input); _timer.Tick += (sender, o) => { // Get Temperature and Humidity Reading GetReading(); }; _timer.Interval = TimeSpan.FromSeconds(1); _timer.Start(); try { _deviceClient = DeviceClient.Create(iotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey(deviceName, deviceKey), TransportType.Http1); } catch (Exception) { //nothing } }
private static void Main(string[] args) { if (readTheFile) { // If you want to decode an output file, put the path in ReadOneRowFromFile(), // uncomment the call here and the return command, then run this application. ReadOneRowFromFile(); } else { // Send messages to the simulated device. Each message will contain a randomly generated // Temperature and Humidity. // The "level" of each message is set randomly to "storage", "critical", or "normal". // The messages are routed to different endpoints depending on the level, temperature, and humidity. // This is set in the tutorial that goes with this sample: // http://docs.microsoft.com/azure/iot-hub/tutorial-routing Console.WriteLine("Routing Tutorial: Simulated device\n"); s_deviceClient = DeviceClient.Create(s_iotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey(s_myDeviceId, s_deviceKey), TransportType.Mqtt); SendDeviceToCloudMessagesAsync(); Console.WriteLine("Press the Enter key to stop."); Console.ReadLine(); } }
private async Task _Twin_DeviceReportedPropertiesRecovery(Client.TransportType transport, string faultType, string reason, int delayInSec) { var propName = Guid.NewGuid().ToString(); var propValue1 = Guid.NewGuid().ToString(); Tuple <string, string> deviceInfo = TestUtil.CreateDevice(DevicePrefix, hostName, registryManager); var deviceClient = DeviceClient.CreateFromConnectionString(deviceInfo.Item2, transport); TwinCollection props = new TwinCollection(); props[propName] = propValue1; await deviceClient.UpdateReportedPropertiesAsync(props); var deviceTwin = await deviceClient.GetTwinAsync(); Assert.AreEqual <String>(deviceTwin.Properties.Reported[propName].ToString(), propValue1); // send error command await deviceClient.SendEventAsync(TestUtil.ComposeErrorInjectionProperties(faultType, reason, delayInSec)); deviceTwin = await deviceClient.GetTwinAsync(); Assert.AreEqual <String>(deviceTwin.Properties.Reported[propName].ToString(), propValue1); var propValue2 = Guid.NewGuid().ToString(); props[propName] = propValue2; await deviceClient.UpdateReportedPropertiesAsync(props); deviceTwin = await deviceClient.GetTwinAsync(); Assert.AreEqual <String>(deviceTwin.Properties.Reported[propName].ToString(), propValue2); await deviceClient.CloseAsync(); await TestUtil.RemoveDeviceAsync(deviceInfo.Item1, registryManager); }
private async Task ReceiveMessageInOperationTimeoutAsync(TestDeviceType type, Client.TransportType transport) { TestDevice testDevice = await TestDevice.GetTestDeviceAsync(Logger, s_devicePrefix, type).ConfigureAwait(false); using DeviceClient deviceClient = testDevice.CreateDeviceClient(transport); Logger.Trace($"{nameof(ReceiveMessageInOperationTimeoutAsync)} - calling OpenAsync() for transport={transport}"); await deviceClient.OpenAsync().ConfigureAwait(false); try { deviceClient.OperationTimeoutInMilliseconds = Convert.ToUInt32(s_oneMinute.TotalMilliseconds); Logger.Trace($"{nameof(ReceiveMessageInOperationTimeoutAsync)} - setting device client default operation timeout={deviceClient.OperationTimeoutInMilliseconds} ms"); if (transport == Client.TransportType.Amqp || transport == Client.TransportType.Amqp_Tcp_Only || transport == Client.TransportType.Amqp_WebSocket_Only) { // TODO: this extra minute on the timeout is undesirable by customers, and tests seems to be failing on a slight timing issue. // For now, add an additional 5 second buffer to prevent tests from failing, and meanwhile address issue 1203. // For AMQP because of static 1 min interval check the cancellation token, in worst case it will block upto extra 1 min to return await ReceiveMessageWithoutTimeoutCheckAsync(deviceClient, s_oneMinute + TimeSpan.FromSeconds(5), Logger).ConfigureAwait(false); } else { await ReceiveMessageWithoutTimeoutCheckAsync(deviceClient, s_fiveSeconds, Logger).ConfigureAwait(false); } } finally { Logger.Trace($"{nameof(ReceiveMessageInOperationTimeoutAsync)} - calling CloseAsync() for transport={transport}"); deviceClient.OperationTimeoutInMilliseconds = DeviceClient.DefaultOperationTimeoutInMilliseconds; await deviceClient.CloseAsync().ConfigureAwait(false); } }
private static async Task SendStatus(DeviceClient device, decimal temperature, decimal oilPressure, decimal coolantLevel, decimal vibrationLevel) { Console.Write("."); await SendMessageTo(device, new TelemetryMessage { SensorName = "Temperature", Value = temperature }); await SendMessageTo(device, new TelemetryMessage { SensorName = "OilPressure", Value = oilPressure }); await SendMessageTo(device, new TelemetryMessage { SensorName = "CoolantLevel", Value = coolantLevel }); await SendMessageTo(device, new TelemetryMessage { SensorName = "VibrationLevel", Value = vibrationLevel }); }
private async Task <DeviceClient> GetDeviceClient(string deviceId, CancellationToken cancellationToken) { if (!DeviceClients.ContainsKey(deviceId)) { // Check if device exists _logger.LogInformation($"Initializing device {deviceId}"); var device = await IoTHubManager.GetDeviceAsync(deviceId, cancellationToken); if (device == null) { await IoTHubManager.AddDeviceAsync(new Device(deviceId), cancellationToken); device = await IoTHubManager.GetDeviceAsync(deviceId, cancellationToken); _logger.LogInformation("Device " + deviceId + " created"); } var deviceConnectionString = $"HostName={IotHubConnectionStringBuilder.Create(_iotHubSettings.IoTHubOwnerConnectionString).HostName};DeviceId={deviceId};SharedAccessKey={device.Authentication.SymmetricKey.PrimaryKey}"; DeviceClients.Add(deviceId, DeviceClient.CreateFromConnectionString(deviceConnectionString)); } return(DeviceClients[deviceId]); }
private async Task UploadFileDisconnectTransport( Client.TransportType transport, string filename, string faultType, string reason, int delayInSec, int durationInSec = 0, int retryDurationInMilliSec = FaultInjection.RecoveryTimeMilliseconds) { TestDevice testDevice = await TestDevice.GetTestDeviceAsync(DevicePrefix).ConfigureAwait(false); using (var deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString, transport)) { deviceClient.OperationTimeoutInMilliseconds = (uint)retryDurationInMilliSec; await FileNotificationTestListener.InitAsync().ConfigureAwait(false); using (var fileStreamSource = new FileStream(filename, FileMode.Open, FileAccess.Read)) { Task fileUploadTask = deviceClient.UploadToBlobAsync(filename, fileStreamSource); Task errorInjectionTask = SendErrorInjectionMessageAsync(deviceClient, faultType, reason, delayInSec, durationInSec); await Task.WhenAll(fileUploadTask, errorInjectionTask).ConfigureAwait(false); await FileNotificationTestListener.VerifyFileNotification(filename, testDevice.Id).ConfigureAwait(false); } try { await deviceClient.CloseAsync().ConfigureAwait(false); } catch { // catch and ignore exceptions resulted incase device client close failed while offline } } }
static void Main(string[] args) { try { DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(DeviceConnectionString); if (deviceClient == null) { Console.WriteLine("Failed to create DeviceClient! deviceClient == null"); } else { Console.WriteLine("I can send messages to the IoT Hub! \n"); SendEvent(deviceClient).Wait(); ReceiveCommands(deviceClient).Wait(); } Console.WriteLine("Exited!\n"); } catch (Exception ex) { Console.WriteLine("Error in sample: {0}", ex.Message); } }
private async Task GetSasUriAsync(Client.TransportType transport, string blobName, bool useX509auth = false) { using TestDevice testDevice = await TestDevice .GetTestDeviceAsync( Logger, _devicePrefix, useX509auth ?TestDeviceType.X509 : TestDeviceType.Sasl) .ConfigureAwait(false); DeviceClient deviceClient; X509Certificate2 cert = null; DeviceAuthenticationWithX509Certificate x509Auth = null; if (useX509auth) { cert = s_selfSignedCertificate; x509Auth = new DeviceAuthenticationWithX509Certificate(testDevice.Id, cert); deviceClient = DeviceClient.Create(testDevice.IoTHubHostName, x509Auth, transport); } else { deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString, transport); } using (deviceClient) { FileUploadSasUriResponse sasUriResponse = await deviceClient.GetFileUploadSasUriAsync(new FileUploadSasUriRequest { BlobName = blobName }); await deviceClient.CloseAsync().ConfigureAwait(false); } x509Auth?.Dispose(); }
public DeviceClient GetDeviceClient(string deviceId, string key) { DeviceClient deviceClient; if (this.ContainsKey(deviceId)) { this[deviceId].DateTimeLastVisit = DateTime.Now; deviceClient = this[deviceId].DeviceClient; } else { var deviceConnectionString = $"HostName={_iotHubName}.azure-devices.net;DeviceId={deviceId};SharedAccessKey={key}"; deviceClient = DeviceClient.CreateFromConnectionString(deviceConnectionString, TransportType.Amqp); // Create thread var starter = new ThreadStart(async() => await ThreadHandler(deviceId, deviceClient)); var thread = new Thread(starter); thread.Start(); // Keep thread in memory var gatewayDeviceClient = new GatewayDeviceClient { DeviceClient = deviceClient, Thread = thread, DateTimeLastVisit = DateTime.Now }; Add(deviceId, gatewayDeviceClient); } TryToRemoveOldDevices(); return(deviceClient); }
/// <summary>� /// Callback to handle Twin desired properties updates� /// </summary>� static async Task OnDesiredPropertiesUpdate(TwinCollection desiredProperties, object userContext) { DeviceClient ioTHubModuleClient = userContext as DeviceClient; try { #if IOT_EDGE // stop all activities while updating configuration await ioTHubModuleClient.SetInputMessageHandlerAsync( "input1", DummyCallBack, null); #endif m_run = false; await Task.WhenAll(m_task_list); m_task_list.Clear(); m_run = true; await UpdateStartFromTwin(desiredProperties, ioTHubModuleClient); } catch (AggregateException ex) { foreach (Exception exception in ex.InnerExceptions) { Console.WriteLine(); Console.WriteLine("Error when receiving desired property: {0}", exception); } } catch (Exception ex) { Console.WriteLine(); Console.WriteLine("Error when receiving desired property: {0}", ex.Message); } }