try fix
Some checks failed
Validate / Validate (push) Has been cancelled

This commit is contained in:
2026-05-31 12:17:42 +02:00
parent abb3c346de
commit b81215415e
4 changed files with 739 additions and 1276 deletions

View File

@@ -1,9 +1,9 @@
"""Energy Monitor MQTT Integration for Home Assistant.""" """Jackery Home Assistant Integration."""
import logging import logging
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.const import Platform from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.components import mqtt from homeassistant.components import mqtt
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@@ -13,48 +13,42 @@ PLATFORMS = [Platform.SENSOR, Platform.SWITCH, Platform.NUMBER]
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up Jackery from a config entry.""" """Set up one Jackery device from a config entry."""
_LOGGER.info("Setting up Jackery integration")
# 检查 MQTT 集成是否已配置和可用
if not await mqtt.async_wait_for_mqtt_client(hass): if not await mqtt.async_wait_for_mqtt_client(hass):
_LOGGER.error( _LOGGER.error("MQTT integration is not available")
"MQTT integration is not available or not configured. "
"Please set up the MQTT integration first: "
"Settings -> Devices & Services -> Add Integration -> MQTT"
)
return False return False
_LOGGER.info("MQTT integration is available and ready") from .sensor import JackeryCoordinator
# 初始化存储结构 config = entry.data
coordinator = JackeryCoordinator(
hass=hass,
entry_id=entry.entry_id,
device_sn=config["device_sn"],
token=config.get("token", ""),
topic_prefix=config.get("topic_prefix", "hb"),
)
hass.data.setdefault(DOMAIN, {}) hass.data.setdefault(DOMAIN, {})
hass.data[DOMAIN][entry.entry_id] = { hass.data[DOMAIN][entry.entry_id] = coordinator
"config": entry.data,
"coordinator": None, # 将在 sensor.py 中设置 # Start MQTT subscriptions now; the poll loop waits 2 s so platform
} # async_setup_entry callbacks are registered before the first poll fires.
await coordinator.async_start()
# 加载传感器平台
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
return True return True
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry.""" """Unload a config entry."""
_LOGGER.info("Unloading Jackery integration") coordinator = hass.data[DOMAIN].get(entry.entry_id)
# 停止协调器
entry_data = hass.data[DOMAIN].get(entry.entry_id, {})
coordinator = entry_data.get("coordinator")
if coordinator: if coordinator:
await coordinator.async_stop() await coordinator.async_stop()
_LOGGER.info("Coordinator stopped")
# 卸载传感器平台
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS) unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
if unload_ok: if unload_ok:
hass.data[DOMAIN].pop(entry.entry_id) hass.data[DOMAIN].pop(entry.entry_id, None)
return unload_ok return unload_ok

View File

