or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

ble-discovery.mdclusters.mdcrypto-credentials.mddevice-controller.mdindex.mdstack-management.mdstorage.mdtlv-data.md

stack-management.mddocs/

0

# Stack Management

1

2

Core Matter stack initialization, configuration, and lifecycle management providing the foundation for all Matter protocol operations.

3

4

## Capabilities

5

6

### CHIP Stack Initialization

7

8

Initialize and manage the core Matter protocol stack.

9

10

```python { .api }

11

class ChipStack:

12

"""Core CHIP stack for Matter protocol operations."""

13

14

def __init__(

15

self,

16

persistentStoragePath: str = None,

17

enableServerInteractions: bool = True,

18

bluetoothAdapter: int = None,

19

**kwargs

20

):

21

"""

22

Initialize the CHIP stack.

23

24

Parameters:

25

- persistentStoragePath: Path for persistent storage (None for in-memory)

26

- enableServerInteractions: Enable server-side interaction handling

27

- bluetoothAdapter: Bluetooth adapter ID (platform-specific)

28

- kwargs: Additional stack configuration options

29

"""

30

...

31

32

def Call(self, f):

33

"""

34

Execute a function on the CHIP stack thread.

35

36

Parameters:

37

- f: Function to execute

38

39

Returns:

40

Function return value

41

"""

42

...

43

44

def CallAsync(self, f):

45

"""

46

Execute an async function on the CHIP stack thread.

47

48

Parameters:

49

- f: Async function to execute

50

51

Returns:

52

Awaitable result

53

"""

54

...

55

56

def Shutdown(self):

57

"""

58

Clean shutdown of the CHIP stack.

59

Stops all operations and releases resources.

60

"""

61

...

62

63

def GetStorageManager(self):

64

"""

65

Get the storage manager instance.

66

67

Returns:

68

Storage manager object

69

"""

70

...

71

72

def GetFabricTable(self):

73

"""

74

Get the fabric table instance.

75

76

Returns:

77

Fabric table object

78

"""

79

...

80

81

def GetCASESessionManager(self):

82

"""

83

Get the CASE session manager.

84

85

Returns:

86

CASE session manager object

87

"""

88

...

89

90

def GetPASESessionManager(self):

91

"""

92

Get the PASE session manager.

93

94

Returns:

95

PASE session manager object

96

"""

97

...

98

```

99

100

### Device Proxy Management

101

102

Manage device proxy objects for communicating with Matter devices.

103

104

```python { .api }

105

class DeviceProxyWrapper:

106

"""Wrapper for device proxy objects."""

107

108

def __init__(self, device):

109

"""

110

Initialize device proxy wrapper.

111

112

Parameters:

113

- device: Native device proxy object

114

"""

115

...

116

117

def GetDevice(self):

118

"""

119

Get the underlying device proxy.

120

121

Returns:

122

Native device proxy object

123

"""

124

...

125

126

def GetDeviceId(self) -> int:

127

"""

128

Get the device node ID.

129

130

Returns:

131

Device node ID

132

"""

133

...

134

135

def IsConnected(self) -> bool:

136

"""

137

Check if device is currently connected.

138

139

Returns:

140

True if device is connected

141

"""

142

...

143

144

def IsSecurelyConnected(self) -> bool:

145

"""

146

Check if device has a secure connection.

147

148

Returns:

149

True if securely connected

150

"""

151

...

152

153

def GetLastError(self) -> int:

154

"""

155

Get the last error code for this device.

156

157

Returns:

158

Error code or 0 if no error

159

"""

160

...

161

162

def ResetErrorCode(self):

163

"""Reset the device error code to 0."""

164

...

165

```

166

167

### Stack Configuration

168

169

Configure various aspects of the Matter stack behavior.

170

171

```python { .api }

172

class ChipStackConfiguration:

173

"""Configuration settings for the CHIP stack."""

174

175

def __init__(self):

176

"""Initialize with default configuration."""

177

...

178

179

def set_ble_platform_config(self, config: dict):

180

"""

181

Set BLE platform-specific configuration.

182

183

Parameters:

184

- config: BLE configuration dictionary

185

"""

186

...

187

188

def set_wifi_platform_config(self, config: dict):

189

"""

190

Set WiFi platform-specific configuration.

191

192

Parameters:

193

- config: WiFi configuration dictionary

194

"""

195

...

196

197

def set_thread_platform_config(self, config: dict):

198

"""

199

Set Thread platform-specific configuration.

200

201

Parameters:

202

- config: Thread configuration dictionary

203

"""

204

...

205

206

def set_commissioning_config(self, config: dict):

207

"""

208

Set commissioning-related configuration.

209

210

Parameters:

211

- config: Commissioning configuration dictionary

212

"""

213

...

214

215

def set_security_config(self, config: dict):

216

"""

217

Set security and cryptographic configuration.

218

219

Parameters:

220

- config: Security configuration dictionary

221

"""

222

...

223

224

def get_config(self) -> dict:

225

"""

226

Get current stack configuration.

227

228

Returns:

229

Complete configuration dictionary

230

"""

231

...

232

```

233

234

### Event Loop Integration

