# Integrate Matter as a service in an existing non-Matter application

## Overview

This guide provides step-by-step instructions for integrating Matter as a service into your existing non-Matter application.

> **Important**: This guide covers Matter development for FreeRTOS-based platforms using **MCUX SDK** only.
>
> **For Zephyr-based Matter development**, refer to the [Matter Zephyr documentation](https://github.com/NXP/matter/blob/release/v1.6.0/docs/platforms/nxp/nxp_zephyr_guide.md).

## Prerequisites

Before integrating Matter into your existing application, ensure that you have:

- MCUX SDK with Matter support, see [Install MCUX SDK with Matter support](../getting_started/installation.md#install-mcux-sdk-with-matter-support)
- All required build tools installed, see [Install Software Tools](../getting_started/installation.md#install-software-tools)
- An NXP development board that supports Matter, see [supported platforms](../getting_started/supported_platforms.md)
- A working non-Matter application built with MCUX SDK

## Build System Integration

### Step 1 : Add Matter in the application CMakeLists.txt

The integration of Matter in an existing example build system can be slightly different based on which architecture is being used.

#### Option A - Monolithic Architecture

In this approach, the Matter libraries and the MCUX SDK are built directly alongside your application as a single executable.

**How to recognize a monolithic architecture in existing MCUX SDK examples:**

- The CMakeLists.txt of the example directly includes the SDK root CMakeLists.txt.
- Everything (application + SDK) is compiled into one executable.
- No use of `find_package()` for loading the MCUX SDK

Add the Matter subdirectory in your application's root CMakeLists.txt.

```cmake
# Pass SDK compiler flags and include paths to Matter
list(APPEND CONFIG_CHIP_EXTERNAL_TARGETS ${MCUX_SDK_PROJECT_NAME})

# Add Matter stack & NXP port libraries
add_subdirectory(${SdkRootDirPath}/middleware/matter ./modules/chip)

# Link matter libraries to your application
target_link_libraries(${MCUX_SDK_PROJECT_NAME}
    PRIVATE
    -Wl,--start-group -lm -lc -lgcc -lnosys
    chip
    -Wl,--end-group
)
```

#### Option B - Modular Architecture

In this architecture, Matter is integrated as an [MCUX module](https://mcuxpresso.nxp.com/mcuxsdk/latest/html/develop/sdk/integration.html#integrate-other-cmake-build-system). The SDK is compiled as a static library and automatically linked to the application target by the build system, resulting in clear separation between the SDK, Matter libraries, and your application. A typical example for this approach is any Matter example under `mcuxsdk/examples/matter_examples` directory.

**How to recognize a modular architecture in existing MCUX SDK examples:**

- The example uses `find_package()` to locate the MCUX SDK. See [McuxSDK CMake Package](https://mcuxpresso.nxp.com/mcuxsdk/latest/html/develop/sdk/integration.html#mcuxsdk-cmake-package) for more information.
- SDK is built as a static library, automatically linked to the application by the build system
- Application source files are added to the `app` target
- Clear separation between SDK and application code

Add Matter as an MCUX module in your application's CMakeLists.txt, this allows the build system to find and link Matter libraries automatically. To achieve this, use the `EXTRA_MCUX_MODULES` variable, this must be added before the `find_package(McuxSDK)` call.

```cmake
list(APPEND EXTRA_MCUX_MODULES ${SdkRootDirPath}/middleware/matter/config/nxp/chip-cmake-freertos)
```

After the `find_package(McuxSDK)` call, make sure the SDK flags and includes are passed to the Matter libraries with `CONFIG_CHIP_EXTERNAL_TARGETS` variable.

```cmake
# Pass SDK compiler flags and include paths to Matter
list(APPEND CONFIG_CHIP_EXTERNAL_TARGETS ${MCUX_SDK_PROJECT_NAME})
```

### Step 2 : Add Matter in the application Kconfig

Your application needs a Kconfig file to serve as the entry-level configuration. This allows you to:

- Override default SDK Kconfig values with Matter-specific settings
- Include Matter-specific configuration options
- Maintain a proper configuration hierarchy

**If your application already has a Kconfig file:**
Add the Matter-specific source lines to your existing Kconfig.

**If your application doesn't have a Kconfig file:**
Create a new `Kconfig` file in your application root with the following content:

```
mainmenu "Your Application Name Configuration"

# Include Matter-specific Kconfig files
# Note: Kconfig.defaults must be included first to override SDK defaults
source "${SdkRootDirPath}/middleware/matter/config/nxp/chip-cmake-freertos/Kconfig.defaults"

# Include this line only for Monolithic Architecture
# For Modular Architecture, this is automatically loaded by the build system
source "${SdkRootDirPath}/middleware/matter/config/nxp/chip-cmake-freertos/Kconfig"

# Optional: Include Matter example configurations
source "${SdkRootDirPath}/middleware/matter/examples/platform/nxp/common/Kconfig"

# Include MCUX SDK root Kconfig
source "${SdkRootDirPath}/Kconfig.mcuxpresso"
```

> **Note:** Place this `Kconfig` file in the same directory as your application's root `CMakeLists.txt`.

### Step 3 : Configure Matter in the application prj.conf

Matter requires specific configuration settings to function properly. Create or modify a `prj.conf` file to include Matter-specific Kconfig options.

#### Locate or Create prj.conf

**If your application already has a `prj.conf` file:**
Add the Matter-specific configurations to your existing file.

**If your application doesn't have a `prj.conf` file:**
Create a `prj.conf` file in your application root directory (same location as your CMakeLists.txt and Kconfig files).

#### Configure Matter Settings

You can use an existing Matter example as a reference point and customize it for your specific needs:

1. **Find a reference configuration:**
   Browse to `mcuxsdk/examples/matter_examples/<example_name>/mcux/prj.conf` and choose an example that closely matches your application type. For example, lighting, thermostat.

2. **Essential Matter configurations to include:**

```
    # Enable Matter support
    CONFIG_CHIP=y

    # Enable networking (adjust based on your connectivity needs)
    CONFIG_CHIP_WIFI=y
    # OR
    CONFIG_NET_L2_OPENTHREAD=y

    # Device-specific Matter configurations
    # For example for a Thermostat device-type:
    CONFIG_BT_DEVICE_NAME="\"NXPThermostat\""
    CONFIG_CHIP_DEVICE_PRODUCT_NAME="Thermostat"
    CONFIG_CHIP_DEVICE_TYPE=769

    # Disable SDK default board files to use Matter board files
    CONFIG_MCUX_PRJSEG_module.board.boardfile=n

    # Optionally you can also :
    # Adjust memory and threading configurations
    CONFIG_APP_TASK_STACK_SIZE=6144
    CONFIG_CHIP_TASK_STACK_SIZE=10240
    # Enable the Matter CLI
    CONFIG_CHIP_LIB_SHELL=y

    # Add other configurations based on your application needs
```

3. **Customize for your application:**
   - **Device Type**: Update `CONFIG_CHIP_DEVICE_TYPE` to match your device, For example, 769 for thermostat.
   - **Device Name**: Change `CONFIG_BT_DEVICE_NAME` and `CONFIG_CHIP_DEVICE_PRODUCT_NAME` to reflect your product
   - **Connectivity**: Choose either WiFi or Thread based on your requirements.
   - **Memory**: Adjust stack sizes based on your application's memory constraints
   - **Features**: Remove configurations that don't apply to your use case

> **Connectivity Note:** Different boards have different default network configurations:
>
> - **Wi-Fi enabled by default**: RW61x, RT1060 boards
> - **Thread enabled by default**: MCXW7x boards
>
> If you want to use a different connectivity option, explicitly disable the default one, for example :

```
    # To switch from Wi-Fi to Thread:
    CONFIG_CHIP_WIFI=n
    CONFIG_NET_L2_OPENTHREAD=y
```

### Step 4 : Update the example's `reconfig.cmake` file

SDK applications typically include a CMake file named `reconfig.cmake`, which allows customization of SDK settings for specific needs per board (compiler options, linker settings, linker files, board files, and other project configurations).

Matter provides a template `nxp_sdk_reconfig.cmake` file that you can use as a reference. Find the template for your platform family:

```
mcuxsdk/middleware/matter/third_party/nxp/nxp_matter_support/examples/platform/<platform_family>/nxp_sdk_reconfig.cmake
```

1. **If your application doesn't have a `reconfig.cmake` file:**
   - Copy the Matter template to your application root directory
   - Customize as needed for your specific requirements
   - Include it in your application CMakeLists.txt

2. **If your application already has a `reconfig.cmake` file:**
   - Compare your existing file with the Matter template
   - Merge the Matter-specific configurations into your existing file
   - Pay special attention to potential conflicts

> **Important notes:**
>
> - The configuration in the Matter template file may conflict with your existing application settings, so the files should be merged carefully and adjusted to match your specific project requirements.
> - If your application is following a [modular architecture](#option-b---modular-architecture), include the `reconfig.cmake` file before the `project()` call to ensure proper SDK configuration.

## Code Integration

After completing the build system integration, you must integrate Matter functionality into your application code. This section covers the essential code changes required.

### Step 5: Copy Matter application files under your project

Find a reference example that closely matches your device type, and copy the relevant source files to your project.

For example, if your application is a thermostat device type :

```bash
$ cp -r <path_to_mcuxsdk>/mcuxsdk/middleware/matter/examples/thermostat/nxp/common/* your_project/common
```

Key files you'll typically need:

- `AppTask.cpp/h` - Main application logic and Matter event handling
- `AppEvent.h` - Application-specific event definitions
- `DeviceCallbacks.cpp/h` - Device-specific callback implementations
- `ZclCallbacks.cpp` - Cluster-specific callback implementations
- `main.cpp` - Application entry point with Matter initialization
- Other device-specific files

### Step 6: Configure Device Data Model

Your device's Matter functionality is defined by its data model (clusters, attributes, commands). Configure this using the ZAP tool.

Use the ZAP tool to modify clusters, attributes, and commands for your specific device requirements.

For detailed ZAP configuration instructions, see: [Customize Matter Device Configuration with ZAP](./application_customization.md#customize-matter-device-configuration-with-zap)

> **Note**: If the reference example you copied closely matches your needs, you can start with the existing configuration as-is and customize it later as your application evolves.

### Step 7: Initialize Matter Stack

Copy Matter initialization logic in your application's `main()`,
the content of the reference example's `main.cpp` file should be used as a reference. Here's a typical Matter stack initialization code:

```cpp
int main(int argc, char * argv[])
{
    TaskHandle_t taskHandle;

    PlatformMgrImpl().HardwareInit();
    chip::NXP::App::GetAppTask().Start();
    vTaskStartScheduler();
}
```

#### Important notes about initialization:

- **Remove duplicate initialization calls**: Matter's initialization logic handles many common initializations (board hardware, crypto, networking, and so on)
- **Check for conflicts**: Compare your existing initialization with the Matter example to avoid duplicate or conflicting calls
- **Task priorities**: Ensure that your existing tasks don't conflict with Matter's task priorities

### Step 8: Update your application linker file

Matter applications require specific memory sections for OTA updates, factory data, and nonvolatile storage.

#### Locate the correct linker template:

Find the Matter linker file for your platform:

```bash
# For RW61x and RT platforms, you can find the .ld file in:
mcuxsdk/middleware/matter/third_party/nxp/nxp_matter_support/examples/platform/rt/<platform>/app/ldscripts

# For MCXWx platforms, the .ld file used is:
mcuxsdk/examples/_boards/<board>/wireless_examples/linker/gcc/connectivity.ld
```

#### Integration options:

- If your memory layout is standard, replace your existing linker file with the Matter version by adding the path in your `reconfig.cmake`.
- If you have custom memory requirements, carefully merge the two by adding those essential Matter sections to your existing linker file (OTA storage, factory data, NVS sections).

## Next Steps

For more information on how to further customize your example, refer to this dedicated section [Customization options](./application_customization.md#customization-options).
