> ## Documentation Index
> Fetch the complete documentation index at: https://docs.heylua.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# DeviceClient API

> Complete API reference for the @lua-ai-global/device-client package

## DeviceClient

The main class for connecting a device to a Lua AI agent. Extends `EventEmitter`.

```typescript theme={null}
import { DeviceClient } from '@lua-ai-global/device-client';

const client = new DeviceClient(config: DeviceClientConfig);
```

### Constructor

<ParamField body="config" type="DeviceClientConfig" required>
  Configuration object for the device client. See [DeviceClientConfig](#deviceclientconfig) below.
</ParamField>

## DeviceClientConfig

<ParamField body="agentId" type="string" required>
  Agent ID to connect to.
</ParamField>

<ParamField body="apiKey" type="string" required>
  API key for authentication.
</ParamField>

<ParamField body="deviceName" type="string" required>
  Unique name for this device. Lowercase with hyphens.
</ParamField>

<ParamField body="commands" type="DeviceCommandDefinition[]">
  Commands this device supports. Sent to the server at connect time.
</ParamField>

<ParamField body="transport" type="'socketio' | 'mqtt'" default="socketio">
  Transport protocol.
</ParamField>

<ParamField body="serverUrl" type="string" default="https://api.heylua.ai">
  Server URL for Socket.IO transport.
</ParamField>

<ParamField body="mqttUrl" type="string" default="mqtts://mqtt.heylua.ai:8883">
  MQTT broker URL. Required when `transport` is `'mqtt'`.
</ParamField>

<ParamField body="cdnUrl" type="string" default="https://cdn.heylua.ai">
  CDN URL for file uploads and downloads.
</ParamField>

<ParamField body="group" type="string">
  Optional device group name.
</ParamField>

## Methods

### connect()

Connect to the device gateway. Resolves when the connection is established and authenticated. Automatically reconnects on disconnect unless `disconnect()` was called.

```typescript theme={null}
await client.connect(): Promise<void>
```

### disconnect()

Disconnect from the device gateway. Stops auto-reconnection.

```typescript theme={null}
await client.disconnect(): Promise<void>
```

### isConnected()

Check if the client is currently connected.

```typescript theme={null}
client.isConnected(): boolean
```

### onCommand()

Register a handler for a specific command name. The handler receives the command payload and must return a result (or throw an error).

```typescript theme={null}
client.onCommand(name: string, handler: CommandHandler): void
```

<ParamField body="name" type="string" required>
  Command name to handle.
</ParamField>

<ParamField body="handler" type="(payload: any) => Promise<any>" required>
  Async function that executes the command. Return value is sent back to the agent. Thrown errors are sent as error responses.
</ParamField>

```typescript theme={null}
client.onCommand('read_temperature', async (payload) => {
  return { temperature: 22.5, unit: 'celsius' };
});
```

### trigger()

Fire a trigger event to the agent. Resolves when the server acknowledges receipt (not execution completion).

```typescript theme={null}
await client.trigger(name: string, payload: any): Promise<DeviceTriggerAckMessage>
```

<ParamField body="name" type="string" required>
  Trigger name.
</ParamField>

<ParamField body="payload" type="any" required>
  Trigger payload data.
</ParamField>

```typescript theme={null}
await client.trigger('temperature_alert', {
  temperature: 42.1,
  threshold: 40,
});
```

### onTriggerResult()

Listen for trigger execution results from the agent. Optional -- triggers are fire-and-forget by default.

```typescript theme={null}
client.onTriggerResult(name: string, handler: TriggerResultHandler): void
```

<ParamField body="name" type="string" required>
  Trigger name to listen for.
</ParamField>

<ParamField body="handler" type="(result: any) => void" required>
  Callback function receiving the trigger execution result.
</ParamField>

## Properties

### cdn

CDN client for uploading and downloading files. Available immediately after construction.

```typescript theme={null}
client.cdn: CDN
```

## CDN

The CDN class provides file upload and download capabilities.

### cdn.upload()

Upload a file to the Lua CDN.

```typescript theme={null}
await client.cdn.upload(
  data: Buffer | Blob,
  filename: string,
  contentType?: string
): Promise<CdnUploadResult>
```

<ParamField body="data" type="Buffer | Blob" required>
  File content.
</ParamField>

<ParamField body="filename" type="string" required>
  Filename with extension.
</ParamField>

<ParamField body="contentType" type="string">
  MIME type. Defaults to `application/octet-stream`.
</ParamField>

**Returns:** `CdnUploadResult`

```typescript theme={null}
interface CdnUploadResult {
  fileId: string;
  mediaType: string;
  extension: string;
  url: string;
}
```

### cdn.download()

Download a file from the CDN.

```typescript theme={null}
await client.cdn.download(fileId: string): Promise<Buffer>
```

### cdn.getUrl()

Get the public URL for a file.

```typescript theme={null}
client.cdn.getUrl(fileId: string): string
```

## Events

The `DeviceClient` extends `EventEmitter` and emits the following events:

| Event           | Payload                   | Description                    |
| --------------- | ------------------------- | ------------------------------ |
| `connected`     | *(none)*                  | Initial connection established |
| `reconnected`   | *(none)*                  | Reconnected after a disconnect |
| `disconnected`  | `reason: string`          | Connection lost                |
| `error`         | `error: any`              | Connection or protocol error   |
| `trigger_ack`   | `DeviceTriggerAckMessage` | Server acknowledged a trigger  |
| `trigger_error` | `error: any`              | Trigger delivery error         |

```typescript theme={null}
client.on('connected', () => console.log('Online'));
client.on('disconnected', (reason) => console.log('Offline:', reason));
client.on('error', (err) => console.error('Error:', err));
```

## DeviceCommandDefinition

Describes a command the device supports.

<ParamField body="name" type="string" required>
  Command name.
</ParamField>

<ParamField body="description" type="string" required>
  Human-readable description shown to the AI agent.
</ParamField>

<ParamField body="inputSchema" type="Record<string, any>">
  JSON Schema for input parameters.
</ParamField>

<ParamField body="timeoutMs" type="number" default="30000">
  Command timeout in milliseconds.
</ParamField>

<ParamField body="retry" type="{ maxAttempts: number; backoffMs: number }">
  Retry configuration for failed commands.
</ParamField>

## Type Exports

The package exports the following types:

```typescript theme={null}
import type {
  DeviceClientConfig,
  DeviceCommandDefinition,
  DeviceCommandMessage,
  DeviceResponseMessage,
  DeviceTriggerAckMessage,
  CommandHandler,
  TriggerResultHandler,
} from '@lua-ai-global/device-client';

import type { CdnUploadResult } from '@lua-ai-global/device-client';
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Node.js Client Guide" icon="node-js" href="/devices/node-client">
    Usage guide with examples
  </Card>

  <Card title="MicroPython Client" icon="microchip" href="/devices/micropython-client">
    API reference for the MicroPython client
  </Card>

  <Card title="Quickstart" icon="rocket" href="/devices/quickstart">
    Get started in 5 minutes
  </Card>

  <Card title="Examples" icon="layer-group" href="/devices/examples/warehouse-inventory">
    Full working examples
  </Card>
</CardGroup>
