static async Task Main() { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { int width = Math.Min(Console.LargestWindowWidth, 150); int height = Math.Min(Console.LargestWindowHeight, 40); Console.SetWindowSize(width, height); } try { // Read configuration data from the IConfiguration config = new ConfigurationBuilder() .AddJsonFile("serviceConfig.json", false, true) .Build(); clientId = config["clientId"]; tenantId = config["tenantId"]; adtInstanceUrl = config["instanceUrl"]; } catch (Exception e) { Log.Error($"Could not read service configuration file serviceConfig.json"); Log.Alert($"Please copy serviceConfig.json.TEMPLATE to serviceConfig.json"); Log.Alert($"and edit to reflect your service connection settings."); Log.Alert($"Make sure that 'Copy always' or 'Copy if newer' is set for serviceConfig.json in VS file properties"); Environment.Exit(0); } Log.Ok("Authenticating..."); try { var credential = new InteractiveBrowserCredential(tenantId, clientId); client = new DigitalTwinsClient(new Uri(adtInstanceUrl), credential); // force authentication to happen here try { client.GetDigitalTwin("---"); } catch (RequestFailedException rex) { } catch (Exception e) { Log.Error($"Authentication or client creation error: {e.Message}"); Log.Alert($"Have you checked that the configuration in serviceConfig.json is correct?"); Environment.Exit(0); } } catch (Exception e) { Log.Error($"Authentication or client creation error: {e.Message}"); Log.Alert($"Have you checked that the configuration in serviceConfig.json is correct?"); Environment.Exit(0); } Log.Ok($"Service client created – ready to go"); CommandLoop CommandLoopInst = new CommandLoop(client); await CommandLoopInst.CliCommandInterpreter(); }
public DigitalTwin() { var credential = new InteractiveBrowserCredential(tenantId, clientId); DigitalTwinsClient client = new DigitalTwinsClient(new Uri(adtInstanceUrl), credential); Utils.IgnoreErrors(() => client.GetDigitalTwin("")); _client = client; _commandLoop = new CommandLoop(client); }
public static async Task Main(string[] args) { var adtInstanceUrl = "https://ADT_INSTANCE_HOST_NAME"; var credential = new DefaultAzureCredential(); var client = new DigitalTwinsClient(new Uri(adtInstanceUrl), credential); //retrieve the factory twin - this query will take a moment longer due to the cold start var factoryId = "FA44212"; var factory = client.GetDigitalTwin <BasicDigitalTwin>(factoryId); Console.WriteLine($"Factory {factory.Value.Id} retrieved."); foreach (KeyValuePair <string, object> prop in factory.Value.Contents) { Console.WriteLine($"Factory {factory.Value.Id} has Property: {prop.Key} with value {prop.Value.ToString()}"); } //output factory property metadata, indicating the last time the property was updated foreach (var md in factory.Value.Metadata.PropertyMetadata) { Console.WriteLine($"Factory {factory.Value.Id} Property: {md.Key} was last updated {md.Value.LastUpdatedOn}"); } //retrieve factory relationships IAsyncEnumerable <BasicRelationship> relationships = client.GetRelationshipsAsync <BasicRelationship>(factoryId); await foreach (BasicRelationship relationship in relationships) { Console.WriteLine($"Factory {factory.Value.Id} has relationship '{relationship.Name}' with {relationship.TargetId}"); } //retrieve only the Efficiency property value for the factory using a projection var projectionQuery1 = $"SELECT Factory.Efficiency FROM DIGITALTWINS Factory WHERE Factory.$dtId='{factoryId}'"; IAsyncEnumerable <JsonElement> response = client.QueryAsync <JsonElement>(projectionQuery1); await foreach (JsonElement ret in response) { Console.WriteLine($"{factoryId} Efficiency is at {ret.GetProperty("Efficiency")}"); } //retrieve factories with Efficiency equal to or over 90 var queryByPropertyValue = $"SELECT Factory FROM DIGITALTWINS Factory WHERE Factory.Efficiency >= 90"; IAsyncEnumerable <BasicDigitalTwin> response2 = client.QueryAsync <IDictionary <string, BasicDigitalTwin> >(queryByPropertyValue).Select(_ => _["Factory"]); await foreach (BasicDigitalTwin ret in response2) { Console.WriteLine($"Factory {ret.Id} has an Efficiency over 90."); } }
// </CreateRelationshipMethod> // <FetchAndPrintMethod> private static async Task FetchAndPrintTwinAsync(string twin_Id, DigitalTwinsClient client) { BasicDigitalTwin twin; Response <BasicDigitalTwin> res = client.GetDigitalTwin(twin_Id); // <UseFindOutgoingRelationships> await FindOutgoingRelationshipsAsync(client, twin_Id); // </UseFindOutgoingRelationships> // <UseFindIncomingRelationships> await FindIncomingRelationshipsAsync(client, twin_Id); // </UseFindIncomingRelationships> return; }
private static BasicDigitalTwin FetchAndPrintTwin(string twin_ID, DigitalTwinsClient client) { BasicDigitalTwin twin; // <GetTwin> // <GetTwinCall> Response <BasicDigitalTwin> twin = client.GetDigitalTwin(twin_ID); // </GetTwinCall> Console.WriteLine($"Model id: {twin.Metadata.ModelId}"); foreach (string prop in twin.Contents.Keys) { if (twin.Contents.TryGetValue(prop, out object value)) { Console.WriteLine($"Property '{prop}': {value}"); } } // </GetTwin> return(twin); }
// Update is called once per frame IEnumerator CheckTwin() { while (true) { foreach (KeyValuePair <string, string[]> models in twinModels) { foreach (string twinId in models.Value) { TwinModel model = null; switch (models.Key) { case "Hall": model = client.GetDigitalTwin <Hall>(twinId); break; case "Light": model = client.GetDigitalTwin <Light>(twinId); break; case "CovidAlarm": model = client.GetDigitalTwin <CovidAlarm>(twinId); break; case "Clim": model = client.GetDigitalTwin <Clim>(twinId); break; case "FireAlarm": model = client.GetDigitalTwin <FireAlarm>(twinId); break; case "Escalator": model = client.GetDigitalTwin <Escalator>(twinId); break; default: break; } SendTwinUpdate(twinId, model); } } yield return(new WaitForSeconds(5)); } }
static void Main(string[] args) { Parser.Default.ParseArguments <CliOptions>(args) .WithParsed(o => { modelPath = o.ModelPath; deleteFirst = o.DeleteFirst; } ); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { int width = Math.Min(Console.LargestWindowWidth, 150); int height = Math.Min(Console.LargestWindowHeight, 40); Console.SetWindowSize(width, height); } try { // Read configuration data from the IConfiguration config = new ConfigurationBuilder() .AddJsonFile("serviceConfig.json", false, true) .Build(); clientId = config["clientId"]; tenantId = config["tenantId"]; adtInstanceUrl = config["instanceUrl"]; } catch (Exception) { Log.Error($"Could not read service configuration file serviceConfig.json"); Log.Alert($"Please copy serviceConfig.json.TEMPLATE to serviceConfig.json"); Log.Alert($"and edit to reflect your service connection settings."); Log.Alert($"Make sure that 'Copy always' or 'Copy if newer' is set for serviceConfig.json in VS file properties"); Environment.Exit(0); } Log.Ok("Authenticating..."); try { var credential = new InteractiveBrowserCredential(tenantId, clientId); client = new DigitalTwinsClient(new Uri(adtInstanceUrl), credential); // force authentication to happen here try { client.GetDigitalTwin("---"); } catch (RequestFailedException) { // As we are intentionally try to retrieve a twin that is most likely not going to exist, this exception is expected // We just do this to force the authentication library to authenticate ahead } catch (Exception e) { Log.Error($"Authentication or client creation error: {e.Message}"); Log.Alert($"Have you checked that the configuration in serviceConfig.json is correct?"); Environment.Exit(0); } } catch (Exception e) { Log.Error($"Authentication or client creation error: {e.Message}"); Log.Alert($"Have you checked that the configuration in serviceConfig.json is correct?"); Environment.Exit(0); } Log.Ok($"Service client created – ready to go"); try { // If -d Option specified Delete All Models first if (deleteFirst) { DeleteAllModels(1); } // Go over directories EnumerationOptions options = new EnumerationOptions() { RecurseSubdirectories = true }; foreach (string file in Directory.EnumerateFiles(modelPath, "*.json", options)) { UploadModel(file); } } catch (RequestFailedException e) { Log.Error($"Response {e.Status}: {e.Message}"); } catch (Exception ex) { Log.Error($"Error: {ex.Message}"); } }
static async Task Main() { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { int width = Math.Min(Console.LargestWindowWidth, 150); int height = Math.Min(Console.LargestWindowHeight, 40); Console.SetWindowSize(width, height); } try { // Read configuration data from the IConfiguration config = new ConfigurationBuilder() .AddJsonFile("serviceConfig.json", true, true) .Build(); //clientId = config["clientId"]; tenantId = config["tenantId"]; adtInstanceUrl = config["instanceUrl"]; } catch (Exception e) { Log.Error($"Could not read service configuration file serviceConfig.json"); Log.Alert($"Please copy serviceConfig.json.TEMPLATE to serviceConfig.json"); Log.Alert($"and edit to reflect your service connection settings"); Environment.Exit(0); } Log.Ok("Authenticating..."); try { //var credential = new InteractiveBrowserCredential(tenantId, clientId); var credential = new DefaultAzureCredential(new DefaultAzureCredentialOptions() { SharedTokenCacheTenantId = tenantId }); client = new DigitalTwinsClient(new Uri(adtInstanceUrl), credential); //var tokenProvider = new AzureServiceTokenProvider("RunAs=Developer; DeveloperTool=AzureCli"); //TokenCredentials tk = new TokenCredentials(await tokenProvider.GetAccessTokenAsync("0b07f429-9f4b-4714-9392-cc5e8e80c8b0")); //var t1 = await tokenProvider.GetAccessTokenAsync("0b07f429-9f4b-4714-9392-cc5e8e80c8b0"); // force authentication to happen here // (for some reason this only happens on first call) try { client.GetDigitalTwin("MilleniumF"); } catch (RequestFailedException rex) { } catch (Exception e) { Log.Error($"Authentication or client creation error: {e.Message}"); Environment.Exit(0); } } catch (Exception e) { Log.Error($"Authentication or client creation error: {e.Message}"); Environment.Exit(0); } Log.Ok($"Service client created – ready to go"); CommandLoop CommandLoopInst = new CommandLoop(client); await CommandLoopInst.CliCommandInterpreter(); }
public async static void Run([EventGridTrigger] EventGridEvent eventGridEvent, ILogger log) { try { log.LogInformation(eventGridEvent.Topic.ToString()); log.LogInformation(eventGridEvent.Subject.ToString()); log.LogInformation(eventGridEvent.Data.ToString()); ManagedIdentityCredential cred = new ManagedIdentityCredential("https://digitaltwins.azure.net"); DigitalTwinsClient client = new DigitalTwinsClient(new Uri(adtInstanceUrl), cred, new DigitalTwinsClientOptions { Transport = new HttpClientTransport(httpClient) }); JObject digitalTwin = JObject.Parse(client.GetDigitalTwin(eventGridEvent.Subject.ToString())); string deviceTwinId = digitalTwin["device_twin_id"].ToString(); ServiceClient service = ServiceClient.CreateFromConnectionString(iotHubConnectionString); JObject digitalTwinData = JObject.Parse(eventGridEvent.Data.ToString()); string digitalTwinModelId = (string)digitalTwinData["data"]["modelId"].ToString(); ModelData digitalTwinModelData = await client.GetModelAsync(digitalTwinModelId); JObject digitalTwinModel = JObject.Parse(digitalTwinModelData.Model); JArray digitalTwinModelContents = (JArray)digitalTwinModel["contents"]; JObject data = (JObject)digitalTwinData["data"]; JArray patch = (JArray)digitalTwinData["data"]["patch"]; JObject reformattedData = new JObject(); reformattedData.Add("device", eventGridEvent.Subject.ToString()); JObject values = new JObject(); foreach (JObject item in patch) { string name = item["path"].ToString().Replace("/", ""); foreach (JObject modelItem in digitalTwinModelContents) { if (modelItem["@type"].ToString().Equals("Property") && modelItem["name"].ToString().Equals(name)) { JToken writable = modelItem.SelectToken("writable"); if (writable != null) { if (writable.ToObject <bool>() == true) { values.Add(new JProperty(name, item["value"])); } } break; } } } if (values.Count > 0) { reformattedData.Add("values", values); log.LogInformation("Sending IOTHub device {0} payload {1}:", deviceTwinId, reformattedData.ToString()); var methodInvocation = new CloudToDeviceMethod("publish") { ResponseTimeout = TimeSpan.FromSeconds(30) }; methodInvocation.SetPayloadJson(reformattedData.ToString()); var response = await service.InvokeDeviceMethodAsync(deviceTwinId, methodInvocation); log.LogInformation("Response status: {0}, payload:", response.Status, response.GetPayloadAsJson()); } else { log.LogInformation("No writable values found that could sent to IOTHub"); } } catch (Exception e) { log.LogError(e.Message); } }