public async Task <InvokeResult> AddDeviceAsync(DeviceRepository deviceRepo, Device device) { SetConnection(deviceRepo.DeviceStorageSettings.Uri, deviceRepo.DeviceStorageSettings.AccessKey, deviceRepo.DeviceStorageSettings.ResourceName); if (deviceRepo.RepositoryType.Value == RepositoryTypes.AzureIoTHub) { var iotHubDevice = new Microsoft.Azure.Devices.Device(device.DeviceId) { Authentication = new Microsoft.Azure.Devices.AuthenticationMechanism() { Type = Microsoft.Azure.Devices.AuthenticationType.Sas, SymmetricKey = new Microsoft.Azure.Devices.SymmetricKey() { PrimaryKey = device.PrimaryAccessKey, SecondaryKey = device.SecondaryAccessKey, } } }; var connString = String.Format(AZURE_DEVICE_CLIENT_STR, deviceRepo.ResourceName, deviceRepo.AccessKeyName, deviceRepo.AccessKey); var regManager = Microsoft.Azure.Devices.RegistryManager.CreateFromConnectionString(connString); var existingDevice = await regManager.GetDeviceAsync(device.DeviceId); if (existingDevice != null) { return(InvokeResult.FromErrors(ErrorCodes.DeviceExistsInIoTHub.ToErrorMessage($"DeviceID={device.DeviceId}"))); } await regManager.AddDeviceAsync(iotHubDevice); } await CreateDocumentAsync(device); return(InvokeResult.Success); }
public static Device MapFromIoTHub(this Microsoft.Azure.Devices.Device data) { Device result = new Device(); if (data != null) { result.AuthenticationType = data.Authentication.Type.ToString(); if (data.Authentication.Type == Microsoft.Azure.Devices.AuthenticationType.Sas) { result.AuthenticationPrimaryKey = data.Authentication.SymmetricKey.PrimaryKey; result.AuthenticationSecondaryKey = data.Authentication.SymmetricKey.SecondaryKey; } else { result.AuthenticationPrimaryKey = data.Authentication.X509Thumbprint.PrimaryThumbprint; result.AuthenticationSecondaryKey = data.Authentication.X509Thumbprint.SecondaryThumbprint; } result.CloudToDeviceMessageCount = data.CloudToDeviceMessageCount; result.ConnectionState = data.ConnectionState.ToString(); result.ConnectionStateUpdatedTime = data.ConnectionStateUpdatedTime; result.ETag = data.ETag; result.GenerationId = data.GenerationId; result.Id = data.Id; result.LastActivityTime = data.LastActivityTime; result.Status = data.Status.ToString(); result.StatusReason = data.StatusReason; result.StatusUpdatedTime = data.StatusUpdatedTime; } return(result); }
public async Task DeviceRegistryAsync() { registryManager = Microsoft.Azure.Devices.RegistryManager.CreateFromConnectionString(Store.Instance.IotHubRegistryConnectionString); device = await registryManager.GetDeviceAsync(GetDeviceID()); if (device == null) { device = await registryManager.AddDeviceAsync(new Microsoft.Azure.Devices.Device(GetDeviceID())); } }
public async Task <int> SaveChangesAsync() { int modified = 0; string twinJson = ""; foreach (var modifiedDevice in modelDevices.modifiedDevices) { if (modifiedDevice.State == EntityState.Added || modifiedDevice.State == EntityState.Modified) { twinJson = "{\"properties\":{\"desired\":" + modifiedDevice.Device.DesiredPropertiesToJson() + "}}"; var test = Newtonsoft.Json.JsonConvert.DeserializeObject(twinJson); } switch (modifiedDevice.State) { case EntityState.Added: var newDevice = new Microsoft.Azure.Devices.Device(modifiedDevice.Device.Id); newDevice = await registryManager.AddDeviceAsync(newDevice); var twin = await registryManager.GetTwinAsync(newDevice.Id); await registryManager.UpdateTwinAsync(newDevice.Id, twinJson, twin.ETag); modified++; break; case EntityState.Modified: var managedDevice = await registryManager.GetDeviceAsync(modifiedDevice.Device.Id); var manageDeviceTwin = await registryManager.GetTwinAsync(modifiedDevice.Device.Id); string etag = manageDeviceTwin.ETag; await registryManager.UpdateTwinAsync(modifiedDevice.Device.Id, twinJson, etag); modified++; break; case EntityState.Deleted: var registered = await registryManager.GetDeviceAsync(modifiedDevice.Device.Id); await registryManager.RemoveDeviceAsync(registered); modified++; break; } } modelDevices.modifiedDevices.Clear(); return(modified); }
public async Task StartAsync(CancellationToken ct) { // TODO: You cannot install certificate on Windows by script - we need to implement certificate verification callback handler. IEnumerable <X509Certificate2> certs = await CertificateHelper.GetTrustBundleFromEdgelet(new Uri(this.workloadUri), this.apiVersion, this.workloadClientApiVersion, this.moduleId, this.moduleGenerationId); ITransportSettings transportSettings = ((Protocol)Enum.Parse(typeof(Protocol), this.transportType.ToString())).ToTransportSettings(); OsPlatform.Current.InstallCaCertificates(certs, transportSettings); Microsoft.Azure.Devices.RegistryManager registryManager = null; try { registryManager = Microsoft.Azure.Devices.RegistryManager.CreateFromConnectionString(this.iotHubConnectionString); Microsoft.Azure.Devices.Device device = await registryManager.AddDeviceAsync(new Microsoft.Azure.Devices.Device(this.deviceId), ct); string deviceConnectionString = $"HostName={this.iotHubHostName};DeviceId={this.deviceId};SharedAccessKey={device.Authentication.SymmetricKey.PrimaryKey};GatewayHostName={this.gatewayHostName}"; this.deviceClient = DeviceClient.CreateFromConnectionString(deviceConnectionString, new ITransportSettings[] { transportSettings }); await this.deviceClient.OpenAsync(); while (!ct.IsCancellationRequested) { this.logger.LogInformation("Ready to receive message"); try { Message message = await this.deviceClient.ReceiveAsync(); this.logger.LogInformation($"Message received. " + $"Sequence Number: {message.Properties[TestConstants.Message.SequenceNumberPropertyName]}, " + $"batchId: {message.Properties[TestConstants.Message.BatchIdPropertyName]}, " + $"trackingId: {message.Properties[TestConstants.Message.TrackingIdPropertyName]}."); await this.ReportTestResult(message); await this.deviceClient.CompleteAsync(message); } catch (Exception ex) { this.logger.LogError(ex, "Error occurred while receiving message."); } } } finally { registryManager?.Dispose(); } }
private async Task deleteDevice(string iotHubConnectionString, string devicePrefix, int clientCount) { Microsoft.Azure.Devices.RegistryManager registryManager; registryManager = Microsoft.Azure.Devices.RegistryManager.CreateFromConnectionString(iotHubConnectionString); for (int deviceCounter = 1; deviceCounter <= clientCount; deviceCounter++) { Microsoft.Azure.Devices.Device mydevice = await registryManager.GetDeviceAsync(devicePrefix + deviceCounter.ToString()); try { await registryManager.RemoveDeviceAsync(mydevice); } catch (Exception) { } } Console.WriteLine("Devices (" + devicePrefix + ") deleted"); }
private async Task <DeviceClient> GetDeviceClient(string deviceId) { DeviceClient deviceClient; if (!deviceClients.TryGetValue(deviceId, out deviceClient)) { Microsoft.Azure.Devices.Device azureDevice = await registryManager.GetDeviceAsync(deviceId); if (azureDevice != null) { deviceClient = DeviceClient.Create( iotHubUri, AuthenticationMethodFactory.CreateAuthenticationWithRegistrySymmetricKey( deviceId, azureDevice.Authentication.SymmetricKey.PrimaryKey), TransportType.Amqp); deviceClients[deviceId] = deviceClient; } } return(deviceClient); }
public async Task ExecuteAsync(OperationParameters parameters) { try { var deviceId = parameters.Arguments["deviceid"].ToString(); if (string.IsNullOrWhiteSpace(deviceId)) { throw new ArgumentNullException("deviceid"); } var autoGenerateDevicekey = Convert.ToBoolean(parameters.Arguments["auto"]); if (autoGenerateDevicekey) { var device = new Microsoft.Azure.Devices.Device(deviceId); device.Authentication = new Microsoft.Azure.Devices.AuthenticationMechanism(); device.Authentication.SymmetricKey.PrimaryKey = CryptoKeyGenerator.GenerateKey(32); device.Authentication.SymmetricKey.SecondaryKey = CryptoKeyGenerator.GenerateKey(32); var devices = await this.IoTHubContext.RegistryManager.AddDeviceAsync(device); } else { var deviceKey = parameters.Arguments["deviceKey"].ToString(); if (string.IsNullOrWhiteSpace(deviceKey)) { throw new ArgumentNullException("devicekey"); } var device = new Microsoft.Azure.Devices.Device(deviceId); device.Authentication = new Microsoft.Azure.Devices.AuthenticationMechanism(); device.Authentication.SymmetricKey.PrimaryKey = deviceKey; device.Authentication.SymmetricKey.SecondaryKey = deviceKey; var devices = await this.IoTHubContext.RegistryManager.AddDeviceAsync(device); } } catch (Exception exception) { // return Task.FromResult(true); } }
private async Task CheckDeviceAsync(string deviceId) { if (_whiteList.ContainsKey(deviceId)) return; if (_serviceSettings == null) return; var connectionString = string.Format("HostName={0}.azure-devices.net;SharedAccessKeyName={1};SharedAccessKey={2}", _serviceSettings.Host, _serviceSettings.KeyName, _serviceSettings.Key); var registry = Microsoft.Azure.Devices.RegistryManager.CreateFromConnectionString(connectionString); var deviceReg = await registry.GetDeviceAsync(deviceId); if (deviceReg == null) { deviceReg = new Microsoft.Azure.Devices.Device(deviceId); deviceReg = await registry.AddDeviceAsync(deviceReg); } var device = new DeviceModel(); device.DeviceId = deviceId; //device.DeviceRegId = deviceReg.Id; device.Key = deviceReg.Authentication.SymmetricKey.PrimaryKey; _whiteList.Add(deviceId, device); var data = new DeviceMetaData(); data.Version = "1.0"; data.IsSimulatedDevice = false; data.Properties.DeviceID = deviceId; data.Properties.FirmwareVersion = "42"; data.Properties.HubEnabledState = true; data.Properties.Processor = "Foo"; data.Properties.Platform = "Yep"; data.Properties.SerialNumber = "Sigfox-" + deviceId; data.Properties.InstalledRAM = "1 MB"; data.Properties.ModelNumber = "007-BOND"; data.Properties.Manufacturer = "Sigfox"; //data.Properties.UpdatedTime = DateTime.UtcNow; data.Properties.DeviceState = DeviceState.Normal; var content = JsonConvert.SerializeObject(data); connectionString = string.Format("HostName={0}.azure-devices.net;DeviceId={1};SharedAccessKey={2}", "sigfoxmonitoring", device.DeviceId, device.Key); _client = DeviceClient.CreateFromConnectionString(connectionString, TransportType.Http1); await _client.SendEventAsync(new Message(Encoding.UTF8.GetBytes(content))); }
private async Task createDevices(string iotHubConnectionString, string devicePrefix, int clientCount, string commonKey) { Microsoft.Azure.Devices.RegistryManager registryManager; registryManager = Microsoft.Azure.Devices.RegistryManager.CreateFromConnectionString(iotHubConnectionString); for (int deviceCounter = 1; deviceCounter <= clientCount; deviceCounter++) { Microsoft.Azure.Devices.Device mydevice = new Microsoft.Azure.Devices.Device(devicePrefix + deviceCounter.ToString()); mydevice.Authentication = new Microsoft.Azure.Devices.AuthenticationMechanism(); mydevice.Authentication.SymmetricKey.PrimaryKey = commonKey; mydevice.Authentication.SymmetricKey.SecondaryKey = commonKey; mydevice.Status = Microsoft.Azure.Devices.DeviceStatus.Enabled; try { await registryManager.AddDeviceAsync(mydevice); } catch (Exception) { } } Console.WriteLine("Devices (" + devicePrefix + ") created"); }
public async Task StartAsync(CancellationToken ct) { // TODO: You cannot install certificate on Windows by script - we need to implement certificate verification callback handler. IEnumerable <X509Certificate2> certs = await CertificateHelper.GetTrustBundleFromEdgelet(new Uri(this.workloadUri), this.apiVersion, this.workloadClientApiVersion, this.moduleId, this.moduleGenerationId); ITransportSettings transportSettings = ((Protocol)Enum.Parse(typeof(Protocol), this.transportType.ToString())).ToTransportSettings(); OsPlatform.Current.InstallCaCertificates(certs, transportSettings); Microsoft.Azure.Devices.RegistryManager registryManager = null; try { registryManager = Microsoft.Azure.Devices.RegistryManager.CreateFromConnectionString(this.iotHubConnectionString); var edgeDevice = await registryManager.GetDeviceAsync(this.edgeDeviceId); var leafDevice = new Microsoft.Azure.Devices.Device(this.deviceId); leafDevice.Scope = edgeDevice.Scope; Microsoft.Azure.Devices.Device device = await registryManager.AddDeviceAsync(leafDevice, ct); string deviceConnectionString = $"HostName={this.iotHubHostName};DeviceId={this.deviceId};SharedAccessKey={device.Authentication.SymmetricKey.PrimaryKey};GatewayHostName={this.gatewayHostName}"; this.deviceClient = DeviceClient.CreateFromConnectionString(deviceConnectionString, new ITransportSettings[] { transportSettings }); var retryStrategy = new Incremental(15, RetryStrategy.DefaultRetryInterval, RetryStrategy.DefaultRetryIncrement); var retryPolicy = new RetryPolicy(new FailingConnectionErrorDetectionStrategy(), retryStrategy); await retryPolicy.ExecuteAsync( async() => { await this.deviceClient.OpenAsync(ct); }, ct); while (!ct.IsCancellationRequested) { this.logger.LogInformation("Ready to receive message"); try { Message message = await this.deviceClient.ReceiveAsync(); if (message == null) { this.logger.LogWarning("Received message is null"); continue; } if (!message.Properties.ContainsKey(TestConstants.Message.SequenceNumberPropertyName) || !message.Properties.ContainsKey(TestConstants.Message.BatchIdPropertyName) || !message.Properties.ContainsKey(TestConstants.Message.TrackingIdPropertyName)) { string messageBody = new StreamReader(message.BodyStream).ReadToEnd(); string propertyKeys = string.Join(",", message.Properties.Keys); this.logger.LogWarning($"Received message doesn't contain required key. property keys: {propertyKeys}, message body: {messageBody}, lock token: {message.LockToken}."); continue; } this.logger.LogInformation($"Message received. " + $"Sequence Number: {message.Properties[TestConstants.Message.SequenceNumberPropertyName]}, " + $"batchId: {message.Properties[TestConstants.Message.BatchIdPropertyName]}, " + $"trackingId: {message.Properties[TestConstants.Message.TrackingIdPropertyName]}, " + $"LockToken: {message.LockToken}."); await this.ReportTestResult(message); await this.deviceClient.CompleteAsync(message); } catch (Exception ex) { this.logger.LogError(ex, "Error occurred while receiving message."); } } } finally { registryManager?.Dispose(); } }
private static async Task CheckDeviceAsync(string deviceId) { if (_whiteList.ContainsKey(deviceId)) return; //var connectionString = IotHubConnectionStringBuilder.Create("sigfoxmonitoring", // AuthenticationMethodFactory.CreateAuthenticationWithSharedAccessPolicyKey(deviceId, "registryReadWrite", "weAJyh51pxOk5f/OVZRGXc4JR6AJDg+JYjiK3rlDTzs=")); var connectionString = string.Format("HostName={0}.azure-devices.net;SharedAccessKeyName={1};SharedAccessKey={2}", "sigfoxmonitoring", "iothubowner", "B2LsypvIEz7bdy0217QYfeUvO1xUjKVujlte4wETrvM="); var registry = Microsoft.Azure.Devices.RegistryManager.CreateFromConnectionString(connectionString); await registry.RemoveDeviceAsync("Sigfox-FAE88"); return; var deviceReg = await registry.GetDeviceAsync(deviceId); if (deviceReg == null) { deviceReg = new Microsoft.Azure.Devices.Device(deviceId); deviceReg = await registry.AddDeviceAsync(deviceReg); } var device = new DeviceModel(); device.DeviceId = deviceId; //device.DeviceRegId = deviceReg.Id; device.Key = deviceReg.Authentication.SymmetricKey.PrimaryKey; _whiteList.Add(deviceId, device); var data = new DeviceMetaData(); data.Version = "1.0"; data.IsSimulatedDevice = false; data.Properties.DeviceID = deviceId; data.Properties.FirmwareVersion = "42"; data.Properties.HubEnabledState = true; data.Properties.Processor = "Foo"; data.Properties.Platform = "Yep"; data.Properties.SerialNumber = "Sigfox-" + deviceId; data.Properties.InstalledRAM = "1 MB"; data.Properties.ModelNumber = "007-BOND"; data.Properties.Manufacturer = "Sigfox"; //data.Properties.UpdatedTime = DateTime.UtcNow; data.Properties.DeviceState = DeviceState.Normal; var content = JsonConvert.SerializeObject(data); connectionString = string.Format("HostName={0}.azure-devices.net;DeviceId={1};SharedAccessKey={2}", "sigfoxmonitoring", device.DeviceId, device.Key); _client = DeviceClient.CreateFromConnectionString(connectionString, TransportType.Http1); await _client.SendEventAsync(new Message(Encoding.UTF8.GetBytes(content))); }