Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Samples in TypeScript #1039

Merged
merged 16 commits into from
Sep 29, 2021
2 changes: 1 addition & 1 deletion .devcontainer/devcontainer.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
// "forwardPorts": [],

// Use 'postCreateCommand' to run commands after the container is created.
"postCreateCommand": "npm run postinstall",
"postCreateCommand": "npm run codespaceinstall",

// Comment out connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root.
"remoteUser": "node"
Expand Down
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,8 @@ digitaltwins/samples/service/typescript/dist
digitaltwins/service/dist
digitaltwins/model_repository/dist

device/samples/typescript/dist

# Build artifacts
build/build_parallel/temp

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,4 @@
"lint": "jshint --show-non-errors .",
"ci": "npm run lint"
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,4 @@
"npmlockrefresh": "npm i --package-lock-only",
"lint": "jshint --show-non-errors ."
}
}
}
File renamed without changes.
5 changes: 5 additions & 0 deletions device/samples/javascript/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Javascript Samples for the Azure IoT device SDK for Node.js

This folder contains simple samples showing how to use the various features of the Microsoft Azure IoT Hub service from a device written using JavaScript.

For instructions on running the JavaScript samples, see the [readme.md](../../samples) in the root samples folder.
174 changes: 86 additions & 88 deletions device/samples/readme.md
Original file line number Diff line number Diff line change
@@ -1,28 +1,28 @@
# Samples for the Azure IoT device SDK for Node.js

This folder contains simple samples showing how to use the various features of the Microsoft Azure IoT Hub service from a device running JavaScript code.
## Run samples using GitHub codespaces

## Read this if you want to run sample using GitHub codespace (fastest)
You can use Github Codespaces to be up and running quickly! Here are the steps to follow.

**1) Make sure you have the prerequisites**

