Quick Start Tutorial¶
This tutorial will get you up and running with pybragerone in just a few minutes.
Installation¶
Install from PyPI:
pip install pybragerone
Or install from TestPyPI for pre-release versions:
pip install -i https://test.pypi.org/simple/ pybragerone
Optional Extras¶
# CLI tools with rich formatting
pip install "pybragerone[cli]"
# Secure token storage
pip install "pybragerone[keyring]"
Basic Usage¶
Step 1: Login and Get Devices¶
Complete example: examples/basic_login.py
1 """Main function demonstrating basic login and device listing."""
2 # Get credentials from environment variables or use defaults
3 email = os.getenv("PYBO_EMAIL", "user@example.com")
4 password = os.getenv("PYBO_PASSWORD", "password")
5
6 # Create API client
7 client = BragerOneApiClient()
8
9 try:
10 # Login with credentials
11 print(f"Logging in as {email}...")
12 await client.ensure_auth(email, password)
13 print("✓ Login successful")
14
15 # Get available objects (heating systems)
16 objects = await client.get_objects()
17 print(f"\n✓ Found {len(objects)} heating system(s)")
18
19 # List each object with its modules
20 for obj in objects:
21 print(f"\n📦 Object: {obj.name}")
22 print(f" ID: {obj.id}")
23 print(f" Address: {obj.addressStreet or 'N/A'}, {obj.addressCity or 'N/A'}")
24
25 # Get modules for this object
26 modules = await client.get_modules(obj.id)
27 print(f" Modules: {len(modules)}")
28
29 for module in modules:
30 devid = module.devid or f"id:{module.id}"
31 version = module.moduleVersion or (module.gateway.version if module.gateway else None) or "unknown"
32 print(f" - {module.name} (devid: {devid}, version: {version})")
33 finally:
34 # Always close the client
35 await client.close()
36
Step 2: Read Parameters¶
Complete example: examples/read_parameters.py
1 object_id_env = os.getenv("PYBO_OBJECT_ID")
2
3 client = BragerOneApiClient()
4
5 try:
6 # Login
7 print(f"Logging in as {email}...")
8 await client.ensure_auth(email, password)
9 print("✓ Login successful")
10
11 # Get object ID (from env or first available)
12 if object_id_env:
13 object_id = int(object_id_env)
14 print(f"\n📦 Using object ID from PYBO_OBJECT_ID: {object_id}")
15 else:
16 objects = await client.get_objects()
17 if not objects:
18 print("❌ No objects found!")
19 return
20 object_id = objects[0].id
21 print(f"\n📦 Using first object: {objects[0].name} (ID: {object_id})")
22
23 # Get modules
24 modules = await client.get_modules(object_id)
25 print(f"✓ Found {len(modules)} module(s)")
26
27 # Get module device IDs
28 devids = [m.devid for m in modules if m.devid]
29 if not devids:
30 print("❌ No device IDs found in modules!")
31 return
32
33 print(f"✓ Device IDs: {', '.join(devids)}")
34
35 # Fetch parameters using prime endpoint
36 print(f"\n📊 Fetching parameters for devices: {', '.join(devids)}")
37 result = await client.modules_parameters_prime(devids, return_data=True)
38
39 # Result is tuple (status, data) when return_data=True
40 if isinstance(result, tuple):
41 status, data = result
42 else:
43 print("❌ Unexpected response format")
44 return
45
46 if status not in (200, 201):
47 print(f"❌ Failed to fetch parameters (status: {status})")
48 return
49
Step 3: Real-time Updates with Gateway¶
Complete example: examples/realtime_updates.py
1 object_id=object_id,
2 modules=modules,
3 )
4
5 # Create event subscriber task
6 async def monitor_updates() -> None:
7 """Subscribe to EventBus and print parameter updates."""
8 print("\n🔔 Monitoring parameter updates (Ctrl+C to stop)...\n")
9 update_count = 0
10
11 async for event in gateway.bus.subscribe():
12 update_count += 1
13
14 # Skip meta-only events (no value change)
15 if event.value is None:
16 continue
17
18 # Format parameter key
19 param_key = f"{event.pool}.{event.chan}{event.idx}"
20
21 # Display update with device ID
22 print(f"[{update_count:4d}] {event.devid:12} {param_key:15} = {event.value}")
23
24 # Start gateway
25 try:
Tip
Set environment variables for easy testing:
export PYBO_EMAIL="user@example.com"
export PYBO_PASSWORD="your-password"
export PYBO_OBJECT_ID="12345"
export PYBO_MODULES="MODULE1,MODULE2"
# Optional: select backend platform (default: bragerone)
export PYBO_PLATFORM="tisconnect"
Step 4: Using ParamStore¶
Complete example: examples/paramstore_usage.py
1 password=password,
2 object_id=object_id,
3 modules=modules,
4 )
5
6 # Create ParamStore in lightweight mode
7 pstore = ParamStore()
8
9 # Subscribe ParamStore to EventBus (background task)
10 store_task = asyncio.create_task(pstore.run_with_bus(gateway.bus))
11
12 try:
13 # Start gateway
14 await gateway.start()
15 print("✓ Gateway started")
16
17 # Wait for initial parameters to populate
18 await asyncio.sleep(2)
19
20 # Access parameters using flatten() method
21 print("\n📊 Sample parameters from ParamStore (lightweight mode):")
22 print("-" * 60)
23
24 # Get flattened view of all parameters
25 params = pstore.flatten()
26 params_list = list(params.items())[:10] # Show first 10
Note
ParamStore modes:
Lightweight mode (shown above): Fast key→value storage for runtime
Asset-aware mode: Rich metadata with i18n labels/units via
ParamResolver(use during HA config flow)
See Architecture Overview for details on when to use each mode.
Using the CLI¶
For quick testing and debugging, use the CLI tool:
# Interactive mode with guided login
pybragerone-cli --email user@example.com --password "***"
# Select backend platform (e.g. TiSConnect)
pybragerone-cli --platform tisconnect --email user@example.com --password "***"
# Enable debug logging
pybragerone-cli --email user@example.com --password "***" --debug
# Show raw WebSocket messages
pybragerone-cli --email user@example.com --password "***" --raw-ws
# Dump ParamStore to JSON files
pybragerone-cli --email user@example.com --password "***" --dump-store
Next Steps¶
See also
Core Components - Common patterns and workflows
Architecture Overview - Understand the architecture
API Reference - Complete API documentation
Pydantic Models Guide - Data models reference
Common Patterns¶
Config Flow (No WebSocket)
For Home Assistant config flow, you don’t need WebSocket:
# Just REST API is enough
client = BragerOneApiClient()
await client.ensure_auth(email, password)
try:
objects = await client.get_objects()
modules = await client.get_modules(object_id=objects[0].id)
devids = [str(m.devid or m.id) for m in modules if (m.devid or m.id) is not None]
# Enable asset-aware resolution for metadata
param_store = ParamStore()
resolver = ParamResolver.from_api(api=client, store=param_store, lang="en")
# Fetch initial data (REST prime)
status, payload = await client.modules_parameters_prime(devids, return_data=True)
if status in (200, 204) and isinstance(payload, dict):
param_store.ingest_prime_payload(payload)
label = await resolver.resolve_label("PARAM_0")
print(f"Example label: {label}")
finally:
await client.close()
Runtime (Lightweight Mode)
For runtime, use lightweight mode for best performance:
param_store = ParamStore() # runtime-light (storage-only)
asyncio.create_task(param_store.run_with_bus(gateway.bus))
# Subscribe to updates
async for event in gateway.bus.subscribe():
pass # ParamStore is updated by the background task
# Fast access
fam = param_store.get_family("P4", 1)
value = fam.value if fam else None
Troubleshooting¶
Connection Issues
If you can’t connect, check:
Valid credentials
Internet connection to BragerOne cloud
Device is online and accessible
No Updates
If WebSocket connects but no updates arrive:
Check that you called
gateway.start()(not just connect)Verify modules are correct
Try fetching parameters manually first
ImportError
If you get import errors:
# Ensure you installed the package
pip install pybragerone
# For CLI features
pip install "pybragerone[cli]"
Need Help?¶
GitHub Issues: https://github.com/marpi82/py-bragerone/issues
GitHub Releases: https://github.com/marpi82/py-bragerone/releases
Documentation: https://marpi82.github.io/py-bragerone/