Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fixed pylint issues #9

Merged
merged 5 commits into from
Apr 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions .github/workflows/lint.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
name: "Lint"

on:
push:
branches:
- "main"
pull_request:
branches:
- "main"

jobs:
ruff:
name: "Ruff"
runs-on: "ubuntu-latest"
steps:
- name: "Checkout the repository"
uses: "actions/checkout@main"

- name: "Set up Python"
uses: actions/setup-python@main
with:
python-version: "3.11"
cache: "pip"

- name: "Install requirements"
run: python3 -m pip install -r requirements.txt

- name: "Run Ruff"
run: python3 -m ruff check .
1 change: 0 additions & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,6 @@ class BMS(BaseBMS):

async def disconnect(self) -> None:
"""Disconnect connection to BMS if active."""
pass

async def async_update(self) -> dict[str, int | float | bool]:
"""Update battery status information."""
Expand Down
6 changes: 3 additions & 3 deletions custom_components/bms_ble/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
await coordinator.async_config_entry_first_refresh()
except ConfigEntryNotReady:
# Ignore, e.g. timeouts, to gracefully handle connection issues
LOGGER.warning("Failed to initialize BMS %s, continuing.", ble_device.name)
pass
LOGGER.warning("Failed to initialize BMS %s, continuing", ble_device.name)

# Insert the coordinator in the global registry
hass.data.setdefault(DOMAIN, {})
hass.data[DOMAIN][entry.entry_id] = coordinator
Expand All @@ -52,5 +52,5 @@ async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
await hass.data[DOMAIN][entry.entry_id].stop()
hass.data[DOMAIN].pop(entry.entry_id)

LOGGER.info("unloaded entry: %s, ok? %s!", entry.unique_id, str(unload_ok))
LOGGER.info("Unloaded config entry: %s, ok? %s!", entry.unique_id, str(unload_ok))
return unload_ok
2 changes: 1 addition & 1 deletion custom_components/bms_ble/binary_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,6 @@ def _handle_coordinator_update(self) -> None:
self._attr_available = True
elif self._attr_available:
self._attr_available = False
LOGGER.info("No update available for %s.", self.entity_description.key)
LOGGER.info("No update available for sensor '%s'", self.entity_description.key)

self.async_write_ha_state()
6 changes: 3 additions & 3 deletions custom_components/bms_ble/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,9 @@ def _device_supported(
self, discovery_info: BluetoothServiceInfoBleak
) -> str | None:
"""Check if device is supported by an available BMS class."""
for type in BMS_TYPES:
for bms_type in BMS_TYPES:
bms_plugin = importlib.import_module(
f".plugins.{type}", package=__name__[: __name__.rfind(".")]
f".plugins.{bms_type}", package=__name__[: __name__.rfind(".")]
)
try:
if bms_plugin.BMS.supported(discovery_info):
Expand All @@ -57,7 +57,7 @@ def _device_supported(
)
return bms_plugin.__name__
except AttributeError:
LOGGER.error("Invalid BMS plugin %s", type)
LOGGER.error("Invalid BMS plugin %s", bms_type)
return None

