Skip to content

Node.js SDK

Connect a device or gateway running Node.js to Espoirnet. For microcontrollers, see the Embedded C SDK.

Requires Node.js 22 or newer. Works with both ES modules and CommonJS, and includes TypeScript types.

Register a key for the device first (see Device Provisioning), then:

import { EspoirnetDevice } from '@espoirnet/device-sdk'
const device = new EspoirnetDevice({
// Paste from SDK config on the device's page
accountId: 'your-account-key',
projectId: 'your-project-key',
deviceId: 'your-device-key',
privateKeyPath: './private.pem',
brokerUrl: 'mqtts://rayon.espoirnet.io:8883',
})
// Always attach this: an unhandled 'error' event throws
device.on('error', (err) => console.error(err))
await device.connect()

The private key must be EC P-256 in PKCS#8 format (-----BEGIN PRIVATE KEY-----). Always set brokerUrl, or the ESPOIRNET_BROKER_URL environment variable, since the default isn’t the hosted platform.

const device = new EspoirnetDevice({
accountId, projectId, deviceId,
brokerUrl: 'mqtts://rayon.espoirnet.io:8883',
certificate: {
certPath: './device.crt', // followed by any intermediate CA certificates
keyPath: './device.key',
},
})

See Device Certificates for how to get one.

device.publish('tempe', 21.5) // one sensor
device.publish({ tempe: 21.5, humid: 40 }) // several in one message

For Binary and State sensors, when something changes on the device itself:

device.turnOn('relay') // a Binary sensor
device.turnOff('relay')
device.reportState('mode', 'heat') // a State sensor

See Sensor State.

device.on('command', (command, ack) => {
// command: { commandId, sensorId, value, ts }
applyToHardware(command.sensorId, command.value)
ack({ success: true, value: command.value })
})

Attaching the listener is all it takes to start receiving commands, and you can attach it before connect(). Call ack() only once you’ve actually applied the command. To report a failure, call ack({ success: false }).

A command can occasionally be delivered more than once, so make your handler safe to repeat, using commandId to spot a repeat. See Sending Commands.

publish, turnOn, turnOff and reportState return true if the data was handed off, or false if the device isn’t connected. Data sent while disconnected is dropped, not queued, so a stale reading is never delivered as if it were current. If you need readings stored during an outage, see the Embedded C SDK, or keep your own buffer.

The SDK stays connected on its own:

  • Temporary problems (a network failure, the platform briefly unavailable) are retried with a growing, randomised delay, including on the first connect().
  • Sessions are renewed shortly before they expire, with a fresh token or a new certificate login.
  • Problems that retrying can’t fix (a revoked or wrong key, an unknown device, a rejected identity) stop the SDK. It emits error and stays disconnected. Fix the cause and call connect() again.

If a login is refused, see Troubleshooting.

Event Arguments When
connected Connected, including after a reconnect
disconnected reason The connection dropped or closed
reconnecting { attempt, delay } Before each reconnect attempt
command command, ack A command arrived
error err A login, connection or sending problem

Errors are subclasses of EspoirnetError: AuthError, ConnectionError and PublishError.

Option Default Notes
accountId, projectId, deviceId required The keys from the device’s page
privateKey or privateKeyPath one login method required Token login: PEM text, or a path to it
certificate one login method required Certificate login: { cert or certPath, key or keyPath }
brokerUrl ESPOIRNET_BROKER_URL, else a local address Use mqtts://rayon.espoirnet.io:8883
ca none Extra CA to trust; only for a private broker
tokenTtl 82800 (23 h) Token lifetime in seconds; at most 24 h
sessionTtl 82800 (23 h) Certificate login: seconds between planned reconnects; at most 24 h
reconnect true Reconnect automatically
reconnectMinDelay 1000 ms Shortest delay between attempts
reconnectMaxDelay 60000 ms Longest delay between attempts
keepalive 60 s How often the connection is checked
logger none Optional { debug, info, warn, error } functions