Skip to content

Version 0.6.0 #238

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 34 commits into from
Aug 18, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
060d05c
Import node-red lib + massive refactoring
pirropirro Jun 15, 2020
dfc2b1d
Enable API Connection
pirropirro Jun 16, 2020
783cbff
Set config file
pirropirro Jun 16, 2020
f8e664f
Refactor w/ HttpClient
pirropirro Jun 16, 2020
dc0a1a1
Add encode uri
pirropirro Jun 16, 2020
9490c9a
Replace body on request
pirropirro Jun 16, 2020
ee5c876
Remove useless stringify
pirropirro Jun 16, 2020
ed691ef
Fix minor bug
pirropirro Jun 16, 2020
13c2a49
Fix typings
pirropirro Jun 16, 2020
2a9b541
Fixed test
pirropirro Jun 17, 2020
e5325f7
Fix tests
pirropirro Jun 17, 2020
b3bebc3
Bump beta version
pirropirro Jun 17, 2020
3362cf7
Rename
pirropirro Jun 17, 2020
8344fe3
Bump version
pirropirro Jun 17, 2020
df79564
Add default
pirropirro Jun 17, 2020
79fe50c
Fix minor bugs
pirropirro Jun 18, 2020
2432767
Remove default export
pirropirro Jun 18, 2020
509b194
Lint
pirropirro Jun 18, 2020
2b54033
Add lint process before build
pirropirro Jun 18, 2020
96917e0
Bump version
pirropirro Jun 18, 2020
4821372
Set useCloudProtocolV2 as true by default
pirropirro Jun 18, 2020
71ce299
Bump version
pirropirro Jun 18, 2020
1bafd8d
Run tests using GitHub actions
Jun 18, 2020
ce875a4
Update readme and add example (#234)
Jun 18, 2020
2367ab6
Add lint before run test
pirropirro Jun 18, 2020
a29c362
Merge pull request #236 from arduino/fmirabito/gh_actions
Jun 18, 2020
f4abbd9
Fix 0 values
pirropirro Jun 19, 2020
aa483f1
Bump version
pirropirro Jun 19, 2020
7a242ff
Fix typo
pirropirro Jun 19, 2020
a90d279
Bump version
pirropirro Jun 19, 2020
8075ba1
Add wildcard on example deps
pirropirro Jun 19, 2020
0c5ab14
Fix mqtt version
pirropirro Aug 14, 2020
3e213fa
Bump version
pirropirro Aug 14, 2020
29c98c3
Remove beta version
pirropirro Aug 18, 2020
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
19 changes: 0 additions & 19 deletions .babelrc

This file was deleted.

12 changes: 0 additions & 12 deletions .editorconfig

This file was deleted.

34 changes: 26 additions & 8 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,28 @@
module.exports = {
"extends": "airbnb-base",
"env": {
"browser": true,
"jest": true
},
"rules": {
"no-await-in-loop": 0
}
env: {
es6: true,
},
ignorePatterns: ['node_modules/*', 'lib/*', 'es/*'],
parser: '@typescript-eslint/parser',
extends: [
'plugin:@typescript-eslint/recommended',
'prettier/@typescript-eslint',
'plugin:prettier/recommended',
],
parserOptions: {
sourceType: 'module',
project: './tsconfig.json',
ecmaVersion: 2018,
},
rules: {
'@typescript-eslint/explicit-function-return-type': 0,
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/no-use-before-define': 'warn',
'@typescript-eslint/camelcase': 'warn',
'@typescript-eslint/no-empty-interface': 'warn',
'@typescript-eslint/no-empty-function': 'warn',
'@typescript-eslint/no-namespace': 'warn',
'prefer-rest-params': 'warn',
'no-else-return': 'error',
},
};
28 changes: 28 additions & 0 deletions .github/workflows/test.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
name: test

on:
pull_request:
push:
branches:
- master

jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Disable EOL conversions
run: git config --global core.autocrlf false

- name: Checkout
uses: actions/checkout@master

- name: Integration tests
uses: actions/setup-node@v1
with:
node-version: '12'
- run: npm install
- run: npm run lint
- run: npm run test
env:
CLIENT_ID: ${{ secrets.CLIENT_ID }}
CLIENT_SECRET: ${{ secrets.CLIENT_SECRET }}
5 changes: 5 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"printWidth": 120,
"singleQuote": true,
"trailingComma": "es5"
}
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