async def async_step_bluetooth(
Expand Down
2 changes: 1 addition & 1 deletion custom_components/bms_ble/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ async def _async_update_data(self) -> dict[str, int | float | bool]:
try:
battery_info.update(await self._device.async_update())
except TimeoutError:
LOGGER.debug("Device communication timeout.")
LOGGER.debug("Device communication timeout")
raise
except BleakError as err:
raise UpdateFailed(
Expand Down
5 changes: 0 additions & 5 deletions custom_components/bms_ble/plugins/basebms.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,11 @@ def __init__(self, ble_device: BLEDevice, reconnect: bool = False) -> None:
ble_device: the Bleak device to connect to
reconnect: if true, the connection will be closed after each update
"""
pass

@staticmethod
@abstractmethod
def matcher_dict_list() -> list[dict[str, Any]]:
"""Return a list of Bluetooth matchers."""
pass

@staticmethod
@abstractmethod
Expand All @@ -47,7 +45,6 @@ def device_info() -> dict[str, str]:

keys: manufacturer, model
"""
pass

@classmethod
def device_id(cls) -> str:
Expand Down Expand Up @@ -97,12 +94,10 @@ def can_calc(value: str, using: frozenset[str]) -> bool:

async def disconnect(self) -> None:
"""Disconnect connection to BMS if active."""
pass

@abstractmethod
async def async_update(self) -> dict[str, int | float | bool]:
"""Retrieve updated values from the BMS.

Returns a dictionary of BMS values, where the keys need to match the keys in the SENSOR_TYPES list.
"""
pass
8 changes: 4 additions & 4 deletions custom_components/bms_ble/plugins/daly_bms.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,9 @@ def __init__(self, ble_device: BLEDevice, reconnect: bool = False) -> None:
(ATTR_VOLTAGE, 80 + self.HEAD_LEN, lambda x: float(x / 10)),
(ATTR_CURRENT, 82 + self.HEAD_LEN, lambda x: float((x - 30000) / 10)),
(ATTR_BATTERY_LEVEL, 84 + self.HEAD_LEN, lambda x: float(x / 10)),
(ATTR_CYCLES, 102 + self.HEAD_LEN, lambda x: int(x)),
(ATTR_CYCLES, 102 + self.HEAD_LEN, lambda x: int(x)), # pylint: disable=unnecessary-lambda
(ATTR_CYCLE_CHRG, 96 + self.HEAD_LEN, lambda x: float(x / 10)),
("numTemp", 100 + self.HEAD_LEN, lambda x: int(x)),
("numTemp", 100 + self.HEAD_LEN, lambda x: int(x)), # pylint: disable=unnecessary-lambda
]

@staticmethod
Expand All @@ -74,7 +74,7 @@ async def _wait_event(self) -> None:
def _on_disconnect(self, client: BleakClient) -> None:
"""Disconnect callback function."""

LOGGER.debug("Disconnected from %s.", client.address)
LOGGER.debug("Disconnected from BMS (%s)", client.address)
self._connected = False

def _notification_handler(self, sender, data: bytearray) -> None:
Expand All @@ -85,7 +85,7 @@ def _notification_handler(self, sender, data: bytearray) -> None:
or data[0:2] != self.HEAD_READ
or int(data[2]) + 1 != len(data) - len(self.HEAD_READ) - self.CRC_LEN
):
LOGGER.debug("Response is invalid.")
LOGGER.debug("Response data is invalid")
self._data = None
return

Expand Down
23 changes: 12 additions & 11 deletions custom_components/bms_ble/plugins/ogt_bms.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
"""Module to support Offgridtec Smart Pro BMS."""

import asyncio
import logging
from typing import Any

from bleak import BleakClient, normalize_uuid_str
from bleak import BleakClient, BleakError, normalize_uuid_str
from bleak.backends.device import BLEDevice

