Skip to content

Commit

Permalink
Merge pull request #43 from slovdahl/make-reading-db-files-async
Browse files Browse the repository at this point in the history
Make reading of DB files async
  • Loading branch information
pszafer authored Jul 23, 2024
2 parents 2f776aa + aead4a7 commit 7429cdc
Show file tree
Hide file tree
Showing 6 changed files with 59 additions and 18 deletions.
25 changes: 21 additions & 4 deletions bosch_thermostat_client/db/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""Retrieve standard data."""

import asyncio
import logging
import json
import os
Expand All @@ -8,6 +9,7 @@
from bosch_thermostat_client.const.nefit import NEFIT
from bosch_thermostat_client.const.ivt import (
CAN,
IVT,
NSC_ICOM_GATEWAY,
RC300_RC200,
MBLAN,
Expand All @@ -29,6 +31,10 @@
}


async def async_open_json(file):
return await asyncio.to_thread(open_json, file)


def open_json(file):
"""Open json file."""
try:
Expand All @@ -40,13 +46,13 @@ def open_json(file):
return {}


def get_initial_db(device_type):
async def get_initial_db(device_type):
filename = os.path.join(MAINPATH, f"db_{device_type}.json")
"""Get initial db. Same for all devices."""
return open_json(filename)
return await async_open_json(filename)


def get_db_of_firmware(device_type, firmware_version):
async def get_db_of_firmware(device_type, firmware_version):
"""Get db of specific device."""
if not firmware_version:
_LOGGER.error("Can't find your fw version.")
Expand All @@ -56,7 +62,7 @@ def get_db_of_firmware(device_type, firmware_version):
)
filepath = os.path.join(MAINPATH, filename)
_LOGGER.debug("Attempt to load database from file %s", filepath)
_db = open_json(filepath)
_db = await async_open_json(filepath)
return _db if _db.get(FIRMWARE_VERSION) == firmware_version else None


Expand All @@ -81,3 +87,14 @@ def get_nefit_errors() -> dict:
def get_easycontrol_errors() -> dict:
"""Get error codes of EASYCONTROL devices."""
return open_json(os.path.join(MAINPATH, "errorcodes_easycontrol.json"))


async def async_get_errors(device_type) -> dict:
"""Get error codes of all devices."""
if device_type == EASYCONTROL:
return await asyncio.to_thread(get_easycontrol_errors)
elif device_type == NEFIT:
return await asyncio.to_thread(get_nefit_errors)
elif device_type == IVT:
return (await asyncio.to_thread(get_nefit_errors)) | (await asyncio.to_thread(get_ivt_errors))
return {}
23 changes: 14 additions & 9 deletions bosch_thermostat_client/gateway/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
CRAWL_SENSORS,
SWITCHES,
)
from bosch_thermostat_client.db import get_custom_db, get_db_of_firmware, get_initial_db
from bosch_thermostat_client.db import get_custom_db, get_db_of_firmware, get_initial_db, async_get_errors
from bosch_thermostat_client.exceptions import (
DeviceException,
FirmwareException,
Expand All @@ -49,6 +49,9 @@
class BaseGateway:
"""Base Gateway class."""

device_type: str
circuit_types: dict[str, str]

def __init__(self, host):
"""BaseGateway constructor
Expand All @@ -63,25 +66,27 @@ def __init__(self, host):
self._initialized = None
self.initialization_msg = None
self._bus_type = None
self._errors = None

def get_base_db(self):
return get_initial_db(self.device_type)
async def get_base_db(self):
return await get_initial_db(self.device_type)

async def initialize(self):
"""Initialize gateway asynchronously."""
initial_db = self.get_base_db()
initial_db = await self.get_base_db()
await self._update_info(initial_db.get(GATEWAY))
self._firmware_version = self._data[GATEWAY].get(FIRMWARE_VERSION)
self._device = self.get_device_model(initial_db)
if self._device and VALUE in self._device:
_LOGGER.debug("Found device %s", json.dumps(self._device))
self._db = get_db_of_firmware(self._device[TYPE], self._firmware_version)
self._db = await get_db_of_firmware(self._device[TYPE], self._firmware_version)
if self._db:
_LOGGER.debug(
f"Loading database: {self._device[TYPE]} for firmware {self._firmware_version}"
)
initial_db.pop(MODELS, None)
self._db.update(initial_db)
self._errors = await async_get_errors(self.device_type)
self._initialized = True
return
raise FirmwareException(
Expand All @@ -90,11 +95,11 @@ async def initialize(self):
)
raise UnknownDevice("Your device is unknown %s" % json.dumps(self._device))

