Skip to content
This repository has been archived by the owner on Oct 12, 2023. It is now read-only.

Commit

Permalink
Azure IoT Plug and Play Public Preview Code Examples (#33)
Browse files Browse the repository at this point in the history
  • Loading branch information
Pierre Cauchois authored Aug 20, 2019
1 parent e9bf54e commit 4893da3
Show file tree
Hide file tree
Showing 41 changed files with 1,398 additions and 1 deletion.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ azure-iot-samples-node provides a set of easy-to-understand, continuously-tested

## Prerequisites

- Node.js v4.x.x or later on your development machine. You can download Node.js for multiple platforms from [nodejs.org](https://nodejs.org). You can verify the current version of Node.js on your development machine using "node --version"
- Node.js LTS or Current version on your development machine. You can download Node.js for multiple platforms from [nodejs.org](https://nodejs.org). You can verify the current version of Node.js on your development machine using "node --version"

## Resources

Expand Down
20 changes: 20 additions & 0 deletions digital-twins/Quickstarts/Device/deviceInformation.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
'use strict';

const BaseInterface = require('azure-iot-digitaltwins-device').BaseInterface;
const Property = require('azure-iot-digitaltwins-device').Property;

module.exports.DeviceInformation = class DeviceInformation extends BaseInterface {
constructor(name, propertyCallback, commandCallback) {
super(name, 'urn:azureiot:DeviceManagement:DeviceInformation:1', propertyCallback, commandCallback);
this.manufacturer = new Property();
this.model = new Property();
this.swVersion = new Property();
this.osName = new Property();
this.processorArchitecture = new Property();
this.processorManufacturer = new Property();
this.totalStorage = new Property();
this.totalMemory = new Property();
}
};
23 changes: 23 additions & 0 deletions digital-twins/Quickstarts/Device/environmentalinterface.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
'use strict';

const BaseInterface = require('azure-iot-digitaltwins-device').BaseInterface;
const Telemetry = require('azure-iot-digitaltwins-device').Telemetry;
const Property = require('azure-iot-digitaltwins-device').Property;
const Command = require('azure-iot-digitaltwins-device').Command;

module.exports.EnvironmentalSensor = class EnvironmentalSensor extends BaseInterface {
constructor(name, propertyCallback, commandCallback) {
super(name, 'urn:contoso:com:EnvironmentalSensor:1', propertyCallback, commandCallback);
this.temp = new Telemetry();
this.humid = new Telemetry();
this.state = new Property();
this.blink = new Command();
this.turnOff = new Command();
this.turnOn = new Command();
this.runDiagnostics = new Command();
this.name = new Property(true);
this.brightness = new Property(true);
}
};
25 changes: 25 additions & 0 deletions digital-twins/Quickstarts/Device/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"name": "azure-iot-digitaltwins-device-samples",
"version": "1.0.0-preview.1",
"description": "Samples for the azure-iot-digitaltwins-device client library",
"repository": {
"type": "git",
"url": "git+https://github.com/azure/azure-iot-sdk-node-digitaltwins.git"
},
"author": "Microsoft Corp.",
"license": "MIT",
"bugs": {
"url": "https://github.com/azure/azure-iot-sdk-node-digitaltwins/issues"
},
"homepage": "https://github.com/azure/azure-iot-sdk-node-digitaltwins#readme",
"dependencies": {
"azure-iot-device": "1.12.0-preview.1",
"azure-iot-common": "1.12.0-preview.1",
"azure-iot-device-mqtt": "1.12.0-preview.1",
"azure-iot-digitaltwins-device": "1.0.0-preview.1"
},
"devDependencies": {
"eslint": "^6.0.1",
"eslint-config-google": "^0.13.0"
}
}
65 changes: 65 additions & 0 deletions digital-twins/Quickstarts/Device/sample_device.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

'use strict';

const DigitalTwinClient = require('azure-iot-digitaltwins-device').DigitalTwinClient;
const DeviceClient = require('azure-iot-device').Client;
const Mqtt = require('azure-iot-device-mqtt').Mqtt;

const EnvironmentalSensor = require('./environmentalinterface').EnvironmentalSensor;
const DeviceInformation = require('./deviceInformation').DeviceInformation;

const propertyUpdateHandler = (interfaceInstance, propertyName, reportedValue, desiredValue, version) => {
console.log('Received an update for ' + propertyName + ': ' + JSON.stringify(desiredValue));
interfaceInstance[propertyName].report(desiredValue, {
code: 200,
description: 'helpful descriptive text',
version: version
})
.then(() => console.log('updated the property'))
.catch(() => console.log('failed to update the property'));
};

const commandHandler = (request, response) => {
console.log('received command: ' + request.commandName + ' for interfaceInstance: ' + request.interfaceInstanceName);
response.acknowledge(200, 'helpful response text')
.then(() => console.log('acknowledgement succeeded.'))
.catch(() => console.log('acknowledgement failed'));
};

const environmentalSensor = new EnvironmentalSensor('environmentalSensor', propertyUpdateHandler, commandHandler);
const deviceInformation = new DeviceInformation('deviceInformation');

const deviceClient = DeviceClient.fromConnectionString(process.env.DEVICE_CONNECTION_STRING, Mqtt);

const capabilityModel = 'urn:azureiot:samplemodel:1';

async function main() {
const digitalTwinClient = new DigitalTwinClient(capabilityModel, deviceClient);
digitalTwinClient.addInterfaceInstance(environmentalSensor);
digitalTwinClient.addInterfaceInstance(deviceInformation);
await digitalTwinClient.register();

// report all of the device information
await deviceInformation.manufacturer.report('Contoso Device Corporation');
await deviceInformation.model.report('Contoso 4762B-turbo');
await deviceInformation.swVersion.report('3.1');
await deviceInformation.osName.report('ContosoOS');
await deviceInformation.processorArchitecture.report('4762');
await deviceInformation.processorManufacturer.report('Contoso Foundries');
await deviceInformation.totalStorage.report('64000');
await deviceInformation.totalMemory.report('640');
console.log('Done sending device Information');

// send telemetry
await environmentalSensor.temp.send(65.5);
await environmentalSensor.humid.send(12.2);
console.log('Done sending telemetry.');

// report a property
await environmentalSensor.state.report('online');
console.log('reported state property as online');
};

main();
29 changes: 29 additions & 0 deletions digital-twins/Quickstarts/Service/get_digital_twin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

const IoTHubTokenCredentials = require('azure-iot-digitaltwins-service').IoTHubTokenCredentials;
const DigitalTwinServiceClient = require('azure-iot-digitaltwins-service').DigitalTwinServiceClient;

const deviceId = '<DEVICE_ID_GOES_HERE>';

// Simple example of how to:
// - create a Digital Twin Service Client using the DigitalTwinServiceClient constructor
// - get the Digital Twin
// - list all the Digital Twin Components
async function main() {
// IoT Hub connection string has to be set to system environment variable IOTHUB_CONNECTION_STRING
// Twin enabled device must be exist on the IoT Hub

// Create digital twin service client
const credentials = new IoTHubTokenCredentials(process.env.IOTHUB_CONNECTION_STRING);
const digitalTwinServiceClient = new DigitalTwinServiceClient(credentials);

console.log('getting full digital twin for device ' + deviceId + '...');
// Get digital twin
const digitalTwin = await digitalTwinServiceClient.getDigitalTwin(deviceId);

// Print digital twin components
console.log(JSON.stringify(digitalTwin.interfaces, null, 2));
};

main();
31 changes: 31 additions & 0 deletions digital-twins/Quickstarts/Service/invoke_command.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

const IoTHubTokenCredentials = require('azure-iot-digitaltwins-service').IoTHubTokenCredentials;
const DigitalTwinServiceClient = require('azure-iot-digitaltwins-service').DigitalTwinServiceClient;

const deviceId = '<DEVICE_ID_GOES_HERE>';
const interfaceInstanceName = '<INTERFACE_INSTANCE_NAME_GOES_HERE>'; // for the environmental sensor, you can try "environmentalSensor"
const commandName = '<COMMAND_NAME_GOES_HERE>'; // for the environmental sensor, you can try "blink", "turnOff" or "turnOn"
const commandArgument = '<COMMAND_ARGUMENT_GOES_HERE>'; // for the environmental sensor, it really doesn't matter. any string will do.

// Simple example of how to:
// - create a Digital Twin Service Client using the DigitalTwinServiceClient constructor
// - invoke a command on a Digital Twin enabled device
async function main() {
// IoT Hub connection string has to be set to system environment variable IOTHUB_CONNECTION_STRING
// Twin enabled device must be exist on the IoT Hub

// Create service client
const credentials = new IoTHubTokenCredentials(process.env.IOTHUB_CONNECTION_STRING);
const digitalTwinServiceClient = new DigitalTwinServiceClient(credentials);

console.log('invoking command ' + commandName + ' on interface instance' + interfaceInstanceName + ' for device ' + deviceId + '...');
// Invoke a command
const digitalTwinCommandResult = await digitalTwinServiceClient.invokeCommand(deviceId, interfaceInstanceName, commandName, commandArgument);

// Print result of the command
console.log(JSON.stringify(digitalTwinCommandResult, null, 2));
};

main();
25 changes: 25 additions & 0 deletions digital-twins/Quickstarts/Service/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"name": "azure-iot-digitaltwins-service-samples",
"version": "1.0.0-preview.1",
"description": "Samples for the azure-iot-digitaltwins-service client library",
"main": "get_digital_twin.js",
"repository": {
"type": "git",
"url": "git+https://github.com/azure/azure-iot-sdk-node-digitaltwins.git"
},
"author": "Microsoft Corp.",
"license": "MIT",
"bugs": {
"url": "https://github.com/azure/azure-iot-sdk-node-digitaltwins/issues"
},
"homepage": "https://github.com/azure/azure-iot-sdk-node-digitaltwins#readme",
"dependencies": {
"azure-iot-digitaltwins-service": "1.0.0-preview.1",
"azure-iothub": "1.12.0-preview.1",
"@azure/event-hubs": "^2.1.1"
},
"devDependencies": {
"eslint": "^6.0.1",
"eslint-config-google": "^0.13.0"
}
}
40 changes: 40 additions & 0 deletions digital-twins/Quickstarts/Service/update_digital_twin_property.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

const IoTHubTokenCredentials = require('azure-iot-digitaltwins-service').IoTHubTokenCredentials;
const DigitalTwinServiceClient = require('azure-iot-digitaltwins-service').DigitalTwinServiceClient;

const deviceId = '<DEVICE_ID_GOES_HERE>';
const interfaceInstanceName = '<INTERFACE_INSTANCE_NAME_GOES_HERE>'; // for the environmental sensor, you can try "environmentalSensor"
const propertyName = '<PROPERTY_NAME_GOES_HERE>'; // for the environmental sensor, try "brightness"
const propertyValue = '<PROPERTY_VALUE_GOES_HERE>'; // for the environmental sensor, try 42 (note that this is a number, not a string, so don't include quotes).

// Simple example of how to:
// - create a Digital Twin Service Client using the DigitalTwinServiceClient constructor
// - update the Digital Twin property using property update API
async function main() {
// IoT Hub connection string has to be set to system environment variable IOTHUB_CONNECTION_STRING
// Twin enabled device must be exist on the IoT Hub

// Create service client
const credentials = new IoTHubTokenCredentials(process.env.IOTHUB_CONNECTION_STRING);
const digitalTwinServiceClient = new DigitalTwinServiceClient(credentials);

// Get digital twin
const digitalTwin = await digitalTwinServiceClient.getDigitalTwin(deviceId);

// Print original Twin
console.log(JSON.stringify(digitalTwin.interfaces, null, 2));

// Update digital twin and verify the update
try {
const updatedDigitalTwin = await digitalTwinServiceClient.updateDigitalTwinProperty(deviceId, interfaceInstanceName, propertyName, propertyValue);

// Print updated Twin
console.log(JSON.stringify(updatedDigitalTwin.interfaces, null, 2));
} catch (err) {
console.log(err);
}
};

main();
9 changes: 9 additions & 0 deletions digital-twins/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# IoT Plug-and-Play Preview

This folder contains code examples showing usage of the IoT Plug-and-Play APIs and client libraries for Node.js.

**Please note that these features are currently in preview, and as such, the final shape of the API might still change**

The `Quickstarts` folder contains code examples associated with the quickstarts and how-to guides for IoT Plug-and-Play.

The `Samples` folder contains a collection of simple samples that show the usage of the various APIs. Each folder contains its own readme that explains how to use the sample.
20 changes: 20 additions & 0 deletions digital-twins/Samples/device/javascript/deviceInformation.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
'use strict';

const BaseInterface = require('azure-iot-digitaltwins-device').BaseInterface;
const Property = require('azure-iot-digitaltwins-device').Property;

module.exports.DeviceInformation = class DeviceInformation extends BaseInterface {
constructor(name, propertyCallback, commandCallback) {
super(name, 'urn:azureiot:DeviceManagement:DeviceInformation:1', propertyCallback, commandCallback);
this.manufacturer = new Property();
this.model = new Property();
this.swVersion = new Property();
this.osName = new Property();
this.processorArchitecture = new Property();
this.processorManufacturer = new Property();
this.totalStorage = new Property();
this.totalMemory = new Property();
}
};
23 changes: 23 additions & 0 deletions digital-twins/Samples/device/javascript/environmentalinterface.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
'use strict';

const BaseInterface = require('azure-iot-digitaltwins-device').BaseInterface;
const Telemetry = require('azure-iot-digitaltwins-device').Telemetry;
const Property = require('azure-iot-digitaltwins-device').Property;
const Command = require('azure-iot-digitaltwins-device').Command;

module.exports.EnvironmentalSensor = class EnvironmentalSensor extends BaseInterface {
constructor(name, propertyCallback, commandCallback) {
super(name, 'urn:contoso:com:EnvironmentalSensor:1', propertyCallback, commandCallback);
this.temp = new Telemetry();
this.humid = new Telemetry();
this.state = new Property();
this.blink = new Command();
this.turnOff = new Command();
this.turnOn = new Command();
this.runDiagnostics = new Command();
this.name = new Property(true);
this.brightness = new Property(true);
}
};
21 changes: 21 additions & 0 deletions digital-twins/Samples/device/javascript/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"name": "azure-iot-digitaltwins-device-samples",
"version": "1.0.0-preview.1",
"description": "Samples for the azure-iot-digitaltwins-device client library",
"repository": {
"type": "git",
"url": "git+https://github.com/azure/azure-iot-sdk-node-digitaltwins.git"
},
"author": "Microsoft Corp.",
"license": "MIT",
"bugs": {
"url": "https://github.com/azure/azure-iot-sdk-node-digitaltwins/issues"
},
"homepage": "https://github.com/azure/azure-iot-sdk-node-digitaltwins#readme",
"dependencies": {
"azure-iot-device": "1.12.0-preview.1",
"azure-iot-common": "1.12.0-preview.1",
"azure-iot-device-mqtt": "1.12.0-preview.1",
"azure-iot-digitaltwins-device": "1.0.0-preview.1"
}
}
38 changes: 38 additions & 0 deletions digital-twins/Samples/device/javascript/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# Azure IoT Digital Twins: Environmental Sensor Example

This sample shows how to implement a simulated environmental sensor using javascript and the `DigitalTwinClient` class.

## Prerequisite

You should have [Node.js](https://nodejs.org/en/) installed.

## How to install the sample

1. Download the files in this folder
2. Install the dependencies by opening a terminal that contains the sample you downloaded and the `package.json` file and type:

```shell
npm install
```

3. Set the following environment variables:

```shell
set DEVICE_CONNECTION_STRING=<your device connection string>
```
*use `export` instead of `set` if you're running MacOS or Linux.*

4. Run the sample with the following command:

```shell
node sample_device.js
```

## What does this sample do?

`environmentalinterface.js` shows how to create an interface instance based on the Environmental Sensor interface published in the public model repository.

`sample_device.js` shows how to:
- instantiate the `DigitalTwinClient` class
- instantiate the interface instance class created with `environmentalinterface.js`
- Combine them together to send telemetry, handle commands, and handle property updates.
Loading

0 comments on commit 4893da3

Please sign in to comment.