Package: azure-digitaltwins-core-patched
Azure Azure Digital Twins Core client library for PythonThis package contains an SDK for Azure Digital Twins API to provide access to the Azure Digital Twins service for managing twins, models, relationships, etc.Getting startedIntroductionAzure Digital Twins is a developer platform for next-generation IoT solutions that lets you create, run, and manage digital representations of your business environment, securely and efficiently in the cloud. With Azure Digital Twins, creating live operational state representations is quick and cost-effective, and digital representations stay current with real-time data from IoT and other data sources. If you are new to Azure Digital Twins and would like to learn more about the platform, please make sure you check out the Azure Digital Twinsofficial documentation page.For an introduction on how to program against the Azure Digital Twins service, visit thecoding tutorial pagefor an easy step-by-step guide. Visitthis tutorialto learn how to interact with an Azure Digital Twin instance using a command-line client application. Finally, for a quick guide on how to build an end-to-end Azure Digital Twins solution that is driven by live data from your environment, make sure you check outthis helpful guide.The guides mentioned above can help you get started with key elements of Azure Digital Twins, such as creating Azure Digital Twins instances, models, twin graphs, etc. Use this samples guide below to familiarize yourself with the various APIs that help you program against Azure Digital Twins.How to InstallInstall [azure-digitaltwins-core][pypi_package_keys] andazure-identitywithpip:pipinstallazure-digitaltiwns-coreazure-identityazure-identityis used for Azure Active Directory
authentication as demonstrated below.How to useAuthentication, permissionTo create a new digital twins client, you need the endpoint to an Azure Digital Twin instance and credentials.
For the samples below, theAZURE_URL,AZURE_TENANT_ID,AZURE_CLIENT_ID, andAZURE_CLIENT_SECRETenvironment variables have to be set.
The client requires an instance ofTokenCredentialorServiceClientCredentials.
In this samples, we illustrate how to use one derived class:DefaultAzureCredentials.Note: In order to access the data plane for the Digital Twins service, the entity must be given permissions.
To do this, use the Azure CLI command:az dt rbac assign-role --assignee '<user-email | application-id>' --role owner -n '<your-digital-twins-instance>'DefaultAzureCredential supports different authentication mechanisms and determines the appropriate credential type based of the environment it is executing in.
It attempts to use multiple credential types in an order until it finds a working credential.Sample code# DefaultAzureCredential supports different authentication mechanisms and determines the appropriate credential type based of the environment it is executing in.# It attempts to use multiple credential types in an order until it finds a working credential.# - AZURE_URL: The tenant ID in Azure Active Directoryurl=os.getenv("AZURE_URL")# DefaultAzureCredential expects the following three environment variables:# - AZURE_TENANT_ID: The tenant ID in Azure Active Directory# - AZURE_CLIENT_ID: The application (client) ID registered in the AAD tenant# - AZURE_CLIENT_SECRET: The client secret for the registered applicationcredential=DefaultAzureCredential()serviceClient=DigitalTwinsClient(url,credential)Key conceptsAzure Digital Twins is an Azure IoT service that creates comprehensive models of the physical environment. It can create spatial intelligence graphs to model the relationships and interactions between people, spaces, and devices.
You can learn more about Azure Digital Twins by visitingAzure Digital Twins Documentation.ExamplesYou can explore the digital twins APIs (using the client library) using the samples project.The samples project demonstrates the following:Instantiate the clientCreate, get, and decommission modelsCreate, query, and delete a digital twinGet and update components for a digital twinCreate, get, and delete relationships between digital twinsCreate, get, and delete event routes for digital twinPublish telemetry messages to a digital twin and digital twin componentCreate, list, decommission, and delete modelsCreate modelsLet's create models using the code below. You need to pass an array containing list of models.temporary_component={"@id":component_id,"@type":"Interface","@context":"dtmi:dtdl:context2","displayName":"Component1","contents":[{"@type":"Property","name":"ComponentProp1","schema":"string"},{"@type":"Telemetry","name":"ComponentTelemetry1","schema":"integer"}]}temporary_model={"@id":model_id,"@type":"Interface","@context":"dtmi:dtdl:context2","displayName":"TempModel","contents":[{"@type":"Property","name":"Prop1","schema":"string"},{"@type":"Component","name":"Component1","schema":component_id},{"@type":"Telemetry","name":"Telemetry1","schema":"integer"}]}new_models=[temporary_component,temporary_model]models=service_client.create_models(new_models)print('Created Models:')print(models)List modelsUsinglist_modelsto retrieve all created modelslisted_models=service_client.list_models(model_id)formodelinlisted_models:print(model+'\n')Get modelUseget_modelwith model's unique identifier to get a specific model.# Get a modelget_model=service_client.get_model(model_id)print('Get Model:')print(get_model)Decommission modelTo decommision a model, pass in a model Id for the model you want to decommision.# Decommission a modelservice_client.decommission_model(model_id)Delete modelTo delete a model, pass in a model Id for the model you want to delete.# Delete a modelservice_client.delete_model(model_id)Create and delete digital twinsCreate digital twinsFor Creating Twin you will need to provide Id of a digital Twin such asmy_twinand the application/json digital twin based on the model created earlier. You can look at sample application/jsonhere.digital_twin_id='digitalTwin-'+str(uuid.uuid4())withopen(r"dtdl\digital_twins_\buildingTwin.json")asf:dtdl_digital_twins_building_twin=json.load(f)created_twin=service_client.upsert_digital_twin(digital_twin_id,dtdl_digital_twins_building_twin)print('Created Digital Twin:')print(created_twin)Get a digital twinGetting a digital twin is extremely easy.get_twin=service_client.get_digital_twin(digital_twin_id)print('Get Digital Twin:')print(get_twin)Query digital twinsQuery the Azure Digital Twins instance for digital twins using theAzure Digital Twins Query Store lanaguage. Query calls support paging. Here's an example of how to query for digital twins and how to iterate over the results.Note that there may be a delay between before changes in your instance are reflected in queries.
For more details on query limitations, see (https://docs.microsoft.com/azure/digital-twins/how-to-query-graph#query-limitations)query_expression='SELECT * FROM digitaltwins'query_result=service_client.query_twins(query_expression)print('DigitalTwins:')fortwininquery_result:print("    -:{}".format(twin["$dtId"]))Delete digital twinsDelete a digital twin simply by providing Id of a digital twin as below.service_client.delete_digital_twin(digital_twin_id)Get and update digital twin componentsUpdate digital twin componentsTo update a component or in other words to replace, remove and/or add a component property or subproperty within Digital Twin, you would need Id of a digital twin, component name and application/json-patch+json operations to be performed on the specified digital twin's component. Here is the sample code on how to do it.component_path="Component1"options={"patchDocument":{"ComponentProp1":"value2"}}service_client.update_component(digital_twin_id,component_path,options)Get digital twin componentsGet a component by providing name of a component and Id of digital twin to which it belongs.get_component=service_client.get_component(digital_twin_id,component_path)print('Get Component:')print(get_component)Create and list digital twin relationshipsCreate digital twin relationshipsupsert_relationshipcreates a relationship on a digital twin provided with Id of a digital twin, name of relationship such as "contains", Id of an relationship such as "FloorContainsRoom" and an application/json relationship to be created. Must contain property with key "$targetId" to specify the target of the relationship. Sample payloads for relationships can be foundhere.withopen(r"dtdl\relationships\hospitalRelationships.json")asf:dtdl_relationships=json.load(f)forrelationshipindtdl_relationships:service_client.upsert_relationship(relationship["$sourceId"],relationship["$relationshipId"],relationship)List digital twin relationshipslist_relationshipsandlist_incoming_relationshipslists all the relationships and all incoming relationships respectively of a digital twin.relationships=service_client.list_relationships(digital_twint_id)forrelationshipinrelationships:print(relationship+'\n')incoming_relationships=service_client.list_incoming_relationships(digital_twin_id)forincoming_relationshipinincoming_relationships:print(incoming_relationship+'\n')Create, list, and delete event routes of digital twinsCreate event routesTo create an event route, provide an Id of an event route such as "myEventRouteId" and event route data containing the endpoint and optional filter like the example shown below.event_route_id='eventRoute-'+str(uuid.uuid4())event_filter="$eventType = 'DigitalTwinTelemetryMessages' or $eventType = 'DigitalTwinLifecycleNotification'"service_client.upsert_event_route(event_route_id,event_hub_endpoint_name,**{"filter":event_filter})For more information on the event route filter language, see the "how to manage routes"filter events documentation.List event routesList a specific event route given event route Id or all event routes setting options withlist_event_routes.event_routes=service_client.list_event_routes()forevent_routeinevent_routes:print(event_route+'\n')Delete event routesDelete an event route given event route Id.service_client.delete_event_route(event_route_id)Publish telemetry messages for a digital twinTo publish a telemetry message for a digital twin, you need to provide the digital twin Id, along with the payload on which telemetry that needs the update.digita_twin_id="<DIGITAL TWIN ID>"telemetry_payload='{"Telemetry1": 5}'service_client.publish_telemetry(digita_twin_id,telemetry_payload)You can also publish a telemetry message for a specific component in a digital twin. In addition to the digital twin Id and payload, you need to specify the target component Id.digita_twin_id="<DIGITAL TWIN ID>"component_path="<COMPONENT_PATH>"telemetry_payload='{"Telemetry1": 5}'service_client.publish_component_telemetry(digita_twin_id,component_path,telemetry_payload)TroubleshootingLoggingThis library uses the standard logging library for logging. Basic information about HTTP sessions (URLs, headers, etc.) is logged at INFO level.Detailed DEBUG level logging, including request/response bodies and unredacted headers, can be enabled on a client with the logging_enable keyword argument:Client level loggingimportsysimportlogging# Create loggerlogger=logging.getLogger('azure')logger.setLevel(logging.DEBUG)handler=logging.StreamHandler(stream=sys.stdout)logger.addHandler(handler)# Create service client and enable logging for all operationsservice_client=DigitalTwinsClient(url,credential,logging_enable=True)Per-operation level loggingimportsysimportlogging# Create loggerlogger=logging.getLogger('azure')logger.setLevel(logging.DEBUG)handler=logging.StreamHandler(stream=sys.stdout)logger.addHandler(handler)# Get model with logging enabledmodel=service_client.get_model(model_id,logging_enable=True)Optional ConfigurationOptional keyword arguments can be passed in at the client and per-operation level. The azure-corereference documentationdescribes available configurations for retries, logging, transport protocols, and more.Next stepsProvide FeedbackIf you encounter bugs or have suggestions, pleaseopen an issue.ContributingThis project welcomes contributions and suggestions.  Most contributions require you to agree to a
Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us
the rights to use your contribution. For details, visithttps://cla.microsoft.com.When you submit a pull request, a CLA-bot will automatically determine whether you need to provide
a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions
provided by the bot. You will only need to do this once across all repos using our CLA.This project has adopted theMicrosoft Open Source Code of Conduct.
For more information see theCode of Conduct FAQor
contactopencode@microsoft.comwith any additional questions or comments.Release History1.0.0 (unreleased)The is the GA release containing the following changes:Added etag and match_condition parameters to upsert_digital_twin and upsert_relationship APIs to support conditional operation.Rename EventRoute type to DigitalTwinsEventRouteRename component_path to component_nameRename models to dtdl_modelsFix some documentation1.0.0b1 (2020-10-31)Initial Release