# ESP Rainmaker Matter TypeScript SDK

The `@espressif/rainmaker-matter-sdk` package provides a comprehensive SDK for integrating Matter protocol support with the ESP Rainmaker ecosystem. It enables seamless Matter device commissioning, fabric management, and certificate handling for mobile app developers.

## Table of Contents

- [Overview](#overview)
- [Key Features](#key-features)
- [Integration with Base SDK](#integration-with-base-sdk)
- [Requirements](#requirements)
- [Installation](#installation)
  - [Package Manager](#package-manager)
  - [Local Installation](#local-installation)
- [Usage](#usage)
  - [Basic Configuration](#basic-configuration)
  - [Creating Matter Fabrics](#creating-matter-fabrics)
  - [Starting Matter Device Commissioning](#starting-matter-device-commissioning)
  - [Adding Matter Nodes (Manual Flow)](#adding-matter-nodes-manual-flow)
  - [Managing User Certificates](#managing-user-certificates)
  - [Advanced Fabric Management](#advanced-fabric-management)
  - [Converting Groups to Fabrics](#converting-groups-to-fabrics)
  - [Matter Local Control](#matter-local-control)
  - [Matter Attribute Subscriptions](#matter-attribute-subscriptions)
  - [Matter Local Discovery Events](#matter-local-discovery-events)
- [Adapter Reference](#adapter-reference)
- [Resources](#resources)
- [License](#license)

## Overview

The `@espressif/rainmaker-matter-sdk` package extends the ESP Rainmaker ecosystem with full Matter protocol support. It provides a unified API for Matter fabric management, device commissioning, and certificate handling, enabling developers to build applications that seamlessly integrate both ESP Rainmaker cloud services and local Matter mesh networks.

The SDK provides:

- **Matter Fabric Management:** Create and manage Matter fabrics with full certificate authority capabilities
- **Device Commissioning:** Support for both pure Matter devices and RainMaker-enabled Matter devices
- **Certificate Management:** Issue and manage Node Operational Certificates (NoCs) and user certificates
- **Local Matter Control:** Read and write cluster attributes via a platform `matterControlAdapter`
- **Real-Time Subscriptions:** Stream Matter attribute updates through the base SDK subscription manager
- **Cross-Platform Compatibility:** Works with React Native and other cross-platform frameworks

## Key Features

- [x] **Matter Fabric Creation:** Create and configure Matter fabrics with automatic certificate generation
- [x] **Certificate Management:** Issue NoCs for devices and user certificates for fabric access
- [x] **Challenge-Response Authentication:** Secure device authentication using cryptographic challenges
- [x] **Local Matter Control:** `getValue` / `setValue` on `ESPRMMatterDeviceParam` using the Matter control adapter
- [x] **Matter Attribute Subscriptions:** Low-latency local updates mapped to RainMaker parameters
- [x] **Local Discovery Events:** Subscribe to Matter operational discovery and device-lost events
- [x] **Paginated Responses:** Efficient handling of large datasets with built-in pagination support

## Integration with Base SDK

Matter local discovery uses the unified local discovery adapter from the base SDK. The base SDK's `localDiscoveryAdapter` supports discovering multiple service types concurrently, including `_matter._tcp` for Matter devices.

## Requirements

Before installing the `@espressif/rainmaker-matter-sdk` package, ensure you meet the following prerequisites:

- **Node.js**: Version 22.0.0 or higher is recommended
- **Package Manager**: Any one from npm, yarn, or pnpm installed
- **ESP Rainmaker Base SDK**: [`@espressif/rainmaker-base-sdk`](https://www.npmjs.com/package/@espressif/rainmaker-base-sdk) **^3.0.1** (required for Matter subscriptions via the base SDK subscription manager)
- **Native Matter adapters**: Platform implementations for commissioning, control, subscriptions, and optional local discovery (see [Adapter Reference](#adapter-reference))

## Installation

### Package Manager

To install the latest version of the `@espressif/rainmaker-matter-sdk` package from the npm registry, you can use your preferred package manager:

#### Using npm:

```bash
npm install @espressif/rainmaker-matter-sdk
```

#### Using Yarn:

```bash
yarn add @espressif/rainmaker-matter-sdk
```

#### Using pnpm:

```bash
pnpm add @espressif/rainmaker-matter-sdk
```

### Local Installation

To build and install the package locally for development and testing:

1. Clone the repository

2. Check out the appropriate branch:

   ```bash
   git checkout main
   ```

3. Ensure you are using Node.js v22.0.0 or higher. If you have `nvm` installed, you can run:

   ```bash
   nvm use
   ```

   If you don't have `nvm`, please install Node.js v22.0.0 or a higher version manually.

4. Install the required dependencies using your preferred package manager:

   ```bash
   npm install
   # or
   yarn install
   ```

5. Build the package:

   ```bash
   npm run build
   # or
   yarn run build
   ```

6. Create a tarball for testing locally:

   ```bash
   npm pack
   # or
   yarn pack
   ```

7. Add the tarball to your project:

   ```bash
   npm install <PATH_TO_PACK_TARBALL_FILE>
   # or
   yarn add <PATH_TO_PACK_TARBALL_FILE>
   ```

After installation, you can import and configure the SDK in your project as shown in the usage examples below.

## Usage

### Basic Configuration

Begin by configuring the base ESP Rainmaker SDK, authenticating the user, and wiring in your native Matter adapters (commissioning is required; control and subscription adapters enable local device interaction):

```javascript
import { ESPRMBase, ESPRMMatterBase } from "@espressif/rainmaker-matter-sdk";
import { matterCommissioningAdaptor } from "./adapters/ESPMatterCommissioningAdaptor";
import { matterControlAdapter } from "./adapters/ESPMatterControlAdapter";
import { matterSubscriptionAdapter } from "./adapters/ESPMatterSubscriptionAdapter";
import { matterLocalDiscoveryAdapter } from "./adapters/ESPMatterLocalDiscoveryAdapter";

// Configure the base RainMaker SDK
ESPRMBase.configure({
  baseUrl: "https://api.rainmaker.espressif.com",
  version: "v1",
});

// Wire Matter SDK adapters + vendor ID (see Adapter Reference in API docs)
ESPRMMatterBase.configure({
  matterCommissioningAdaptor,
  matterControlAdapter, // required for local getValue/setValue
  matterSubscriptionAdapter, // optional; enables Matter subscription channel
  matterLocalDiscoveryAdapter, // optional; enables discovery event subscriptions
  matterVendorId: "0x131B",
});

// Register the Matter subscription channel with the base SDK (after login)
await ESPRMMatterBase.initializeMatterSubscription();

// Prefer local Matter updates when both cloud and Matter are available
ESPRMBase.subscriptionManager?.setGlobalChannelOrder?.([
  ESPRMMatterBase.MATTER_SUBSCRIPTION_CHANNEL_ID,
  "notification",
]);

// Authenticate user via the base SDK
const authInstance = ESPRMBase.getAuthInstance();
const user = await authInstance.login("<USERNAME>", "<PASSWORD>");
```

Implement adapter contracts in your app layer — see [Adapter Reference](#adapter-reference) for TypeScript interfaces and the published [API documentation](https://espressif.github.io/esp-rainmaker-matter-app-sdk-ts/).

### Creating Matter Fabrics

Create a new Matter fabric to enable Matter device commissioning:

```javascript
try {
  // Create a new Matter fabric
  const fabric = await user.createFabric({
    name: "My Smart Home Fabric",
    description: "Main fabric for smart home devices",
    type: "home",
  });

  // Get fabric details including certificates and keys
  const fabricDetails = await fabric.getFabricDetails();
} catch (error) {
  console.error("Failed to create fabric:", error.message);
}
```

### Starting Matter Device Commissioning

Start the Matter device commissioning process using the high-level `startCommissioning` method:

```javascript
try {
  const fabric = (
    await user.getGroups({
      fabricOnly: true,
      withFabricDetails: true,
    })
  ).groups.find((entry) => entry.name === "My Smart Home Fabric") as ESPRMFabric;

  // Start commissioning with QR code or onboarding payload
  const cleanup = await fabric.startCommissioning(
    "<QR_CODE_OR_ONBOARDING_PAYLOAD>",
    (progress) => {
      console.log(`Commissioning: ${progress.description}`);
      // Handle progress updates (ON_PROGRESS, SUCCESS, FAILED)
    }
  );

  // Cleanup event listeners when done
  // cleanup();
} catch (error) {
  console.error("Commissioning failed:", error.message);
}
```

### Adding Matter Nodes (Manual Flow)

For advanced use cases, you can manually handle the commissioning flow:

```javascript
try {
  // Add a Matter node using a Certificate Signing Request (CSR)
  const commissioningRequest = await fabric.issueNodeNoC({
    csr: "<BASE64_ENCODED_CSR_FROM_DEVICE>",
    tags: ["device_type:light", "room:living_room"],
    metadata: {
      deviceName: "Smart Light",
      manufacturer: "Espressif",
      location: "Living Room",
    },
  });

  // Confirm commissioning for a RainMaker-enabled Matter device
  const confirmationResult =
    await commissioningRequest.confirmMatterNodeCommissioning({
      nodeType: "rainmaker_matter",
      status: "success",
      rainmakerNodeId: "<RAINMAKER_NODE_ID>",
      matterNodeId: "<MATTER_NODE_ID>",
      challengeResponse: "<SIGNED_CHALLENGE_RESPONSE>",
      metadata: {
        firmwareVersion: "1.0.0",
        deviceCapabilities: ["lighting", "dimming"],
      },
    });
} catch (error) {
  console.error("Device commissioning failed:", error.message);
}
```

### Managing User Certificates

Issue user certificates for Matter fabric access (the CSR is generated automatically via the configured commissioning adaptor):

```javascript
try {
  // Issue a user certificate for fabric access
  const userCertResponse = await fabric.issueUserNoC();

  const userCert = userCertResponse.certificates?.[0];
  if (userCert) {
    const { userNoC, matterUserId, groupId } = userCert;
  }
} catch (error) {
  console.error("Certificate issuance failed:", error.message);
}
```

### Advanced Fabric Management

Retrieve fabric information and manage subgroups:

```javascript
try {
  // Get Matter fabrics (is_matter groups are returned as ESPRMFabric)
  const fabricsResponse = await user.getGroups({
    fabricOnly: true,
    withFabricDetails: true,
    withNodeList: true,
  });

  const fabric = fabricsResponse.groups.find(
    (entry) => entry.name === "My Smart Home Fabric"
  ) as ESPRMFabric;

  // Or fetch a specific fabric by RainMaker group ID:
  const fabricById = await user.getFabricById("<FABRIC_GROUP_ID>", {
    withFabricDetails: true,
    withNodeList: true,
  });

  // Get nodes in the fabric (Matter and RainMaker)
  const nodes = await fabric.getNodesWithDetails();
} catch (error) {
  console.error("Fabric management error:", error.message);
}
```

### Converting Groups to Fabrics

Convert existing RainMaker groups to Matter fabrics:

```javascript
try {
  // List groups and fabrics via getGroups (Matter entries are ESPRMFabric instances)
  const response = await user.getGroups({
    withFabricDetails: true,
  });

  const regularGroups = response.groups.filter((group) => !group.isMatter);
  const fabrics = response.groups.filter((group) => group.isMatter) as ESPRMFabric[];

  // Find a regular group to convert (skip if already a Matter fabric)
  if (regularGroups.length > 0) {
    const regularGroup = regularGroups[0];

    // Convert the group to a Matter fabric
    const matterFabric = await regularGroup.convertToFabric();

    // Now you can use Matter features on this fabric
    const fabricDetails = await matterFabric.getFabricDetails();
  } else {
    console.log("No regular groups available to convert");
  }
} catch (error) {
  console.error("Conversion failed:", error.message);
}
```

### Matter Local Control

After configuring `matterControlAdapter`, read and write Matter cluster attributes on device parameters. Transformed node details do not include live attribute values — call `getValue()` to read from the device, or `setValue()` to control it locally.

```javascript
try {
  const nodes = await fabric.getNodesWithDetails();
  const matterNode = nodes.find((n) => n.isMatter);

  const device = matterNode?.devices?.[0];
  const powerParam = device?.params?.find((p) => p.name === "Power");

  if (powerParam) {
    // Read current OnOff (or other cluster) value from the Matter device
    await powerParam.getValue();
    console.log("Power:", powerParam.value);

    // Write a new value (encoded via cluster registry when configured)
    await powerParam.setValue(true);
  }
} catch (error) {
  console.error("Matter control failed:", error.message);
}
```

Your `matterControlAdapter` must implement `read`, `write`, and optionally `invoke` for command-based parameters. See [`ESPMatterControlAdapterInterface`](https://espressif.github.io/esp-rainmaker-matter-app-sdk-ts/interfaces/services_ESPMatterTransport_ESPMatterControlAdapterInterface.ESPMatterControlAdapterInterface.html) in the API docs.

### Matter Attribute Subscriptions

Real-time parameter updates use the base SDK `subscriptionManager` with the Matter channel registered by `initializeMatterSubscription()`. Provide a `matterSubscriptionAdapter` that bridges your native Matter controller (`subscribeToDevice`, `unsubscribeFromDevice`, etc.).

```javascript
// After ESPRMMatterBase.configure({ matterSubscriptionAdapter, ... })
await ESPRMMatterBase.initializeMatterSubscription();

// Optional: resolve fabric ID per RainMaker node ID for multi-fabric apps
ESPRMMatterBase.getMatterSubscriptionChannel()?.setFabricIdResolver(
  (nodeId) => "<MATTER_FABRIC_ID>"
);

// Use the base SDK subscription manager (same API as cloud/notification channels)
await ESPRMBase.subscriptionManager.subscribeToNode("<NODE_ID>", (update) => {
  console.log("Update from", update.source, update.payload);
});
```

The Matter channel maps cluster reports (OnOff, LevelControl, ColorControl, etc.) into RainMaker-compatible parameter payloads. See [`ESPMatterAdapter`](https://espressif.github.io/esp-rainmaker-matter-app-sdk-ts/interfaces/services_ESPMatterSubscriptionChannel_MatterSubscriptionChannel.ESPMatterAdapter.html) and [`MatterSubscriptionChannel`](https://espressif.github.io/esp-rainmaker-matter-app-sdk-ts/classes/services_ESPMatterSubscriptionChannel_MatterSubscriptionChannel.MatterSubscriptionChannel.html).

### Matter Local Discovery Events

Subscribe to operational Matter discovery on the local network. Configure `matterLocalDiscoveryAdapter` (or use the base SDK `localDiscoveryAdapter` with `_matter._tcp` alongside other service types).

```javascript
import { ESPRMMatterEventType } from "@espressif/rainmaker-matter-sdk";

const onDiscovered = (event) => {
  const { matterNodeId, host, port } = event.transportDetails.metadata;
  console.log("Discovered Matter device:", matterNodeId, host, port);
};

const onLost = (event) => {
  console.log("Matter device lost:", event.transportDetails.metadata.matterNodeId);
};

user.subscribe(ESPRMMatterEventType.matterLocalDiscovery, onDiscovered);
user.subscribe(ESPRMMatterEventType.matterLocalDiscoveryLost, onLost);

// Remove listeners when done
user.unsubscribe(ESPRMMatterEventType.matterLocalDiscovery, onDiscovered);
user.unsubscribe(ESPRMMatterEventType.matterLocalDiscoveryLost, onLost);
```

Event payloads and adapter contracts are documented under [`ESPRMMatterEventType`](https://espressif.github.io/esp-rainmaker-matter-app-sdk-ts/variables/types_subscription.ESPRMMatterEventType.html) and [`ESPMatterLocalDiscoveryAdapterInterface`](https://espressif.github.io/esp-rainmaker-matter-app-sdk-ts/interfaces/types_io_input.ESPMatterLocalDiscoveryAdapterInterface.html).

## Adapter Reference

Platform apps implement native Matter bridges and pass them into `ESPRMMatterBase.configure()`. The published API reference lists each contract:

| Adapter | Config key | Purpose | API reference |
| --- | --- | --- | --- |
| Commissioning | `matterCommissioningAdaptor` | CSR generation, NOC/confirm events, commissioning flow | [`ESPMatterCommissioningAdaptorInterface`](https://espressif.github.io/esp-rainmaker-matter-app-sdk-ts/interfaces/types_io_input.ESPMatterCommissioningAdaptorInterface.html) |
| Control | `matterControlAdapter` | Local read/write/invoke on Matter clusters | [`ESPMatterControlAdapterInterface`](https://espressif.github.io/esp-rainmaker-matter-app-sdk-ts/interfaces/services_ESPMatterTransport_ESPMatterControlAdapterInterface.ESPMatterControlAdapterInterface.html) |
| Subscription | `matterSubscriptionAdapter` | Per-node attribute subscriptions for the Matter channel | [`ESPMatterAdapter`](https://espressif.github.io/esp-rainmaker-matter-app-sdk-ts/interfaces/services_ESPMatterSubscriptionChannel_MatterSubscriptionChannel.ESPMatterAdapter.html) |
| Local discovery | `matterLocalDiscoveryAdapter` | mDNS operational discovery and lost events | [`ESPMatterLocalDiscoveryAdapterInterface`](https://espressif.github.io/esp-rainmaker-matter-app-sdk-ts/interfaces/types_io_input.ESPMatterLocalDiscoveryAdapterInterface.html) |

Additional entry points:

- [`ESPRMMatterBase`](https://espressif.github.io/esp-rainmaker-matter-app-sdk-ts/classes/ESPRMMatterBase.ESPRMMatterBase.html) — `configure()`, `initializeMatterSubscription()`, `MATTER_SUBSCRIPTION_CHANNEL_ID`
- [`ESPRMMatterDeviceParam`](https://espressif.github.io/esp-rainmaker-matter-app-sdk-ts/classes/ESPRMMatterDeviceParam.ESPRMMatterDeviceParam.html) — `getValue()`, `setValue()`
- [Full API index](https://espressif.github.io/esp-rainmaker-matter-app-sdk-ts/)

## Resources

- [Changelog](CHANGELOG.md)
- [API Documentation](https://espressif.github.io/esp-rainmaker-matter-app-sdk-ts/) (includes [Adapter Reference](#adapter-reference) links above)
- [RainMaker Base SDK](https://www.npmjs.com/package/@espressif/rainmaker-base-sdk)
- [Matter Protocol Specification](https://csa-iot.org/all-solutions/matter/)
- [ESP RainMaker Documentation](https://rainmaker.espressif.com/)

## License

This project is licensed under the Apache 2.0 license - see the [LICENSE](LICENSE) file for details.