235

236

Integrate the Matter stack with application event loops.

237

238

```python { .api }

239

class ChipEventLoop:

240

"""Event loop integration for CHIP stack."""

241

242

def __init__(self, stack: ChipStack):

243

"""

244

Initialize event loop integration.

245

246

Parameters:

247

- stack: CHIP stack instance

248

"""

249

...

250

251

def start(self):

252

"""Start the event loop processing."""

253

...

254

255

def stop(self):

256

"""Stop the event loop processing."""

257

...

258

259

def run_until_complete(self, coro):

260

"""

261

Run until the given coroutine completes.

262

263

Parameters:

264

- coro: Coroutine to run

265

266

Returns:

267

Coroutine result

268

"""

269

...

270

271

def schedule_callback(self, callback, delay: float = 0):

272

"""

273

Schedule a callback to run after a delay.

274

275

Parameters:

276

- callback: Function to call

277

- delay: Delay in seconds

278

"""

279

...

280

281

def is_running(self) -> bool:

282

"""

283

Check if event loop is running.

284

285

Returns:

286

True if event loop is running

287

"""

288

...

289

```

290

291

### Thread Management

292

293

Manage threading for Matter stack operations.

294

295

```python { .api }

296

class ChipThreadManager:

297

"""Thread management for CHIP operations."""

298

299

def __init__(self, stack: ChipStack):

300

"""

301

Initialize thread manager.

302

303

Parameters:

304

- stack: CHIP stack instance

305

"""

306

...

307

308

def start_thread(self, target, args: tuple = (), name: str = None):

309

"""

310

Start a new thread for CHIP operations.

311

312

Parameters:

313

- target: Function to run in thread

314

- args: Arguments for target function

315

- name: Thread name (optional)

316

317

Returns:

318

Thread object

319

"""

320

...

321

322

def run_on_chip_thread(self, func, *args, **kwargs):

323

"""

324

Run function on the main CHIP thread.

325

326

Parameters:

327

- func: Function to execute

328

- args: Positional arguments

329

- kwargs: Keyword arguments

330

331

Returns:

332

Function result

333

"""

334

...

335

336

def run_on_chip_thread_async(self, func, *args, **kwargs):

337

"""

338

Run async function on the main CHIP thread.

339

340

Parameters:

341

- func: Async function to execute

342

- args: Positional arguments

343

- kwargs: Keyword arguments

344

345

Returns:

346

Awaitable result

347

"""

348

...

349

350

def is_chip_thread(self) -> bool:

351

"""

352

Check if current thread is the CHIP thread.

353

354

Returns:

355

True if running on CHIP thread

356

"""

357

...

358

359

def join_all_threads(self, timeout: float = None):

360

"""

361

Wait for all CHIP threads to complete.

362

363

Parameters:

364

- timeout: Maximum wait time in seconds

365

"""

366

...

367

```

368

369

### Stack State Management

370

371

Monitor and manage the overall state of the Matter stack.

372

373

```python { .api }

374

class ChipStackState:

375

"""State monitoring for CHIP stack."""

376

377

def __init__(self, stack: ChipStack):

378

"""

379

Initialize stack state monitor.

380

381

Parameters:

382

- stack: CHIP stack instance

383

"""

384

...

385

386

def is_initialized(self) -> bool:

387

"""

388

Check if stack is fully initialized.

389

390

Returns:

391

True if stack is initialized

392

"""

393

...

394

395

def is_running(self) -> bool:

396

"""

397

Check if stack is currently running.

398

399

Returns:

400

True if stack is running

401

"""

402

...

403

404

def is_shutting_down(self) -> bool:

405

"""

406

Check if stack is in shutdown process.

407

408

Returns:

409

True if stack is shutting down

410

"""

411

...

412

413

def get_active_connections(self) -> int:

414

"""

415

Get number of active device connections.

416

417

Returns:

418

Number of active connections

419

"""

420

...

421

422

def get_memory_usage(self) -> dict:

423

"""

424

Get memory usage statistics.

425

426

Returns:

427

Dictionary with memory usage information

428

"""

429

...

430

431

def get_performance_metrics(self) -> dict:

432

"""

433

Get performance metrics.

434

435

Returns:

436

Dictionary with performance statistics

437

"""

438

...

439

440

def reset_metrics(self):

441

"""Reset performance metrics counters."""

442

...

443

```

444

445

## Usage Examples

446

447

### Basic Stack Initialization

448

449

```python

450

from chip.ChipStack import ChipStack

451

452

# Initialize stack with persistent storage

453

stack = ChipStack(

454

persistentStoragePath="/tmp/chip_storage",

455

enableServerInteractions=True

456

)

457

458

try:

459

# Perform stack operations

460

print("Stack initialized successfully")

461

462

# Execute functions on stack thread

463

def get_fabric_count():

464

fabric_table = stack.GetFabricTable()

465

return fabric_table.GetFabricCount()

466

467

fabric_count = stack.Call(get_fabric_count)

468

print(f"Number of fabrics: {fabric_count}")

469

470

finally:

471

# Always shutdown cleanly

472

stack.Shutdown()

473

```

474

