private void InitializeDeviceClientAsync() { IAsyncAction asyncAction = Windows.System.Threading.ThreadPool.RunAsync( async(workItem) => { while (true) { #if ENABLE_AUTO_DEVICE_PROVISIONING // Hands-on Lab: // Implement logics to filter conditions which require to // run device provisioning before reset IoT Hub connection // In this lab, we simply check if there's connection info setup in TPM, // if there's one, we'll move on to reset IoT hub connection, // if there's none in TPM, we'll do device provisioning to register this device (a valid connection info will then be store in TPM). string deviceConnectionString = null; // check if there's any valid connection info setup in TPM try { var tpmDevice = new TpmDevice(); deviceConnectionString = await tpmDevice.GetConnectionStringAsync(); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("GetConnectionStringAsync Exception: " + ex.Message); } if (String.IsNullOrEmpty(deviceConnectionString) || String.IsNullOrWhiteSpace(deviceConnectionString)) { // there's no connection info stored in TPM, must run device provisioning... var registrationStatus = await RunDeviceProvisioning(); switch (registrationStatus) { case ProvisioningRegistrationStatusType.Assigned: break; default: // with these conditions, retry provisioning with a longer delay interval... await Task.Delay(60 * 60 * 1000); // 60 minutes continue; } } #endif _iotHubOfflineEvent.WaitOne(); try { await ResetConnectionAsync(); } catch (Exception e) { _iotHubOfflineEvent.Set(); var msg = "InitializeDeviceClientAsync exception: " + e.Message + "\n" + e.StackTrace; System.Diagnostics.Debug.WriteLine(msg); Logger.Log(msg, LoggingLevel.Error); } await Task.Delay(1 * 60 * 1000); } }); }
public static async Task <bool> SendDeviceToCloudMessageAsync(string str) { try { TpmDevice myDevice = new TpmDevice(0); // Use logical device 0 on the TPM string hubUri = myDevice.GetHostName(); string deviceId = myDevice.GetDeviceId(); string hwID = myDevice.GetHardwareDeviceId(); string sasToken = myDevice.GetSASToken(); DeviceClient deviceClient = DeviceClient.Create( hubUri, AuthenticationMethodFactory. CreateAuthenticationWithToken(deviceId, sasToken), TransportType.Mqtt_WebSocket_Only); //string m = "{\"pkey\":\"" + deviceId + "\", \"msg\":"+ str +"}"; var message = new Message(Encoding.ASCII.GetBytes(str)); await deviceClient.SendEventAsync(message); return(true); } catch (Exception ex) { return(false); } }
public Task Initialize() { this.CancellationTokenSource = new CancellationTokenSource(); // *** // *** Create a TpmDevice to access the credential information. Specify // *** a logical device ID of 0 (this is the slot we used to store the // *** credentials). // *** uint logicalDeviceId = 0; TpmDevice tpm = new TpmDevice(logicalDeviceId); // *** // *** Get the connection properties from the TPM. // *** string uri = tpm.GetHostName(); string deviceId = tpm.GetDeviceId(); string sasToken = tpm.GetSASToken(); // *** // *** Create the device connection. // *** this.DeviceClient = DeviceClient.Create(uri, AuthenticationMethodFactory.CreateAuthenticationWithToken(deviceId, sasToken)); this.ReceiveMessages(this.DeviceClient, this.CancellationTokenSource.Token); return(Task.FromResult(0)); }
public MainPage() { this.InitializeComponent(); var iotDevice = new TpmDevice(0); string hubUri = iotDevice.GetHostName(); string deviceId = iotDevice.GetDeviceId(); string sasToken = iotDevice.GetSASToken(); deviceName = deviceId; deviceClient = DeviceClient.Create(hubUri, AuthenticationMethodFactory.CreateAuthenticationWithToken(deviceId, sasToken), TransportType.Mqtt); _timer.Interval = TimeSpan.FromSeconds(1); _timer.Tick += _timer_Tick; GpioController controller = GpioController.GetDefault(); if (controller != null) { _pin = GpioController.GetDefault().OpenPin(17, GpioSharingMode.Exclusive); _dht = new Dht11(_pin, GpioPinDriveMode.Input); _timer.Start(); _startedAt = DateTimeOffset.Now; } }
public async void Run(IBackgroundTaskInstance taskInstance) { _deferral = taskInstance.GetDeferral(); var device = new TpmDevice(0); try { string deviceConnectionString = await device.GetConnectionStringAsync(); // Create DeviceClient. Application uses DeviceClient for telemetry messages, device twin // as well as device management DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(deviceConnectionString, TransportType.Mqtt); // 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); // 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(); } }
private DeviceClient InitializeDeviceClient() { TpmDevice device = new TpmDevice(0); string hubUri = device.GetHostName(); string deviceId = device.GetDeviceId(); string sasToken = device.GetSASToken(); _deviceId = deviceId; DeviceClient deviceClient = null; try { deviceClient = DeviceClient.Create( hubUri, AuthenticationMethodFactory.CreateAuthenticationWithToken(deviceId, sasToken)); return(deviceClient); } catch { Debug.WriteLine("ERROR! Unable to create device client!"); } return(deviceClient); }
private async Task <string> GetConnectionStringAsync() { var tpmDevice = new TpmDevice(); string connectionString = ""; do { try { // CHANGED: geertp 22/08/2018 -> //connectionString = await tpmDevice.GetConnectionStringAsync(); var conn = await tpmDevice.GetConnectionStringAsync().ConfigureAwait(false); connectionString = conn.Item1; // connection string // CHANGED: geertp 22/08/2018 <- break; } catch (Exception) { // We'll just keep trying. } await Task.Delay(1000); } while (true); return(connectionString); }
public static async Task <string> TestHubConnection(bool sendRestartMessage, string restartMessage) { string deviceid = null; try { TpmDevice myDevice = new TpmDevice(0); // Use logical device 0 on the TPM string hubUri = myDevice.GetHostName(); deviceid = myDevice.GetDeviceId(); string sasToken = myDevice.GetSASToken(); if ((hubUri.Length == 0) || (sasToken.Length == 0)) { return(null); } } catch (Exception ex) { return(null); } if (sendRestartMessage) { await SendDeviceToCloudMessageAsync(restartMessage); return(deviceid); } return(deviceid); }
public static async Task <string> ReceiveCloudToDeviceMessageAsync() { TpmDevice myDevice = new TpmDevice(0); // Use logical device 0 on the TPM by default string hubUri = myDevice.GetHostName(); string deviceId = myDevice.GetDeviceId(); string sasToken = myDevice.GetSASToken(); var deviceClient = DeviceClient.Create( hubUri, AuthenticationMethodFactory. CreateAuthenticationWithToken(deviceId, sasToken), TransportType.Amqp); while (true) { var receivedMessage = await deviceClient.ReceiveAsync(); if (receivedMessage != null) { var messageData = Encoding.ASCII.GetString(receivedMessage.GetBytes()); await deviceClient.CompleteAsync(receivedMessage); return(messageData); } await Task.Delay(TimeSpan.FromSeconds(1)); } }
private void initDevice() { TpmDevice device = new TpmDevice(0); string hubUri = device.GetHostName(); string deviceId = device.GetDeviceId(); string sasToken = device.GetSASToken(); _sendDeviceClient = DeviceClient.Create(hubUri, AuthenticationMethodFactory.CreateAuthenticationWithToken(deviceId, sasToken), TransportType.Amqp); }
public async void ConnectAzure() { var tpm = new TpmDevice(0); var connectionString = tpm.GetConnectionString(); client = DeviceClient.CreateFromConnectionString(connectionString, TransportType.Amqp_Tcp_Only); await client.OpenAsync(); ReceiveMessages(); }
private static string GetIotHubConnectionString() { if (Configuration.Instance.UseTpm) { var device = new TpmDevice(0); return(device.GetConnectionString()); } return(Configuration.Instance.ConnectionString); }
/// <summary> /// attempt to create a device client with the user credentials stored in the tpm /// </summary> public void initializeWithProvisionedDevice() { TpmDevice myDevice = new TpmDevice(0); string hubUri = myDevice.GetHostName(); devID = myDevice.GetDeviceId(); string sasToken = myDevice.GetSASToken(); deviceClient = DeviceClient.Create(hubUri, AuthenticationMethodFactory.CreateAuthenticationWithToken(devID, sasToken), TransportType.Amqp); }
static void Main(string[] args) { if (args.Length < 2) { HowTo(); return; } // Pick the logical LimpetID UInt32 logicalId = System.Convert.ToUInt32(args[0]); TpmDevice myLimpet = new TpmDevice(logicalId); // Decode the command if (args[1].ToUpper().Equals("-H")) { Console.WriteLine("Limpet[{0}] HWDeviceID = {1}", logicalId, myLimpet.GetHardwareDeviceId()); } else if ((args[1].ToUpper().Equals("-P")) && (args.Length > 4)) { if (args.Length > 4) { myLimpet.Provision(args[2], args[3], args[4]); } else { myLimpet.Provision(args[2], args[3]); } Console.WriteLine("Limpet[{0}] provisioned.", logicalId); } else if (args[1].ToUpper().Equals("-S")) { if (args.Length > 2) { UInt32 validity = System.Convert.ToUInt32(args[2]); Console.WriteLine(myLimpet.GetSASToken(validity)); } else { Console.WriteLine(myLimpet.GetSASToken()); } } else if (args[1].ToUpper().Equals("-D")) { myLimpet.Destroy(); Console.WriteLine("Limpet[{0}] destroyed.", logicalId); } else { HowTo(); return; } }
public MainPage() { this.InitializeComponent(); TpmDevice myDevice = new TpmDevice(0); // The following strings should be replaced with the actual information from Azure Portal or using the DeviceExplorer: string primaryKey = "..."; string hostname = "iot-open-house-demo.azure-devices.net"; string deviceID = "humidity-sensor"; myDevice.Provision(primaryKey, hostname, deviceID); }
private static void RefreshDeviceClient() { var myDevice = new TpmDevice(0); // Use logical device 0 on the TPM string hubUri = myDevice.GetHostName(); string deviceId = myDevice.GetDeviceId(); string sasToken = myDevice.GetSASToken((uint)SasTokenValidity.TotalSeconds); _validityExpiryTime = DateTime.Now + SasTokenValidity; _deviceClient = DeviceClient.Create( hubUri, AuthenticationMethodFactory. CreateAuthenticationWithToken(deviceId, sasToken), TransportType.Amqp); }
private void initConnectString() { TpmDevice myDevice = new TpmDevice(0); hubUri = myDevice.GetHostName(); deviceId = myDevice.GetDeviceId(); sasToken = myDevice.GetSASToken(); if (String.IsNullOrEmpty(hubUri) || String.IsNullOrEmpty(deviceId) || String.IsNullOrEmpty(sasToken)) { throw new ArgumentNullException("", "Please fill Device ConnectString (From Azure) on TPM."); } }
private DeviceClient InitializeDeviceClient() { TpmDevice device = new TpmDevice(0); string hubUri = device.GetHostName(); string deviceId = device.GetDeviceId(); string sasToken = device.GetSASToken(); _deviceId = deviceId; return(DeviceClient.Create( hubUri, AuthenticationMethodFactory.CreateAuthenticationWithToken(deviceId, sasToken))); }
public void Run(IBackgroundTaskInstance taskInstance) { TpmDevice device = new TpmDevice(0); string hubUri = device.GetHostName(); string deviceId = device.GetDeviceId(); string sasToken = device.GetSASToken(); DeviceClient _sendDeviceClient = DeviceClient.Create(hubUri, AuthenticationMethodFactory.CreateAuthenticationWithToken(deviceId, sasToken), TransportType.Amqp); while (true) { string messageString = "Hello World"; var message = new Message(Encoding.ASCII.GetBytes(messageString)); _sendDeviceClient.SendEventAsync(message); Task.Delay(1000).Wait(); } }
DeviceClient Connect() { // Get credentials from TPM store/chip TpmDevice device = new TpmDevice(0); // Use logical device 0 on the TPM by default string iotHubUri = device.GetHostName(); string deviceId = device.GetDeviceId(); string sasToken = device.GetSASToken(validity: 3600); // Connect var deviceClient = DeviceClient.Create( iotHubUri, AuthenticationMethodFactory.CreateAuthenticationWithToken(deviceId, sasToken), TransportType.Http1); return(deviceClient); }
public MainPage() { this.InitializeComponent(); //init device and shield TpmDevice mytpmdevice = new TpmDevice(0); _deviceClient = DeviceClient.CreateFromConnectionString(mytpmdevice.GetConnectionString(86400)); //SAS Token: 24h initFezhat(); //timer setup and start -> 1 msg every second _timer = new DispatcherTimer(); _timer.Interval = TimeSpan.FromSeconds(1); _timer.Tick += _timer_Tick; _timer.Start(); }
public static async Task <string> ReceiveCloudToDeviceMessageAsync() { try { while (true) { TpmDevice myDevice = new TpmDevice(0); // Use logical device 0 on the TPM by default string hubUri = myDevice.GetHostName(); string deviceId = myDevice.GetDeviceId(); string sasToken = myDevice.GetSASToken(); var deviceClient = DeviceClient.Create( hubUri, AuthenticationMethodFactory. CreateAuthenticationWithToken(deviceId, sasToken), TransportType.Mqtt_WebSocket_Only); // while (true) // { Message receivedMessage = null; Debug.Write("."); try { receivedMessage = await deviceClient.ReceiveAsync(); } catch (Exception ex) { Debug.WriteLine("----- ERROR awaiting ReceiveAsync"); } if (receivedMessage != null) { var messageData = Encoding.ASCII.GetString(receivedMessage.GetBytes()); await deviceClient.CompleteAsync(receivedMessage); deviceClient.Dispose(); return(messageData); } await Task.Delay(TimeSpan.FromSeconds(1)); } } catch (Exception ex) { Debug.WriteLine("----ERROR Receive:" + ex.Message + " " + ex.InnerException.Message); return(null); } }
public static async Task SendDeviceToCloudMessageAsync() { TpmDevice myDevice = new TpmDevice(0); // Use logical device 0 on the TPM by default string hubUri = myDevice.GetHostName(); string deviceId = myDevice.GetDeviceId(); string sasToken = myDevice.GetSASToken(); var deviceClient = DeviceClient.Create( hubUri, AuthenticationMethodFactory. CreateAuthenticationWithToken(deviceId, sasToken), TransportType.Amqp); var str = "Hello, Cloud from a secure C# UWP app!"; var message = new Message(Encoding.ASCII.GetBytes(str)); await deviceClient.SendEventAsync(message); }
private async Task <ProvisioningRegistrationStatusType> RunDeviceProvisioning() { ProvisioningRegistrationStatusType registrationStatus = ProvisioningRegistrationStatusType.Failed; string registrationId = Dns.GetHostName().ToLower(); using (var security = new SecurityProviderTpmHsm(registrationId)) using (var transport = new ProvisioningTransportHandlerHttp()) { Logger.Log($"ProvisioningClient RegisterAsync({registrationId})... ", LoggingLevel.Verbose); ProvisioningDeviceClient provClient = ProvisioningDeviceClient.Create(GlobalDeviceEndpoint, s_idScope, security, transport); try { DeviceRegistrationResult result = await provClient.RegisterAsync().ConfigureAwait(false); Logger.Log($"ProvisioningClient RegisterAsync Result = {result.Status}", LoggingLevel.Verbose); Logger.Log($"ProvisioningClient AssignedHub: {result.AssignedHub}; DeviceID: {result.DeviceId}", LoggingLevel.Information); if (result.Status == ProvisioningRegistrationStatusType.Assigned) { // The symmetric key of the assigned device identity is stored in TPM (this is done in ProvisioningDeviceClient.RegisterAsync()), // for this use case (DM sample), we will need to store some other connection properties // such as device Id and IoT Hub hostname in TPM for later use to establish IoTHub connection try { var tpmDevice = new TpmDevice(); await tpmDevice.SetConnectionInfoAsync(-1, result.AssignedHub, result.DeviceId); } catch (Exception ex) { Logger.Log($"SetConnectionInfoAsync Error: Fail to set service Url in TPM. Exception: {ex.Message}", LoggingLevel.Error); } } registrationStatus = result.Status; } catch (Exception ex) { Logger.Log($"ProvisioningClient Exception: {ex.Message}", LoggingLevel.Error); } } return(registrationStatus); }
public static async Task SendDeviceToCloudMessageAsyncUseTPM(string msg) { TpmDevice myDevice = new TpmDevice(0); // Use logical device 0 on the TPM string hubUri = myDevice.GetHostName(); string deviceId = myDevice.GetDeviceId(); string sasToken = myDevice.GetSASToken(); var deviceClient = DeviceClient.Create( hubUri, AuthenticationMethodFactory. CreateAuthenticationWithToken(deviceId, sasToken), TransportType.Amqp); //Not using TPM //var deviceClient = DeviceClient.CreateFromConnectionString(deviceConnectionString, TransportType.Amqp); var message = new Message(Encoding.ASCII.GetBytes(msg)); await deviceClient.SendEventAsync(message); }
public async void Run(IBackgroundTaskInstance taskInstance) { //Deferral task to allow for async BackgroundTaskDeferral deferral = taskInstance.GetDeferral(); //Config _localSettings = ApplicationData.Current.LocalSettings; //Get TPM Device ConnectionString _tpmDevice = new TpmDevice(0); //Create services _logging = new LoggingChannel("LunchBagCamera", null, new Guid("8e2fb18a-e7ae-45f9-bf05-d42455ba6ce0")); _azureIoTHubService = new AzureIoTHubService(_logging, ReceiveConfiguration, ReceiveSubscription); _cognitiveService = new CognitiveVisionService(_logging); _cameraService = new CameraService(_logging); await RunApplication(); deferral.Complete(); }
public IoTHub() { this.InitializeComponent(); try { TpmDevice device = new TpmDevice(0); hubUri = device.GetHostName(); deviceId = device.GetDeviceId(); sasToken = device.GetSASToken(); //Todo deviceClient = DeviceClient.Create(hubUri, AuthenticationMethodFactory.CreateAuthenticationWithToken(deviceId, sasToken), TransportType.Amqp); runtwin(); deviceClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertyChanged, null); } catch (Exception ex) { rootPage.NotifyUser("Connection String error", NotifyType.ErrorMessage); return; } ReceiveDataFromAzure(); }
public static void ProvisionDevice(string hostname, string deviceId) { TpmDevice tpm = new TpmDevice(0); if (Guid.TryParse(tpm.GetDeviceId(), out Guid parsed)) { try { tpm.Destroy(); } catch { DebugHelper.LogWarning($"Error while resetting TPM."); } } //The real private key can be stored in HSM/TPM //The Microsoft.Devices.TPM is used solemnly for TPM enrollement, and not certificate, here we're just using it to persist hostname/deviceId tpm.Provision(Convert.ToBase64String(Encoding.ASCII.GetBytes("REALKEYINTPM")), hostname, deviceId); ClearRSAKey(); }
private async Task <string> GetConnectionStringAsync() { var tpmDevice = new TpmDevice(); string connectionString = ""; do { try { connectionString = await tpmDevice.GetConnectionStringAsync(); break; } catch (Exception) { // We'll just keep trying. } await Task.Delay(1000); } while (true); return(connectionString); }
private async Task <string> GetConnectionStringAsync() { var tpmDevice = new TpmDevice(); string connectionString = ""; do { try { // connectionString = await tpmDevice.GetConnectionStringAsync(); connectionString = "HostName=remote-monitoring-pcs.azure-devices.net;DeviceId=gmileka06;SharedAccessKey=7iKTI2S9w0tY65kx8Ble7fk649guK6oCNZ27FpWD8co="; break; } catch (Exception) { // We'll just keep trying. } await Task.Delay(1000); } while (true); return(connectionString); }