In order to run the device samples you will first need the following prerequisites:
* An Azure IoT Hub instance. [Link if you don't.](https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-create-through-portal)
* A device identity for your device. [Link if you don't.](https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-create-through-portal#register-a-new-device-in-the-iot-hub)

- An Azure IoT Hub instance. [(Link if you don't.)][https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-create-through-portal]
- A device identity for your device. [(Link if you don't.)][https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-create-through-portal#register-a-new-device-in-the-iot-hub]

**2) Create and open Codespace**

* Select the Codespaces tab and the "New codespace" button
- Select the Codespaces tab and the "New codespace" button

![screen shot of create codespace](./media/github-codespace.png)

* Once the Codespace is open, all required packages to run the samples will be setup for you
- Once the Codespace is open, all required packages to run the samples will be setup for you

**3) Set the DEVICE_CONNECTION_STRING environment variable**

* From the command command prompt, navigate to the folder where you placed the sample files.
* Set the `DEVICE_CONNECTION_STRING` environment variable:
- From a shell or Node.js command prompt, navigate to the folder where you placed the sample files.
- Set the `DEVICE_CONNECTION_STRING` environment variable:

```bash
export DEVICE_CONNECTION_STRING="<YourIoTHubConnectionString>"
Expand All @@ -32,130 +32,128 @@ export DEVICE_CONNECTION_STRING="<YourIoTHubConnectionString>"

Run the sample application using the following commands:

_for JavaScript_

```bash
cd device/samples/javascript
node simple_sample_device.js
```

_for TypeScript_

```bash
cd device/samples/typescript/dist
node simple_sample_device.js
```

## Read this if you want to run a sample locally
*How to run a sample in your own folder using published npm packages.*
## Run samples locally

_How to run a sample in your own folder using published npm packages._

**1) Make sure you have the prerequisites**

In order to run the device samples you will first need the following prerequisites:
* The latest or LTS version of Node.js on your device. (Check out [Nodejs.org](https://nodejs.org/) for more info)
* An Azure IoT Hub instance. [(Link if you don't.)][lnk-setup-iot-hub]
* A device identity for your device. [(Link if you don't.)][lnk-manage-iot-hub]

**2) Grab the right files**
- The latest or LTS version of Node.js on your device. (Check out [Nodejs.org](https://nodejs.org/) for more info)
- An Azure IoT Hub instance. [(Link if you don't.)][https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-create-through-portal]
- A device identity for your device. [(Link if you don't.)][https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-create-through-portal#register-a-new-device-in-the-iot-hub]
- Clone this repo to your local machine

Once you have the prerequisites, get the following files from the current folder:
* **package.json**
* **__sample_file.js__** (where **__sample_file.js__** is one of the files listed above and available in this folder)
**2) Install dependencies**

You need to install proper dependencies as defined in the **package.json**. Run the following commands:

_for JavaScript_

Copy them into your directory of choice. Once they've been placed in that directory, navigate using a terminal window to the folder. Then execute the following command:
```
cd device/samples/javascript
npm install
```

This should install the proper dependencies as specified in the **package.json** you copied.
_for TypeScript_

```
cd device/samples/typescript
npm install
```

**3) Set the DEVICE_CONNECTION_STRING environment variable**

* From a shell or Node.js command prompt, navigate to the folder where you placed the sample files.
* Set the `DEVICE_CONNECTION_STRING` environment variable:
- From a shell or Node.js command prompt, navigate to the folder where you placed the sample files.
- Set the `DEVICE_CONNECTION_STRING` environment variable:

_in bash_

*in bash*
```bash
export DEVICE_CONNECTION_STRING="<YourIoTHubConnectionString>"
```
*in powershell*

_in powershell_

```powershell
$env:DEVICE_CONNECTION_STRING="<YourIoTHubConnectionString>"
```

**4) Build it**

**4) Run it**
For the TypeScript samples, we need to run the `build` command to transpile the TypeScript code into the JavaScript files:

```
npm run build
```

The JavaScript files are placed into the `dist` folder.

**5) Run it**

Run the sample application using the following commands:

JavaScript

```bash
npm install
node sample_file.js
node sample_sample_device.js
```

## Read this if you want to run a sample in VS Code

**1) Do steps 1 and 2 above**

**2) Open Visual Studio Code**

Open the folder containing your Node.js project in Visual Studio Code.

**3) Set up the Debug Configuration**

* Click on the *Debug* tab. (also `ctrl-shift-D`)
* Find the little gear and click on it (When hovered over it says "Open launch.json")
* Add the following launch configuration:

```json
{
"type": "node",
"request": "launch",
"name": "IoT Hub Sample Device",
"program": "${workspaceFolder}/device/samples/simple_sample_device.js",
"protocol": "inspector",
"sourceMaps": true,
"console": "integratedTerminal",
"env": {
"DEBUG": "mqtt*,rhea*,azure*",
"NODE_ENV": "development",
"DEVICE_CONNECTION_STRING": "<YourConnectionString>"
},
"outFiles": [
"${workspaceFolder}/common/core/lib/*.js",
"${workspaceFolder}/common/transport/amqp/lib/*.js",
"${workspaceFolder}/common/transport/http/lib/*.js",
"${workspaceFolder}/common/transport/mqtt/lib/*.js",
"${workspaceFolder}/device/core/lib/*.js",
"${workspaceFolder}/device/transport/amqp/lib/*.js",
"${workspaceFolder}/device/transport/http/lib/*.js",
"${workspaceFolder}/device/transport/mqtt/lib/*.js",
"${workspaceFolder}/dtclient/lib/*.js",
"${workspaceFolder}/service/lib/*.js",
]
}
```
* Edit the `DEVICE_CONNECTION_STRING` environment variable to use your IoT Hub device connection string.
* Edit the `program` to the path to the code you want to run.
* If you do not want debug logs to be printed, delete the `DEBUG` environment variable. Otherwise you can leave it as it is.
TypeScript

**4) Run it**
```bash
cd dist
node sample_sample_device.js
```

* In the debug tab, click on the configuration drop down and select `IoT Hub Sample Device`, then press `Start Debugging`.
## List of available samples

### **Simple send and receive messages...**

## List of samples
| Sample | Description | JavaScript | TypeScript |
| ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | :--------: | :--------: |
| simple_sample_device | Connect to IoT Hub and send and receive messages. | ✔ | ✔ |
| simple_sample_device_with_sas | Connect using a SAS Token to IoT Hub and send and receive messages. | ✔ | |
| simple_sample_device_x50 | Connect using an X-509 certificate to IoT Hub and send and receive messages. | ✔ | |
| send_batch_http | Connect to IoT Hub and send a batch of messages over an HTTP connection. | ✔ | ✔ |
| remote_monitoring | Implements the device code used to connect to an [Azure IoT Suite Remote Monitoring preconfigured solution][remote-monitoring-pcs]. | ✔ | ✔ |
| edge_downstream_device | Connect a downstream device to IoT Edge and send and receive messages. | ✔ | |

* Simple send and receive messages:
* **simple_sample_device.js**: Connect to IoT Hub and send and receive messages.
* **simple_sample_device_with_sas.js**: Connect using a SAS Token to IoT Hub and send and receive messages.
* **simple_sample_device_x509.js**: Connect using an X-509 certificate to IoT Hub and send and receive messages.
* **send_batch_http.js**: Connect to IoT Hub and send a batch of messages over an HTTP connection.
* **remote_monitoring**: Implements the device code used to connect to an [Azure IoT Suite Remote Monitoring preconfigured solution][remote-monitoring-pcs].
* **edge_downstream_device.js**: Connect a downstream device to IoT Edge and send and receive messages.
### **Device services samples (Device Twins, Methods, and Device Management)...**

* Device services samples (Device Twins, Methods, and Device Management):
* **simple_sample_device_twin.js**: Shows how to synchronize a Device Twin with Azure IoT Hub on a device.
* **device_method.js**: Shows how to implement an Azure IoT Hub Cloud to Device Direct Method on a device.
* **dmpatterns_reboot_device.js**: Shows how a device handles a C2D method to reboot and provides progress updates through twin reported properties. See [device management patterns][dm-patterns] for instructions on running the device management patterns samples.
* **dmpatterns_fwupdate_device.js**: Shows how a device handles a C2D method to initiate a firmware update and provides progress updates through twin reported properties. See [device management patterns][dm-patterns] for instructions on running the device management patterns samples.
| Sample | Description | JavaScript | TypeScript |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------: | :--------: |
| simple_sample_device_twin | Shows how to synchronize a Device Twin with Azure IoT Hub on a device. | ✔ | ✔ |
| device_method | Shows how to implement an Azure IoT Hub Cloud to Device Direct Method on a device. | ✔ | ✔ |
| dmpatterns_reboot_device | Shows how a device handles a C2D method to reboot and provides progress updates through twin reported properties. See [device management patterns][dm-patterns] for instructions on running the device management patterns samples. | ✔ | |
| dmpatterns_fwupdate_device | Shows how a device handles a C2D method to initiate a firmware update and provides progress updates through twin reported properties. See [device management patterns][dm-patterns] for instructions on running the device management patterns samples. | ✔ | |

* Uploading blob to Azure:
* **device_blob_upload.js**: Uploads a blob to Azure through IoT Hub
### **Uploading blob to Azure...**

| Sample | Description | JavaScript | TypeScript |
| ----------------------- | --------------------------------------------------------------------- | :--------: | :--------: |
| upload_to_blob | Uploads a blob to Azure through IoT Hub | ✔ | ✔ |
| upload_to_blob_advanced | More advanced scenario for greater control over the blob upload calls | ✔ | ✔ |

## Read More

For more information on how to use this library refer to the documents below:

- [Prepare your node.js development environment][node-devbox-setup]
- [Setup IoT Hub][lnk-setup-iot-hub]
- [Provision devices][lnk-manage-iot-hub]
Expand Down
75 changes: 75 additions & 0 deletions device/samples/typescript/device_methods.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

import { Client } from 'azure-iot-device';
import { Mqtt as Protocol } from 'azure-iot-device-mqtt';

let client: Client = null;

function main(): void {
// open a connection to the device
const deviceConnectionString = process.env.DEVICE_CONNECTION_STRING || '';

if (deviceConnectionString === '') {
console.log('device connection string has not been set');
process.exit(-1);
}

client = Client.fromConnectionString(deviceConnectionString, Protocol);
client.open(onConnect);
}

function onConnect(err: Error): void {
if (!!err) {
console.error('Could not connect: ' + err.message);
} else {
console.log('Connected to device. Registering handlers for methods.');

// register handlers for all the method names we are interested in
client.onDeviceMethod('getDeviceLog', onGetDeviceLog);
client.onDeviceMethod('lockDoor', onLockDoor);
}
}

function onGetDeviceLog(request: any, response: any): void {
printDeviceMethodRequest(request);

// Implement actual logic here.

// complete the response
response.send(200, 'example payload', function (err: Error): void {
if (!!err) {
console.error('An error ocurred when sending a method response:\n' + err.toString());
} else {
console.log('Response to method "%s" sent successfully.', request.methodName);
}
});
}

function onLockDoor(request: any, response: any): void {
printDeviceMethodRequest(request);

// Implement actual logic here.

// complete the response
response.send(200, function (err: Error): void {
if (!!err) {
console.error('An error ocurred when sending a method response:\n' + err.toString());
} else {
console.log('Response to method "%s" sent successfully.', request.methodName);
}
});
}

function printDeviceMethodRequest(request: any): void {
// print method name
console.log('Received method call for method "%s"', request.methodName);

// if there's a payload just do a default console log on it
if (!!request.payload) {
console.log('Payload:\n' + request.payload);
}
}

// get the app rolling
main();