public static async Task GetDeviceTwinAsync() { CreateClient(); Console.WriteLine("Getting device twin"); Twin twin = await deviceClient.GetTwinAsync(); Console.WriteLine(twin.ToJson()); }
static void Main(string[] args) { TransportType transport = TransportType.Mqtt; string environmentConnectionString = Environment.GetEnvironmentVariable("IOTHUB_DEVICE_CONN_STR"); if (!String.IsNullOrEmpty(environmentConnectionString)) { DeviceConnectionString = environmentConnectionString; } if (args.Length == 1 && args[0].ToLower().Equals("amqp")) { transport = TransportType.Amqp; } try { Console.WriteLine("Connecting to hub"); Client = DeviceClient.CreateFromConnectionString(DeviceConnectionString, transport); Client.SetConnectionStatusChangesHandler(ConnectionStatusChangeHandler); Client.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertyChanged, null).Wait(); Console.WriteLine("Retrieving twin"); var twinTask = Client.GetTwinAsync(); twinTask.Wait(); var twin = twinTask.Result; Console.WriteLine("initial twin value received:"); Console.WriteLine(JsonConvert.SerializeObject(twin)); Console.WriteLine("Sending app start time as reported property"); TwinCollection reportedProperties = new TwinCollection(); reportedProperties["DateTimeLastAppLaunch"] = DateTime.Now; Client.UpdateReportedPropertiesAsync(reportedProperties); } catch (AggregateException ex) { foreach (Exception exception in ex.InnerExceptions) { Console.WriteLine(); Console.WriteLine("Error in sample: {0}", exception); } } catch (Exception ex) { Console.WriteLine(); Console.WriteLine("Error in sample: {0}", ex.Message); } Console.WriteLine("Waiting for Events. Press enter to exit..."); Console.ReadLine(); Console.WriteLine("Exiting..."); Client?.CloseAsync().Wait(); }
private async Task GetAndApplyDeviceTwins() { var twin = await Client.GetTwinAsync(); if (!LightBulbFromTwins(twin.Properties.Desired)) { LightBulb(TrafficLightState.Off); await ReportCurrentLight(); } }
private async Task GetWritablePropertiesAndHandleChangesAsync() { Twin twin = await _deviceClient.GetTwinAsync(); _logger.LogInformation($"Device retrieving twin values on CONNECT: {twin.ToJson()}"); TwinCollection twinCollection = twin.Properties.Desired; long serverWritablePropertiesVersion = twinCollection.Version; // Check if the writable property version is outdated on the local side. // For the purpose of this sample, we'll only check the writable property versions between local and server // side without comparing the property values. if (serverWritablePropertiesVersion > s_localWritablePropertiesVersion) { _logger.LogInformation($"The writable property version cached on local is changing " + $"from {s_localWritablePropertiesVersion} to {serverWritablePropertiesVersion}."); foreach (KeyValuePair <string, object> propertyUpdate in twinCollection) { string componentName = propertyUpdate.Key; switch (componentName) { case Thermostat1: case Thermostat2: // This will be called when a device client gets initialized and the _temperature dictionary is still empty. if (!_temperature.TryGetValue(componentName, out double value)) { _temperature[componentName] = 21d; // The default temperature value is 21°C. } await TargetTemperatureUpdateCallbackAsync(twinCollection, componentName); break; default: _logger.LogWarning($"Property: Received an unrecognized property update from service:" + $"\n[ {propertyUpdate.Key}: {propertyUpdate.Value} ]."); break; } } _logger.LogInformation($"The writable property version on local is currently {s_localWritablePropertiesVersion}."); } }
public void Run(IBackgroundTaskInstance taskInstance) { try { bme280Sensor = new BME280(0x76); } catch (Exception ex) { Debug.WriteLine($"BME280 Initialisation failed:{ex.Message}"); return; } try { azureIoTHubClient = DeviceClient.CreateFromConnectionString(AzureIoTHubConnectionString, TransportType.Mqtt); } catch (Exception ex) { Debug.WriteLine($"CreateFromConnectionString failed:{ex.Message}"); return; } try { deviceTwin = azureIoTHubClient.GetTwinAsync().Result; } catch (Exception ex) { Debug.WriteLine($"Azure IoT Hub device twin configuration retrieval failed:{ex.Message}"); return; } try { if (deviceTwin.Properties.Desired.Contains("TimerDue")) { timerDue = TimeSpan.Parse(deviceTwin.Properties.Desired["TimerDue"].ToString()); } if (deviceTwin.Properties.Desired.Contains("TimerPeriod")) { timerPeriod = TimeSpan.Parse(deviceTwin.Properties.Desired["TimerPeriod"].ToString()); } } catch (Exception ex) { Debug.WriteLine($"Sensor due or period configuration retrieval failed, using default:{ex.Message}"); return; } bme280InputPollingTimer = new Timer(SensorUpdateTimerCallback, null, timerDue, timerPeriod); backgroundTaskDeferral = taskInstance.GetDeferral(); }
async Task <(TwinCollection, TwinCollection)> TestTwinUpdate( DeviceClient deviceClient, string deviceName, RegistryManager rm, Twin twinPatch) { var receivedDesiredProperties = new TwinCollection(); bool desiredPropertiesUpdateCallbackTriggered = false; Task DesiredPropertiesUpdateCallback(TwinCollection desiredproperties, object usercontext) { receivedDesiredProperties = desiredproperties; desiredPropertiesUpdateCallbackTriggered = true; return(Task.CompletedTask); } await deviceClient.SetDesiredPropertyUpdateCallbackAsync(DesiredPropertiesUpdateCallback, null); // fetch the newly minted twin Twin originalCloudTwin = await deviceClient.GetTwinAsync(); Twin rmTwin = await rm.GetTwinAsync(deviceName); // updated twin in the cloud with the patch await rm.UpdateTwinAsync(deviceName, twinPatch, rmTwin.ETag); // Get the updated twin Twin updatedCloudTwin = await deviceClient.GetTwinAsync(); // replicate the patch operation locally var delayTask = Task.Delay(TimeSpan.FromSeconds(60)); while (!desiredPropertiesUpdateCallbackTriggered && !delayTask.IsCompleted) { await Task.Delay(TimeSpan.FromMilliseconds(500)); } string mergedJson = JsonEx.Merge(originalCloudTwin.Properties.Desired, receivedDesiredProperties, true); var localMergedTwinProperties = new TwinCollection(mergedJson); return(localMergedTwinProperties, updatedCloudTwin.Properties.Desired); }
private async void MainPage_Loaded(object sender, RoutedEventArgs e) { var client = DeviceClient.CreateFromConnectionString(DeviceConnectionString, TransportType.Mqtt); this.client = client; OutputLabel.Text = DeviceConnectionString; var deviceInfo = new DeviceModel { ObjectType = "DeviceInfo", ObjectName = DeviceId, Version = "1.0", DeviceProperties = new DeviceProperties { DeviceID = "test1", HubEnabledState = true, Manufacturer = "Digital Thailand Club", FirmwareVersion = "2.0", DeviceState = "normal", }, IsSimulatedDevice = false, }; deviceInfo.Commands.Add(new Command("MyCommand", DeliveryType.Message, "My Command Description")); deviceInfo.Telemetry.Add(new Telemetry("Temperature", "Temperature", "double")); deviceInfo.Telemetry.Add(new Telemetry("LightLevel", "LightLevel", "double")); await client.OpenAsync(); // Enable device await client.SendEventAsync(ToMessage(deviceInfo)); // Working with Device Twin var twin = await client.GetTwinAsync(); await client.SetDesiredPropertyUpdateCallback(twinDesiredPropertiesUpdated, client); // Set Device Twin properties OutputLabel.Text = JsonConvert.SerializeObject(twin); var methods = new TwinCollection { ["Method1"] = "Method 1 Description" }; var properties = new TwinCollection { ["MyProp"] = "my value 1", ["SupportedMethods"] = methods, }; await client.UpdateReportedPropertiesAsync(properties); // Handle Cloud-to-Device Methods await client.SetMethodHandlerAsync("MyMethod", MyMethod, null); }
public async Task <Twin> GetTwinAsync() { if (_deviceClient == null) { throw new Exception("Should be Initial first"); } Twin twin = await _deviceClient.GetTwinAsync(); return(twin); }
public async Task <Twin> GetTwinAsync() { if (client == null) { return(await mockClient.GetTwinAsync()); } else { return(await client.GetTwinAsync()); } }
static async Task UpdateReportedProperties(TwinCollection reportedConfig) { try { await deviceClient.UpdateReportedPropertiesAsync(reportedConfig); Twin updatedtwin = await deviceClient.GetTwinAsync(); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine($"Updated Twin: {updatedtwin.ToJson(Formatting.Indented)}"); Console.ResetColor(); } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Debug.WriteLine($"An error occurred while updateing reported configuration from the twin: {ex.Message}"); Debug.WriteLine($"{ex.InnerException}"); Console.ResetColor(); } }
private async Task SendEventToHub(DeviceClient deviceClient, CancellationToken cancellationToken) { Console.WriteLine("Sending event to hub."); var twin = await deviceClient.GetTwinAsync(cancellationToken); var message = $"The current time from {twin.DeviceId} is {DateTime.Now.ToLongTimeString()}."; var encodedMessage = new Message(Encoding.ASCII.GetBytes(message)); Console.WriteLine($"Sending message [{message}]"); await deviceClient.SendEventAsync(encodedMessage, cancellationToken); }
public async Task RunAsync() { Console.WriteLine($"RegistrationID = {security.GetRegistrationID()}"); // Register the Device with DPS Console.Write("ProvisioningClient RegisterAsync . . . "); DeviceRegistrationResult result = await provClient.RegisterAsync().ConfigureAwait(false); Console.WriteLine($"Device Registration Status: {result.Status}"); Console.WriteLine($"ProvisioningClient AssignedHub: {result.AssignedHub}; DeviceID: {result.DeviceId}"); deviceId = result.DeviceId; // Verify Device Registration Status if (result.Status != ProvisioningRegistrationStatusType.Assigned) { throw new Exception($"DeviceRegistrationResult.Status is NOT 'Assigned'"); } // Create x509 DeviceClient Authentication Console.WriteLine("Creating X509 DeviceClient authentication."); var auth = new DeviceAuthenticationWithX509Certificate(result.DeviceId, (security as SecurityProviderX509).GetAuthenticationCertificate()); Console.WriteLine("Simulated Device. Ctrl-C to exit."); using (iotClient = DeviceClient.Create(result.AssignedHub, auth, TransportType.Amqp)) { // Explicitly open DeviceClient to communicate with Azure IoT Hub Console.WriteLine("DeviceClient OpenAsync."); await iotClient.OpenAsync().ConfigureAwait(false); // TODO 1: Setup OnDesiredPropertyChanged Event Handling to receive Desired Properties changes Console.WriteLine("Connecting SetDesiredPropertyUpdateCallbackAsync event handler..."); await iotClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertyChanged, null).ConfigureAwait(false); // TODO 2: Load Device Twin Properties since device is just starting up Console.WriteLine("Loading Device Twin Properties..."); var twin = await iotClient.GetTwinAsync().ConfigureAwait(false); // Use OnDesiredPropertyChanged event handler to set the loaded Device Twin Properties (re-use!) await OnDesiredPropertyChanged(twin.Properties.Desired, null); // Start reading and sending device telemetry Console.WriteLine("Start reading and sending device telemetry..."); await SendDeviceToCloudMessagesAsync(iotClient); // Explicitly close DeviceClient Console.WriteLine("DeviceClient CloseAsync."); await iotClient.CloseAsync().ConfigureAwait(false); } }
static async Task Main(string[] args) { Console.WriteLine("Simulated Bowl \n"); deviceClient = DeviceClient.Create(iotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey(DeviceId, DeviceKey), TransportType.Mqtt); var twin = await deviceClient.GetTwinAsync(); maxDoses = Convert.ToDouble(twin.DesiredProperty("dosesCounter")); if (twin.IsReportedPropertyEmpty("dosesCounter")) { doses = maxDoses; Console.WriteLine($"Doses {doses}"); } else { doses = Convert.ToDouble(twin.ReportedProperty("dosesCounter")); } while (true) { Console.WriteLine($"Doses {doses}"); Console.WriteLine($"[enter command (type 'i' for instructions)]"); string input = Console.ReadLine(); switch (input.ToLower()) { case "cat wants to eat": await CatEats(deviceClient); break; case "add dose": await AddDose(deviceClient); break; case "refill": await Refill(deviceClient); break; case "i": Console.WriteLine("- cat wants to eat: a dose gets eaten"); Console.WriteLine("- add dose: add a dose"); Console.WriteLine("- refill: restore doses quantity"); break; default: Console.WriteLine("Syntax error"); break; } } }
async Task ReadTwinPropsAsync() { var t = await deviceClient.GetTwinAsync(); var desiredProperties = t.Properties.Desired; string desiredPropertyValue = GetPropertyValueIfFound(desiredProperties, refreshIntervalPropertyName); if (int.TryParse(desiredPropertyValue, out int intValue)) { refreshInterval = intValue; } }
public async void Run(IBackgroundTaskInstance taskInstance) { _deferral = taskInstance.GetDeferral(); var device = new TpmDevice(0); try { string deviceConnectionString; do { try { deviceConnectionString = await device.GetConnectionStringAsync(); break; } catch { LogError(); } await Task.Delay(3000); }while (true); // Create DeviceClient. Application uses DeviceClient for telemetry messages, device twin // as well as device management DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(deviceConnectionString, TransportType.Mqtt); // update the initial twin var twin = await deviceClient.GetTwinAsync(); // IDeviceTwin abstracts away communication with the back-end. // AzureIoTHubDeviceTwinProxy is an implementation of Azure IoT Hub IDeviceTwin deviceTwinProxy = new AzureIoTHubDeviceTwinProxy(deviceClient); // IDeviceManagementRequestHandler handles device management-specific requests to the app, // such as whether it is OK to perform a reboot at any givem moment, according the app business logic // ToasterDeviceManagementRequestHandler is the Toaster app implementation of the interface IDeviceManagementRequestHandler appRequestHandler = new DeviceManagementRequestHandler(); // Create the DeviceManagementClient, the main entry point into device management _dmClient = await DeviceManagementClient.CreateAsync(deviceTwinProxy, appRequestHandler); await OnDesiredPropertyUpdate(twin.Properties.Desired, null); // Set the callback for desired properties update. The callback will be invoked // for all desired properties -- including those specific to device management await deviceClient.SetDesiredPropertyUpdateCallback(OnDesiredPropertyUpdate, null); } catch { LogError(); } }
public async Task Connect() { await _client.SetMethodHandlerAsync("log", HandleMessage, null); await _client.SetDesiredPropertyUpdateCallbackAsync(DesiredPropertyUpdate, null); await _client.OpenAsync(); Twin twin = await _client.GetTwinAsync(); await DesiredPropertyUpdate(twin.Properties.Desired, null); }
/// <summary> /// Get the configuration for the module (in this case the threshold temperature)s. /// </summary> static async Task <ModuleConfig> GetConfiguration(DeviceClient deviceClient) { // First try to get the config from the Module twin Twin twin = await deviceClient.GetTwinAsync(); if (twin.Properties.Desired.Contains(AutoCallKey)) { bool autoCall = (bool)twin.Properties.Desired[AutoCallKey]; return(new ModuleConfig(autoCall)); } return(null); }
public async Task Initialize() { client = DeviceClient.CreateFromConnectionString(DeviceConnectionString, TransportType.Mqtt); deviceTwin = await client.GetTwinAsync(); await client.SetMethodHandlerAsync("StartRecording", startRecordingAsync, null); await client.SetMethodHandlerAsync("StopRecording", stopRecordingAsync, null); await initializeCameraAsync(); isInitialized = true; }
public static async Task Twin_DeviceSetsReportedPropertyAndGetsItBack(DeviceClient deviceClient) { var propName = Guid.NewGuid().ToString(); var propValue = Guid.NewGuid().ToString(); TwinCollection props = new TwinCollection(); props[propName] = propValue; await deviceClient.UpdateReportedPropertiesAsync(props).ConfigureAwait(false); Twin deviceTwin = await deviceClient.GetTwinAsync().ConfigureAwait(false); Assert.AreEqual <String>(deviceTwin.Properties.Reported[propName].ToString(), propValue); }
public async Task RunAsync() { colorMessage($"\nRegistrationID = {_security.GetRegistrationID()}", ConsoleColor.Yellow); // Register the Device with DPS. whiteMessage("ProvisioningClient RegisterAsync . . . "); DeviceRegistrationResult result = await _provClient.RegisterAsync().ConfigureAwait(false); if (result.Status == ProvisioningRegistrationStatusType.Assigned) { greenMessage($"Device Registration Status: {result.Status}"); greenMessage($"ProvisioningClient AssignedHub: {result.AssignedHub}; DeviceID: {result.DeviceId}"); } else { redMessage($"Device Registration Status: {result.Status}"); throw new Exception($"DeviceRegistrationResult.Status is NOT 'Assigned'"); } // Create x509 DeviceClient Authentication. whiteMessage("Creating X509 DeviceClient authentication."); var auth = new DeviceAuthenticationWithX509Certificate(result.DeviceId, (_security as SecurityProviderX509).GetAuthenticationCertificate()); whiteMessage("Simulated Device. Ctrl-C to exit."); using (s_deviceClient = DeviceClient.Create(result.AssignedHub, auth, TransportType.Amqp)) { // Explicitly open DeviceClient to communicate with Azure IoT Hub. whiteMessage("DeviceClient OpenAsync."); await s_deviceClient.OpenAsync().ConfigureAwait(false); // Setup OnDesiredPropertyChanged Event Handling to receive Desired Properties changes. whiteMessage("Connecting SetDesiredPropertyUpdateCallbackAsync event handler..."); await s_deviceClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertyChanged, null).ConfigureAwait(false); // Load Device Twin Properties since device is just starting up. whiteMessage("Loading Device Twin Properties..."); var twin = await s_deviceClient.GetTwinAsync().ConfigureAwait(false); // Use OnDesiredPropertyChanged event handler to set the loaded Device Twin properties. await OnDesiredPropertyChanged(twin.Properties.Desired, null); // Start reading and sending device telemetry. colorMessage("\nStart reading and sending device telemetry...\n", ConsoleColor.Yellow); await SendDeviceToCloudMessagesAsync2(s_deviceClient); // Explicitly close DeviceClient. whiteMessage("DeviceClient CloseAsync."); await s_deviceClient.CloseAsync().ConfigureAwait(false); } }
private async Task ConfirmExpectedDeviceCapabilities(DeviceRegistrationResult result, Client.IAuthenticationMethod auth, DeviceCapabilities capabilities) { if (capabilities != null) { //hardcoding amqp since http does not support twin, but tests that call into this may use http using (DeviceClient iotClient = DeviceClient.Create(result.AssignedHub, auth, Client.TransportType.Amqp)) { //Confirm that the device twin reflects what the enrollment dictated Twin twin = await iotClient.GetTwinAsync().ConfigureAwait(false); Assert.AreEqual(capabilities.IotEdge, twin.Capabilities.IotEdge); } } }
public async Task <Twin> SetModelId(string connectionString, string modelId) { Twin twin = null; int retry = 10; var options = new ClientOptions { ModelId = modelId, }; if (_deviceClient == null) { _deviceClient = DeviceClient.CreateFromConnectionString(connectionString, Microsoft.Azure.Devices.Client.TransportType.Mqtt, options); _deviceClient.SetConnectionStatusChangesHandler(ConnectionStatusChangedHandler); await _deviceClient.OpenAsync(); while (_isConnected == false && retry > 0) { await Task.Delay(1000); retry--; } twin = await _deviceClient.GetTwinAsync(); } else { twin = await _deviceClient.GetTwinAsync(); await _deviceClient.CloseAsync(); _deviceClient.Dispose(); _deviceClient = null; } return(twin); }
void QueryFWStatus() { try { var twin = Me.GetTwinAsync().Result; var myFwid = Helpers.Hexify(Helpers.HashData(new byte[] { (byte)CurrentFwVersionNumber }, 0, 1)); var targetFwVersionNumber = twin.Properties.Desired["VersionNumber"]; Int64 currentReportedVersionNumber = -1; if (twin.Properties.Reported.Contains("VersionNumber")) { currentReportedVersionNumber = (Int64)twin.Properties?.Reported["VersionNumber"]; } // update our version number if hub version number is not current if (currentReportedVersionNumber < 0 || CurrentFwVersionNumber != currentReportedVersionNumber || updateCurrentVersionNumber ) { TwinCollection t = new TwinCollection(); t["VersionNumber"] = CurrentFwVersionNumber; Me.UpdateReportedPropertiesAsync(t).Wait(); updateCurrentVersionNumber = false; } // if the target version number is not current, then flag that we need a FW update if (targetFwVersionNumber != CurrentFwVersionNumber.ToString()) { FirmwareUpdateNeeded = true; DesiredFwVersionNumber = targetFwVersionNumber; Debug.WriteLine("Need to update myself"); } else { FirmwareUpdateNeeded = false; Debug.WriteLine("Firmware version is good"); } // am I p0wned? If I'm P0wned I won't update myself if (twin.Properties.Desired.Contains("POwned")) { P0wned = (bool)twin.Properties?.Desired["POwned"]; } } catch (Exception e) { Debug.WriteLine("Error querying status" + e.ToString()); throw; } return; }
public async Task RunAsync(string connectionString, ILogger logger, CancellationToken quitSignal) { this.logger = logger; //deviceClient = DeviceClient.CreateFromConnectionString(connectionString, // TransportType.Mqtt, new ClientOptions { ModelId = modelId }); temperatureSeries.Add(DateTime.Now, CurrentTemperature); deviceClient = await DeviceClientFactory.CreateDeviceClientAsync(connectionString, logger, modelId); await deviceClient.SetDesiredPropertyUpdateCallbackAsync(DesiredPropertyUpdateCallback, this, quitSignal); await deviceClient.SetMethodHandlerAsync("getMaxMinReport", root_getMaxMinReportCommandHadler, this); var twin = await deviceClient.GetTwinAsync(); double targetTemperature = GetPropertyValue <double>(twin.Properties.Desired, "targetTemperature"); if (targetTemperature > 0) { await AckDesiredPropertyReadAsync("targetTemperature", targetTemperature, 200, "property synced", twin.Properties.Desired.Version); } await this.ProcessTempUpdateAsync(targetTemperature); await Task.Run(async() => { while (!quitSignal.IsCancellationRequested) { temperatureSeries.Add(DateTime.Now, CurrentTemperature); await deviceClient.SendEventAsync( new Message( Encoding.UTF8.GetBytes( "{" + "\"temperature\": " + CurrentTemperature + "," + "\"workingSet\" : " + Environment.WorkingSet + "}")) { ContentEncoding = "utf-8", ContentType = "application/json" }); logger.LogInformation("Sending CurrentTemperature and workingset " + CurrentTemperature); await Task.Delay(1000); } }); }
//Create a connection to the IoT Hub static async Task <bool> CreateIoTHubClient(dynamic settings, bool usePrimaryConnectionString = true) { if (settings == null) { throw new Exception("Can't start IoT Hub connection based on an empty settings file!"); } Task <bool> success = Task.Run(() => true); Console.WriteLine("Starting IoT Hub connection"); try { string iotDeviceConnectionString = usePrimaryConnectionString ? settings.primaryConnectionString : settings.secondaryConnectionString; MqttTransportSettings mqttSetting = new MqttTransportSettings(TransportType.Mqtt_Tcp_Only); ITransportSettings[] transportSettings = { mqttSetting }; deviceClient = DeviceClient.CreateFromConnectionString(iotDeviceConnectionString, transportSettings); await deviceClient.OpenAsync(); Console.WriteLine($"Connected to IoT Hub with connection string [{iotDeviceConnectionString}]"); //read twin setting upon first load var twin = await deviceClient.GetTwinAsync(); await onDesiredPropertiesUpdate(twin.Properties.Desired, deviceClient); //register for Twin desiredProperties changes await deviceClient.SetDesiredPropertyUpdateCallbackAsync(onDesiredPropertiesUpdate, null); } catch (Exception ex) { Console.WriteLine(ex.Message); if (usePrimaryConnectionString) { success = CreateIoTHubClient(settings, false); } else { success = Task.Run(() => false); }; } if (!success.Result) { Console.WriteLine("Could not establish connection to IoT Hub"); } return(success.Result); }
public static async void InitClient() { try { Console.WriteLine("Simulated device: Joker\n"); deviceClient = DeviceClient.Create(iotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey("Joker", deviceKey), TransportType.Mqtt); Console.WriteLine("Retrieving twin"); await deviceClient.GetTwinAsync(); } catch (Exception ex) { Console.WriteLine(); Console.WriteLine("Error in sample: {0}", ex.Message); } }
public static async void InitClient() { try { Console.WriteLine("Connecting to hub"); Client = DeviceClient.CreateFromConnectionString(DeviceConnectionString, Microsoft.Azure.Devices.Client.TransportType.Mqtt); Console.WriteLine("Retrieving twin"); await Client.GetTwinAsync(); } catch (Exception ex) { Console.WriteLine(); Console.WriteLine("Error in sample: {0}", ex.Message); } }
public CiotolaModel(string deviceId, DeviceClient client) { Task.Run(async() => { var twin = await client.GetTwinAsync(); if (twin.Properties.Desired.Contains("SetPoint")) { _setPoint = (int)twin.Properties.Desired["SetPoint"]; } if (twin.Properties.Desired.Contains("AlarmPoint")) { } Dosi = _setPoint; await client.SetDesiredPropertyUpdateCallbackAsync(async(tc, oc) => { if (tc.Contains("SetPoint")) { _setPoint = (int)tc["SetPoint"]; Dosi = _setPoint; } }, null); var random = new Random(); while (true) { //Dosi--; var sample = new { Timestamp = DateTime.Now.ToUniversalTime(), DeviceId = deviceId, SampleType = "dosi", Value = Dosi }; var json = JsonConvert.SerializeObject(sample); var bytes = Encoding.UTF8.GetBytes(json); var message = new Message(bytes); message.Properties["sampleType"] = "dosi"; client.SendEventAsync(message).Wait(); Task.Delay(1000).Wait(); } }); _client = client; }
public async Task Initialize() { client = DeviceClient.CreateFromConnectionString(connectionString, transportType); if (client != null) { var twinTask = client.GetTwinAsync(); var restartCollectionTask = client.SetMethodHandlerAsync(nameof(RestartCollection), RestartCollection, null); var twin = await twinTask; await restartCollectionTask; } else { throw new ArgumentException() } }
private async Task<TwinCollection> GetDesiredProperties() { Log.Information("Getting desired device twin properties"); try { var twin = await _deviceClient.GetTwinAsync(); return twin.Properties.Desired; } catch (Exception ex) { Log.Error("Error occured on GetDesiredProperties:", ex); } return new TwinCollection(); }