JavaScript/TypeScript library for connecting to the Arduino IoT Cloud MQTT broker with support for both browser and Node.js applications.
Property sending and listening capabilities for IoT device communication. Handle bidirectional property updates with Arduino IoT Cloud devices and things.
Send property values to Arduino IoT Cloud for either multi-property or single-property clients.
/**
* Send a property value to a specific thing
* @param thingId - The ID of the thing to send the property to
* @param name - The property name
* @param value - The property value (string, number, boolean, or object)
* @param tmp - Optional timestamp (defaults to current time)
* @throws Error if thingId, name invalid, or connection issues
*/
sendProperty<T extends CloudMessageValue>(
thingId: string,
name: string,
value: T,
tmp?: number
): Promise<void>;Usage Examples:
import { ArduinoIoTCloud } from "arduino-iot-js";
const client = await ArduinoIoTCloud.connect({
clientId: "your-client-id",
clientSecret: "your-client-secret"
});
// Send simple values
await client.sendProperty("thing-123", "temperature", 25.5);
await client.sendProperty("thing-123", "humidity", 60);
await client.sendProperty("thing-123", "status", "active");
await client.sendProperty("thing-123", "enabled", true);
// Send object values
await client.sendProperty("thing-123", "sensor_data", {
temperature: 25.5,
humidity: 60,
pressure: 1013.25
});
// Send with custom timestamp
const customTime = Date.now() - 60000; // 1 minute ago
await client.sendProperty("thing-123", "temperature", 24.8, customTime);/**
* Send a property value from this device
* @param name - The property name
* @param value - The property value (string, number, boolean, or object)
* @param tmp - Optional timestamp (defaults to current time)
* @throws Error if name invalid, no thing associated, or connection issues
*/
sendProperty<T extends CloudMessageValue>(
name: string,
value: T,
tmp?: number
): Promise<void>;Usage Examples:
import { ArduinoIoTCloud } from "arduino-iot-js";
const client = await ArduinoIoTCloud.connect({
deviceId: "your-device-id",
secretKey: "your-secret-key"
});
// Send device property values
await client.sendProperty("temperature", 25.5);
await client.sendProperty("led_status", false);
await client.sendProperty("message", "Hello from device!");
// Send complex data
await client.sendProperty("readings", {
voltage: 3.3,
current: 0.5,
power: 1.65
});Listen to property value changes with callback functions.
/**
* Listen to property value changes from a specific thing
* @param thingId - The ID of the thing to listen to
* @param name - The property name to listen for
* @param cb - Callback function called when property value changes
* @throws Error if invalid property name or callback
*/
onPropertyValue<T extends CloudMessageValue>(
thingId: string,
name: string,
cb: OnMessageCallback<T>
): void;Usage Examples:
import { ArduinoIoTCloud } from "arduino-iot-js";
const client = await ArduinoIoTCloud.connect({
clientId: "your-client-id",
clientSecret: "your-client-secret"
});
// Listen to simple property changes
client.onPropertyValue("thing-123", "temperature", (value: number) => {
console.log(`Temperature updated: ${value}°C`);
});
client.onPropertyValue("thing-123", "status", (value: string) => {
console.log(`Status changed to: ${value}`);
});
client.onPropertyValue("thing-123", "enabled", (value: boolean) => {
console.log(`Device ${value ? 'enabled' : 'disabled'}`);
});
// Listen to object property changes
client.onPropertyValue("thing-123", "sensor_data", (value: object) => {
console.log("Sensor data updated:", value);
// Handle complex object data
if (typeof value === 'object' && value !== null) {
const data = value as any;
if (data.temperature) {
console.log(`New temperature: ${data.temperature}`);
}
}
});/**
* Listen to property value changes for this device
* @param name - The property name to listen for
* @param cb - Callback function called when property value changes
* @throws Error if invalid property name or callback
*/
onPropertyValue<T extends CloudMessageValue>(
name: string,
cb: OnMessageCallback<T>
): void;Usage Examples:
import { ArduinoIoTCloud } from "arduino-iot-js";
const client = await ArduinoIoTCloud.connect({
deviceId: "your-device-id",
secretKey: "your-secret-key"
});
// Listen to device property changes
client.onPropertyValue("led_control", (value: boolean) => {
console.log(`LED control: ${value ? 'ON' : 'OFF'}`);
// Control physical LED based on value
});
client.onPropertyValue("target_temperature", (value: number) => {
console.log(`Target temperature set to: ${value}°C`);
// Adjust heating/cooling system
});
client.onPropertyValue("configuration", (value: object) => {
console.log("Configuration updated:", value);
// Apply new device configuration
});For single property clients (device credentials), manage the associated thing.
/**
* Get the thing ID associated with this device
* @returns Promise resolving to the thing ID
* @throws Error if no thing is associated or timeout after 10 seconds
*/
getThing(): Promise<string>;Usage Examples:
import { ArduinoIoTCloud } from "arduino-iot-js";
const client = await ArduinoIoTCloud.connect({
deviceId: "your-device-id",
secretKey: "your-secret-key"
});
try {
const thingId = await client.getThing();
console.log(`Device is associated with thing: ${thingId}`);
// Now you can use the thing ID for other operations
// Note: Single property clients typically don't need the thing ID directly
// as property operations are automatically scoped to this device's thing
} catch (error) {
console.error("No thing associated with device:", error.message);
}Valid types for IoT property values.
type CloudMessageValue = string | number | boolean | object;type OnMessageCallback<T extends CloudMessageValue> = (message: T) => void;Additional interface for clients that use JWT token authentication, providing token management capabilities.
interface ITokenCloudClient {
/** Get the current JWT token */
getToken(): string;
/** Update the JWT token and reconnect with new token */
updateToken(newToken: string): Promise<void>;
}Usage Examples:
import { ArduinoIoTCloud } from "arduino-iot-js";
// For clients that support token operations (API and Browser connections)
const client = await ArduinoIoTCloud.connect({
token: "your-initial-jwt-token"
}) as ITokenCloudClient & IMultiPropertiesCloudClient;
// Get current token
const currentToken = client.getToken();
console.log("Current token:", currentToken);
// Update token when it expires
const newToken = await getRefreshedToken(); // Your token refresh logic
await client.updateToken(newToken);
// Continue using client with new token
await client.sendProperty("thing-123", "status", "reconnected");Common error scenarios and how to handle them:
import { ArduinoIoTCloud } from "arduino-iot-js";
const client = await ArduinoIoTCloud.connect({
clientId: "your-client-id",
clientSecret: "your-client-secret"
});
// Handle property send errors
try {
await client.sendProperty("thing-123", "temperature", 25.5);
} catch (error) {
if (error.message.includes("timestamp must be Integer")) {
console.error("Invalid timestamp provided");
} else if (error.message.includes("name must be a valid string")) {
console.error("Invalid property name");
} else {
console.error("Property send failed:", error.message);
}
}
// Handle invalid property listeners
try {
client.onPropertyValue("thing-123", "", (value) => {
// This will throw an error due to empty property name
});
} catch (error) {
console.error("Invalid property listener:", error.message);
}import { ArduinoIoTCloud } from "arduino-iot-js";
const client = await ArduinoIoTCloud.connect({
token: "your-jwt-token"
});
// Listen to multiple properties from the same thing
const thingId = "thing-123";
const properties = ["temperature", "humidity", "pressure"];
properties.forEach(property => {
client.onPropertyValue(thingId, property, (value) => {
console.log(`${property} updated: ${value}`);
// Store in database, trigger alerts, etc.
handlePropertyUpdate(property, value);
});
});
function handlePropertyUpdate(property: string, value: any) {
// Custom handling logic
switch (property) {
case "temperature":
if (value > 30) {
console.warn("High temperature alert!");
}
break;
case "humidity":
if (value < 20) {
console.warn("Low humidity alert!");
}
break;
}
}import { ArduinoIoTCloud } from "arduino-iot-js";
const client = await ArduinoIoTCloud.connect({
deviceId: "your-device-id",
secretKey: "your-secret-key"
});
// Send sensor readings periodically
setInterval(async () => {
const temperature = readTemperatureSensor(); // Your sensor reading function
const humidity = readHumiditySensor(); // Your sensor reading function
await client.sendProperty("temperature", temperature);
await client.sendProperty("humidity", humidity);
}, 5000);
// Listen for control commands
client.onPropertyValue("led_control", (enabled: boolean) => {
controlLED(enabled); // Your LED control function
// Send acknowledgment back
client.sendProperty("led_status", enabled);
});
client.onPropertyValue("fan_speed", (speed: number) => {
setFanSpeed(speed); // Your fan control function
// Send confirmation
client.sendProperty("current_fan_speed", speed);
});
// Mock hardware functions (replace with actual hardware control)
function readTemperatureSensor(): number { return 25.5; }
function readHumiditySensor(): number { return 60; }
function controlLED(enabled: boolean): void { /* control LED */ }
function setFanSpeed(speed: number): void { /* control fan */ }Install with Tessl CLI
npx tessl i tessl/npm-arduino-iot-js