@@ -1,6 +1,6 @@
"""Jackery Number Platform.""" """Jackery Number Platform."""
import logging import logging
from typing import Any, TYPE_CHECKING from typing import TYPE_CHECKING
from homeassistant.components.number import NumberEntity, NumberMode from homeassistant.components.number import NumberEntity, NumberMode
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
@@ -10,16 +10,15 @@ from homeassistant.helpers.entity_platform import AddEntitiesCallback
from . import DOMAIN from . import DOMAIN
if TYPE_CHECKING: if TYPE_CHECKING:
from .sensor import JackeryDataCoordinator from .sensor import JackeryCoordinator
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
NUMBERS = { NUMBERS = {
"socChgLimit": {"name": "SOC Charge Limit", "min": 0, "max": 100, "step": 1}, "socChgLimit": {"name": "SOC Charge Limit", "min": 0, "max": 100, "step": 1},
"socDischgLimit": {"name": "SOC Discharge Limit", "min": 0, "max": 100, "step": 1}, "socDischgLimit": {"name": "SOC Discharge Limit", "min": 0, "max": 100, "step": 1},
"maxOutPw": {"name": "Max Output Power (OnGrid)", "min": 0, "max": 10000, "step": 10}, "maxOutPw": {"name": "Max Output Power (OnGrid)", "min": 0, "max": 10000, "step": 10},
"autoStandby": {"name": "Auto Standby Mode", "min": 0, "max": 2, "step": 1}, "autoStandby": {"name": "Auto Standby Mode", "min": 0, "max": 2, "step": 1},
} }
@@ -28,75 +27,53 @@ async def async_setup_entry(
config_entry: ConfigEntry, config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback, async_add_entities: AddEntitiesCallback,
) -> None: ) -> None:
"""Set up Jackery number entities.""" coordinator: "JackeryCoordinator" = hass.data[DOMAIN][config_entry.entry_id]
coordinator = hass.data[DOMAIN][config_entry.entry_id]["coordinator"]
if coordinator is None:
_LOGGER.warning("Coordinator not ready for numbers")
return
entities = [] async_add_entities([
for key, cfg in NUMBERS.items(): JackeryMainNumber(key=key, coordinator=coordinator, **cfg)
entities.append( for key, cfg in NUMBERS.items()
JackeryMainNumber( ])
key=key,
name=cfg["name"],
min_value=cfg["min"],
max_value=cfg["max"],
step=cfg["step"],
coordinator=coordinator,
config_entry_id=config_entry.entry_id,
)
)
if entities:
async_add_entities(entities)
class JackeryMainNumber(NumberEntity): class JackeryMainNumber(NumberEntity):
"""Main device number (cmd=5).""" """Numeric setting on the main Jackery device."""
_attr_should_poll = False
_attr_has_entity_name = True
_attr_mode = NumberMode.SLIDER
def __init__( def __init__(
self, self,
key: str, key: str,
name: str, name: str,
min_value: float, min: float,
max_value: float, max: float,
step: float, step: float,
coordinator: "JackeryDataCoordinator", coordinator: "JackeryCoordinator",
config_entry_id: str,
) -> None: ) -> None:
self._key = key self._key = key
self._coordinator = coordinator self._coordinator = coordinator
self._attr_name = name self._attr_name = name
self._attr_unique_id = f"jackery_{config_entry_id}_main_{key}" self._attr_unique_id = f"jackery_{coordinator.entry_id}_main_{key}"
self._attr_has_entity_name = True self._attr_native_min_value = min
self._attr_mode = NumberMode.SLIDER self._attr_native_max_value = max
self._attr_native_min_value = min_value
self._attr_native_max_value = max_value
self._attr_native_step = step self._attr_native_step = step
device_sn = coordinator._device_sn or "Unknown"
self._attr_device_info = { self._attr_device_info = {
"identifiers": {(DOMAIN, config_entry_id)}, "identifiers": {(DOMAIN, coordinator.entry_id)},
"name": f"Jackery {device_sn}", "name": f"Jackery {coordinator.device_sn}",
"manufacturer": "Jackery", "manufacturer": "Jackery",
"model": "Energy Monitor", "model": "Energy Monitor",
} }
@property
def should_poll(self) -> bool:
return False
async def async_added_to_hass(self) -> None: async def async_added_to_hass(self) -> None:
await super().async_added_to_hass() await super().async_added_to_hass()
self._coordinator.register_sensor(f"main_number_{self._key}", self) self._coordinator.register_entity(f"main_number_{self._key}", self)
async def async_will_remove_from_hass(self) -> None: async def async_will_remove_from_hass(self) -> None:
self._coordinator.unregister_sensor(f"main_number_{self._key}") self._coordinator.unregister_entity(f"main_number_{self._key}")
await super().async_will_remove_from_hass() await super().async_will_remove_from_hass()
def _update_from_coordinator(self, data: dict) -> None: def _update_from_coordinator(self, data: dict) -> None:
if self._key not in data:
return
val = data.get(self._key) val = data.get(self._key)
if val is None: if val is None:
return return
@@ -108,4 +85,4 @@ class JackeryMainNumber(NumberEntity):
pass pass
async def async_set_native_value(self, value: float) -> None: async def async_set_native_value(self, value: float) -> None:
await self._coordinator.async_control_main_device({self._key: int(value)}) await self._coordinator.control_main({self._key: int(value)})

File diff suppressed because it is too large Load Diff

View File

