0
# Storage
1
2
Storage interfaces for device credentials, fabric information, and configuration persistence across application restarts.
3
4
## Capabilities
5
6
### Persistent Storage Interface
7
8
Core persistent storage interface for Matter stack data.
9
10
```python { .api }
11
class PersistentStorage:
12
"""Persistent storage interface for CHIP stack data."""
13
14
def __init__(self, path: str):
15
"""
16
Initialize persistent storage.
17
18
Parameters:
19
- path: File system path for storage
20
"""
21
...
22
23
def set(self, key: str, value: bytes) -> bool:
24
"""
25
Store a key-value pair.
26
27
Parameters:
28
- key: Storage key string
29
- value: Binary data to store
30
31
Returns:
32
True if storage successful
33
"""
34
...
35
36
def get(self, key: str) -> bytes:
37
"""
38
Retrieve value by key.
39
40
Parameters:
41
- key: Storage key string
42
43
Returns:
44
Binary data or None if key not found
45
"""
46
...
47
48
def delete(self, key: str) -> bool:
49
"""
50
Delete a key-value pair.
51
52
Parameters:
53
- key: Storage key to delete
54
55
Returns:
56
True if deletion successful
57
"""
58
...
59
60
def clear(self) -> bool:
61
"""
62
Clear all stored data.
63
64
Returns:
65
True if clear successful
66
"""
67
...
68
69
def keys(self) -> list:
70
"""
71
Get all storage keys.
72
73
Returns:
74
List of all keys in storage
75
"""
76
...
77
78
def exists(self, key: str) -> bool:
79
"""
80
Check if key exists in storage.
81
82
Parameters:
83
- key: Storage key to check
84
85
Returns:
86
True if key exists
87
"""
88
...
89
90
def size(self) -> int:
91
"""
92
Get total number of stored items.
93
94
Returns:
95
Number of key-value pairs in storage
96
"""
97
...
98
99
def sync(self) -> bool:
100
"""
101
Force synchronization to persistent media.
102
103
Returns:
104
True if sync successful
105
"""
106
...
107
```
108
109
### Configuration Storage
110
111
High-level interface for storing configuration data.
112
113
```python { .api }
114
class ConfigurationStorage:
115
"""High-level configuration storage interface."""
116
117
def __init__(self, storage: PersistentStorage):
118
"""
119
Initialize configuration storage.
120
121
Parameters:
122
- storage: Underlying persistent storage instance
123
"""
124
...
125
126
def set_device_config(self, node_id: int, config: dict) -> bool:
127
"""
128
Store device-specific configuration.
129
130
Parameters:
131
- node_id: Device node ID
132
- config: Configuration dictionary
133
134
Returns:
135
True if storage successful
136
"""
137
...
138
139
def get_device_config(self, node_id: int) -> dict:
140
"""
141
Retrieve device configuration.
142
143
Parameters:
144
- node_id: Device node ID
145
146
Returns:
147
Configuration dictionary or None if not found
148
"""
149
...
150
151
def delete_device_config(self, node_id: int) -> bool:
152
"""
153
Delete device configuration.
154
155
Parameters:
156
- node_id: Device node ID
157
158
Returns:
159
True if deletion successful
160
"""
161
...
162
163
def set_fabric_config(self, fabric_id: int, config: dict) -> bool:
164
"""
165
Store fabric-specific configuration.
166
167
Parameters:
168
- fabric_id: Fabric ID
169
- config: Fabric configuration dictionary
170
171
Returns:
172
True if storage successful
173
"""
174
...
175
176
def get_fabric_config(self, fabric_id: int) -> dict:
177
"""
178
Retrieve fabric configuration.
179
180
Parameters:
181
- fabric_id: Fabric ID
182
183
Returns:
184
Fabric configuration dictionary or None if not found
185
"""
186
...
187
188
def set_controller_config(self, controller_id: int, config: dict) -> bool:
189
"""
190
Store controller configuration.
191
192
Parameters:
193
- controller_id: Controller node ID
194
- config: Controller configuration dictionary
195
196
Returns:
197
True if storage successful
198
"""
199
...
200
201
def get_controller_config(self, controller_id: int) -> dict:
202
"""
203
Retrieve controller configuration.
204
205
Parameters:
206
- controller_id: Controller node ID
207
208
Returns:
209
Controller configuration dictionary or None if not found
210
"""
211
...
212
213
def list_devices(self) -> list:
214
"""
215
List all devices with stored configurations.
216
217
Returns:
218
List of device node IDs
219
"""
220
...
221
222
def list_fabrics(self) -> list:
223
"""
224
List all fabrics with stored configurations.
225
226
Returns:
227
List of fabric IDs
228
"""
229
...
230
```
231
232
### Credential Storage
233
234
Secure storage for certificates, keys, and other security credentials.
235
236
```python { .api }
237
class CredentialStorage:
238
"""Secure storage for security credentials."""
239
240
def __init__(self, storage: PersistentStorage):
241
"""
242
Initialize credential storage.
243
244
Parameters:
245
- storage: Underlying persistent storage instance
246
"""
247
...
248
249
def store_fabric_credentials(
250
self,
251
fabric_id: int,
252
root_cert: bytes,
253
intermediate_cert: bytes = None,
254
operational_cert: bytes = None,
255
private_key: bytes = None
256
) -> bool:
257
"""
258
Store fabric credentials.
259
260
Parameters:
261
- fabric_id: Fabric ID
262
- root_cert: Root certificate (required)
263
- intermediate_cert: Intermediate certificate (optional)
264
- operational_cert: Operational certificate (optional)
265
- private_key: Private key (optional)
266
267
Returns:
268
True if storage successful
269
"""
270
...
271
272
def get_fabric_credentials(self, fabric_id: int) -> dict:
273
"""
274
Retrieve fabric credentials.
275
276
Parameters:
277
- fabric_id: Fabric ID
278
279
Returns:
280
Dictionary with credential data or None if not found
281
"""
282
...
283
284
def store_device_credentials(
285
self,
286
node_id: int,
287
fabric_id: int,
288
device_cert: bytes,
289
device_key: bytes = None
290
) -> bool:
291
"""
292
Store device-specific credentials.
293
294
Parameters:
295
- node_id: Device node ID
296
- fabric_id: Associated fabric ID
297
- device_cert: Device certificate
298
- device_key: Device private key (optional)
299
300
Returns:
301
True if storage successful
302
"""
303
...
304
305
def get_device_credentials(self, node_id: int, fabric_id: int) -> dict:
306
"""
307
Retrieve device credentials.
308
309
Parameters:
310
- node_id: Device node ID
311
- fabric_id: Fabric ID
312
313
Returns:
314
Dictionary with credential data or None if not found
315
"""
316
...
317
318
def store_paa_certificates(self, paa_certs: list) -> bool:
319
"""
320
Store Product Attestation Authority certificates.
321
322
Parameters:
323
- paa_certs: List of PAA certificate bytes
324
325
Returns:
326
True if storage successful
327
"""
328
...
329
330
def get_paa_certificates(self) -> list:
331
"""
332
Retrieve all PAA certificates.
333
334
Returns:
335
List of PAA certificate bytes
336
"""
337
...
338
339
def delete_fabric_credentials(self, fabric_id: int) -> bool:
340
"""
341
Delete all credentials for a fabric.
342
343
Parameters:
344
- fabric_id: Fabric ID
345
346
Returns:
347
True if deletion successful
348
"""
349
...
350
351
def delete_device_credentials(self, node_id: int, fabric_id: int) -> bool:
352
"""
353
Delete device credentials.
354
355
Parameters:
356
- node_id: Device node ID
357
- fabric_id: Fabric ID
358
359
Returns:
360
True if deletion successful
361
"""
362
...
363
```
364
365
### Session Storage
366
367
Storage for session information and security contexts.
368
369
```python { .api }
370
class SessionStorage:
371
"""Storage for session information."""
372
373
def __init__(self, storage: PersistentStorage):
374
"""
375
Initialize session storage.
376
377
Parameters:
378
- storage: Underlying persistent storage instance
379
"""
380
...
381
382
def store_session(
383
self,
384
node_id: int,
385
fabric_id: int,
386
session_data: dict
387
) -> bool:
388
"""
389
Store session information.
390
391
Parameters:
392
- node_id: Device node ID
393
- fabric_id: Fabric ID
394
- session_data: Session information dictionary
395
396
Returns:
397
True if storage successful
398
"""
399
...
400
401
def get_session(self, node_id: int, fabric_id: int) -> dict:
402
"""
403
Retrieve session information.
404
405
Parameters:
406
- node_id: Device node ID
407
- fabric_id: Fabric ID
408
409
Returns:
410
Session information dictionary or None if not found
411
"""
412
...
413
414
def delete_session(self, node_id: int, fabric_id: int) -> bool:
415
"""
416
Delete session information.
417
418
Parameters:
419
- node_id: Device node ID
420
- fabric_id: Fabric ID
421
422
Returns:
423
True if deletion successful
424
"""
425
...
426
427
def cleanup_expired_sessions(self) -> int:
428
"""
429
Remove expired session information.
430
431
Returns:
432
Number of sessions cleaned up
433
"""
434
...
435
436
def get_active_sessions(self) -> list:
437
"""
438
Get list of active sessions.
439
440
Returns:
441
List of (node_id, fabric_id) tuples
442
"""
443
...
444
```
445
446
### Subscription Storage
447
448
Persistent storage for subscription information.
449
450
```python { .api }
451
class SubscriptionStorage:
452
"""Storage for subscription information."""
453
454
def __init__(self, storage: PersistentStorage):
455
"""
456
Initialize subscription storage.
457
458
Parameters:
459
- storage: Underlying persistent storage instance
460
"""
461
...
462
463
def store_subscription(
464
self,
465
subscription_id: int,
466
node_id: int,
467
fabric_id: int,
468
subscription_data: dict
469
) -> bool:
470
"""
471
Store subscription information.
472
473
Parameters:
474
- subscription_id: Unique subscription ID
475
- node_id: Target device node ID
476
- fabric_id: Fabric ID
477
- subscription_data: Subscription configuration dictionary
478
479
Returns:
480
True if storage successful
481
"""
482
...
483
484
def get_subscription(self, subscription_id: int) -> dict:
485
"""
486
Retrieve subscription information.
487
488
Parameters:
489
- subscription_id: Subscription ID
490
491
Returns:
492
Subscription information dictionary or None if not found
493
"""
494
...
495
496
def get_subscriptions_for_device(self, node_id: int, fabric_id: int) -> list:
497
"""
498
Get all subscriptions for a specific device.
499
500
Parameters:
501
- node_id: Device node ID
502
- fabric_id: Fabric ID
503
504
Returns:
505
List of subscription information dictionaries
506
"""
507
...
508
509
def delete_subscription(self, subscription_id: int) -> bool:
510
"""
511
Delete subscription information.
512
513
Parameters:
514
- subscription_id: Subscription ID
515
516
Returns:
517
True if deletion successful
518
"""
519
...
520
521
def cleanup_orphaned_subscriptions(self) -> int:
522
"""
523
Remove subscriptions for non-existent devices.
524
525
Returns:
526
Number of subscriptions cleaned up
527
"""
528
...
529
```
530
531
## Usage Examples
532
533
### Basic Persistent Storage
534
535
```python
536
from chip.storage import PersistentStorage
537
538
# Initialize storage
539
storage = PersistentStorage("/var/lib/chip/storage")
540
541
# Store configuration data
542
config_data = b'{"setting1": "value1", "setting2": 42}'
543
success = storage.set("app_config", config_data)
544
print(f"Storage success: {success}")
545
546
# Retrieve data
547
retrieved_data = storage.get("app_config")
548
if retrieved_data:
549
print(f"Retrieved: {retrieved_data}")
550
551
# Check if key exists
552
if storage.exists("app_config"):
553
print("Configuration found")
554
555
# List all keys
556
all_keys = storage.keys()
557
print(f"All stored keys: {all_keys}")
558
559
# Get storage size
560
print(f"Total items: {storage.size()}")
561
562
# Force sync to disk
563
storage.sync()
564
565
# Clean up
566
storage.delete("app_config")
567
```
568
569
### Configuration Storage
570
571
```python
572
from chip.storage import PersistentStorage, ConfigurationStorage
573
574
# Initialize storage layers
575
storage = PersistentStorage("/var/lib/chip/config")
576
config_storage = ConfigurationStorage(storage)
577
578
# Store device configuration
579
device_config = {
580
"name": "Living Room Light",
581
"type": "dimmable_light",
582
"endpoints": [1],
583
"clusters": ["OnOff", "LevelControl", "ColorControl"],
584
"last_seen": "2024-09-10T13:30:00Z"
585
}
586
587
success = config_storage.set_device_config(node_id=1, config=device_config)
588
print(f"Device config stored: {success}")
589
590
# Store fabric configuration
591
fabric_config = {
592
"name": "Home Fabric",
593
"created": "2024-09-01T10:00:00Z",
594
"max_devices": 100,
595
"security_policy": "strict"
596
}
597
598
config_storage.set_fabric_config(fabric_id=1, config=fabric_config)
599
600
# Retrieve configurations
601
device_info = config_storage.get_device_config(node_id=1)
602
if device_info:
603
print(f"Device name: {device_info['name']}")
604
print(f"Device type: {device_info['type']}")
605
606
fabric_info = config_storage.get_fabric_config(fabric_id=1)
607
if fabric_info:
608
print(f"Fabric name: {fabric_info['name']}")
609
610
# List all devices and fabrics
611
devices = config_storage.list_devices()
612
fabrics = config_storage.list_fabrics()
613
print(f"Configured devices: {devices}")
614
print(f"Configured fabrics: {fabrics}")
615
```
616
617
### Credential Storage
618
619
```python
620
from chip.storage import PersistentStorage, CredentialStorage
621
622
# Initialize credential storage
623
storage = PersistentStorage("/var/lib/chip/credentials")
624
cred_storage = CredentialStorage(storage)
625
626
# Store fabric credentials (example with dummy data)
627
root_cert = b"-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----"
628
operational_cert = b"-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----"
629
private_key = b"-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----"
630
631
success = cred_storage.store_fabric_credentials(
632
fabric_id=1,
633
root_cert=root_cert,
634
operational_cert=operational_cert,
635
private_key=private_key
636
)
637
print(f"Fabric credentials stored: {success}")
638
639
# Store PAA certificates
640
paa_certs = [
641
b"-----BEGIN CERTIFICATE-----\nPAA1...\n-----END CERTIFICATE-----",
642
b"-----BEGIN CERTIFICATE-----\nPAA2...\n-----END CERTIFICATE-----"
643
]
644
cred_storage.store_paa_certificates(paa_certs)
645
646
# Retrieve credentials
647
fabric_creds = cred_storage.get_fabric_credentials(fabric_id=1)
648
if fabric_creds:
649
print("Fabric credentials found:")
650
print(f" Root cert length: {len(fabric_creds.get('root_cert', b''))}")
651
print(f" Operational cert available: {'operational_cert' in fabric_creds}")
652
print(f" Private key available: {'private_key' in fabric_creds}")
653
654
# Get PAA certificates
655
paa_list = cred_storage.get_paa_certificates()
656
print(f"Number of PAA certificates: {len(paa_list)}")
657
```
658
659
### Session and Subscription Storage
660
661
```python
662
from chip.storage import PersistentStorage, SessionStorage, SubscriptionStorage
663
import time
664
665
# Initialize storage
666
storage = PersistentStorage("/var/lib/chip/sessions")
667
session_storage = SessionStorage(storage)
668
subscription_storage = SubscriptionStorage(storage)
669
670
# Store session information
671
session_data = {
672
"session_id": "abc123",
673
"established": time.time(),
674
"last_activity": time.time(),
675
"encryption_key": "key_data_here",
676
"expires": time.time() + 3600 # 1 hour from now
677
}
678
679
session_storage.store_session(
680
node_id=1,
681
fabric_id=1,
682
session_data=session_data
683
)
684
685
# Store subscription information
686
subscription_data = {
687
"attributes": [
688
{"endpoint": 1, "cluster": "OnOff", "attribute": "OnOff"},
689
{"endpoint": 1, "cluster": "LevelControl", "attribute": "CurrentLevel"}
690
],
691
"min_interval": 1,
692
"max_interval": 10,
693
"created": time.time(),
694
"active": True
695
}
696
697
subscription_storage.store_subscription(
698
subscription_id=12345,
699
node_id=1,
700
fabric_id=1,
701
subscription_data=subscription_data
702
)
703
704
# Retrieve session
705
session_info = session_storage.get_session(node_id=1, fabric_id=1)
706
if session_info:
707
print(f"Session established: {session_info['established']}")
708
print(f"Session expires: {session_info['expires']}")
709
710
# Get subscriptions for device
711
device_subscriptions = subscription_storage.get_subscriptions_for_device(
712
node_id=1,
713
fabric_id=1
714
)
715
print(f"Device has {len(device_subscriptions)} subscriptions")
716
717
# Get active sessions
718
active_sessions = session_storage.get_active_sessions()
719
print(f"Active sessions: {active_sessions}")
720
721
# Cleanup expired sessions
722
cleaned_sessions = session_storage.cleanup_expired_sessions()
723
print(f"Cleaned up {cleaned_sessions} expired sessions")
724
```
725
726
### Integrated Storage Management
727
728
```python
729
from chip.storage import PersistentStorage, ConfigurationStorage, CredentialStorage
730
from chip.ChipDeviceCtrl import ChipDeviceController
731
732
# Initialize comprehensive storage system
733
base_storage = PersistentStorage("/var/lib/chip")
734
config_storage = ConfigurationStorage(base_storage)
735
cred_storage = CredentialStorage(base_storage)
736
737
# Initialize controller with storage
738
controller = ChipDeviceController(
739
controllerNodeId=12345,
740
persistentStoragePath="/var/lib/chip"
741
)
742
743
try:
744
# Commission a device and store its configuration
745
success = controller.CommissionOnNetwork(
746
nodeId=1,
747
setupPinCode=20202021
748
)
749
750
if success:
751
# Wait for commissioning to complete...
752
# Then store device configuration
753
device_config = {
754
"commissioned": time.time(),
755
"vendor_id": 0x1234,
756
"product_id": 0x5678,
757
"device_type": "light",
758
"endpoints": [1],
759
"clusters": ["OnOff", "LevelControl"]
760
}
761
762
config_storage.set_device_config(node_id=1, config=device_config)
763
764
# Store fabric information
765
fabric_config = {
766
"fabric_label": "My Smart Home",
767
"created": time.time(),
768
"devices_count": 1
769
}
770
771
config_storage.set_fabric_config(fabric_id=1, config=fabric_config)
772
773
print("Device commissioned and configuration stored")
774
775
# Later, retrieve device information
776
stored_config = config_storage.get_device_config(node_id=1)
777
if stored_config:
778
print(f"Device type: {stored_config['device_type']}")
779
print(f"Commissioned on: {stored_config['commissioned']}")
780
781
finally:
782
controller.Shutdown()
783
```