Skip to content

Models

Data models for BSB-LAN API responses.

Core types

EntityInfo

bsblan.EntityInfo

Bases: BaseModel, Generic[T]

BSB-LAN parameter info with automatic type conversion.

This object holds info about specific objects and handles automatic type conversion based on data_type and unit.

The generic parameter T indicates the expected value type after conversion:

  • EntityInfo[float] for temperature / numeric sensor values
  • EntityInfo[int] for enums, weekdays and plain integers
  • EntityInfo[time] for HH:MM time values
  • EntityInfo[str] for string / datetime values

When the device returns "---" or "None" (sensor not in use, per BSB-LAN's replaceDisabled setting), value is set to None.

Attributes:

Name Type Description
name str

Name attribute.

value T | None

Converted value, or None when sensor/parameter is inactive.

unit str

Unit of measurement.

desc str

Description of the entity.

data_type int

Type of data (see DataType enum).

error int

Error code (0 for no error).

readonly int

Whether the value is read-only.

readwrite int

Permission code: 0=read/write, 1=read-only, 2=write-only.

precision float | None

Optional precision for numeric values.

data_type_name str

BSB-LAN data type name (e.g., "TEMP", "ENUM").

data_type_family str

BSB-LAN data type family (e.g., "VALS", "ENUM").

read_write_permission property

read_write_permission: bool | None

Return explicit permission without treating absent default zeros as proof.

enum_description property

enum_description: str | None

Get the description for ENUM values.

Returns:

Type Description
str | None

str | None: The description of the ENUM value, or None.

suggested_device_class property

suggested_device_class: str | None

Suggest HA SensorDeviceClass based on unit and data type.

Only PLAIN_NUMBER data types are considered sensor-like values. Returns None for ENUM, TIME, WEEKDAY, STRING, and other non-numeric types even if they carry a unit.

Returns:

Type Description
str | None

str | None: The suggested HA device class (e.g., "temperature", "energy", "power"), or None if no mapping exists or the data type is not numeric.

suggested_state_class property

suggested_state_class: str | None

Suggest HA SensorStateClass based on unit and data type.

Only PLAIN_NUMBER data types are considered sensor-like values. Returns None for ENUM, TIME, WEEKDAY, STRING, and other non-numeric types even if they carry a unit.

Energy counters (kWh, MWh, Wh) are mapped to "total_increasing", while other numeric measurements use "measurement".

Returns:

Type Description
str | None

str | None: The suggested HA state class (e.g., "measurement", "total_increasing"), or None if the data type is not numeric or no mapping exists.

convert_raw_value classmethod

convert_raw_value(data: dict[str, Any]) -> dict[str, Any]

Convert raw string values before pydantic validates types.

BSB-LAN always sends values as strings. This validator converts them to the correct Python type (float, int, time) before pydantic's type checking runs.

Some STRING-type parameters (e.g. "7968 kWh") embed a numeric value with a unit suffix. When the unit field is empty and the value matches <number> <known-unit>, the numeric part is extracted and the unit field is populated automatically.

Source code in src/bsblan/models.py
@model_validator(mode="before")
@classmethod
def convert_raw_value(cls, data: dict[str, Any]) -> dict[str, Any]:
    """Convert raw string values before pydantic validates types.

    BSB-LAN always sends values as strings. This validator converts
    them to the correct Python type (float, int, time) before
    pydantic's type checking runs.

    Some STRING-type parameters (e.g. "7968 kWh") embed a numeric
    value with a unit suffix.  When the ``unit`` field is empty and
    the value matches ``<number> <known-unit>``, the numeric part is
    extracted and the ``unit`` field is populated automatically.
    """
    raw_value = data.get("value")
    # Resolve data_type from either alias or field name
    data_type = data.get("dataType", data.get("data_type", 0))
    unit = data.get("unit", "")

    data["value"] = _convert_bsblan_value(raw_value, data_type, unit)

    # Handle STRING values with embedded units (e.g. "7968 kWh")
    converted = data["value"]
    if isinstance(converted, str) and not unit and data_type == DataType.STRING:
        match = re.match(r"^(\d+(?:\.\d+)?)\s+(\S+)$", converted)
        if match and match.group(2) in UNIT_DEVICE_CLASS_MAP:
            num_str = match.group(1)
            data["value"] = float(num_str) if "." in num_str else int(num_str)
            data["unit"] = match.group(2)

    return data

read_write_permission distinguishes explicit readable/writable (True), denied or write-only (False), and absent permission metadata (None). Firmware readwrite codes are 0=read/write, 1=read-only, 2=write-only—not booleans. Missing fields retain their legacy numeric defaults without granting affirmative proof. Both permission fields require integer JSON values.

EntityValue

bsblan.EntityValue module-attribute

EntityValue = float | int | str | time

Heating

State

bsblan.State

Bases: BaseModel

Object that holds information about the state of a climate system.

All fields are optional to support partial fetching via the include parameter. When using state() without include, all required parameters will be populated.

StaticState

bsblan.StaticState

Bases: BaseModel

Class for entities that are not changing.

Sensor

bsblan.Sensor

Bases: BaseModel

Object holds info about object for sensor climate.

Hot water

HotWaterState

bsblan.HotWaterState

Bases: BaseModel

Essential hot water state information (READ from device).

This class contains only the most important hot water parameters that are typically checked frequently for monitoring purposes.

Note

This is for READING from the device. For WRITING parameters, use SetHotWaterParam with set_hot_water().

HotWaterConfig

bsblan.HotWaterConfig

Bases: BaseModel

Hot water configuration and advanced settings (READ from device).

This class contains configuration parameters that are typically set once and checked less frequently.

Note

This is for READING from the device. For WRITING parameters, use SetHotWaterParam with set_hot_water().

SetHotWaterParam

bsblan.SetHotWaterParam dataclass

SetHotWaterParam(
    nominal_setpoint: float | None = None,
    reduced_setpoint: float | None = None,
    nominal_setpoint_max: float | None = None,
    operating_mode: str | None = None,
    eco_mode_selection: str | None = None,
    dhw_charging_priority: str | None = None,
    legionella_function_setpoint: float | None = None,
    legionella_function_periodicity: str | None = None,
    legionella_function_day: str | None = None,
    legionella_function_time: str | None = None,
    legionella_function_dwelling_time: float | None = None,
    operating_mode_changeover: str | None = None,
)

Parameters for setting hot water configuration.

Use this dataclass to pass parameters to set_hot_water(). Only one parameter should be set at a time (BSB-LAN API limitation).

Note

This is for WRITING to the device. For READING hot water data, use HotWaterState or HotWaterConfig. Schedules use bsblan.schedules.

Attributes:

Name Type Description
nominal_setpoint float | None

The nominal setpoint temperature.

reduced_setpoint float | None

The reduced setpoint temperature.

nominal_setpoint_max float | None

The maximum nominal setpoint temperature.

operating_mode str | None

The operating mode (e.g., "0"=Off, "1"=On).

eco_mode_selection str | None

Eco mode selection.

dhw_charging_priority str | None

DHW charging priority.

legionella_function_setpoint float | None

Legionella function setpoint temperature.

legionella_function_periodicity str | None

Legionella function periodicity.

legionella_function_day str | None

Day for legionella function.

legionella_function_time str | None

Time for legionella function (HH:MM).

legionella_function_dwelling_time float | None

Legionella dwelling time (min).

operating_mode_changeover str | None

Operating mode changeover.

Schedules

Heating and DHW share immutable observations and a separate partial-update payload. See the migration guide for breaking changes.

ScheduleMapping

bsblan.ScheduleMapping

Bases: BaseModel

Independently confirmed weekday IDs for one target and schedule group.

validate_id classmethod

validate_id(value: str) -> str

Keep the exact canonical ID spelling used by /JQ and /JS.

Source code in src/bsblan/schedules.py
@field_validator(*WEEKDAYS)
@classmethod
def validate_id(cls, value: str) -> str:
    """Keep the exact canonical ID spelling used by /JQ and /JS."""
    if not re.fullmatch(r"[1-9]\d*(?:\.[1-9])?", value, flags=re.ASCII):
        msg = "Invalid schedule parameter ID"
        raise ValueError(msg)
    return value

validate_unique

validate_unique() -> ScheduleMapping

Reject IDs assigned to more than one day.

Source code in src/bsblan/schedules.py
@model_validator(mode="after")
def validate_unique(self) -> ScheduleMapping:
    """Reject IDs assigned to more than one day."""
    if len({getattr(self, name) for name in WEEKDAYS}) != 7:
        msg = "Schedule parameter IDs must be unique"
        raise ValueError(msg)
    return self

ScheduleMappings

bsblan.ScheduleMappings

Bases: BaseModel

Immutable weekday mappings; absent groups contain no mapping assertion.

validate_circuits classmethod

validate_circuits(value: Any) -> dict[int, Any]

Normalize canonical JSON IDs without accepting coercion or collisions.

Source code in src/bsblan/schedules.py
@field_validator("heating", mode="before")
@classmethod
def validate_circuits(cls, value: Any) -> dict[int, Any]:
    """Normalize canonical JSON IDs without accepting coercion or collisions."""
    if not isinstance(value, Mapping):
        msg = "Heating profiles must be a circuit-keyed mapping"
        raise ValueError(msg)  # noqa: TRY004 - pydantic validation error
    normalized: dict[int, Any] = {}
    for key, profile in value.items():
        if type(key) is int and key in (1, 2):
            circuit = key
        elif type(key) is str and key in ("1", "2"):
            circuit = int(key)
        else:
            msg = "Heating circuit keys must be 1 or 2"
            raise ValueError(msg)
        if circuit in normalized:
            msg = "Duplicate heating circuit after key normalization"
            raise ValueError(msg)
        normalized[circuit] = profile
    return normalized

freeze_heating classmethod

freeze_heating(
    value: Mapping[int, ScheduleMapping],
) -> Mapping[int, ScheduleMapping]

Capture a read-only copy, including the empty default collection.

Source code in src/bsblan/schedules.py
@field_validator("heating", mode="after")
@classmethod
def freeze_heating(
    cls, value: Mapping[int, ScheduleMapping]
) -> Mapping[int, ScheduleMapping]:
    """Capture a read-only copy, including the empty default collection."""
    return _CircuitMappings(tuple(sorted(value.items())))

serialize_heating

serialize_heating(
    value: Mapping[int, ScheduleMapping],
) -> dict[int, ScheduleMapping]

Serialize read-only internals as a normal JSON-compatible mapping.

Source code in src/bsblan/schedules.py
@field_serializer("heating")
def serialize_heating(
    self, value: Mapping[int, ScheduleMapping]
) -> dict[int, ScheduleMapping]:
    """Serialize read-only internals as a normal JSON-compatible mapping."""
    return dict(value)

ScheduleProfileIdentity

bsblan.ScheduleProfileIdentity

Bases: BaseModel

Exact installation scope certified by a profile's independent evidence.

require_text classmethod

require_text(value: str) -> str

Reject absent provenance scope rather than accepting wildcard matches.

Source code in src/bsblan/schedule_profiles.py
@field_validator("firmware_version", "controller", "table")
@classmethod
def require_text(cls, value: str) -> str:
    """Reject absent provenance scope rather than accepting wildcard matches."""
    if not value.strip():
        msg = "Profile identity requires nonempty text"
        raise ValueError(msg)
    return value

ScheduleProfile

bsblan.ScheduleProfile

Bases: BaseModel

Weekday mappings and their provenance for exactly one installation scope.

require_text classmethod

require_text(value: str) -> str

Require an auditable identifier and an evidence reference.

Source code in src/bsblan/schedule_profiles.py
@field_validator("id", "evidence")
@classmethod
def require_text(cls, value: str) -> str:
    """Require an auditable identifier and an evidence reference."""
    if not value.strip():
        msg = "Profile ID and evidence must be nonempty"
        raise ValueError(msg)
    return value

require_mapping

require_mapping() -> ScheduleProfile

Require certification for at least one schedule group.

Source code in src/bsblan/schedule_profiles.py
@model_validator(mode="after")
def require_mapping(self) -> ScheduleProfile:
    """Require certification for at least one schedule group."""
    if not self.mappings.heating and self.mappings.hot_water is None:
        msg = "Profile requires at least one schedule mapping"
        raise ValueError(msg)
    if self.table_parameters:
        mappings = tuple(self.mappings.heating.values()) + (
            (self.mappings.hot_water,)
            if self.mappings.hot_water is not None
            else ()
        )
        expected = {
            getattr(mapping, day) for mapping in mappings for day in WEEKDAYS
        }
        declared = dict(self.table_parameters)
        if (
            len(declared) != len(self.table_parameters)
            or set(declared) != expected
            or any(not name.strip() for name in declared.values())
        ):
            msg = "Table signature must name every mapped ID exactly once"
            raise ValueError(msg)
    return self

ScheduleAvailability

bsblan.ScheduleAvailability

Bases: BaseModel

Group enablement and repair/retry advice, not a schedule snapshot.

enabled property

enabled: bool

Return whether the group can be used without a mapping repair.

repair_required property

repair_required: bool

Return whether a mapping override or supported profile is needed.

retry_required property

retry_required: bool

Return whether discovery was inconclusive and should be retried.

ScheduleCandidateProbe

bsblan.ScheduleCandidateProbe

Bases: BaseModel

Diagnostic compatibility only; weekday meaning still needs confirmation.

retry_required property

retry_required: bool

Return whether missing/inactive/transient data warrants another probe.

A diagnostic candidate is never enabled, even when compatible. Its proposed mapping requires independent active-table/weekday confirmation before use.

See profile evidence and compatibility before adding profiles. The standard registry includes one narrowly scoped, verified RVS21 entry. ScheduleProfile.table_parameters declares immutable ID/name pairs covering every mapped ID exactly once; a matching profile can then recognize each group's active /JC layout without a caller schedule_table assertion.

ScheduleSnapshot

bsblan.ScheduleSnapshot

Bases: BaseModel

A fresh immutable observation, not an atomic week or write verification.

complete property

complete: bool

Return whether every day has a supported structured value.

retry_required property

retry_required: bool

Advise later reads for missing/inactive/possibly transient device data.

validate_week

validate_week() -> ScheduleSnapshot

Require seven ordered days, UTC-compatible time and a valid target.

Source code in src/bsblan/schedules.py
@model_validator(mode="after")
def validate_week(self) -> ScheduleSnapshot:
    """Require seven ordered days, UTC-compatible time and a valid target."""
    if tuple(day.weekday for day in self.days) != WEEKDAYS:
        msg = "A snapshot requires seven canonical ordered weekdays"
        raise ValueError(msg)
    if self.received_at.tzinfo is None or self.received_at.utcoffset() is None:
        msg = "A snapshot requires an aware receipt timestamp"
        raise ValueError(msg)
    if (self.kind == "heating" and self.circuit not in (1, 2)) or (
        self.kind == "hot_water" and self.circuit is not None
    ):
        msg = "Snapshot circuit does not match the schedule group"
        raise ValueError(msg)
    return self

day

day(weekday: Weekday) -> ScheduleDay

Look up an observed day by its canonical weekday name.

Source code in src/bsblan/schedules.py
def day(self, weekday: Weekday) -> ScheduleDay:
    """Look up an observed day by its canonical weekday name."""
    return self.days[WEEKDAYS.index(weekday)]

ScheduleDay

bsblan.ScheduleDay

Bases: BaseModel

One observed day; unavailable and unsupported text are never clear intent.

validate_status

validate_status() -> ScheduleDay

Keep structured values consistent with the observation status.

Source code in src/bsblan/schedules.py
@model_validator(mode="after")
def validate_status(self) -> ScheduleDay:
    """Keep structured values consistent with the observation status."""
    if self.status in {"readable", "empty"}:
        if self.schedule is None or bool(self.schedule.slots) != (
            self.status == "readable"
        ):
            msg = "Parsed schedule must agree with readable/empty status"
            raise ValueError(msg)
    elif self.schedule is not None:
        msg = "Unavailable or unparsed days cannot contain a schedule"
        raise ValueError(msg)
    return self

ScheduleUpdate

bsblan.ScheduleUpdate dataclass

ScheduleUpdate(
    monday: DaySchedule | None = None,
    tuesday: DaySchedule | None = None,
    wednesday: DaySchedule | None = None,
    thursday: DaySchedule | None = None,
    friday: DaySchedule | None = None,
    saturday: DaySchedule | None = None,
    sunday: DaySchedule | None = None,
)

A partial update: None leaves a day unchanged, an empty day requests clear.

__post_init__

__post_init__() -> None

Reject raw values and defensively copy every populated day.

Source code in src/bsblan/schedules.py
def __post_init__(self) -> None:
    """Reject raw values and defensively copy every populated day."""
    for name in WEEKDAYS:
        day = getattr(self, name)
        if day is not None:
            if not isinstance(day, DaySchedule):
                msg = f"{name} must be a DaySchedule or None"
                raise ValueError(msg)
            object.__setattr__(self, name, DaySchedule(day.slots))

DaySchedule

bsblan.DaySchedule dataclass

DaySchedule(slots: tuple[TimeSlot, ...] = ())

Up to three non-overlapping intervals; no slots expresses clear intent.

__post_init__

__post_init__() -> None

Validate and defensively copy slots, preserving their order.

Source code in src/bsblan/schedules.py
def __post_init__(self) -> None:
    """Validate and defensively copy slots, preserving their order."""
    if not isinstance(self.slots, (tuple, list)):
        msg = "Schedule slots must be a sequence of TimeSlot values"
        raise ValueError(msg)  # noqa: TRY004 - uniform value validation
    if len(self.slots) > MAX_TIME_SLOTS_PER_DAY or any(
        not isinstance(slot, TimeSlot) for slot in self.slots
    ):
        msg = "A day supports at most three TimeSlot values"
        raise ValueError(msg)
    slots = tuple(TimeSlot(slot.start, slot.end) for slot in self.slots)
    if any(
        slot.start < other.end and other.start < slot.end
        for i, slot in enumerate(slots)
        for other in slots[i + 1 :]
    ):
        msg = "Overlapping schedule intervals are unsupported"
        raise ValueError(msg)
    object.__setattr__(self, "slots", slots)

from_bsblan_format classmethod

from_bsblan_format(value: str) -> DaySchedule

Parse active and disabled physical slots, never inactive entities.

Source code in src/bsblan/schedules.py
@classmethod
def from_bsblan_format(cls, value: str) -> DaySchedule:
    """Parse active and disabled physical slots, never inactive entities."""
    if not isinstance(value, str):
        msg = "Schedule text must be a string"
        raise ValueError(msg)  # noqa: TRY004 - uniform codec rejection
    tokens = value.split()
    if not tokens or len(tokens) > MAX_TIME_SLOTS_PER_DAY:
        msg = "Unsupported physical schedule slot count"
        raise ValueError(msg)
    slots = []
    for token in tokens:
        if token == _DISABLED_SLOT:
            continue
        match = re.fullmatch(
            r"(\d{2}):(\d{2})-(\d{2}):(\d{2})", token, flags=re.ASCII
        )
        if match is None:
            msg = "Unsupported schedule interval format"
            raise ValueError(msg)
        start_h, start_m, end_h, end_m = map(int, match.groups())
        slots.append(TimeSlot(time(start_h, start_m), time(end_h, end_m)))
    return cls(slots=tuple(slots))

to_bsblan_format

to_bsblan_format() -> str

Serialize active intervals; a verified clear encoding is not known.

Source code in src/bsblan/schedules.py
def to_bsblan_format(self) -> str:
    """Serialize active intervals; a verified clear encoding is not known."""
    validated = DaySchedule(self.slots)
    if not validated.slots:
        msg = "Schedule clear encoding has not been verified for this device"
        raise BSBLANUnsupportedFeatureError(msg)
    return " ".join(
        f"{slot.start:%H:%M}-{slot.end:%H:%M}" for slot in validated.slots
    )

TimeSlot

bsblan.TimeSlot dataclass

TimeSlot(start: time, end: time)

One naive, minute-precision interval with an exclusive end.

__post_init__

__post_init__() -> None

Reject values that would be truncated or misrepresented on the bus.

Source code in src/bsblan/schedules.py
def __post_init__(self) -> None:
    """Reject values that would be truncated or misrepresented on the bus."""
    for value in (self.start, self.end):
        if (
            not isinstance(value, time)
            or value.tzinfo is not None
            or value.second
            or value.microsecond
        ):
            msg = "Schedule times must be naive, minute-precision time values"
            raise ValueError(msg)
    if self.start >= self.end:
        msg = "Schedule start must be before end"
        raise ValueError(msg)

Device

Device

bsblan.Device

Bases: BaseModel

Object holds bsblan device information.

is_pps_bus property

is_pps_bus: bool

Return whether the device is connected to a PPS bus.

is_bus_writable property

is_bus_writable: bool

Return the gateway default write indicator, not per-parameter permission.

BSB/LPB active-table flags can permit individual parameters even when this indicator is false. PPS still uses a gateway-wide write enable setting.

supports_time_sync property

supports_time_sync: bool

Return whether normal BSB/LPB time synchronization is supported.

busdest is optional but strictly integer when present: no coercion of booleans, floats or numeric strings into a profile identity. Missing/null stays unknown.

is_bus_writable reflects the gateway default indicator. On BSB/LPB it is not an absolute veto on individual active-table parameters; see parameter permissions.

ApiVersion

bsblan.ApiVersion

Bases: BaseModel

Object holding the BSB-LAN JSON-API version reported by /JV.

This is the JSON-API version (e.g. "2.0"), which is distinct from the adapter firmware version reported by /JI. It is the documented, firmware-independent signal used to select a compatible API configuration.

Info

bsblan.Info

Bases: BaseModel

Object holding the heatingSystem info.

All fields are optional to support partial fetching via the include parameter.

DeviceTime

bsblan.DeviceTime

Bases: BaseModel

Object holds device time information.