This package contains an isomorphic SDK for Azure Digital Twins API to provide access to the Azure Digital Twins service for managing twins, models, relationships, etc.
See our support policy for more details.
@azure/digital-twins-core
packageInstall the Digital Twins Core client library for JavaScript with npm
:
npm install @azure/digital-twins-core
To use this client library in the browser, first you need to use a bundler. For details on how to do this, please refer to our bundling documentation.
Azure Digital Twins doesn't currently support Cross-Origin Resource Sharing (CORS). As a result, this library cannot be used to make direct calls to the template service from a browser. Please refer to this document for guidance.
Azure 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 visiting Azure Digital Twins Documentation.
DigitalTwinsClient
DigitalTwinsClient
is the client object that users of this library use to manage their Azure Digital Twins instance.
To create a new DigitalTwinsClient
, you need the endpoint to an Azure Digital Twins instance and credentials.
Here, we use DefaultAzureCredential
for credentials from the package @azure/identity
.
It supports different authentication mechanisms and determines the appropriate credential type based of the environment it is executing in.
See the readme for @azure/identity for more information on the different authentication options you can use.
const { DefaultAzureCredential } = require("@azure/identity");
const { DigitalTwinsClient } = require("@azure/digital-twins-core");
const url = "<URL to Azure Digital Twins instance>";
const credential = new DefaultAzureCredential();
const serviceClient = new DigitalTwinsClient(url, credential);
In order to create models, we pass in a list of models to createModels
.
Here, we only create one model.
const myComponent = {
"@id": "dtmi:my_component;1",
"@type": "Interface",
"@context": "dtmi:dtdl:context;2",
displayName: "Component1",
contents: [
{
"@type": "Property",
name: "ComponentProp1",
schema: "string"
}
]
};
const models = await serviceClient.createModels([myComponent]);
We use listModels
to list all the models.
const models = await serviceClient.listModels();
for await (const model of models) {
console.log(`Model ID: ${model.id}`);
}
We can get a specific model using getModel
with the model ID.
const model = await serviceClient.getModel("<model ID>");
We can decommission a model using decomissionModel
with the model ID.
await serviceClient.decomissionModel("<model ID>");
We can delete a model using deleteModel
with the model ID.
await serviceClient.deleteModel("<model ID>");
To create a twin, you will need to provide an ID for the digital twin and a JSON string containing the digital twin object.
const digitalTwinId = "myTwin";
const newTwin = "<JSON containing the digitalTwin object>";
const createdTwin = await serviceClient.upsertDigitalTwin(digitalTwinId, newTwin);
We can get a digital twin using getDigitalTwin
with the digital twin ID.
const digitalTwinId = "myTwin";
const twin = await serviceClient.getDigitalTwin(digitalTwinId);
console.log(`DigitalTwin's etag: ${twin.eTag}`);
console.log(`DigitalTwin: ${twin.body}`);
Query the Azure Digital Twins instance for digital twins using the Azure Digital Twins query language. Here's an example of how to query for digital twins and how to iterate over the results.
const query = "SELECT * FROM digitaltwins";
const queryResult = serviceClient.queryTwins(query);
for await (const item of queryResult) {
console.log(`DigitalTwin: ${item}`);
}
We can delete a digital twin using deleteDigitalTwin
with the digital twin ID.
const digitalTwinId = "myTwin";
await serviceClient.deleteDigitalTwin(digitalTwinId);
We can get a digital twin component using getComponent
with the digital twin ID and the path of the component.
const digitalTwinId = "myTwin";
const componentPath = "Component1";
const component = await serviceClient.getComponent(digitalTwinId, componentPath);
console.log(`Component: ${component}`);
To update a digital twin component (i.e., replace, remove, or add a component property or sub-property within a digital twin), you need to provide a digital twin ID, component path, and a list of patch objects with the properties op
and path
.
The value of op
is "replace", "remove", or "add", and the value of path
is the path to the digital twin component being updated.
For "replace" and "add" operations, the value
property should be included with your desired value of the component property.
const digitalTwinId = "myTwin";
const componentPath = "Component1";
const patch = {
op: "replace",
path: "/ComponentProp1",
value: "value2"
};
const updateComponentResponse = await serviceClient.updateComponent(digitalTwinId, componentPath, [
patch
]);
upsertRelationship
creates a relationship on a digital twin provided with ID of a digital twin, name of relationship (in this case, "has"), ID of an relationship (in this case "BuildingHasFloor") and the object representing the relationship to be created.
The object must contain property with key "$targetId" to specify the target of the relationship.
const relationship = {
$relationshipId: "BuildingHasFloor",
$sourceId: "BuildingTwin",
$relationshipName: "has",
$targetId: "FloorTwin",
isAccessRestricted: false
};
await serviceClient.upsertRelationship(
relationship["$sourceId"],
relationship["$relationshipId"],
relationship
);
For a digital twin, listRelationships
and listIncomingRelationships
list all the relationships and all incoming relationships, respectively.
const digitalTwinId = "myTwin";
const relationships = serviceClient.listRelationships(digitalTwinId);
for await (const relationship of relationships) {
console.log(`Relationship: ${relationship}`);
}
const digitalTwinId = "myTwin";
const incomingRelationships = serviceClient.listIncomingRelationships(digitalTwinId);
for await (const incomingRelationship of incomingRelationships) {
console.log(`Relationship: ${incomingRelationship}`);
}
To create an event route, provide an ID of an event route (in this case, "myEventRouteId") and event route data containing the endpoint and optional filter like the example shown below. For more information on filtering events, see this documentation.
const eventHubEndpointName = "myEventHubEndpointName";
const eventRouteId = "myEventRouteId";
const eventFilter =
"$eventType = 'DigitalTwinTelemetryMessages' or $eventType = 'DigitalTwinLifecycleNotification'";
await serviceClient.upsertEventRoute(eventRouteId, eventHubEndpointName, eventFilter);
We can get an event route using getEventRoute
with the event route ID.
const eventRouteId = "myEventRouteId";
const eventRoute = serviceClient.getEventRoute(eventRouteId);
console.log(`EventRoute: ${eventRoute}`);
We can list event routes using listEventRoutes
.
const eventRoutes = serviceClient.listEventRoutes();
for await (const eventRoute of eventRoutes) {
console.log(`EventRoute: ${eventRoute}`);
}
We can delete an event route using deleteEventRoute
with the event route ID.
const eventRouteId = "myEventRouteId";
await serviceClient.deleteEventRoute(eventRouteId);
To publish a telemetry message for a digital twin, you need to provide the digital twin ID, the payload, and a unique ID for the message.
const digitalTwinId = "<digital twin ID>";
const telemetryPayload = '{"Telemetry1": 5}';
const response = await serviceClient.publishTelemetry(
digitalTwinId,
telemetryPayload,
"<unique message ID>"
);
You can also publish a telemetry message for a specific component in a digital twin. In addition to the digital twin ID, payload, and unique message ID, you need to specify the target component path.
const digitalTwinId = "<digital twin ID>";
const componentPath = "<component path>";
const telemetryPayload = '{"Telemetry1": 5}';
const response = await serviceClient.publishComponentTelemetry(
digitalTwinId,
componentPath,
telemetryPayload,
"<unique message ID>"
);
Additional examples can be found in the samples directory.
Enabling logging may help uncover useful information about failures. In order to see a log of HTTP requests and responses, set the AZURE_LOG_LEVEL
environment variable to info
. Alternatively, logging can be enabled at runtime by calling setLogLevel
in the @azure/logger
:
import { setLogLevel } from "@azure/logger";
setLogLevel("info");
For more detailed instructions on how to enable logs, you can look at the @azure/logger package docs.
If you'd like to contribute to this library, please read the contributing guide to learn more about how to build and test the code.
Generated using TypeDoc