### Real-World Example: Home Energy Monitor Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/quickstart.md A comprehensive example demonstrating how to build a home energy monitor using the victron-ble library. ```python import asyncio import json from datetime import datetime from victron_ble.scanner import Scanner, DeviceDataEncoder class EnergyMonitor: def __init__(self, device_keys: dict): self.scanner = Scanner(device_keys=device_keys, indent=None) self.readings = {} async def start(self): """Start monitoring all configured devices.""" await self.scanner.start() def store_reading(self, address: str, data: dict): """Store latest reading with timestamp.""" self.readings[address] = { "timestamp": datetime.now().isoformat(), **data } def get_system_status(self) -> dict: """Get current system status.""" total_power = 0 total_voltage = 0 for addr, reading in self.readings.items(): if "payload" in reading: payload = reading["payload"] if "power" in payload: total_power += payload.get("power", 0) if "voltage" in payload: total_voltage += payload.get("voltage", 0) return { "total_power": total_power, "devices": len(self.readings), "last_update": datetime.now().isoformat() } # Usage if __name__ == "__main__": keys = { "AA:BB:CC:DD:EE:FF": "0df4d0395b7d1a876c0c33ecb9e70dcd", "11:22:33:44:55:66": "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4" } monitor = EnergyMonitor(keys) asyncio.run(monitor.start()) ``` -------------------------------- ### Error Handling Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/quickstart.md Example demonstrating how to handle potential exceptions during device parsing. ```python from victron_ble.exceptions import ( AdvertisementKeyMismatchError, AdvertisementKeyMissingError, UnknownDeviceError ) try: device_class = detect_device_type(raw_data) if not device_class: raise UnknownDeviceError("Device type not supported") parser = device_class(encryption_key) data = parser.parse(raw_data) except AdvertisementKeyMismatchError: print("Wrong encryption key for this device") print("Verify the key from Victron Connect app") except UnknownDeviceError: print("Device type not yet supported") print("Submit raw data via: victron-ble dump ADDRESS") except IndexError: print("Advertisement data is malformed or too short") ``` -------------------------------- ### Measurements Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/quickstart.md Basic example of accessing common measurements from a device. ```python battery_voltage = data.get_battery_voltage() # Volts battery_current = data.get_battery_charging_current() # Amps solar_power = data.get_solar_power() # Watts yield_today = data.get_yield_today() # Watt-hours ``` -------------------------------- ### Try CLI Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/quickstart.md Example of using the victron-ble command-line interface to read device data. ```bash victron-ble read "ADDRESS@KEY" ``` -------------------------------- ### Using the Scanner Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/quickstart.md Example of using the Scanner class for asynchronous BLE scanning. ```python import asyncio from victron_ble.scanner import Scanner async def main(): # Map device addresses to encryption keys device_keys = { "AA:BB:CC:DD:EE:FF": "0df4d0395b7d1a876c0c33ecb9e70dcd", "11:22:33:44:55:66": "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4" } # Create scanner scanner = Scanner(device_keys=device_keys, indent=2) # Start scanning (runs indefinitely) await scanner.start() asyncio.run(main()) ``` -------------------------------- ### Data Access Patterns for Solar Chargers Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/quickstart.md Example of accessing charge state and error information for Solar Chargers. ```python from victron_ble.devices import SolarCharger parser = SolarCharger(key) data = parser.parse(raw_data) # State state = data.get_charge_state() # OperationMode enum error = data.get_charger_error() # ChargerError enum or None ``` -------------------------------- ### Data Access Patterns for Battery Monitors Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/quickstart.md Example of accessing core measurements and auxiliary data for Battery Monitors. ```python from victron_ble.devices import BatteryMonitor parser = BatteryMonitor(key) data = parser.parse(raw_data) # Core measurements voltage = data.get_voltage() # Volts current = data.get_current() # Amps (+ charging, - discharging) soc = data.get_soc() # Percent 0-100 consumed_ah = data.get_consumed_ah() # Amp-hours # Auxiliary input (depends on configuration) aux_mode = data.get_aux_mode() # Enum: TEMPERATURE, STARTER_VOLTAGE, etc. temperature = data.get_temperature() # Celsius (if aux is TEMPERATURE) starter_voltage = data.get_starter_voltage() # Volts (if aux is STARTER_VOLTAGE) # Status alarm = data.get_alarm() # AlarmReason enum remaining_mins = data.get_remaining_mins() # Minutes of battery life ``` -------------------------------- ### Discover Command Usage Example Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/cli.md A usage example for the victron-ble discover command. ```bash $ victron-ble discover INFO:victron_ble.scanner:Scanning for Victron devices... BLEDevice(addr=AA:BB:CC:DD:EE:FF, name=SmartShunt HT4531A246S, ...) BLEDevice(addr=11:22:33:44:55:66, name=Blue Smart Charger 12V/15A, ...) # Continue until Ctrl+C ``` -------------------------------- ### Read Command Usage Example - Multiple Devices Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/cli.md Usage example for reading multiple devices. ```bash victron-ble read \ "AA:BB:CC:DD:EE:FF@0df4d0395b7d1a876c0c33ecb9e70dcd" \ "11:22:33:44:55:66@a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4" ``` -------------------------------- ### Inverter Measurements Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/quickstart.md Example of parsing data specifically for an Inverter device. ```python from victron_ble.devices import Inverter parser = Inverter(key) data = parser.parse(raw_data) # State state = data.get_device_state() # OperationMode alarm = data.get_alarm() # AlarmReason # Input (battery) battery_voltage = data.get_battery_voltage() # Volts # Output (AC) ac_voltage = data.get_ac_voltage() # Volts ac_current = data.get_ac_current() # Amps ac_power = data.get_ac_apparent_power() # Volt-amps ``` -------------------------------- ### Basic Library Usage Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/quickstart.md Demonstrates the basic pattern for using the victron-ble library to parse advertisement data. ```python from victron_ble.devices import detect_device_type # 1. Get raw BLE advertisement data (from your BLE scanner) raw_data = bytes.fromhex("100289a302413bafd03bb245e131ae926267f6fd0b59e0") # 2. Detect device type device_class = detect_device_type(raw_data) if not device_class: raise ValueError("Unknown device type") # 3. Create parser with encryption key key = "0df4d0395b7d1a876c0c33ecb9e70dcd" parser = device_class(key) # 4. Parse advertisement parsed_data = parser.parse(raw_data) # 5. Access measurements print(f"Voltage: {parsed_data.get_voltage()}V") print(f"Current: {parsed_data.get_current()}A") print(f"State of Charge: {parsed_data.get_soc()}%") ``` -------------------------------- ### Read Command Usage Example - Single Device Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/cli.md Usage example for reading a single device. ```bash victron-ble read "AA:BB:CC:DD:EE:FF@0df4d0395b7d1a876c0c33ecb9e70dcd" ``` -------------------------------- ### BaseScanner start Method Example Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/scanner.md Example of how to start the BaseScanner. ```python import asyncio from victron_ble.scanner import Scanner async def main(): scanner = Scanner(device_keys={"address1": "key1"}) await scanner.start() # Scanner runs indefinitely until stop() is called asyncio.run(main()) ``` -------------------------------- ### Install victron_ble Source: https://github.com/keshavdv/victron-ble/blob/main/README.md Install the victron_ble library using pip. ```bash pip install victron_ble ``` -------------------------------- ### Read Command Usage Example - Verbose Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/cli.md Usage example for reading a device with verbose logging. ```bash victron-ble -v read "AA:BB:CC:DD:EE:FF@0df4d0395b7d1a876c0c33ecb9e70dcd" ``` -------------------------------- ### Dump Command Usage Example - Basic Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/cli.md Basic usage example for the victron-ble dump command. ```bash victron-ble dump "AA:BB:CC:DD:EE:FF" ``` -------------------------------- ### Device Detection Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/quickstart.md Example of using the detect_device_type function to identify the device class. ```python from victron_ble.devices import detect_device_type # Returns appropriate parser class or None device_class = detect_device_type(raw_data) if device_class is BatteryMonitor: # Device is a battery monitor elif device_class is SolarCharger: # Device is a solar charger ``` -------------------------------- ### Dump Command Usage Example - Verbose Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/cli.md Usage example for the dump command with verbose logging. ```bash victron-ble -v dump "AA:BB:CC:DD:EE:FF" ``` -------------------------------- ### Project initialization example Source: https://github.com/keshavdv/victron-ble/blob/main/ABOUT_THIS_TEMPLATE.md Shows how to initialize the project with a specific application template, like Flask. ```bash $ make init Which template do you want to apply? [flask, fastapi, click, typer]? > flask Generating a new project with Flask ... ``` -------------------------------- ### Read Command Usage Example - Capture to File Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/cli.md Usage example for capturing read command output to a file. ```bash victron-ble read "AA:BB:CC:DD:EE:FF@0df4d0395b7d1a876c0c33ecb9e70dcd" > device_log.jsonl ``` -------------------------------- ### Example Usage of kelvin_to_celsius Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/device-base.md Shows an example of converting Kelvin to Celsius using the helper function. ```python from victron_ble.devices.base import kelvin_to_celsius temp_c = kelvin_to_celsius(298.15) # Returns 25.0 ``` -------------------------------- ### Example of reading version from a static file Source: https://github.com/keshavdv/victron-ble/blob/main/ABOUT_THIS_TEMPLATE.md Demonstrates how to read the project version from a plain text file. ```bash cat victron_ble/VERSION ``` -------------------------------- ### Usage Example Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/ac-charger.md Example of how to use the AcCharger parser to get charging data. ```python from victron_ble.devices import AcCharger parser = AcCharger("0df4d0395b7d1a876c0c33ecb9e70dcd") data = parser.parse(raw_advertisement_bytes) state = data.get_charge_state() print(f"Charging state: {state.name if state else 'Unknown'}") # Check three-phase voltages for phase in [1, 2, 3]: method_name = f"get_output_voltage{phase}" voltage = getattr(data, method_name)() current = getattr(data, f"get_output_current{phase}")() print(f"Phase {phase}: {voltage}V @ {current}A") print(f"Temperature: {data.get_temperature()}°C") print(f"AC Input: {data.get_ac_current()}A") ``` -------------------------------- ### Inverter Usage Example Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/inverter.md Example demonstrating how to use the Inverter parser and access its data. ```python from victron_ble.devices import Inverter parser = Inverter("0df4d0395b7d1a876c0c33ecb9e70dcd") data = parser.parse(raw_advertisement_bytes) state = data.get_device_state() battery_voltage = data.get_battery_voltage() ac_voltage = data.get_ac_voltage() ac_current = data.get_ac_current() ac_power = data.get_ac_apparent_power() print(f"State: {state.name if state else 'Unknown'}") print(f"Battery: {battery_voltage}V") print(f"AC Output: {ac_voltage}V @ {ac_current}A ({ac_power}VA)") ``` -------------------------------- ### Dump Command Usage Example - Save to File Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/cli.md Usage example for saving dump command output to a file for support. ```bash victron-ble dump "AA:BB:CC:DD:EE:FF" > advertisement_samples.txt # Collect ~10-20 samples while device state changes ``` -------------------------------- ### Install the project in develop mode Source: https://github.com/keshavdv/victron-ble/blob/main/CONTRIBUTING.md Command to install the project in develop mode using make. ```bash make install ``` -------------------------------- ### Get Device Keys on macOS Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/quickstart.md Command to retrieve device keys from the Victron Connect SQLite database on macOS. ```bash sqlite3 ~/Library/Containers/com.victronenergy.victronconnect.mac/Data/Library/Application\ Support/Victron\ Energy/Victron\ Connect/d25b6546b47ebb21a04ff86a2c4fbb76.sqlite \ 'select address,advertisementKey from advertisementKeys' ``` -------------------------------- ### DiscoveryScanner Usage Example Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/scanner.md Example of how to use the DiscoveryScanner. ```python import asyncio from victron_ble.scanner import DiscoveryScanner async def main(): scanner = DiscoveryScanner() await scanner.start() # Prints: # BLEDevice(addr=AA:BB:CC:DD:EE:FF, name=SmartShunt HT4531A246S, ...) # BLEDevice(addr=11:22:33:44:55:66, name=Blue Smart Charger 12V/15A, ...) asyncio.run(main()) ``` -------------------------------- ### AdvertisementContainer Example Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/device-base.md Example of parsing advertisement container and accessing its fields. ```python from victron_ble.devices.base import Device device = SomeDeviceType(key) container = device.parse_container(raw_data) print(f"Model ID: {hex(container.model_id)}") print(f"IV: {hex(container.iv)}") ``` -------------------------------- ### DeviceData.get_model_name Example Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/device-base.md Example of getting the model name from parsed data. ```python parsed_data = parser.parse(raw_data) print(parsed_data.get_model_name()) # "SmartShunt HT4531A246S" ``` -------------------------------- ### Usage Example Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/scanner.md Example of how to use the DebugScanner to start scanning and receive advertisement data. ```python import asyncio from victron_ble.scanner import DebugScanner async def main(): scanner = DebugScanner("AA:BB:CC:DD:EE:FF") await scanner.start() # Prints: # 1671843194.0534039 : 100289a302413bafd03bb245e131ae926267f6fd0b59e0 # 1671843194.682535 : 100289a302423baf58a1546e5262dcdf0ef642f353ed65 asyncio.run(main()) ``` -------------------------------- ### Device.get_model_id Example Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/device-base.md Example of getting the model ID from raw data. ```python model_id = parser.get_model_id(raw_data) # Use model_id to identify exact device model ``` -------------------------------- ### Discover Command Output Format Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/cli.md Example output format for the victron-ble discover command. ```text BLEDevice(addr=AA:BB:CC:DD:EE:FF, name=SmartShunt HT4531A246S, rssi=-79, ...) BLEDevice(addr=11:22:33:44:55:66, name=Blue Smart Charger 12V/15A, rssi=-65, ...) ``` -------------------------------- ### BatteryMonitor Usage Example Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/battery-monitor.md A comprehensive example showing initialization, parsing, accessing various data fields, checking alarm states, and retrieving the model name. ```python from victron_ble.devices import BatteryMonitor # Initialize and parse key = "0df4d0395b7d1a876c0c33ecb9e70dcd" parser = BatteryMonitor(key) data = parser.parse(raw_advertisement_bytes) # Access parsed fields voltage = data.get_voltage() # e.g., 12.87 current = data.get_current() # e.g., 5.3 soc = data.get_soc() # e.g., 87.5 temp = data.get_temperature() # e.g., 25.0 (if aux mode is TEMPERATURE) # Check alarm state alarm = data.get_alarm() if alarm.value > 0: print(f"Battery alarm: {alarm.name}") # Get model name print(data.get_model_name()) # e.g., "BMV-712 Smart" ``` -------------------------------- ### BatteryMonitor Example Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/device-base.md Example of initializing a BatteryMonitor parser and parsing raw BLE data. ```python from victron_ble.devices import BatteryMonitor # Initialize parser with encryption key key = "0df4d0395b7d1a876c0c33ecb9e70dcd" parser = BatteryMonitor(key) # Parse raw BLE advertisement data raw_data = bytes.fromhex("100289a302413bafd03bb245e131ae926267f6fd0b59e0") parsed = parser.parse(raw_data) # Access parsed fields print(f"Voltage: {parsed.get_voltage()}V") print(f"Current: {parsed.get_current()}A") print(f"SOC: {parsed.get_soc()}%") ``` -------------------------------- ### Read Command Error Handling - Unknown Device Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/cli.md Example error message for an unknown device and its solution. ```text ERROR:victron_ble.scanner:Could not identify device type - Solution: Device type may not be supported; submit issue with raw data ``` -------------------------------- ### Scanner Usage Example Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/scanner.md Example of how to use the Scanner class with device keys. ```python import asyncio from victron_ble.scanner import Scanner async def main(): # Map device addresses to encryption keys device_keys = { "AA:BB:CC:DD:EE:FF": "0df4d0395b7d1a876c0c33ecb9e70dcd", "11:22:33:44:55:66": "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4" } # Create scanner with key mapping scanner = Scanner(device_keys=device_keys, indent=2) await scanner.start() asyncio.run(main()) ``` -------------------------------- ### Dump Command Output Format Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/cli.md Example output format for the victron-ble dump command. ```text 1671843194.0534039 : 100289a302413bafd03bb245e131ae926267f6fd0b59e0 1671843194.682535 : 100289a302423baf58a1546e5262dcdf0ef642f353ed65 1671843197.676384 : 100289a302453baf804707549cffb2ab970c981ae897b6 ``` -------------------------------- ### Scanner Initialization with Device Keys Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/errors.md Example of initializing a Scanner with a mapping of device addresses to encryption keys. ```python import asyncio from victron_ble.scanner import Scanner from victron_ble.exceptions import AdvertisementKeyMissingError async def main(): scanner = Scanner(device_keys={ "AA:BB:CC:DD:EE:FF": "0df4d0395b7d1a876c0c33ecb9e70dcd" }) await scanner.start() # If advertisement from unmapped address arrives: # 2024-01-15 10:30:45 - No key available for 11:22:33:44:55:66 # (logged at WARNING level, scanning continues) ``` -------------------------------- ### Scanner start Method Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/scanner.md Start scanning and printing parsed device data as JSON. Logs which devices are being monitored. ```python async def start() -> None ``` -------------------------------- ### Read Command Error Handling - Missing Key Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/cli.md Example error message for a missing encryption key and its solution. ```text ERROR:victron_ble.scanner:No key available for aa:bb:cc:dd:ee:ff - Solution: Add the device address and encryption key to the command ``` -------------------------------- ### Example Usage of BitReader Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/device-base.md Demonstrates how to use the BitReader to read various fields from decrypted data. ```python from victron_ble.devices.base import BitReader decrypted = bytes.fromhex("...") reader = BitReader(decrypted) # Read various fields remaining_mins = reader.read_unsigned_int(16) voltage = reader.read_signed_int(16) alarm = reader.read_unsigned_int(16) ``` -------------------------------- ### Read Command Error Handling - Key Mismatch Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/cli.md Example error message for an incorrect encryption key and its solution. ```text ERROR:victron_ble.scanner:Incorrect advertisement key - Solution: Verify the key from Victron Connect app is correct for this device ``` -------------------------------- ### Verbose Option Usage Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/cli.md Usage examples for the -v or --verbose option. ```bash victron-ble -v discover victron-ble --verbose read "AA:BB:CC:DD:EE:FF@0df4d0395b7d1a876c0c33ecb9e70dcd" ``` -------------------------------- ### Read Command Output Format Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/cli.md Example JSON output format for the victron-ble read command. ```json { "name": "SmartShunt HT4531A246S", "address": "AA:BB:CC:DD:EE:FF", "rssi": -79, "payload": { "aux_mode": "temperature", "consumed_ah": 0.0, "current": 0.0, "high_starter_battery_voltage_alarm": false, "high_temperature_alarm": false, "high_voltage_alarm": false, "low_soc_alarm": false, "low_starter_battery_voltage_alarm": false, "low_temperature_alarm": false, "low_voltage_alarm": false, "midpoint_deviation_alarm": false, "remaining_mins": 65535, "soc": 100.0, "temperature": 25.3, "voltage": 12.87 } } ``` -------------------------------- ### Consume as a library Source: https://github.com/keshavdv/victron-ble/blob/main/README.md Example of how to import and use the victron-ble library to detect device type and parse BLE advertisement data. ```python from victron_ble.devices import detect_device_type data = parser = detect_device_type(data) parsed_data = parser().parse() ``` -------------------------------- ### Catching AdvertisementKeyMismatchError Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/errors.md Example of how to catch AdvertisementKeyMismatchError when parsing device data. ```python from victron_ble.devices import BatteryMonitor from victron_ble.exceptions import AdvertisementKeyMismatchError key = "wrongkey123456789abcdef" parser = BatteryMonitor(key) try: data = parser.parse(raw_advertisement) except AdvertisementKeyMismatchError as e: print(f"Encryption key error: {e}") # Verify the correct key from Victron Connect app ``` -------------------------------- ### Workflow 2: Support New Device Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/cli.md Steps to collect raw advertisement samples for a new device type to aid in support requests. ```bash # Step 1: Dump raw data victron-ble dump "AA:BB:CC:DD:EE:FF" > samples.txt # Ctrl+C after collecting ~20 samples over 1-2 minutes # Step 2: Note device name from discover victron-ble discover # Shows: SmartShunt XYZ123 # Step 3: Create GitHub issue with: # - Device name and model # - Samples from dump # - Screenshots from official app showing current values ``` -------------------------------- ### Workflow 1: Discover Then Read Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/cli.md Command-line steps to first discover Bluetooth devices and then read specific data from a device using its address and key. ```bash # Step 1: Discover devices victron-ble discover # Step 2: Note the address and get key from Victron Connect app # Output shows: BLEDevice(addr=AA:BB:CC:DD:EE:FF, name=SmartShunt HT4531A246S, ...) # Step 3: Read with key victron-ble read "AA:BB:CC:DD:EE:FF@0df4d0395b7d1a876c0c33ecb9e70dcd" ``` -------------------------------- ### Usage Example Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/device-detection.md Demonstrates how to use the `detect_device_type` function to parse raw advertisement data and instantiate the correct device parser. ```python from victron_ble.devices import detect_device_type # Get raw advertisement data from BLE scanning raw_data = bytes.fromhex("100289a302413bafd03bb245e131ae926267f6fd0b59e0") # Detect device type device_class = detect_device_type(raw_data) if device_class is None: print("Unknown device type") else: # Use detected device class with encryption key key = "0df4d0395b7d1a876c0c33ecb9e70dcd" parser = device_class(key) parsed_data = parser.parse(raw_data) print(f"Device: {parsed_data.get_model_name()}") ``` -------------------------------- ### BatteryMonitor Constructor and Parsing Example Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/battery-monitor.md Demonstrates how to initialize the BatteryMonitor parser and parse raw BLE advertisement data. ```python from victron_ble.devices import BatteryMonitor parser = BatteryMonitor("0df4d0395b7d1a876c0c33ecb9e70dcd") parsed_data = parser.parse(raw_ble_advertisement_data) ``` -------------------------------- ### Build the docs locally Source: https://github.com/keshavdv/victron-ble/blob/main/CONTRIBUTING.md Command to build the documentation locally using make. ```bash make docs ``` -------------------------------- ### Global Options Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/cli.md Global options for the victron-ble command. ```bash victron-ble [OPTIONS] COMMAND [ARGS] ``` -------------------------------- ### DeviceDataEncoder Usage Example Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/scanner.md Example of manually serializing DeviceData objects to JSON using DeviceDataEncoder. ```python import json from victron_ble.scanner import DeviceDataEncoder # When using Scanner class, this is handled automatically # For manual JSON serialization: from victron_ble.devices import BatteryMonitor parser = BatteryMonitor(key) data = parser.parse(raw_data) json_str = json.dumps(data, cls=DeviceDataEncoder, indent=2) print(json_str) ``` -------------------------------- ### SmartBatteryProtect get_off_reason Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/additional-devices.md Get reason for shutdown. ```python def get_off_reason(self) -> OffReason: # Get reason for shutdown. ``` -------------------------------- ### SmartBatteryProtect get_error_code Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/additional-devices.md Get error code if any. ```python def get_error_code(self) -> Optional[ChargerError]: # Get error code if any. ``` -------------------------------- ### Run the tests Source: https://github.com/keshavdv/victron-ble/blob/main/CONTRIBUTING.md Command to run tests using make. ```bash make test ``` -------------------------------- ### DcEnergyMeter get_voltage Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/additional-devices.md Get voltage in volts. ```python def get_voltage(self) -> Optional[float]: # Get voltage in volts. ``` -------------------------------- ### InverterData get_alarm Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/inverter.md Get the current alarm condition, if any. ```python def get_alarm(self) -> Optional[AlarmReason] ``` -------------------------------- ### Enter the directory Source: https://github.com/keshavdv/victron-ble/blob/main/CONTRIBUTING.md Command to navigate into the cloned repository directory. ```bash cd victron-ble ``` -------------------------------- ### SmartLithium get_battery_temperature Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/additional-devices.md Get pack temperature in Celsius. ```python def get_battery_temperature(self) -> Optional[int]: # Get pack temperature in Celsius. ``` -------------------------------- ### Run the linter Source: https://github.com/keshavdv/victron-ble/blob/main/CONTRIBUTING.md Command to run the linter using make. ```bash make lint ``` -------------------------------- ### SmartLithium get_battery_voltage Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/additional-devices.md Get pack voltage in volts. ```python def get_battery_voltage(self) -> Optional[float]: # Get pack voltage in volts. ``` -------------------------------- ### SmartBatteryProtect get_warning_reason Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/additional-devices.md Get warning condition code. ```python def get_warning_reason(self) -> AlarmReason: # Get warning condition code. ``` -------------------------------- ### victron-ble discover help Source: https://github.com/keshavdv/victron-ble/blob/main/docs/index.md Help output for the 'victron-ble discover' command. ```bash ❯ victron-ble discover --help ⏎ ✹ Usage: victron-ble discover [OPTIONS] Discover Victron devices with Instant Readout Options: --help Show this message and exit. ``` -------------------------------- ### SmartBatteryProtect get_alarm_reason Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/additional-devices.md Get alarm condition code. ```python def get_alarm_reason(self) -> AlarmReason: # Get alarm condition code. ``` -------------------------------- ### SolarCharger Initialization and Parsing Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/solar-charger.md Example of how to initialize the SolarCharger parser and parse raw BLE advertisement data. ```python from victron_ble.devices import SolarCharger parser = SolarCharger("0df4d0395b7d1a876c0c33ecb9e70dcd") parsed_data = parser.parse(raw_ble_advertisement_data) ``` -------------------------------- ### SmartBatteryProtect get_output_state Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/additional-devices.md Get output state (SHUTDOWN, ON, or OFF). ```python def get_output_state(self) -> Optional[OutputState]: # Get output state (SHUTDOWN, ON, or OFF). # Returns: OutputState - Enum ``` -------------------------------- ### SmartBatteryProtect get_device_state Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/additional-devices.md Get device operating state. ```python def get_device_state(self) -> Optional[OperationMode]: # Get device operating state. ``` -------------------------------- ### DcEnergyMeter get_aux_mode Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/additional-devices.md Get auxiliary input mode. ```python def get_aux_mode(self) -> AuxMode: # Get auxiliary input mode. ``` -------------------------------- ### DcDcConverter get_off_reason Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/additional-devices.md Get reason code for why output is off. ```python def get_off_reason(self) -> OffReason: # Get reason code for why output is off. # Returns: OffReason - Enum indicating shutdown reason ``` -------------------------------- ### Discover Command Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/cli.md Command to discover all available Victron devices with Instant Readout enabled. ```bash victron-ble discover ``` -------------------------------- ### DcDcConverter get_output_voltage Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/additional-devices.md Get output voltage in volts. ```python def get_output_voltage(self) -> Optional[float]: # Get output voltage in volts. ``` -------------------------------- ### DcDcConverter get_input_voltage Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/additional-devices.md Get input voltage in volts. ```python def get_input_voltage(self) -> Optional[float]: # Get input voltage in volts. ``` -------------------------------- ### Create a virtual environment Source: https://github.com/keshavdv/victron-ble/blob/main/CONTRIBUTING.md Command to create a virtual environment using make. ```bash make virtualenv ``` -------------------------------- ### DcDcConverter get_charger_error Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/additional-devices.md Get any active error code. ```python def get_charger_error(self) -> Optional[ChargerError]: # Get any active error code. ``` -------------------------------- ### DcDcConverter get_charge_state Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/additional-devices.md Get converter operating state. ```python def get_charge_state(self) -> Optional[OperationMode]: # Get converter operating state. ``` -------------------------------- ### BatterySense get_voltage Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/additional-devices.md Get battery voltage in volts. ```python def get_voltage(self) -> Optional[float]: # Get battery voltage in volts. # Returns: Optional[float] - Voltage or None if unavailable ``` -------------------------------- ### BatterySense get_temperature Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/additional-devices.md Get ambient temperature in Celsius. ```python def get_temperature(self) -> float: # Get ambient temperature in Celsius. # Returns: float - Temperature (always returns Celsius, never None) ``` -------------------------------- ### InverterData get_ac_current Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/inverter.md Get the AC output current in amperes. ```python def get_ac_current(self) -> Optional[float] ``` -------------------------------- ### Makefile utilities Source: https://github.com/keshavdv/victron-ble/blob/main/CONTRIBUTING.md List of available targets in the Makefile. ```bash ❯ make Usage: make Targets: help: ## Show the help. install: ## Install the project in dev mode. fmt: ## Format code using black & isort. lint: ## Run pep8, black, mypy linters. test: lint ## Run tests and generate coverage report. watch: ## Run tests on every change. clean: ## Clean unused files. virtualenv: ## Create a virtual environment. release: ## Create a new tag for release. docs: ## Build the documentation. switch-to-poetry: ## Switch to poetry package manager. init: ## Initialize the project based on an application template. ``` -------------------------------- ### InverterData get_ac_voltage Source: https://github.com/keshavdv/victron-ble/blob/main/_autodocs/api-reference/inverter.md Get the AC output voltage in volts. ```python def get_ac_voltage(self) -> Optional[float] ``` -------------------------------- ### Project Structure Source: https://github.com/keshavdv/victron-ble/blob/main/ABOUT_THIS_TEMPLATE.md This is the directory structure of the template. ```text ├── Containerfile # The file to build a container using buildah or docker ├── CONTRIBUTING.md # Onboarding instructions for new contributors ├── docs # Documentation site (add more .md files here) │   └── index.md # The index page for the docs site ├── .github # Github metadata for repository │   ├── release_message.sh # A script to generate a release message │   └── workflows # The CI pipeline for Github Actions ├── .gitignore # A list of files to ignore when pushing to Github ├── HISTORY.md # Auto generated list of changes to the project ├── LICENSE # The license for the project ├── Makefile # A collection of utilities to manage the project ├── MANIFEST.in # A list of files to include in a package ├── mkdocs.yml # Configuration for documentation site ├── victron_ble # The main python package for the project │   ├── base.py # The base module for the project │   ├── __init__.py # This tells Python that this is a package │   ├── __main__.py # The entry point for the project │   └── VERSION # The version for the project is kept in a static file ├── README.md # The main readme for the project ├── setup.py # The setup.py file for installing and packaging the project ├── requirements.txt # An empty file to hold the requirements for the project ├── requirements-test.txt # List of requirements for testing and devlopment ├── setup.py # The setup.py file for installing and packaging the project └── tests # Unit tests for the project (add mote tests files here) ├── conftest.py # Configuration, hooks and fixtures for pytest ├── __init__.py # This tells Python that this is a test package └── test_base.py # The base test case for the project ```