Skip to content

Commit

Permalink
Merge pull request #9 from litinoveweedle/fix_async_track_state_chang…
Browse files Browse the repository at this point in the history
…e_deprecation

move common device json data handling into common class
  • Loading branch information
litinoveweedle authored May 20, 2024
2 parents ca69b91 + d47bf25 commit 0cc1ee0
Show file tree
Hide file tree
Showing 5 changed files with 136 additions and 164 deletions.
90 changes: 90 additions & 0 deletions custom_components/smartir/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,91 @@
"""The SmartIR component."""

import logging
import os.path
import json

_LOGGER = logging.getLogger(__name__)


class DeviceData:
@staticmethod
def load_file(device_code, device_class, required_keys):
"""Load device JSON file."""
device_json_filename = str(device_code) + ".json"

device_files_subdir = os.path.join("custom_codes", device_class)
device_files_absdir = os.path.join(
os.path.dirname(os.path.abspath(__file__)), device_files_subdir
)
if os.path.isdir(device_files_absdir):
device_json_path = os.path.join(device_files_absdir, device_json_filename)
if os.path.exists(device_json_path):
if device_data := DeviceData.check_file(
device_json_filename, device_json_path, required_keys
):
return device_data
else:
os.makedirs(device_files_absdir)

device_files_subdir = os.path.join("codes", device_class)
device_files_absdir = os.path.join(
os.path.dirname(os.path.abspath(__file__)), device_files_subdir
)
if os.path.isdir(device_files_absdir):
device_json_path = os.path.join(device_files_absdir, device_json_filename)
if os.path.exists(device_json_path):
if device_data := DeviceData.check_file(
device_json_filename, device_json_path, required_keys
):
return device_data
else:
_LOGGER.error(
"Device Json file '%s' doesn't exists!", device_json_filename
)
return None
else:
_LOGGER.error(
"Devices Json files directory '%s' doesn't exists!", device_files_absdir
)
return None

return None

@staticmethod
def check_file(device_json_filename, device_json_path, required_keys):
with open(device_json_path) as j:
try:
_LOGGER.debug("Loading device json file '%s'", device_json_path)
device_data = json.load(j)
_LOGGER.debug("Device json file '%s' loaded", device_json_path)
except Exception:
_LOGGER.error(
"The device JSON file '%s' is not valid json!", device_json_filename
)
return None

if not isinstance(device_data, dict):
_LOGGER.error("Invalid device code file '%s.", device_json_filename)
return None

for key in required_keys:
if not (key in device_data and device_data[key]):
_LOGGER.error(
"Invalid device JSON file '%s', missing or not defined '%s'!",
device_json_filename,
key,
)
return None

if not (
"commands" in device_data
and isinstance(device_data["commands"], dict)
and len(device_data["commands"])
):
_LOGGER.error(
"Invalid device JSON file '%s', missing 'commands'!",
device_json_filename,
)
return None

return device_data
74 changes: 18 additions & 56 deletions custom_components/smartir/climate.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import asyncio
import json
import logging
import os.path

import voluptuous as vol

Expand Down Expand Up @@ -29,6 +27,7 @@
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.typing import ConfigType
from . import DeviceData
from .controller import get_controller

_LOGGER = logging.getLogger(__name__)
Expand Down Expand Up @@ -71,62 +70,25 @@ async def async_setup_platform(
hass: HomeAssistant, config: ConfigType, async_add_entities, discovery_info=None
):
"""Set up the IR Climate platform."""
_LOGGER.debug("Setting up the startir platform")
device_code = config.get(CONF_DEVICE_CODE)
device_files_subdir = os.path.join("codes", "climate")
device_files_absdir = os.path.join(
os.path.dirname(os.path.abspath(__file__)), device_files_subdir
)

device_json_filename = str(device_code) + ".json"
device_json_path = os.path.join(device_files_absdir, device_json_filename)

if not os.path.exists(device_json_path):
_LOGGER.error("Couldn't find the device Json file %s!", device_json_filename)
return

with open(device_json_path) as j:
try:
_LOGGER.debug(f"loading json file {device_json_path}")
device_data = json.load(j)
_LOGGER.debug(f"{device_json_path} file loaded")
except Exception:
_LOGGER.error(
"The device JSON file '%s' is not valid json!", device_json_filename
)
return

if not isinstance(device_data, dict):
_LOGGER.error("Invalid device code file '%s.", device_json_filename)
return

for key in [
"manufacturer",
"supportedModels",
"supportedController",
"commandsEncoding",
"minTemperature",
"maxTemperature",
"precision",
"operationModes",
"fanModes",
]:
if not (key in device_data and device_data[key]):
_LOGGER.error(
"Invalid device JSON file '%s, missing or not defined '%s'!",
device_json_filename,
key,
)
return

_LOGGER.debug("Setting up the smartir climate platform")
if not (
"commands" in device_data
and isinstance(device_data["commands"], dict)
and len(device_data["commands"])
):
_LOGGER.error(
"Invalid device JSON file '%s, missing 'commands'!", device_json_filename
device_data := DeviceData.load_file(
config.get(CONF_DEVICE_CODE),
"climate",
[
"manufacturer",
"supportedModels",
"supportedController",
"commandsEncoding",
"minTemperature",
"maxTemperature",
"precision",
"operationModes",
"fanModes",
],
)
):
_LOGGER.error("Smartir climate device data init failed!")
return

