public async Task AddDeviceAsync(string deviceId) { Console.Write($"Adding device '{deviceId}' with default authentication . . . "); await _registryManager.AddDeviceAsync(new Device(deviceId)).ConfigureAwait(false); Console.WriteLine("DONE"); }
public async Task <bool> RegisterDeviceByKey(string deviceId, string deviceKey) { Device device = new Device(deviceId) { Authentication = new AuthenticationMechanism() { SymmetricKey = new SymmetricKey() { PrimaryKey = deviceKey, SecondaryKey = deviceKey } } }; try { Device existDevice = await _registryManager.GetDeviceAsync(deviceId); if (existDevice == null) { await _registryManager.AddDeviceAsync(device); } else { await _registryManager.UpdateDeviceAsync(device, true); } } catch (Exception ex) { Console.WriteLine(ex.Message); throw; } return(true); }
public async Task RegistryManager_AddAndRemoveDeviceWithScope() { RegistryManager registryManager = RegistryManager.CreateFromConnectionString(Configuration.IoTHub.ConnectionString); string deviceId = DevicePrefix + Guid.NewGuid(); var edgeDevice = new Device(deviceId) { Capabilities = new DeviceCapabilities { IotEdge = true } }; edgeDevice = await registryManager.AddDeviceAsync(edgeDevice).ConfigureAwait(false); var leafDevice = new Device(Guid.NewGuid().ToString()) { Scope = edgeDevice.Scope }; Device receivedDevice = await registryManager.AddDeviceAsync(leafDevice).ConfigureAwait(false); Assert.IsNotNull(receivedDevice); Assert.AreEqual(leafDevice.Id, receivedDevice.Id, $"Expected Device ID={leafDevice.Id}; Actual Device ID={receivedDevice.Id}"); Assert.AreEqual(leafDevice.Scope, receivedDevice.Scope, $"Expected Device Scope={leafDevice.Scope}; Actual Device Scope={receivedDevice.Scope}"); await registryManager.RemoveDeviceAsync(leafDevice.Id).ConfigureAwait(false); await registryManager.RemoveDeviceAsync(edgeDevice.Id).ConfigureAwait(false); }
/// <summary> /// Creates some edge devices with a parent and child, and a leaf device as a child. /// </summary> private async Task CreateDeviceHierarchyAsync(RegistryManager registryManager) { Console.WriteLine("=== Creating a hierarchy of devices using default (symmetric key) authentication ===\n"); string edgeParentId = GenerateDeviceId(); var edgeParent = new Device(edgeParentId) { Capabilities = new DeviceCapabilities { // To create an edge device, this must be set to true IotEdge = true, }, }; // Add the device and capture the output which includes system-assigned properties like ETag and Scope. edgeParent = await registryManager.AddDeviceAsync(edgeParent); Console.WriteLine($"Added edge {edgeParent.Id} with device scope {edgeParent.Scope}."); string nestedEdgeId = GenerateDeviceId(); var nestedEdge = new Device(nestedEdgeId) { Capabilities = new DeviceCapabilities { IotEdge = true, }, // To make this edge device a child of another edge device, add the parent's device scope to the parent scopes property. // The scope property is immutable for an edge device, and should not be set by the client. ParentScopes = { edgeParent.Scope }, }; nestedEdge = await registryManager.AddDeviceAsync(nestedEdge); Console.WriteLine($"Added edge {nestedEdge.Id} with device scope {nestedEdge.Scope} and parent scope {nestedEdge.ParentScopes.First()}."); // Create a device with default (shared key) authentication string basicDeviceId = GenerateDeviceId(); var basicDevice = new Device(basicDeviceId) { // To make this device a child of an edge device, set the scope property to the parent's scope property value. // Note, this is different to how hierarchy is specified on edge devices. // The parent scopes property can be set to the same value, or left alone and the service will set it for you. Scope = nestedEdge.Scope, }; basicDevice = await registryManager.AddDeviceAsync(basicDevice); Console.WriteLine($"Added device '{basicDevice.Id}' with device scope of {basicDevice.Scope} and parent scope of {basicDevice.ParentScopes.First()}."); }
/// <summary> /// Initializes a device client. /// </summary> public void Init() { //TODO: make the registration to be a separate method RegistryManager registryManager = RegistryManager.CreateFromConnectionString(iotHubConnectionString); var device = registryManager.GetDeviceAsync(machineName).Result; if (device == null) { device = registryManager.AddDeviceAsync(new Microsoft.Azure.Devices.Device(machineName)).Result; } string deviceConnStr = string.Format("{0};DeviceId={1};SharedAccessKey={2}", iotHubConnectionString.Split(new char[] { ';' }).Where(m => m.Contains("HostName")).FirstOrDefault(), device.Id, device.Authentication.SymmetricKey.PrimaryKey); // Use below 2 lines with IOT hub only deviceClient = DeviceClient.CreateFromConnectionString(deviceConnStr, Microsoft.Azure.Devices.Client.TransportType.Http1); //await deviceClient.OpenAsync(); // Use below 2 lines when not using IOT hub only //string paths = GenerateBlobUri(); //GetBlobUris(paths); SendD2CMessage(); }
/// <summary> /// Adds the device to IoT Hub if it isn't already. /// </summary> /// <param name="deviceId">Device Identifier of IoT device</param> /// <returns>ConnectionString for device</returns> public async Task <string> AddDeviceAsync(string deviceId) { Device device; try { var d = new Device(deviceId) { Status = Microsoft.Azure.Devices.DeviceStatus.Enabled }; device = await _registryManager?.AddDeviceAsync(d); } catch (DeviceAlreadyExistsException) { device = await _registryManager?.GetDeviceAsync(deviceId); } catch (Exception e) { System.Diagnostics.Debug.WriteLine($"Error creating the device: {e.Message}"); return(string.Empty); } var connectionString = $"HostName={Constants.IotHubConfig.HostName};DeviceId={device.Id};SharedAccessKey={device.Authentication.SymmetricKey.PrimaryKey}"; //Get return(connectionString); }
public async Task <Tuple <string, string> > RegisterDeviceAsync(string deviceId) { if (string.IsNullOrEmpty(deviceId)) { return(null); } string deviceKey = null; string err = null; try { deviceId = deviceId.ToLower(); var device = await registryManager.AddDeviceAsync(new Device(deviceId)); deviceKey = device.Authentication.SymmetricKey.PrimaryKey; } catch (DeviceAlreadyExistsException e) { var device = await registryManager.GetDeviceAsync(deviceId); deviceKey = device.Authentication.SymmetricKey.PrimaryKey; err = "Already exists" + e.ToString(); } catch (Exception ex) { var device = await registryManager.GetDeviceAsync(deviceId); deviceKey = device?.Authentication?.SymmetricKey?.PrimaryKey; err = "Failed to register " + ex.ToString(); } return(new Tuple <string, string>(deviceKey, err)); }
private async Task <bool> CreateVehicleIfNotExistsAndSendMessageAsync(string vehicleName) { string iotHubConnectionString = theSettings["IotHubConnectionString"]; RegistryManager registryManager = RegistryManager.CreateFromConnectionString(iotHubConnectionString); Console.WriteLine("Getting details of " + vehicleName); Device device = await registryManager.GetDeviceAsync(vehicleName); Console.WriteLine("Got details of " + vehicleName); if (device == null) { // this is not registered device .. Console.WriteLine("Vehcile does not exist" + vehicleName); await registryManager.AddDeviceAsync(new Device(vehicleName)); device = await registryManager.GetDeviceAsync(vehicleName); } if (device != null) { Console.WriteLine(vehicleName + "Connect And SendMessage To Hub"); await ConnectAndSendMessageToHubAsync(device, vehicleName); } else { Console.WriteLine("Issue creating vehcile"); } return(true); }
public static async Task <Tuple <string, string> > CreateDevice(string devicePrefix, string iotHubConnectionString, RegistryManager registryManager, bool iotEdgeCapable = false, bool appendGatewayHostName = true, string scope = null) { string deviceName = devicePrefix + Guid.NewGuid(); var device = new Device(deviceName) { Authentication = new AuthenticationMechanism() { Type = AuthenticationType.Sas } }; if (!string.IsNullOrWhiteSpace(scope)) { device.Scope = scope; } if (iotEdgeCapable) { device.Capabilities = new DeviceCapabilities { IotEdge = true }; } device = await registryManager.AddDeviceAsync(device); string deviceConnectionString = GetDeviceConnectionString(device, ConnectionStringHelper.GetHostName(iotHubConnectionString), appendGatewayHostName); await Task.Delay(1000); return(new Tuple <string, string>(deviceName, deviceConnectionString)); }
/// <summary> /// Add the device to the registry manager /// </summary> /// <param name="deviceConfig">the device to add</param> /// <returns></returns> private static async Task <string> AddDeviceAsync(DeviceConfig deviceConfig) { Device device; try { DeviceStatus status; if (!Enum.TryParse(deviceConfig.Status, true, out status)) { status = DeviceStatus.Disabled; } var d = new Device(deviceConfig.DeviceId) { Status = status }; device = await _registryManager.AddDeviceAsync(d); Console.WriteLine($"Device: {deviceConfig.DeviceId} created"); } catch (DeviceAlreadyExistsException) { device = await _registryManager.GetDeviceAsync(deviceConfig.DeviceId); Console.WriteLine($"Device: {deviceConfig.DeviceId} already exist"); } return(device.Authentication.SymmetricKey.PrimaryKey); }
// Method used to add device into the Registry, takes in a string as a parameter private static async Task AddDevice(string deviceId) { // A Device object Device device; try { // Lets try and create a Device into the Device Registry Device newdevice = new Device(deviceId); newdevice.Authentication = new AuthenticationMechanism() { Type = AuthenticationType.CertificateAuthority }; device = await registryManager.AddDeviceAsync(newdevice); if (device != null) { Console.WriteLine("Device: {0} added successfully!", deviceId); // Hooray! } } catch (DeviceAlreadyExistsException) // What? { Console.WriteLine("---"); Console.WriteLine("This device has already been registered...");// When did I do that?? Console.WriteLine("---"); device = await registryManager.GetDeviceAsync(deviceId); } Console.WriteLine(); Console.WriteLine("Generated device key: {0}", device.Authentication.SymmetricKey.PrimaryKey); // Now you're talking! Console.WriteLine(); }
async Task CreateEdgeDeviceIdentity(RegistryManager rm) { var device = new Device(this.deviceId) { Authentication = new AuthenticationMechanism() { Type = AuthenticationType.Sas }, Capabilities = new DeviceCapabilities() { IotEdge = true } }; IotHubConnectionStringBuilder builder = IotHubConnectionStringBuilder.Create(this.iothubConnectionString); Console.WriteLine($"Registering device '{device.Id}' on IoT hub '{builder.HostName}'"); device = await rm.AddDeviceAsync(device); this.context = new DeviceContext { Device = device, IotHubConnectionString = this.iothubConnectionString, RegistryManager = rm, RemoveDevice = true }; }
private Task <Device> CreateDeviceClientAsync(RegistryManager registryManager) { string deviceName = DevicePrefix + Guid.NewGuid(); Console.WriteLine($"Creating device {deviceName}"); return(registryManager.AddDeviceAsync(new Device(deviceName))); }
static async Task AddDeviceAsync() { RegistryManager manager = RegistryManager.CreateFromConnectionString(connectionString); await manager.AddDeviceAsync(new Device(deviceID)); Console.WriteLine("Device Added"); }
private async static Task AddDeviceAsync() { Device device; try { device = await registryManager.AddDeviceAsync(new Device(deviceId)); if (string.IsNullOrEmpty(tags) == false) { ServiceProperties sps = new ServiceProperties(); sps.Tags.AddRange(tags.Split(',')); sps.ETag = device.ServiceProperties.ETag; var properties = await registryManager.SetServicePropertiesAsync(deviceId, sps); } //device = await registryManager.GetDeviceAsync(deviceId); } catch (DeviceAlreadyExistsException) { device = await registryManager.GetDeviceAsync(deviceId); } deviceKey = device.Authentication.SymmetricKey.SecondaryKey; Log($"device id {deviceId} : {deviceKey}"); Log($"Device Tags:{string.Join(",",device.ServiceProperties.Tags)}"); }
// POST api/Register public async Task <iotDevice> Post(string name, string type, string owner = "unk") { iotDevice device = _db.Devices.Where(d => d.Name == name).FirstOrDefault(); if (device == null) { Device myDevice; try { Device newDevice = new Device(name); myDevice = await _registery.AddDeviceAsync(newDevice); } catch (DeviceAlreadyExistsException) { myDevice = await _registery.GetDeviceAsync(name); } device = _db.Devices.Add(new iotDevice() { Name = name, //IoTHubURL = myHubURL, Key = myDevice.Authentication.SymmetricKey.PrimaryKey.ToString(), Type = type, Owner = owner, RegisterDt = DateTime.UtcNow }); _db.SaveChanges(); } return(device); }
private async static Task AddDeviceAsync(string deviceId) { Device device; string deviceKey; registryManager = RegistryManager.CreateFromConnectionString(connectionString); try { device = await registryManager.AddDeviceAsync(new Device(deviceId)); } catch (DeviceAlreadyExistsException) { device = await registryManager.GetDeviceAsync(deviceId); } deviceKey = device.Authentication.SymmetricKey.PrimaryKey; if (deviceId == deviceId1) { deviceKey1 = deviceKey; } else { deviceKey2 = deviceKey; } }
private async static Task AddDeviceAsync(Registration deviceRegistration) { //if (deviceRegistration.key != string.Empty) return; // create a unique id for this device var deviceId = deviceRegistration.model + "-" + deviceRegistration.id; // this class represents the device registered with IoT Hub Device device; // register or lookup the device try { device = await _registryManager.AddDeviceAsync(new Device(deviceId)); device.Authentication.SymmetricKey; } catch (DeviceAlreadyExistsException) { device = await _registryManager.GetDeviceAsync(deviceId); } try { // update the application registry deviceRegistration.key = device.Authentication.SymmetricKey.PrimaryKey; _registryM.Update(deviceRegistration); Console.WriteLine("{0} Generated device {1} key: {2}", _count++, deviceRegistration.model, device.Authentication.SymmetricKey.PrimaryKey); Thread.Sleep(3000); } catch (Exception err) { Console.WriteLine("{0} {1}", _count++, err.Message); } }
void AddDevices() { //Type your Devices Name instead RegistryManager manager = RegistryManager.CreateFromConnectionString(connectionString); manager.AddDeviceAsync(new Device("YOUR DEVICE NAME")); }
public async Task <DeviceRegistration> RegisterAsync(Guid id) { var primaryKey = "cHJpbWFyeTEyMyFAI2toamtkc2hmZHNqZmtzag=="; var deviceId = id.ToString(); var existing = await GetDevice(id); if (existing is null) { var device = new Device(deviceId) { Authentication = new AuthenticationMechanism() { Type = AuthenticationType.Sas, SymmetricKey = new SymmetricKey() { PrimaryKey = primaryKey, SecondaryKey = "c2Vjb25kYXJ5YnVhaGFoYTEyMzQ1Njc4IUAkIw==" } } }; var registeredDevice = await _registryManager.AddDeviceAsync(device); } return(new DeviceRegistration { DeviceId = id, HubName = _hubName, Key = primaryKey }); }
public static Tuple <string, string> CreateDeviceWithX509(string devicePrefix, string hostName, RegistryManager registryManager) { string deviceName = null; Task.Run(async() => { deviceName = devicePrefix + Guid.NewGuid(); Debug.WriteLine("Creating device " + deviceName); var device1 = new Device(deviceName) { Authentication = new AuthenticationMechanism() { X509Thumbprint = new X509Thumbprint() { PrimaryThumbprint = Environment.GetEnvironmentVariable("IOTHUB_PFX_X509_THUMBPRINT") } } }; var device = await registryManager.AddDeviceAsync(device1); Debug.WriteLine("Device successfully created"); }).Wait(); Thread.Sleep(1000); return(new Tuple <string, string>(deviceName, hostName)); }
/********************************************************************************** * Register a new device with IoT Hub *********************************************************************************/ public async Task <bool> AddIoTHubDevice(string deviceId) { Device device = null; bool bCreated = false; try { device = await _registryManager.GetDeviceAsync(deviceId.ToString()); if (device == null) { _logger.LogDebug($"Creating a new device : '{deviceId}'"); device = await _registryManager.AddDeviceAsync(new Device(deviceId.ToString())); bCreated = true; } else { _logger.LogWarning($"Device already exist : '{deviceId}'"); } } catch (DeviceAlreadyExistsException) { _logger.LogWarning($"Exception Device already exist : '{deviceId}'"); } catch (Exception e) { _logger.LogError($"Exception in AddIoTHubDevice() : {e.Message}"); } return(bCreated); }
private static async Task <DeviceIdentityResponseModel> AddDeviceAsync(string deviceId) { //HostName=rspdeviotreg.azure-devices.net;DeviceId=dev1;SharedAccessKey=ErSTGgMRI9uZCTtUn7zMb/yECrgRt8C6BRdIKCwmeag=" Device device; var response = new DeviceIdentityResponseModel(); try { device = await _registryManager.AddDeviceAsync(new Device(deviceId)); var conn = host + "DeviceId=" + deviceId + ";SharedAccessKey=" + device.Authentication.SymmetricKey.PrimaryKey; response = new DeviceIdentityResponseModel(); response.GwaRegistrationResponseCommand.ConnectionString = conn; } catch (DeviceAlreadyExistsException) { device = await _registryManager.GetDeviceAsync(deviceId); var conn = host + "DeviceId=" + deviceId + ";SharedAccessKey=" + device.Authentication.SymmetricKey.PrimaryKey; response = new DeviceIdentityResponseModel(); response.GwaRegistrationResponseCommand.ConnectionString = conn; } catch (Exception e) { var exp = JsonConvert.SerializeObject(e); throw e; } return(response); }
private async void createButton_Click(object sender, EventArgs e) { try { Device device = new Device(deviceIDTextBox.Text); await registryManager.AddDeviceAsync(device); device = await registryManager.GetDeviceAsync(device.Id); device.Authentication.SymmetricKey.PrimaryKey = primaryKeyTextBox.Text; device.Authentication.SymmetricKey.SecondaryKey = secondaryKeyTextBox.Text; device = await registryManager.UpdateDeviceAsync(device); string deviceInfo = String.Format("ID={0}\nPrimaryKey={1}\nSecondaryKey={2}", device.Id, device.Authentication.SymmetricKey.PrimaryKey, device.Authentication.SymmetricKey.SecondaryKey); DeviceCreatedForm deviceCreated = new DeviceCreatedForm(device.Id, device.Authentication.SymmetricKey.PrimaryKey, device.Authentication.SymmetricKey.SecondaryKey); deviceCreated.ShowDialog(); this.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
async Task CreateDeviceIdentity(RegistryManager rm) { var device = new Device(this.deviceId) { Authentication = new AuthenticationMechanism() { Type = AuthenticationType.Sas }, Capabilities = new DeviceCapabilities() { IotEdge = false } }; Microsoft.Azure.Devices.IotHubConnectionStringBuilder builder = Microsoft.Azure.Devices.IotHubConnectionStringBuilder.Create(this.iothubConnectionString); Console.WriteLine($"Registering device '{device.Id}' on IoT hub '{builder.HostName}'"); device = await rm.AddDeviceAsync(device); this.context = new DeviceContext { Device = device, DeviceClientInstance = Option.None <DeviceClient>(), IotHubConnectionString = this.iothubConnectionString, RegistryManager = rm, RemoveDevice = true, MessageGuid = Guid.NewGuid().ToString() }; }
public static Tuple <string, string> CreateDeviceWithX509(string devicePrefix, string hostName, RegistryManager registryManager) { string deviceName = null; Task.Run(async() => { deviceName = devicePrefix + Guid.NewGuid(); Console.WriteLine($"Creating device X509 {deviceName} on {hostName}"); var device1 = new Device(deviceName) { Authentication = new AuthenticationMechanism() { X509Thumbprint = new X509Thumbprint() { PrimaryThumbprint = Configuration.IoTHub.GetCertificateWithPrivateKey().Thumbprint } } }; var device = await registryManager.AddDeviceAsync(device1); Console.WriteLine("Device successfully created"); }).Wait(); Thread.Sleep(1000); return(new Tuple <string, string>(deviceName, hostName)); }
async Task CreateEdgeDeviceIdentity(RegistryManager rm) { var device = new Device(this.deviceId) { Authentication = new AuthenticationMechanism() { Type = AuthenticationType.Sas }, Capabilities = new DeviceCapabilities() { IotEdge = true } }; await this.parentEdgeDevice.ForEachAsync(async p => { var parentDevice = await rm.GetDeviceAsync(p); device.ParentScopes = new[] { parentDevice.Scope }; }); IotHubConnectionStringBuilder builder = IotHubConnectionStringBuilder.Create(this.iothubConnectionString); Console.WriteLine($"Registering device '{device.Id}' on IoT hub '{builder.HostName}'"); device = await rm.AddDeviceAsync(device); this.context = new DeviceContext(device, builder.ToString(), rm, true); }
public async Task <ActionResult> Create([Bind(Include = "DispositivoID,Nombre,ClaveDispositivo,Activo,EmpresaID,TipoMedidaID")] Dispositivos dispositivo) { if (ModelState.IsValid) { //string deviceId = "minwinpc"; Device device; try { device = await registryManager.AddDeviceAsync(new Device(dispositivo.Nombre)); } catch (DeviceAlreadyExistsException) { device = await registryManager.GetDeviceAsync(dispositivo.Nombre); } //dispositivo.ClaveDispositivo = device.Authentication.SymmetricKey.PrimaryKey; dbActiveContext.Dispositivos.Add(dispositivo); dispositivo.Activo = true; dbActiveContext.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.TipoMedidaID = new SelectList(dbActiveContext.TipoMedidas, "TipoMedidaID", "Nombre", dispositivo.TipoMedidaID); //ViewBag.Medida = new SelectList(Enum.GetValues(typeof(enumMedidas)).Cast<enumMedidas>().Select(v => new SelectListItem //{ // Value = ((int)v).ToString(), // Text = v.ToString() //}).ToList(), "Value", "Text" //); ViewBag.EmpresaID = new SelectList(dbActiveContext.Empresas, "EmpresaID", "Nombre", dispositivo.EmpresaID); return(View(dispositivo)); }
private static async Task AddDeviceAsync() { Device device; try { device = await _registryManager.AddDeviceAsync(new Device(DeviceId)); SendTelemetry("success", "register new device"); } catch (DeviceAlreadyExistsException) { device = await _registryManager.GetDeviceAsync(DeviceId); SendTelemetry("success", "device existed"); } catch (Exception e) { SendTelemetry("failed", $"register device failed: {e.Message}"); Console.WriteLine($"register device failed: {e.Message}"); throw; } Console.WriteLine($"device key : {device.Authentication.SymmetricKey.PrimaryKey}"); }
private async Task <ActionResult> AddDeviceAsync() { var deviceGuid = Guid.NewGuid(); var devices = await registryManager.GetDevicesAsync(1000); int numDevice = devices.Count <Device>() + 1; string deviceId = "Device-" + numDevice.ToString("D6") + "-" + deviceGuid.ToString(); var device = await registryManager.GetDeviceAsync(deviceId); if (device == null) { device = new Device(deviceId); device = await registryManager.AddDeviceAsync(device); } ViewData["id"] = device.Id; ViewData["key"] = device.Authentication.SymmetricKey.PrimaryKey; var returnD = new { deviceNbr = numDevice, Id = device.Id, Key = device.Authentication.SymmetricKey.PrimaryKey }; return(Json(returnD, JsonRequestBehavior.AllowGet)); }