475

### Advanced Stack Configuration

476

477

```python

478

from chip.ChipStack import ChipStack, ChipStackConfiguration

479

480

# Create custom configuration

481

config = ChipStackConfiguration()

482

483

# Configure BLE settings

484

config.set_ble_platform_config({

485

'adapter_id': 0,

486

'scan_timeout': 30,

487

'connection_timeout': 15

488

})

489

490

# Configure WiFi settings

491

config.set_wifi_platform_config({

492

'max_networks': 10,

493

'scan_interval': 60

494

})

495

496

# Configure commissioning

497

config.set_commissioning_config({

498

'enable_enhanced_commissioning': True,

499

'commissioning_timeout': 300,

500

'max_concurrent_commissions': 5

501

})

502

503

# Initialize stack with custom config

504

stack = ChipStack(

505

persistentStoragePath="/var/lib/chip",

506

enableServerInteractions=True,

507

configuration=config

508

)

509

510

# Monitor stack state

511

from chip.ChipStack import ChipStackState

512

513

state_monitor = ChipStackState(stack)

514

515

if state_monitor.is_initialized():

516

print("Stack is ready")

517

print(f"Active connections: {state_monitor.get_active_connections()}")

518

519

# Get performance metrics

520

metrics = state_monitor.get_performance_metrics()

521

print(f"Commands processed: {metrics.get('commands_processed', 0)}")

522

print(f"Attributes read: {metrics.get('attributes_read', 0)}")

523

524

stack.Shutdown()

525

```

526

527

### Event Loop Integration

528

529

```python

530

import asyncio

531

from chip.ChipStack import ChipStack, ChipEventLoop

532

533

async def main():

534

# Initialize stack

535

stack = ChipStack(persistentStoragePath="/tmp/chip_storage")

536

537

# Create event loop integration

538

chip_loop = ChipEventLoop(stack)

539

chip_loop.start()

540

541

try:

542

# Run async operations on CHIP stack

543

async def async_operation():

544

# Simulate some async work

545

await asyncio.sleep(1)

546

return "Operation completed"

547

548

result = await chip_loop.run_until_complete(async_operation())

549

print(result)

550

551

# Schedule periodic callback

552

def periodic_task():

553

print(f"Periodic task - Active connections: {stack.GetActiveConnections()}")

554

555

chip_loop.schedule_callback(periodic_task, delay=5.0)

556

557

# Wait a bit for the callback

558

await asyncio.sleep(6)

559

560

finally:

561

chip_loop.stop()

562

stack.Shutdown()

563

564

# Run the async main function

565

asyncio.run(main())

566

```

567

568

### Thread Management

569

570

```python

571

import threading

572

import time

573

from chip.ChipStack import ChipStack, ChipThreadManager

574

575

stack = ChipStack(persistentStoragePath="/tmp/chip_storage")

576

thread_mgr = ChipThreadManager(stack)

577

578

try:

579

# Function to run on CHIP thread

580

def chip_work():

581

print(f"Running on CHIP thread: {thread_mgr.is_chip_thread()}")

582

return "CHIP work completed"

583

584

# Execute on CHIP thread

585

result = thread_mgr.run_on_chip_thread(chip_work)

586

print(result)

587

588

# Start background thread for monitoring

589

def monitor_thread():

590

while not stop_monitoring:

591

if thread_mgr.is_chip_thread():

592

print("Monitor running on CHIP thread")

593

else:

594

print("Monitor running on separate thread")

595

time.sleep(2)

596

597

stop_monitoring = False

598

monitor = thread_mgr.start_thread(

599

target=monitor_thread,

600

name="StackMonitor"

601

)

602

603

# Let it run for a while

604

time.sleep(10)

605

606

# Stop monitoring

607

stop_monitoring = True

608

609

# Wait for all threads to complete

610

thread_mgr.join_all_threads(timeout=5.0)

611

612

finally:

613

stack.Shutdown()

614

```

615

616

### Device Proxy Management

617

618

```python

619

from chip.ChipStack import ChipStack, DeviceProxyWrapper

620

from chip.ChipDeviceCtrl import ChipDeviceController

621

622

# Initialize stack and controller

623

stack = ChipStack(persistentStoragePath="/tmp/chip_storage")

624

controller = ChipDeviceController(controllerNodeId=12345)

625

626

try:

627

# Commission a device first...

628

# (commissioning code omitted for brevity)

629

630

# Get device proxy

631

device_proxy = controller.GetConnectedDevice(nodeId=1)

632

633

if device_proxy:

634

# Wrap the device proxy

635

wrapped_device = DeviceProxyWrapper(device_proxy)

636

637

print(f"Device ID: {wrapped_device.GetDeviceId()}")

638

print(f"Connected: {wrapped_device.IsConnected()}")

639

print(f"Secure: {wrapped_device.IsSecurelyConnected()}")

640

641

# Check for errors

642

error_code = wrapped_device.GetLastError()

643

if error_code != 0:

644

print(f"Device error: {error_code}")

645

wrapped_device.ResetErrorCode()

646

647

finally:

648

controller.Shutdown()

649

stack.Shutdown()

650

```