async_add_entities([SmartIRClimate(hass, config, device_data)])
Expand Down
68 changes: 14 additions & 54 deletions custom_components/smartir/fan.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import asyncio
import json
import logging
import os.path

import voluptuous as vol

Expand All @@ -25,6 +23,7 @@
ordered_list_item_to_percentage,
percentage_to_ordered_list_item,
)
from . import DeviceData
from .controller import get_controller

_LOGGER = logging.getLogger(__name__)
Expand Down Expand Up @@ -60,60 +59,21 @@ async def async_setup_platform(
hass: HomeAssistant, config: ConfigType, async_add_entities, discovery_info=None
):
"""Set up the IR Fan platform."""
device_code = config.get(CONF_DEVICE_CODE)
device_files_subdir = os.path.join("codes", "fan")
device_files_absdir = os.path.join(
os.path.dirname(os.path.abspath(__file__)), device_files_subdir
)

if not os.path.isdir(device_files_absdir):
os.makedirs(device_files_absdir)

device_json_filename = str(device_code) + ".json"
device_json_path = os.path.join(device_files_absdir, device_json_filename)

if not os.path.exists(device_json_path):
_LOGGER.error("Couldn't find the device Json file %s!", device_json_filename)
return

with open(device_json_path) as j:
try:
_LOGGER.debug(f"loading json file {device_json_path}")
device_data = json.load(j)
_LOGGER.debug(f"{device_json_path} file loaded")
except Exception:
_LOGGER.error(
"The device JSON file '%s' is not valid json!", device_json_filename
)
return

if not isinstance(device_data, dict):
_LOGGER.error("Invalid device JSON file '%s.", device_json_filename)
return

for key in [
"manufacturer",
"supportedModels",
"supportedController",
"commandsEncoding",
"speed",
]:
if not (key in device_data and device_data[key]):
_LOGGER.error(
"Invalid device JSON file '%s, missing or not defined '%s'!",
device_json_filename,
key,
)
return

_LOGGER.debug("Setting up the smartir fan platform")
if not (
"commands" in device_data
and isinstance(device_data["commands"], dict)
and len(device_data["commands"])
):
_LOGGER.error(
"Invalid device JSON file '%s, missing 'commands'!", device_json_filename
device_data := DeviceData.load_file(
config.get(CONF_DEVICE_CODE),
"fan",
[
"manufacturer",
"supportedModels",
"supportedController",
"commandsEncoding",
"speed",
],
)
):
_LOGGER.error("Smartir fan device data init failed!")
return

async_add_entities([SmartIRFan(hass, config, device_data)])
Expand Down
66 changes: 13 additions & 53 deletions custom_components/smartir/media_player.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import asyncio
import json
import logging
import os.path

import voluptuous as vol

Expand All @@ -23,6 +21,7 @@
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.typing import ConfigType
from . import DeviceData
from .controller import get_controller

_LOGGER = logging.getLogger(__name__)
Expand Down Expand Up @@ -57,59 +56,20 @@ async def async_setup_platform(
hass: HomeAssistant, config: ConfigType, async_add_entities, discovery_info=None
):
"""Set up the IR Media Player platform."""
device_code = config.get(CONF_DEVICE_CODE)
device_files_subdir = os.path.join("codes", "media_player")
device_files_absdir = os.path.join(
os.path.dirname(os.path.abspath(__file__)), device_files_subdir
)

if not os.path.isdir(device_files_absdir):
os.makedirs(device_files_absdir)

device_json_filename = str(device_code) + ".json"
device_json_path = os.path.join(device_files_absdir, device_json_filename)

if not os.path.exists(device_json_path):
_LOGGER.error("Couldn't find the device Json file %s!", device_json_filename)
return

with open(device_json_path) as j:
try:
_LOGGER.debug(f"loading json file {device_json_path}")
device_data = json.load(j)
_LOGGER.debug(f"{device_json_path} file loaded")
except Exception:
_LOGGER.error(
"The device JSON file '%s' is not valid json!", device_json_filename
)
return

if not isinstance(device_data, dict):
_LOGGER.error("Invalid device code file '%s.", device_json_filename)
return

for key in [
"manufacturer",
"supportedModels",
"supportedController",
"commandsEncoding",
]:
if not (key in device_data and device_data[key]):
_LOGGER.error(
"Invalid device JSON file '%s, missing or not defined '%s'!",
device_json_filename,
key,
)
return

_LOGGER.debug("Setting up the smartir media player platform")
if not (
"commands" in device_data
and isinstance(device_data["commands"], dict)
and len(device_data["commands"])
):
_LOGGER.error(
"Invalid device JSON file '%s, missing 'commands'!", device_json_filename
device_data := DeviceData.load_file(
config.get(CONF_DEVICE_CODE),
"media_player",
[
"manufacturer",
"supportedModels",
"supportedController",
"commandsEncoding",
],
)
):
_LOGGER.error("Smartir media player device data init failed!")
return

async_add_entities([SmartIRMediaPlayer(hass, config, device_data)])
Expand Down
2 changes: 1 addition & 1 deletion hacs.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "SmartIR",
"homeassistant": "2024.5.0",
"persistent_directory": "codes",
"persistent_directory": "custom_codes",
"zip_release": true,
"hide_default_branch": true,
"filename": "smartir.zip",
Expand Down

0 comments on commit 0cc1ee0

Please sign in to comment.