from ..const import (
Expand Down Expand Up @@ -59,7 +60,7 @@ def __init__(self, ble_device: BLEDevice, reconnect: bool = False) -> None:
if self._type == "A":
self._OGT_REGISTERS = {
# SOC (State of Charge)
2: {"name": ATTR_BATTERY_LEVEL, "len": 1, "func": lambda x: int(x)},
2: {"name": ATTR_BATTERY_LEVEL, "len": 1, "func": lambda x: int(x)}, # pylint: disable=unnecessary-lambda
4: {
"name": ATTR_CYCLE_CHRG,
"len": 3,
Expand All @@ -75,7 +76,7 @@ def __init__(self, ble_device: BLEDevice, reconnect: bool = False) -> None:
# length for current is actually only 2, 3 used to detect signed value
16: {"name": ATTR_CURRENT, "len": 3, "func": lambda x: float(x) / 100},
24: {"name": ATTR_RUNTIME, "len": 2, "func": lambda x: int(x * 60)},
44: {"name": ATTR_CYCLES, "len": 2, "func": lambda x: int(x)},
44: {"name": ATTR_CYCLES, "len": 2, "func": lambda x: int(x)}, # pylint: disable=unnecessary-lambda
}
self._OGT_HEADER = "+RAA"
elif self._type == "B":
Expand All @@ -89,14 +90,14 @@ def __init__(self, ble_device: BLEDevice, reconnect: bool = False) -> None:
9: {"name": ATTR_VOLTAGE, "len": 2, "func": lambda x: float(x) / 1000},
10: {"name": ATTR_CURRENT, "len": 3, "func": lambda x: float(x) / 1000},
# SOC (State of Charge)
13: {"name": ATTR_BATTERY_LEVEL, "len": 1, "func": lambda x: int(x)},
13: {"name": ATTR_BATTERY_LEVEL, "len": 1, "func": lambda x: int(x)}, # pylint: disable=unnecessary-lambda
15: {
"name": ATTR_CYCLE_CHRG,
"len": 3,
"func": lambda x: float(x) / 1000,
},
18: {"name": ATTR_RUNTIME, "len": 2, "func": lambda x: int(x * 60)},
23: {"name": ATTR_CYCLES, "len": 2, "func": lambda x: int(x)},
23: {"name": ATTR_CYCLES, "len": 2, "func": lambda x: int(x)}, # pylint: disable=unnecessary-lambda
}
self._OGT_HEADER = "+R16"
else:
Expand Down Expand Up @@ -131,7 +132,7 @@ async def async_update(self) -> dict[str, int | float | bool]:
try:
await asyncio.wait_for(self._wait_event(), timeout=BAT_TIMEOUT)
except TimeoutError:
LOGGER.debug("Reading %s timed out.", self._OGT_REGISTERS[key]["name"])
LOGGER.debug("Reading %s timed out", self._OGT_REGISTERS[key]["name"])

self.calc_values(
self._values, {ATTR_CYCLE_CAP, ATTR_POWER, ATTR_BATTERY_CHARGING}
Expand All @@ -146,7 +147,7 @@ async def async_update(self) -> dict[str, int | float | bool]:
def _on_disconnect(self, client: BleakClient) -> None:
"""Disconnect callback for Bleak."""

LOGGER.debug("Disconnected from %s.", client.address)
LOGGER.debug("Disconnected from BMS (%s)", client.address)
self._connected = False

def _notification_handler(self, sender, data: bytearray) -> None:
Expand All @@ -167,14 +168,14 @@ def _notification_handler(self, sender, data: bytearray) -> None:
)
self._values[register["name"]] = value
else:
LOGGER.debug("Response is invalid.")
LOGGER.debug("Response data is invalid")
self._data_event.set()

async def _connect(self) -> None:
"""Connect to the BMS and setup notification if not connected."""

if not self._connected:
LOGGER.debug("Connecting BMS (%s).", self._ble_device.name)
LOGGER.debug("Connecting BMS (%s)", self._ble_device.name)
self._client = BleakClient(
self._ble_device.address,
disconnected_callback=self._on_disconnect,
Expand All @@ -194,8 +195,8 @@ async def disconnect(self) -> None:
try:
self._data_event.clear()
await self._client.disconnect()
except Exception:
LOGGER.warning("disconnect failed!")
except BleakError:
LOGGER.warning("Disconnect failed!")

self._client = None

Expand Down
2 changes: 1 addition & 1 deletion custom_components/bms_ble/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,6 @@ def _handle_coordinator_update(self) -> None:
self._attr_available = True
elif self._attr_available:
self._attr_available = False
LOGGER.info("No update available for %s.", self.entity_description.key)
LOGGER.info("No update available for sensor '%s'", self.entity_description.key)

self.async_write_ha_state()
4 changes: 4 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
homeassistant==2023.8.0
pip>=21.3.1
ruff==0.4.2