def custom_initialize(self, extra_db):
async def custom_initialize(self, extra_db):
"Custom initialization of component"
if self._firmware_version:
self._db = get_custom_db(self._firmware_version, extra_db)
initial_db = get_initial_db()
initial_db = await get_initial_db()
initial_db.pop(MODELS, None)
self._db.update(initial_db)
self._initialized = True
Expand Down Expand Up @@ -273,7 +278,7 @@ async def initialize_sensors(self):
"""Initialize sensors objects."""
if SENSORS in self._db:
self._data[SENSORS] = Sensors(
connector=self._connector, sensors_db=self._db[SENSORS]
connector=self._connector, sensors_db=self._db[SENSORS], errors=self._errors
)
if CRAWL_SENSORS in self._db:
_LOGGER.info("Initializing Crawl Sensors.")
Expand Down Expand Up @@ -357,7 +362,7 @@ async def close(self, force: bool = False) -> None:
async def check_firmware_validity(self):
"""Run query against firmware version."""
fw = await self._connector.get(self._db.get(BASE_FIRMWARE_VERSION))
if get_db_of_firmware(self._device[TYPE], fw.get(VALUE, "")):
if await get_db_of_firmware(self._device[TYPE], fw.get(VALUE, "")):
return True
raise FirmwareException(
"You might have unsupported firmware version %s. Maybe it get updated?"
Expand Down
10 changes: 9 additions & 1 deletion bosch_thermostat_client/sensors/notification_easycontrol.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,15 @@


class NotificationSensor(Sensor):
errorcodes = get_easycontrol_errors()
errorcodes: dict

def __init__(
self,
**kwargs,
) -> None:
"""Notification sensor init."""
super().__init__(**kwargs)
self.errorcodes = kwargs.get("errorcodes", {})

def get_error_message(self, dcd: str, ccd: str, act: str, fc: str) -> str:
msg = "Unknown error"
Expand Down
10 changes: 9 additions & 1 deletion bosch_thermostat_client/sensors/notification_ivt.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,15 @@


class NotificationSensor(Sensor):
errorcodes = get_nefit_errors() | get_ivt_errors()
errorcodes: dict

def __init__(
self,
**kwargs,
) -> None:
"""Notification sensor init."""
super().__init__(**kwargs)
self.errorcodes = kwargs.get("errorcodes", {})

def process_results(self, result, key=None, return_data=False):
"""Convert multi-level json object to one level object."""
Expand Down
3 changes: 2 additions & 1 deletion bosch_thermostat_client/sensors/notification_nefit.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@


class NotificationSensor(Sensor):
errorcodes = get_nefit_errors()
errorcodes: dict
_allowed_types = "notification"

def __init__(
Expand Down Expand Up @@ -42,6 +42,7 @@ def __init__(
attr_id: {RESULT: {}, URI: path, TYPE: kind},
"cause": {RESULT: {}, URI: cause_uri, TYPE: kind},
}
self.errorcodes = kwargs.get("errorcodes", {})

@property
def state(self):
Expand Down
6 changes: 4 additions & 2 deletions bosch_thermostat_client/sensors/sensors.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ class Sensors(BoschEntities):
"""Sensors object containing multiple Sensor objects."""

def __init__(
self, connector, sensors_db={}, uri_prefix=None, data=None, parent=None
self, connector, sensors_db: dict | None = None, uri_prefix=None, data=None, parent=None, errors: dict | None = None
):
"""
Initialize sensors.
Expand All @@ -71,7 +71,7 @@ def __init__(
super().__init__(connector.get)
self._items = {}

for sensor_id, sensor in sensors_db.items():
for sensor_id, sensor in (sensors_db or {}).items():
if sensor_id not in self._items:
kwargs = {
"connector": connector,
Expand All @@ -87,6 +87,8 @@ def __init__(
"parent": parent,
**sensor,
}
if sensor_id == NOTIFICATIONS and errors:
kwargs["errorcodes"] = errors
SensorClass = get_sensor_class(
device_type=connector.device_type, sensor_type=sensor_id
)
Expand Down

0 comments on commit 7429cdc

Please sign in to comment.