Astarte NodeJS Device SDK
NodeJS Device SDK for Astarte IOT Platform. Create Astarte Devices and Simulators with NodeJS 14+. It integrates with MQTT.js & async-mqtt to ensure a smooth developer experience and to hide complex details regarding MQTT interactions.
Installation
Install with NPM
npm i astarte-device-sdk
Usage
Register Device
import { Pairing } from 'astarte-device-sdk'
/* Global Constants */
const astartePairingUrl = ""
const astartePairingToken = ""
const astarteRealm = ""
/* Initialize Pairing SDK */
const pairing = new Pairing({
pairingUrl: astartePairingUrl,
pairingToken: astartePairingToken,
realm: astarteRealm
})
/* Register Device */
pairing.register({ hardwareId: "<uuid5 encoded device_id>" }).then((credentialSecret) => {
/* Store this credentialSecret somewhere as this will be used later for
interacting with the device */
})
Once the device is registered and you saved the credentialSecret, the job of Pairing helper is all done, from here onwards you will be using Device SDK for all device related operations.
Un-Register Device
pairing.unregister(hardwareId)
Initialize Device
import Device from 'astarte-device-sdk`
const device = new Device({
pairingUrl: astartePairingUrl,
pairingToken: astartePairingToken,
realm: astarteRealm,
hardwareId: "<uuid5 encoded device_id>", /* Used during registration */
credentialSecret: deviceCredentialSecret, /* Got & Saved during registration */
dir: "<path_to_local_file_directory>" /* This directory will be used by SDK to save device certificates */
})
Adding/Removing Interfaces in Device Introspection
device.addInterface({ /* Astarte Interface Definition */ })
device.removeInterface(interfaceName)
Device Connection
device.connect()
.then(() => /* Device Connected with Astarte Broker */)
.catch((err) => /* Device Connection Error */ )
Publishing Data
- Device SDK expose two seperate methods to publish device data.
-
sendIndividual
: Used to publish data for interfaces that hasaggregation = individual
-
sendAggregate
: Used to publish data for interfaces that hasaggregation = object
-
sendIndividual ( interfaceName, path, value: number | string, timestamp?: Date): Promise
device.sendIndividual('com.astarte.interface.Status', '/status/astarte/endpoint', 2.22, new Date());
sendAggregate ( interfaceName, path, value: Object, timestamp?: Date): Promise
device.sendAggregate('com.astarte.interface.Status', '/status/astarte/endpoint', { name: "", age: "", city: "" }, new Date());
Note: Timestamp is Optional
Subscribing Interfaces
- In order to recieve data of a particular interface (Note: only the one's with
ownership=server
) you need to subscribe the device to that respective interface MQTT topic.
device.subscribe(interfaceName)
Receiving Data
device.on('message', (topic, payload) => {
console.log(topic) /* MQTT Topic on which data is received */
console.log(payload) /* Javascript Object of the data received */
})
Device SDK exposes following events which can be subscribed using device.on(eventName, callback)
method. (Just like we did while receiving data)
'connect'
Event function (connack) {}
Emitted on successful (re)connection (i.e. connack rc=0).
-
connack
received connack packet. Whenclean
connection option isfalse
and server has a previous session forclientId
connection option, thenconnack.sessionPresent
flag istrue
. When that is the case, you may rely on stored session and prefer not to send subscribe commands for the client.
'reconnect'
Event function () {}
Emitted when a reconnect starts.
'close'
Event function () {}
Emitted after a disconnection.
'disconnect'
Event function (packet) {}
Emitted after receiving disconnect packet from broker. MQTT 5.0 feature.
'offline'
Event function () {}
Emitted when the client goes offline.
'error'
Event function (error) {}
Emitted when the client cannot connect (i.e. connack rc != 0) or when a parsing error occurs.
The following TLS errors will be emitted as an error
event:
ECONNREFUSED
ECONNRESET
EADDRINUSE
ENOTFOUND
'end'
Event function () {}
Emitted when mqtt.Client#end()
is called.
If a callback was passed to mqtt.Client#end()
, this event is emitted once the
callback returns.
'message'
Event function (topic, message, packet) {}
Emitted when the client receives a publish packet
-
topic
topic of the received packet -
message
payload of the received packet -
packet
received packet, as defined in mqtt-packet
'packetsend'
Event function (packet) {}
Emitted when the client sends any packet. This includes .published() packets as well as packets used by MQTT for managing subscriptions and connections
-
packet
received packet, as defined in mqtt-packet
'packetreceive'
Event function (packet) {}
Emitted when the client receives any packet. This includes packets from subscribed topics as well as packets used by MQTT for managing subscriptions and connections
-
packet
received packet, as defined in mqtt-packet
Logging
- While initializing the SDK you can pass
LOG_LEVEL = debug
to get more logging information, By default theLOG_LEVEL
isinfo
.
const pairing = new Pairing({ ...pairingOptions, LOG_LEVEL: 'debug' })
const device = new Device({ ...deviceOptions, LOG_LEVEL: 'debug' })