Skip to content

Commit

Permalink
Fixed a lot of lint, manifest file bug and deprecated code.
Browse files Browse the repository at this point in the history
  • Loading branch information
giachello committed Aug 26, 2024
1 parent ecb92eb commit 7244118
Show file tree
Hide file tree
Showing 7 changed files with 174 additions and 172 deletions.
87 changes: 46 additions & 41 deletions custom_components/mlgw/__init__.py
Original file line number Diff line number Diff line change
@@ -1,49 +1,55 @@
"""The MasterLink Gateway integration."""

import asyncio
from homeassistant.helpers import device_registry as dr
from homeassistant.helpers.typing import ServiceDataType
from .gateway import create_mlgw_gateway, MasterLinkGateway
from .const import reverse_ml_destselectordict, reverse_ml_selectedsourcedict, BEO4_CMDS
from .media_player import BeoSpeaker
import logging
import json

import requests
from requests.auth import HTTPBasicAuth, HTTPDigestAuth
from requests.exceptions import RequestException
import voluptuous as vol

from homeassistant.config_entries import ConfigEntry, ConfigEntryNotReady
from homeassistant.const import (
CONF_DEVICES,
CONF_HOST,
CONF_PASSWORD,
CONF_PORT,
CONF_DEVICES,
CONF_USERNAME,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import config_validation as cv, discovery
from homeassistant.helpers import (
config_validation as cv,
device_registry as dr,
discovery,
)
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.typing import ServiceDataType

from .const import (
DOMAIN,
MLGW_GATEWAY,
MLGW_GATEWAY_CONFIGURATION_DATA,
MLGW_DEVICES,
CONF_MLGW_DEFAULT_SOURCE,
ATTR_MLGW_ACTION,
ATTR_MLGW_BUTTON,
BASE_URL,
BEO4_CMDS,
CONF_MLGW_AVAILABLE_SOURCES,
MLGW_DEFAULT_SOURCE,
MLGW_AVAILABLE_SOURCES,
CONF_MLGW_DEVICE_NAME,
CONF_MLGW_DEFAULT_SOURCE,
CONF_MLGW_DEVICE_MLID,
CONF_MLGW_DEVICE_MLN,
CONF_MLGW_DEVICE_NAME,
CONF_MLGW_DEVICE_ROOM,
CONF_MLGW_DEVICE_MLID,
CONF_MLGW_USE_MLLOG,
BASE_URL,
TIMEOUT,
DOMAIN,
MLGW_AVAILABLE_SOURCES,
MLGW_CONFIG_JSON_PATH,
ATTR_MLGW_ACTION,
ATTR_MLGW_BUTTON,
MLGW_DEFAULT_SOURCE,
MLGW_DEVICES,
MLGW_GATEWAY,
MLGW_GATEWAY_CONFIGURATION_DATA,
TIMEOUT,
reverse_ml_destselectordict,
reverse_ml_selectedsourcedict,
reverse_mlgw_virtualactiondict,
)

from .gateway import MasterLinkGateway, create_mlgw_gateway

CONFIG_SCHEMA = vol.Schema(
{
Expand Down Expand Up @@ -97,8 +103,8 @@

def yaml_to_json_config(manual_devices, availabe_sources):
"""Convert the YAML configuration into the equivalent json config from the MLGW."""
result = dict()
result["zones"] = list()
result = {}
result["zones"] = []
i = 1
for device in manual_devices:
if CONF_MLGW_DEVICE_MLN in device.keys():
Expand All @@ -116,32 +122,32 @@ def yaml_to_json_config(manual_devices, availabe_sources):
r = 0
_zl = [w for w in result["zones"] if w["number"] == room]
if len(_zl) == 0:
_z = dict()
_z = {}
_z["number"] = room
result["zones"].append(_z)
r = result["zones"].index(_z)
else:
r = result["zones"].index(_zl[0])

if "products" not in result["zones"][r]:
result["zones"][r]["products"] = list()
result["zones"][r]["products"] = []

product = dict()
product = {}
product["MLN"] = mln
product["ML"] = ml
product["name"] = device[CONF_MLGW_DEVICE_NAME]

device_sources = list()
device_sources = []
for _x in availabe_sources:
_source = dict()
_source = {}
_source["name"] = _x
_source["destination"] = reverse_ml_destselectordict.get("AUDIO SOURCE")
_source["format"] = "F0"
_source["secondary"] = 0
_source["link"] = 0
_source["statusID"] = reverse_ml_selectedsourcedict.get(_x)
_source["selectID"] = BEO4_CMDS.get(_x)
_source["selectCmds"] = list()
_source["selectCmds"] = []
_source["selectCmds"].append({"cmd": BEO4_CMDS.get(_x), "format": "F0"})
device_sources.append(_source)

Expand Down Expand Up @@ -207,8 +213,6 @@ async def async_setup(hass: HomeAssistant, config: dict):

def get_mlgw_configuration_data(host: str, username: str, password: str):
"""Get the configuration data from the mlgw using the mlgwpservices.json endpoint."""
import requests
from requests.auth import HTTPDigestAuth, HTTPBasicAuth

# try with Digest Auth first
response = requests.get(
Expand Down Expand Up @@ -245,6 +249,7 @@ def send_all_standby(service: ServiceDataType):
if not gateway:
return False
gateway.mlgw_send_all_standby()
return True

# Register the services
hass.services.async_register(
Expand All @@ -264,7 +269,6 @@ def send_all_standby(service: ServiceDataType):

async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Set up MasterLink Gateway from a config entry."""
from requests.exceptions import RequestException

host = entry.data.get(CONF_HOST)
password = entry.data.get(CONF_PASSWORD)
Expand All @@ -275,7 +279,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
mlgw_configurationdata = await hass.async_add_executor_job(
get_mlgw_configuration_data, host, username, password
)
except (RequestException) as ex:
except RequestException as ex:
# this will cause Home Assistant to retry setting up the integration later.
raise ConfigEntryNotReady(f"Cannot connect to {host}, is it on?") from ex

Expand All @@ -296,9 +300,9 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):

hass.data[DOMAIN][entry.entry_id] = {}
hass.data[DOMAIN][entry.entry_id][MLGW_GATEWAY] = gateway
hass.data[DOMAIN][entry.entry_id][
MLGW_GATEWAY_CONFIGURATION_DATA
] = mlgw_configurationdata
hass.data[DOMAIN][entry.entry_id][MLGW_GATEWAY_CONFIGURATION_DATA] = (
mlgw_configurationdata
)
hass.data[DOMAIN][entry.entry_id]["serial"] = entry.unique_id
_LOGGER.debug("Serial: %s", entry.unique_id)

Expand All @@ -314,10 +318,11 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
device_registry = dr.async_get(hass)
device_registry.async_get_or_create(**device_info)

for component in PLATFORMS:
hass.async_create_task(
hass.config_entries.async_forward_entry_setup(entry, component)
)
# for component in PLATFORMS:
# hass.async_create_task(
# hass.config_entries.async_forward_entry_setup(entry, component)
# )
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)

register_services(hass, gateway)

Expand Down
36 changes: 18 additions & 18 deletions custom_components/mlgw/config_flow.py
Original file line number Diff line number Diff line change
@@ -1,34 +1,33 @@
"""
Config flow for MasterLink Gateway integration.
"""Config flow for MasterLink Gateway integration.
Includes code from Lele-72. Thank you!
"""
import logging

import ipaddress
import logging
import re
import voluptuous as vol
import requests
import socket
import xml.etree.ElementTree as ET
from requests.auth import HTTPDigestAuth, HTTPBasicAuth

import requests
from requests.auth import HTTPBasicAuth, HTTPDigestAuth
from requests.exceptions import ConnectTimeout
import voluptuous as vol

from homeassistant import config_entries, core, exceptions, data_entry_flow
from homeassistant import config_entries, core, data_entry_flow, exceptions
from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME

from .const import (
CONF_MLGW_USE_MLLOG,
BASE_URL,
CONF_MLGW_USE_MLLOG,
DOMAIN,
MLGW_CONFIG_JSON_PATH,
TIMEOUT,
) # pylint:disable=unused-import

from .const import DOMAIN

_LOGGER = logging.getLogger(__name__)
_Discovered_MLGW : dict = { }
_Discovered_MLGW: dict = {}

# Data schema for the configuration flows
USER_STEP_DATA_SCHEMA = vol.Schema(
Expand Down Expand Up @@ -60,6 +59,7 @@ def host_valid(host):

## Get serial number of mlgw


# Get the MLGW/BLGW Serial number from the integrated Jabber Client
#
# This code causes the MLGW to crash if called too many times. Given that it is called every time there is
Expand All @@ -72,8 +72,8 @@ def host_valid(host):
# <?xml version='1.0'?><stream:stream to='products.bang-olufsen.com' version='1.0' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams'></stream:stream>
# <stream:stream xmlns="jabber:client" version="1.0" xmlns:stream="http://etherx.jabber.org/streams" from="7060.2706081.22996958@products.bang-olufsen.com">

async def mlgw_get_xmpp_serial(_host: str) -> str:

async def mlgw_get_xmpp_serial(_host: str) -> str:
if _host in _Discovered_MLGW:
_LOGGER.debug("XMPP found cached sn")
return _Discovered_MLGW[_host]
Expand Down Expand Up @@ -117,7 +117,7 @@ async def mlgw_get_xmpp_serial(_host: str) -> str:
class CheckPasswordMLGWHub:
"""Checks Password for the MLGW Hub and gets basic information."""

def __init__(self, host):
def __init__(self, host) -> None:
"""Initialize."""
self._host = host
self._data = None
Expand All @@ -140,7 +140,7 @@ def authenticate(self, user, password) -> bool:

if response.status_code == 401:
_LOGGER.warning("Invalid authentication to MLGW")
raise InvalidAuth()
raise InvalidAuth

if response.status_code != 200:
return False
Expand Down Expand Up @@ -184,7 +184,7 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
# TODO pick one of the available connection classes in homeassistant/config_entries.py
CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_POLL

def __init__(self):
def __init__(self) -> None:
"""Initialize."""
self.host = None

Expand All @@ -201,7 +201,7 @@ async def async_step_user(self, user_input=None):

try:
if not host_valid(user_input[CONF_HOST]):
raise InvalidHost()
raise InvalidHost

info = await validate_input(self.hass, user_input)
except CannotConnect:
Expand Down Expand Up @@ -284,7 +284,7 @@ async def async_step_zeroconf_confirm(self, user_input=None):

try:
if not host_valid(user_input[CONF_HOST]):
raise InvalidHost()
raise InvalidHost

info = await validate_input(self.hass, user_input)

Expand Down
20 changes: 11 additions & 9 deletions custom_components/mlgw/device_action.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,22 @@
"""
"""Provides Device Actions for the integration.
Provides the following Device Actions:
Virtual Buttons
All Standby
Virtual Buttons
All Standby
"""

from __future__ import annotations

import homeassistant.helpers.config_validation as cv
import voluptuous as vol

from homeassistant.const import CONF_DEVICE_ID, CONF_DOMAIN, CONF_TYPE
from homeassistant.core import Context, HomeAssistant
from homeassistant.helpers import entity_registry
from homeassistant.helpers import entity_registry as er
import homeassistant.helpers.config_validation as cv

from . import DOMAIN, SERVICE_ALL_STANDBY, SERVICE_VIRTUAL_BUTTON
from .const import ATTR_MLGW_BUTTON

from . import DOMAIN, SERVICE_VIRTUAL_BUTTON, SERVICE_ALL_STANDBY

ACTION_TYPES = {"all_standby", "virtual_button"}

ALL_STANDBY_SCHEMA = cv.DEVICE_ACTION_BASE_SCHEMA.extend(
Expand All @@ -41,10 +43,10 @@ async def async_get_actions(
hass: HomeAssistant, device_id: str
) -> list[dict[str, str]]:
"""List device actions for aketest_integration devices."""
registry = entity_registry.async_get(hass)
registry = er.async_get(hass)
actions = []

if not entity_registry.async_entries_for_device(registry, device_id):
if not er.async_entries_for_device(registry, device_id):
base_action = {
CONF_DEVICE_ID: device_id,
CONF_DOMAIN: DOMAIN,
Expand Down
Loading

0 comments on commit 7244118

Please sign in to comment.