@@ -10,7 +10,7 @@ from homeassistant.helpers.entity_platform import AddEntitiesCallback
from . import DOMAIN from . import DOMAIN
if TYPE_CHECKING: if TYPE_CHECKING:
from .sensor import JackeryDataCoordinator from .sensor import JackeryCoordinator
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@@ -20,178 +20,43 @@ async def async_setup_entry(
config_entry: ConfigEntry, config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback, async_add_entities: AddEntitiesCallback,
) -> None: ) -> None:
"""Set up Jackery switches.""" coordinator: "JackeryCoordinator" = hass.data[DOMAIN][config_entry.entry_id]
coordinator = hass.data[DOMAIN][config_entry.entry_id]["coordinator"]
if coordinator is None:
_LOGGER.warning("Coordinator not ready for switches")
return
# Register callback for dynamic switch entities coordinator.add_switch_entities = async_add_entities
def add_switch_entities_callback(new_entities):
async_add_entities(new_entities)
coordinator.add_switch_entities_callback = add_switch_entities_callback
entities = [] async_add_entities([
JackeryMainSwitch("isAutoStandby", "Auto Standby Allowed", coordinator),
# Main device switches JackeryMainSwitch("swEps", "EPS Switch", coordinator),
entities.extend( ])
[
JackeryMainSwitch(
key="isAutoStandby",
name="Auto Standby Allowed",
coordinator=coordinator,
config_entry_id=config_entry.entry_id,
),
JackeryMainSwitch(
key="swEps",
name="EPS Switch",
coordinator=coordinator,
config_entry_id=config_entry.entry_id,
),
]
)
# Add any existing sub-devices as switches (non-CT)
for item in coordinator.get_subdevices():
sn = item.get("deviceSn") or item.get("sn")
dev_type = item.get("devType")
if dev_type is None and item.get("subType") == 2:
dev_type = 2
if sn and dev_type != 2:
entities.append(
JackeryPlugSwitch(
plug_sn=sn,
dev_type=dev_type,
coordinator=coordinator,
config_entry_id=config_entry.entry_id,
)
)
if entities:
async_add_entities(entities)
class JackeryPlugSwitch(SwitchEntity):
"""Jackery Smart Plug Switch."""
def __init__(
self,
plug_sn: str,
dev_type: int,
coordinator: "JackeryDataCoordinator",
config_entry_id: str,
) -> None:
"""Initialize."""
self._plug_sn = plug_sn
self._dev_type = dev_type
self._coordinator = coordinator
self._raw_data = {}
self._attr_name = "Switch"
self._attr_unique_id = f"jackery_plug_{plug_sn}_switch"
self._attr_has_entity_name = True
self._attr_device_info = {
"identifiers": {(DOMAIN, f"sub_{plug_sn}")},
"via_device": (DOMAIN, config_entry_id),
"name": f"Jackery Plug {plug_sn}",
"manufacturer": "Jackery",
"model": f"Sub-device Type {dev_type}",
}
@property
def should_poll(self) -> bool:
return False
async def async_added_to_hass(self) -> None:
await super().async_added_to_hass()
self._coordinator.register_sensor(f"plug_switch_{self._plug_sn}", self)
async def async_will_remove_from_hass(self) -> None:
self._coordinator.unregister_sensor(f"plug_switch_{self._plug_sn}")
await super().async_will_remove_from_hass()
def _update_from_coordinator(self, data: dict) -> None:
plugs = data.get("plugs") or data.get("plug")
if not plugs or not isinstance(plugs, list):
return
my_plug = next((p for p in plugs if (p.get("sn") == self._plug_sn or p.get("deviceSn") == self._plug_sn)), None)
if not my_plug:
return
self._raw_data = dict(my_plug)
val = my_plug.get("sysSwitch")
if val is None:
val = my_plug.get("switchSta")
if val is None:
return
self._attr_is_on = bool(int(val))
self._attr_available = True
self.async_write_ha_state()
async def async_turn_on(self, **kwargs: Any) -> None:
await self._coordinator.async_control_subdevice_switch(
plug_sn=self._plug_sn,
dev_type=self._dev_type,
is_on=True,
)
async def async_turn_off(self, **kwargs: Any) -> None:
await self._coordinator.async_control_subdevice_switch(
plug_sn=self._plug_sn,
dev_type=self._dev_type,
is_on=False,
)
@property
def extra_state_attributes(self) -> dict[str, Any]:
return {
"plug_sn": self._plug_sn,
"dev_type": self._dev_type,
"raw_data": self._raw_data,
}
class JackeryMainSwitch(SwitchEntity): class JackeryMainSwitch(SwitchEntity):
"""Main device switch (cmd=5).""" """On/off switch for a main-device boolean setting."""
def __init__( _attr_should_poll = False
self, _attr_has_entity_name = True
key: str,
name: str, def __init__(self, key: str, name: str, coordinator: "JackeryCoordinator") -> None:
coordinator: "JackeryDataCoordinator",
config_entry_id: str,
) -> None:
self._key = key self._key = key
self._coordinator = coordinator self._coordinator = coordinator
self._attr_name = name self._attr_name = name
self._attr_unique_id = f"jackery_{config_entry_id}_main_{key}" self._attr_unique_id = f"jackery_{coordinator.entry_id}_main_{key}"
self._attr_has_entity_name = True
device_sn = coordinator._device_sn or "Unknown"
self._attr_device_info = { self._attr_device_info = {
"identifiers": {(DOMAIN, config_entry_id)}, "identifiers": {(DOMAIN, coordinator.entry_id)},
"name": f"Jackery {device_sn}", "name": f"Jackery {coordinator.device_sn}",
"manufacturer": "Jackery", "manufacturer": "Jackery",
"model": "Energy Monitor", "model": "Energy Monitor",
} }
@property
def should_poll(self) -> bool:
return False
async def async_added_to_hass(self) -> None: async def async_added_to_hass(self) -> None:
await super().async_added_to_hass() await super().async_added_to_hass()
self._coordinator.register_sensor(f"main_switch_{self._key}", self) self._coordinator.register_entity(f"main_switch_{self._key}", self)
async def async_will_remove_from_hass(self) -> None: async def async_will_remove_from_hass(self) -> None:
self._coordinator.unregister_sensor(f"main_switch_{self._key}") self._coordinator.unregister_entity(f"main_switch_{self._key}")
await super().async_will_remove_from_hass() await super().async_will_remove_from_hass()
def _update_from_coordinator(self, data: dict) -> None: def _update_from_coordinator(self, data: dict) -> None:
if self._key not in data:
return
val = data.get(self._key) val = data.get(self._key)
if val is None: if val is None:
return return
@@ -200,7 +65,77 @@ class JackeryMainSwitch(SwitchEntity):
self.async_write_ha_state() self.async_write_ha_state()
async def async_turn_on(self, **kwargs: Any) -> None: async def async_turn_on(self, **kwargs: Any) -> None:
await self._coordinator.async_control_main_device({self._key: 1}) await self._coordinator.control_main({self._key: 1})
async def async_turn_off(self, **kwargs: Any) -> None: async def async_turn_off(self, **kwargs: Any) -> None:
await self._coordinator.async_control_main_device({self._key: 0}) await self._coordinator.control_main({self._key: 0})
class JackeryPlugSwitch(SwitchEntity):
"""On/off switch for a smart plug sub-device."""
_attr_should_poll = False
_attr_has_entity_name = True
def __init__(
self,
plug_sn: str,
dev_type: int,
coordinator: "JackeryCoordinator",
entry_id: str,
) -> None:
self._plug_sn = plug_sn
self._dev_type = dev_type
self._coordinator = coordinator
self._raw_data: dict = {}
self._attr_name = "Switch"
self._attr_unique_id = f"jackery_plug_{plug_sn}_switch"
self._attr_device_info = {
"identifiers": {(DOMAIN, f"sub_{plug_sn}")},
"via_device": (DOMAIN, entry_id),
"name": f"Jackery Plug {plug_sn}",
"manufacturer": "Jackery",
"model": f"Sub-device Type {dev_type}",
}
async def async_added_to_hass(self) -> None:
await super().async_added_to_hass()
self._coordinator.register_entity(f"plug_switch_{self._plug_sn}", self)
async def async_will_remove_from_hass(self) -> None:
self._coordinator.unregister_entity(f"plug_switch_{self._plug_sn}")
await super().async_will_remove_from_hass()
def _update_from_coordinator(self, data: dict) -> None:
pool = data.get("plugs") or data.get("plug")
if not isinstance(pool, list):
return
my = next(
(p for p in pool
if p.get("sn") == self._plug_sn or p.get("deviceSn") == self._plug_sn),
None,
)
if not my:
return
self._raw_data = dict(my)
val = my.get("sysSwitch") if my.get("sysSwitch") is not None else my.get("switchSta")
if val is None:
return
self._attr_is_on = bool(int(val))
self._attr_available = True
self.async_write_ha_state()
async def async_turn_on(self, **kwargs: Any) -> None:
await self._coordinator.control_subdevice(self._plug_sn, self._dev_type, True)
async def async_turn_off(self, **kwargs: Any) -> None:
await self._coordinator.control_subdevice(self._plug_sn, self._dev_type, False)
@property
def extra_state_attributes(self) -> dict:
return {
"plug_sn": self._plug_sn,
"dev_type": self._dev_type,
"raw_data": self._raw_data,
}