Skip to content

Update readme and add example #234

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

Merged
merged 11 commits into from
Jun 18, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
208 changes: 142 additions & 66 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,88 +1,164 @@

[![License: GPL v3](https://img.shields.io/badge/License-GPL%20v3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0)
[![npm version](https://badge.fury.io/js/arduino-iot-js.svg)](https://badge.fury.io/js/arduino-iot-js)

# arduino-iot-js
## Introduction
This NPM module provides interaction with the Arduino IoT Cloud MQTT broker. It can be used both from the browser and node.js

JS module providing interaction with Arduino Cloud
The main features of this module are:
- Connection/disconnection to Arduino IoT Cloud Broker using WebSocket
- Send IoT Cloud *property* updates
- Listen for IoT Cloud *property* updates made by other clients and/or devices

## Installation
If you are looking for a way to create, read, update, delete resources like
- Devices
- Things
- Properties
- Data Timeseries

```bash
$ npm install arduino-iot-js
```
please check the official [Javascript Rest API client](https://www.npmjs.com/package/@arduino/arduino-iot-client).

## How to use
```javascript
import ArduinoCloud from 'arduino-iot-js';

// connect establishes a connection with mqtt, using token as the password
// options = {
// host: 'BROKER_URL', // Default is wss.iot.arduino.cc
// port: BROKER_PORT, // Default is 8443
// ssl: true/false, // Default is true
// token: 'YOUR_BEARER_TOKEN' // Required!
// apiUrl: 'AUTH SERVER URL', // Default is https://api2.arduino.cc
// onDisconnect: message => { /* Disconnection callback */ },
// useCloudProtocolV2: true/false, // Default is false
// }
ArduinoCloud.connect(options).then(() => {
// Connected
});
If you want to learn more about Arduino IoT Cloud architecture, check the official [getting started documentation](https://www.arduino.cc/en/IoT/HomePage).

ArduinoCloud.disconnect().then(() => {
// Disconnected
});

ArduinoCloud.subscribe(topic, cb).then(topic => {
// Subscribed to topic, messaged fired in the cb
});

ArduinoCloud.unsubscribe(topic).then(topic => {
// Unsubscribed to topic
});
## Installation

ArduinoCloud.sendMessage(topic, message).then(() => {
// Message sent
});
```bash
$ npm install arduino-iot-js
```

ArduinoCloud.openCloudMonitor(deviceId, cb).then(topic => {
// Cloud monitor messages fired to cb
});
## How to use
The MQTT connection over Websocket relies on Username / Password authentication. Under the hood, this module uses your user ID (plus a timestamp) as *Username* and needs a valid JWT Token as *Password*. You can use either a valid JWT token or just your API Credentials (*clientId* and *clientSecret*).

ArduinoCloud.writeCloudMonitor(deviceId, message).then(() => {
// Message sent to cloud monitor
});
### How to import arduino-iot-js in your project
Using a web application in the browser
```javascript
import { ArduinoIoTCloud } from 'arduino-iot-js'
```
Using nodejs
```javascript
const { ArduinoIoTCloud } = require('arduino-iot-js');
```

ArduinoCloud.closeCloudMonitor(deviceId).then(topic => {
// Close cloud monitor
});
### How to connect to Arduino IoT Cloud broker using API Credentials
```javascript
const { ArduinoIoTCloud } = require('arduino-iot-js');

const options = {
clientId: "YOUR_CLIENT_ID",
clientSecret: "YOUR_CLIENT_SECRET",
onDisconnect: message => {
console.error(message);
}
}

ArduinoIoTCloud.connect(options)
.then(() => console.log("Connected to Arduino IoT Cloud broker"))
.catch(error => console.error(error));
```

// Send a property value to a device
// - value can be a string, a boolean or a number
// - timestamp is a unix timestamp, not required
ArduinoCloud.sendProperty(thingId, name, value, timestamp).then(() => {
// Property value sent
});
### How to listen for property value updates
After a successful connection, you can listen for property updates.
To do this you need:
- The ID of the *Thing* the *property* belongs to. You can list all your things and properties using the [Javascript Rest API client](https://www.npmjs.com/package/@arduino/arduino-iot-client), calling the [GET Things endpoint](https://www.arduino.cc/reference/en/iot/api/index.html#api-ThingsV2-thingsV2List)
- The *variable name* of the property you want to listen

// Register a callback on a property value change
//
ArduinoCloud.onPropertyValue(thingId, propertyName, updateCb).then(() => {
// updateCb(message) will be called every time a new value is available. Value can be string, number, or a boolean depending on the property type
});
```javascript
const { ArduinoIoTCloud } = require('arduino-iot-js');
const thingId = "THING_ID"
const variableName = "PROPERTY_NAME"

const options = {
clientId: "YOUR_CLIENT_ID",
clientSecret: "YOUR_CLIENT_SECRET",
onDisconnect: message => {
console.error(message);
}
}

ArduinoIoTCloud.connect(options)
.then(() => {
console.log("Connected to Arduino IoT Cloud broker");
return ArduinoIoTCloud.onPropertyValue(thingId, variableName, showUpdates = value => console.log(value));
})
.then(() => console.log("Callback registered"))
.catch(error => console.log(error));
```
Each time a new value is sent from the Device, the `counterUpdates` callback will be called.

// Re-connect with a new authentication token, keeping the subscriptions
// to the Things topics
ArduinoCloud.updateToken(newToken).then(() => {
// Successful reconnection with the provided new token
### How to disconnect from Arduino IoT Cloud Broker
```javascript
ArduinoCloud.disconnect()
.then(() => console.log("Successfully disconnected"));
```
### How to send property values to the device
To do this you need:
- The ID of the *Thing* the *property* belongs to. You can list all your things and properties using the [Javascript Rest API client](https://www.npmjs.com/package/@arduino/arduino-iot-client), calling the [GET Things endpoint](https://www.arduino.cc/reference/en/iot/api/index.html#api-ThingsV2-thingsV2List)
- The *variable name* of the property you want to set
- Value can be either a string, a boolean or a number
```javascript
const { ArduinoIoTCloud } = require('arduino-iot-js');
const thingId = "THING_ID"
const variableName = "PROPERTY_NAME"

const options = {
clientId: "YOUR_CLIENT_ID",
clientSecret: "YOUR_CLIENT_SECRET",
onDisconnect: message => {
console.error(message);
}
}

ArduinoIoTCloud.connect(options).then(() => {
console.log("Connected to Arduino IoT Cloud broker");
ArduinoCloud.sendProperty(thingId, variableName, value).then(() => {
console.log("Property value correctly sent");
});
});

```

## Run tests
First of all you need a valid Hydra Arduino token, you can get it from [Arduino Create IoT Cloud](https://create.arduino.cc/cloud/)

Then you can use this token to run tests

```bash
$ TOKEN=YOUR_HYDRA_TOKEN_HERE npm run test
### How to listen to every user properties updates
```javascript
const { ArduinoIoTCloud } = require('arduino-iot-js');
const ArduinoIoTApi = require('@arduino/arduino-iot-client');

const options = {
clientId: "YOUR_CLIENT_ID",
clientSecret: "YOUR_CLIENT_SECRET",
onDisconnect: message => {
console.error(message);
}
}

// Connect to Arduino IoT Cloud MQTT Broker
ArduinoIoTCloud.connect(options)
.then(() => {
console.log("Connected to Arduino IoT Cloud MQTT broker");

// Init Arduino API Client
const ArduinoIoTClient = ArduinoIoTApi.ApiClient.instance;
ArduinoIoTClient.authentications['oauth2'].accessToken = ArduinoIoTCloud.getToken();

const thingsApi = new ArduinoIoTAPI.ThingsV2Api(ArduinoIoTClient);
const propertiesAPI = new ArduinoIoTApi.PropertiesV2Api(ArduinoIoTClient);

return thingsApi.thingsV2List()
.then(things => {
things.forEach(thing => {
propertiesAPI.propertiesV2List(thing.id)
.then(properties => {
properties.forEach(property => {
ArduinoIoTCloud.onPropertyValue(thing.id, property.variable_name,
showUpdates = value => console.log(property.variable_name + ": " + value))
.then(() => console.log("Callback registered for " + property.variable_name))
.catch(error => console.error(error));
});
})
.catch(error => console.error(error));
});
});
})
.catch(error => console.error(error));
```
41 changes: 41 additions & 0 deletions examples/listenProperties/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
const { ArduinoIoTCloud } = require('arduino-iot-js');
const ArduinoIoTAPI = require('@arduino/arduino-iot-client');

options = {
clientId: "YOUR_CLIENT_ID",
clientSecret: "YOUR_CLIENT_SECRET",
onDisconnect: message => {
console.error(message);
}
}

// Connect to Arduino IoT Cloud MQTT Broker
ArduinoIoTCloud.connect(options)
.then(() => {
console.log("Connected to Arduino IoT Cloud MQTT broker");

// Init Arduino API Client
const ArduinoIoTClient = ArduinoIoTAPI.ApiClient.instance;
ArduinoIoTClient.authentications['oauth2'].accessToken = ArduinoIoTCloud.getToken();

const thingsAPI = new ArduinoIoTAPI.ThingsV2Api(ArduinoIoTClient);
const propertiesAPI = new ArduinoIoTAPI.PropertiesV2Api(ArduinoIoTClient);

thingsAPI.thingsV2List()
.then(things => {
things.forEach(thing => {
propertiesAPI.propertiesV2List(thing.id)
.then(properties => {
properties.forEach(property => {
ArduinoIoTCloud.onPropertyValue(thing.id, property.variable_name,
showUpdates = update = value => console.log(property.variable_name+": "+value))
.then(() => console.log("Callback registered for "+property.variable_name))
.catch(error => console.error(error));
});
})
.catch(error => console.error(error));
});
})
.catch(error => console.error(error));
})
.catch(error => console.error(error));
Loading