forked from HomeAssistant/fn_nas
Compare commits
3 Commits
Author | SHA1 | Date | |
---|---|---|---|
![]() |
fae53cf5b9 | ||
![]() |
f185b7e3ee | ||
![]() |
e3bb42e3de |
@@ -1,62 +1,89 @@
|
||||
import logging
|
||||
import asyncio
|
||||
import asyncssh
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.core import HomeAssistant
|
||||
from .const import DOMAIN, DATA_UPDATE_COORDINATOR, PLATFORMS, CONF_ENABLE_DOCKER # 导入新增常量
|
||||
from homeassistant.helpers import config_validation as cv
|
||||
|
||||
from .const import (
|
||||
DOMAIN, DATA_UPDATE_COORDINATOR, PLATFORMS, CONF_ENABLE_DOCKER,
|
||||
CONF_HOST, DEFAULT_PORT
|
||||
)
|
||||
from .coordinator import FlynasCoordinator, UPSDataUpdateCoordinator
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
|
||||
config = {**entry.data, **entry.options}
|
||||
|
||||
coordinator = FlynasCoordinator(hass, config)
|
||||
await coordinator.async_config_entry_first_refresh()
|
||||
|
||||
_LOGGER.debug("协调器类型: %s", type(coordinator).__name__)
|
||||
_LOGGER.debug("协调器是否有control_vm方法: %s", hasattr(coordinator, 'control_vm'))
|
||||
_LOGGER.debug("协调器是否有vm_manager属性: %s", hasattr(coordinator, 'vm_manager'))
|
||||
|
||||
# 检查是否启用Docker,并初始化Docker管理器(如果有)
|
||||
enable_docker = config.get(CONF_ENABLE_DOCKER, False)
|
||||
if enable_docker:
|
||||
# 导入Docker管理器并初始化
|
||||
from .docker_manager import DockerManager
|
||||
coordinator.docker_manager = DockerManager(coordinator)
|
||||
_LOGGER.debug("已启用Docker容器监控")
|
||||
else:
|
||||
coordinator.docker_manager = None
|
||||
_LOGGER.debug("未启用Docker容器监控")
|
||||
|
||||
ups_coordinator = UPSDataUpdateCoordinator(hass, config, coordinator)
|
||||
await ups_coordinator.async_config_entry_first_refresh()
|
||||
|
||||
coordinator = FlynasCoordinator(hass, config, entry)
|
||||
# 直接初始化,不阻塞等待NAS上线
|
||||
hass.data.setdefault(DOMAIN, {})
|
||||
hass.data[DOMAIN][entry.entry_id] = {
|
||||
DATA_UPDATE_COORDINATOR: coordinator,
|
||||
"ups_coordinator": ups_coordinator,
|
||||
CONF_ENABLE_DOCKER: enable_docker # 存储启用状态
|
||||
"ups_coordinator": None,
|
||||
CONF_ENABLE_DOCKER: coordinator.config.get(CONF_ENABLE_DOCKER, False)
|
||||
}
|
||||
|
||||
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
|
||||
entry.async_on_unload(entry.add_update_listener(async_update_entry))
|
||||
# 异步后台初始化
|
||||
hass.async_create_task(async_delayed_setup(hass, entry, coordinator))
|
||||
return True
|
||||
|
||||
async def async_delayed_setup(hass: HomeAssistant, entry: ConfigEntry, coordinator: FlynasCoordinator):
|
||||
try:
|
||||
# 不阻塞等待NAS上线,直接尝试刷新数据
|
||||
await coordinator.async_config_entry_first_refresh()
|
||||
enable_docker = coordinator.config.get(CONF_ENABLE_DOCKER, False)
|
||||
if enable_docker:
|
||||
from .docker_manager import DockerManager
|
||||
coordinator.docker_manager = DockerManager(coordinator)
|
||||
_LOGGER.debug("已启用Docker容器监控")
|
||||
else:
|
||||
coordinator.docker_manager = None
|
||||
_LOGGER.debug("未启用Docker容器监控")
|
||||
ups_coordinator = UPSDataUpdateCoordinator(hass, coordinator.config, coordinator)
|
||||
await ups_coordinator.async_config_entry_first_refresh()
|
||||
hass.data[DOMAIN][entry.entry_id]["ups_coordinator"] = ups_coordinator
|
||||
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
|
||||
entry.async_on_unload(entry.add_update_listener(async_update_entry))
|
||||
_LOGGER.info("飞牛NAS集成初始化完成")
|
||||
except Exception as e:
|
||||
_LOGGER.error("飞牛NAS集成初始化失败: %s", str(e))
|
||||
await coordinator.async_disconnect()
|
||||
if hasattr(coordinator, '_ping_task') and coordinator._ping_task:
|
||||
coordinator._ping_task.cancel()
|
||||
|
||||
async def async_update_entry(hass: HomeAssistant, entry: ConfigEntry):
|
||||
await hass.config_entries.async_reload(entry.entry_id)
|
||||
"""更新配置项"""
|
||||
# 卸载现有集成
|
||||
await async_unload_entry(hass, entry)
|
||||
# 重新加载集成
|
||||
await async_setup_entry(hass, entry)
|
||||
|
||||
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry):
|
||||
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
|
||||
"""卸载集成"""
|
||||
# 获取集成数据
|
||||
domain_data = hass.data.get(DOMAIN, {}).get(entry.entry_id, {})
|
||||
unload_ok = True
|
||||
|
||||
if unload_ok:
|
||||
domain_data = hass.data[DOMAIN][entry.entry_id]
|
||||
if DATA_UPDATE_COORDINATOR in domain_data:
|
||||
coordinator = domain_data[DATA_UPDATE_COORDINATOR]
|
||||
ups_coordinator = domain_data["ups_coordinator"]
|
||||
ups_coordinator = domain_data.get("ups_coordinator")
|
||||
|
||||
# 关闭主协调器的SSH连接
|
||||
await coordinator.async_disconnect()
|
||||
# 关闭UPS协调器
|
||||
await ups_coordinator.async_shutdown()
|
||||
# 卸载平台
|
||||
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
|
||||
|
||||
# 从DOMAIN中移除该entry的数据
|
||||
hass.data[DOMAIN].pop(entry.entry_id)
|
||||
if unload_ok:
|
||||
# 关闭主协调器的SSH连接
|
||||
await coordinator.async_disconnect()
|
||||
|
||||
# 关闭UPS协调器(如果存在)
|
||||
if ups_coordinator:
|
||||
await ups_coordinator.async_shutdown()
|
||||
|
||||
# 取消监控任务(如果存在)
|
||||
if hasattr(coordinator, '_ping_task') and coordinator._ping_task and not coordinator._ping_task.done():
|
||||
coordinator._ping_task.cancel()
|
||||
|
||||
# 从DOMAIN中移除该entry的数据
|
||||
hass.data[DOMAIN].pop(entry.entry_id, None)
|
||||
|
||||
return unload_ok
|
@@ -1,5 +1,5 @@
|
||||
import logging
|
||||
import re
|
||||
import asyncio
|
||||
import asyncssh
|
||||
from datetime import timedelta
|
||||
from homeassistant.core import HomeAssistant
|
||||
@@ -20,8 +20,10 @@ from .docker_manager import DockerManager
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
class FlynasCoordinator(DataUpdateCoordinator):
|
||||
def __init__(self, hass: HomeAssistant, config) -> None:
|
||||
def __init__(self, hass: HomeAssistant, config, config_entry) -> None:
|
||||
self.config = config
|
||||
self.config_entry = config_entry
|
||||
self.hass = hass
|
||||
self.host = config[CONF_HOST]
|
||||
self.port = config.get(CONF_PORT, DEFAULT_PORT)
|
||||
self.username = config[CONF_USERNAME]
|
||||
@@ -60,6 +62,9 @@ class FlynasCoordinator(DataUpdateCoordinator):
|
||||
|
||||
self.disk_manager = DiskManager(self)
|
||||
self.system_manager = SystemManager(self)
|
||||
self._system_online = False
|
||||
self._ping_task = None
|
||||
self._retry_interval = 30 # 系统离线时的检测间隔(秒)
|
||||
|
||||
async def async_connect(self):
|
||||
if self.ssh is None or self.ssh_closed:
|
||||
@@ -69,7 +74,8 @@ class FlynasCoordinator(DataUpdateCoordinator):
|
||||
port=self.port,
|
||||
username=self.username,
|
||||
password=self.password,
|
||||
known_hosts=None
|
||||
known_hosts=None,
|
||||
connect_timeout=5 # 缩短连接超时时间
|
||||
)
|
||||
|
||||
if await self.is_root_user():
|
||||
@@ -81,7 +87,7 @@ class FlynasCoordinator(DataUpdateCoordinator):
|
||||
result = await self.ssh.run(
|
||||
f"echo '{self.password}' | sudo -S -i",
|
||||
input=self.password + "\n",
|
||||
timeout=10
|
||||
timeout=5
|
||||
)
|
||||
|
||||
whoami_result = await self.ssh.run("whoami")
|
||||
@@ -95,7 +101,7 @@ class FlynasCoordinator(DataUpdateCoordinator):
|
||||
result = await self.ssh.run(
|
||||
f"echo '{self.root_password}' | sudo -S -i",
|
||||
input=self.root_password + "\n",
|
||||
timeout=10
|
||||
timeout=5
|
||||
)
|
||||
|
||||
whoami_result = await self.ssh.run("whoami")
|
||||
@@ -105,10 +111,10 @@ class FlynasCoordinator(DataUpdateCoordinator):
|
||||
self.ssh_closed = False
|
||||
return True
|
||||
else:
|
||||
_LOGGER.warning("切换到 root 会话失败,将使用 sudo")
|
||||
# 切换到 root 会话失败,将使用 sudo
|
||||
self.use_sudo = True
|
||||
else:
|
||||
_LOGGER.warning("非 root 用户且未提供 root 密码,将使用 sudo")
|
||||
# 非 root 用户且未提供 root 密码,将使用 sudo
|
||||
self.use_sudo = True
|
||||
|
||||
self.ssh_closed = False
|
||||
@@ -117,13 +123,13 @@ class FlynasCoordinator(DataUpdateCoordinator):
|
||||
except Exception as e:
|
||||
self.ssh = None
|
||||
self.ssh_closed = True
|
||||
_LOGGER.error("连接失败: %s", str(e), exc_info=True)
|
||||
_LOGGER.debug("连接失败: %s", str(e))
|
||||
return False
|
||||
return True
|
||||
|
||||
async def is_root_user(self):
|
||||
try:
|
||||
result = await self.ssh.run("id -u", timeout=5)
|
||||
result = await self.ssh.run("id -u", timeout=3)
|
||||
return result.stdout.strip() == "0"
|
||||
except Exception:
|
||||
return False
|
||||
@@ -133,9 +139,9 @@ class FlynasCoordinator(DataUpdateCoordinator):
|
||||
try:
|
||||
self.ssh.close()
|
||||
self.ssh_closed = True
|
||||
_LOGGER.info("SSH connection closed")
|
||||
_LOGGER.debug("SSH connection closed")
|
||||
except Exception as e:
|
||||
_LOGGER.error("Error closing SSH connection: %s", str(e))
|
||||
_LOGGER.debug("Error closing SSH connection: %s", str(e))
|
||||
finally:
|
||||
self.ssh = None
|
||||
|
||||
@@ -150,14 +156,36 @@ class FlynasCoordinator(DataUpdateCoordinator):
|
||||
except (asyncssh.Error, TimeoutError):
|
||||
return False
|
||||
|
||||
async def ping_system(self) -> bool:
|
||||
"""轻量级系统状态检测"""
|
||||
# 对于本地主机直接返回True
|
||||
if self.host in ['localhost', '127.0.0.1']:
|
||||
return True
|
||||
|
||||
try:
|
||||
# 使用异步ping检测
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
'ping', '-c', '1', '-W', '1', self.host,
|
||||
stdout=asyncio.subprocess.DEVNULL,
|
||||
stderr=asyncio.subprocess.DEVNULL
|
||||
)
|
||||
await proc.wait()
|
||||
return proc.returncode == 0
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
async def run_command(self, command: str, retries=2) -> str:
|
||||
# 系统离线时直接返回空字符串,避免抛出异常
|
||||
if not self._system_online:
|
||||
return ""
|
||||
|
||||
for attempt in range(retries):
|
||||
try:
|
||||
if not await self.is_ssh_connected():
|
||||
if not await self.async_connect():
|
||||
if self.data and "system" in self.data:
|
||||
self.data["system"]["status"] = "off"
|
||||
raise UpdateFailed("SSH 连接失败")
|
||||
return ""
|
||||
|
||||
if self.use_sudo:
|
||||
if self.root_password or self.password:
|
||||
@@ -175,31 +203,26 @@ class FlynasCoordinator(DataUpdateCoordinator):
|
||||
except asyncssh.process.ProcessError as e:
|
||||
if e.exit_status in [4, 32]:
|
||||
return ""
|
||||
_LOGGER.error("Command failed: %s (exit %d)", command, e.exit_status)
|
||||
_LOGGER.debug("Command failed: %s (exit %d)", command, e.exit_status)
|
||||
self.ssh = None
|
||||
self.ssh_closed = True
|
||||
if attempt == retries - 1:
|
||||
if self.data and "system" in self.data:
|
||||
self.data["system"]["status"] = "off"
|
||||
raise UpdateFailed(f"Command failed after {retries} attempts: {command}") from e
|
||||
return ""
|
||||
|
||||
except asyncssh.Error as e:
|
||||
_LOGGER.error("SSH connection error: %s", str(e))
|
||||
_LOGGER.debug("SSH connection error: %s", str(e))
|
||||
self.ssh = None
|
||||
self.ssh_closed = True
|
||||
if attempt == retries - 1:
|
||||
if self.data and "system" in self.data:
|
||||
self.data["system"]["status"] = "off"
|
||||
raise UpdateFailed(f"SSH error after {retries} attempts: {str(e)}") from e
|
||||
return ""
|
||||
|
||||
except Exception as e:
|
||||
self.ssh = None
|
||||
self.ssh_closed = True
|
||||
_LOGGER.error("Unexpected error: %s", str(e), exc_info=True)
|
||||
_LOGGER.debug("Unexpected error: %s", str(e))
|
||||
if attempt == retries - 1:
|
||||
if self.data and "system" in self.data:
|
||||
self.data["system"]["status"] = "off"
|
||||
raise UpdateFailed(f"Unexpected error after {retries} attempts") from e
|
||||
return ""
|
||||
return ""
|
||||
|
||||
async def get_network_macs(self):
|
||||
try:
|
||||
@@ -216,20 +239,71 @@ class FlynasCoordinator(DataUpdateCoordinator):
|
||||
|
||||
return macs
|
||||
except Exception as e:
|
||||
self.logger.error("获取MAC地址失败: %s", str(e))
|
||||
self.logger.debug("获取MAC地址失败: %s", str(e))
|
||||
return {}
|
||||
|
||||
async def _monitor_system_status(self):
|
||||
"""系统离线时轮询检测状态"""
|
||||
self.logger.debug("启动系统状态监控,每%d秒检测一次", self._retry_interval)
|
||||
while True:
|
||||
await asyncio.sleep(self._retry_interval)
|
||||
|
||||
if await self.ping_system():
|
||||
self.logger.info("检测到系统已开机,触发重新加载")
|
||||
# 触发集成重新加载
|
||||
self.hass.async_create_task(
|
||||
self.hass.config_entries.async_reload(self.config_entry.entry_id)
|
||||
)
|
||||
break
|
||||
|
||||
async def _async_update_data(self):
|
||||
_LOGGER.debug("Starting data update...")
|
||||
is_online = await self.ping_system()
|
||||
self._system_online = is_online
|
||||
if not is_online:
|
||||
_LOGGER.debug("系统离线,跳过数据更新")
|
||||
# 修复:确保 self.data 结构有效
|
||||
if self.data is None or not isinstance(self.data, dict):
|
||||
self.data = {}
|
||||
if "system" not in self.data or not isinstance(self.data.get("system"), dict):
|
||||
self.data["system"] = {}
|
||||
self.data["system"]["status"] = "off"
|
||||
# 启动后台监控任务(非阻塞)
|
||||
if not self._ping_task or self._ping_task.done():
|
||||
self._ping_task = asyncio.create_task(self._monitor_system_status())
|
||||
await self.async_disconnect()
|
||||
# 直接返回空数据,不阻塞
|
||||
return {
|
||||
"disks": [],
|
||||
"system": {
|
||||
"uptime": "未知",
|
||||
"cpu_temperature": "未知",
|
||||
"motherboard_temperature": "未知",
|
||||
"status": "off"
|
||||
},
|
||||
"ups": {},
|
||||
"vms": [],
|
||||
"docker_containers": []
|
||||
}
|
||||
|
||||
# 系统在线处理
|
||||
try:
|
||||
if await self.is_ssh_connected():
|
||||
status = "on"
|
||||
else:
|
||||
if not await self.async_connect():
|
||||
status = "off"
|
||||
else:
|
||||
status = "on"
|
||||
# 确保SSH连接
|
||||
if not await self.async_connect():
|
||||
self.data["system"]["status"] = "off"
|
||||
return {
|
||||
"disks": [],
|
||||
"system": {
|
||||
"uptime": "未知",
|
||||
"cpu_temperature": "未知",
|
||||
"motherboard_temperature": "未知",
|
||||
"status": "off"
|
||||
},
|
||||
"ups": {},
|
||||
"vms": []
|
||||
}
|
||||
|
||||
status = "on"
|
||||
|
||||
disks = await self.disk_manager.get_disks_info()
|
||||
system = await self.system_manager.get_system_info()
|
||||
@@ -257,7 +331,12 @@ class FlynasCoordinator(DataUpdateCoordinator):
|
||||
return data
|
||||
|
||||
except Exception as e:
|
||||
_LOGGER.error("Failed to update data: %s", str(e), exc_info=True)
|
||||
_LOGGER.debug("数据更新失败: %s", str(e))
|
||||
# 检查错误类型,如果是连接问题,标记为离线
|
||||
self._system_online = False
|
||||
if not self._ping_task or self._ping_task.done():
|
||||
self._ping_task = asyncio.create_task(self._monitor_system_status())
|
||||
|
||||
return {
|
||||
"disks": [],
|
||||
"system": {
|
||||
@@ -297,10 +376,14 @@ class UPSDataUpdateCoordinator(DataUpdateCoordinator):
|
||||
self.ups_manager = UPSManager(main_coordinator)
|
||||
|
||||
async def _async_update_data(self):
|
||||
# 如果主协调器检测到系统离线,跳过UPS更新
|
||||
if not self.main_coordinator._system_online:
|
||||
return {}
|
||||
|
||||
try:
|
||||
return await self.ups_manager.get_ups_info()
|
||||
except Exception as e:
|
||||
_LOGGER.error("Failed to update UPS data: %s", str(e), exc_info=True)
|
||||
_LOGGER.debug("UPS数据更新失败: %s", str(e))
|
||||
return {}
|
||||
|
||||
async def control_vm(self, vm_name, action):
|
||||
@@ -311,5 +394,5 @@ class UPSDataUpdateCoordinator(DataUpdateCoordinator):
|
||||
result = await self.vm_manager.control_vm(vm_name, action)
|
||||
return result
|
||||
except Exception as e:
|
||||
_LOGGER.error("虚拟机控制失败: %s", str(e), exc_info=True)
|
||||
_LOGGER.debug("虚拟机控制失败: %s", str(e))
|
||||
return False
|
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"domain": "fn_nas",
|
||||
"name": "飞牛NAS",
|
||||
"version": "1.3.0",
|
||||
"version": "1.3.4",
|
||||
"documentation": "https://github.com/anxms/fn_nas",
|
||||
"dependencies": [],
|
||||
"codeowners": ["@anxms"],
|
||||
|
@@ -243,6 +243,38 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
|
||||
)
|
||||
)
|
||||
existing_ids.add(sensor_uid)
|
||||
|
||||
# 添加剩余内存传感器
|
||||
mem_available_uid = f"{config_entry.entry_id}_memory_available"
|
||||
if mem_available_uid not in existing_ids:
|
||||
entities.append(
|
||||
MemoryAvailableSensor(
|
||||
coordinator,
|
||||
"可用内存",
|
||||
mem_available_uid,
|
||||
"GB",
|
||||
"mdi:memory"
|
||||
)
|
||||
)
|
||||
existing_ids.add(mem_available_uid)
|
||||
|
||||
# 添加存储卷的剩余容量传感器(每个卷一个)
|
||||
system_data = coordinator.data.get("system", {})
|
||||
volumes = system_data.get("volumes", {})
|
||||
for mount_point in volumes:
|
||||
# 创建剩余容量传感器
|
||||
vol_avail_uid = f"{config_entry.entry_id}_{mount_point.replace('/', '_')}_available"
|
||||
if vol_avail_uid not in existing_ids:
|
||||
entities.append(
|
||||
VolumeAvailableSensor(
|
||||
coordinator,
|
||||
f"{mount_point} 可用空间",
|
||||
vol_avail_uid,
|
||||
"mdi:harddisk",
|
||||
mount_point
|
||||
)
|
||||
)
|
||||
existing_ids.add(vol_avail_uid)
|
||||
|
||||
async_add_entities(entities)
|
||||
|
||||
@@ -537,4 +569,129 @@ class DockerContainerStatusSensor(CoordinatorEntity, SensorEntity):
|
||||
"dead": "死亡"
|
||||
}
|
||||
return status_map.get(container["status"], container["status"])
|
||||
return "未知"
|
||||
return "未知"
|
||||
|
||||
class MemoryAvailableSensor(CoordinatorEntity, SensorEntity):
|
||||
"""剩余内存传感器(包含总内存和已用内存作为属性)"""
|
||||
|
||||
def __init__(self, coordinator, name, unique_id, unit, icon):
|
||||
super().__init__(coordinator)
|
||||
self._attr_name = name
|
||||
self._attr_unique_id = unique_id
|
||||
self._attr_native_unit_of_measurement = unit
|
||||
self._attr_icon = icon
|
||||
self._attr_device_info = {
|
||||
"identifiers": {(DOMAIN, DEVICE_ID_NAS)},
|
||||
"name": "飞牛NAS系统监控",
|
||||
"manufacturer": "飞牛"
|
||||
}
|
||||
self._attr_state_class = SensorStateClass.MEASUREMENT
|
||||
|
||||
@property
|
||||
def native_value(self):
|
||||
"""返回可用内存(GB)"""
|
||||
system_data = self.coordinator.data.get("system", {})
|
||||
mem_available = system_data.get("memory_available")
|
||||
|
||||
if mem_available is None or mem_available == "未知":
|
||||
return None
|
||||
|
||||
try:
|
||||
# 将字节转换为GB
|
||||
return round(float(mem_available) / (1024 ** 3), 2)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
@property
|
||||
def extra_state_attributes(self):
|
||||
"""返回总内存和已用内存(GB)以及原始字节值"""
|
||||
system_data = self.coordinator.data.get("system", {})
|
||||
mem_total = system_data.get("memory_total")
|
||||
mem_used = system_data.get("memory_used")
|
||||
mem_available = system_data.get("memory_available")
|
||||
|
||||
# 转换为GB
|
||||
try:
|
||||
mem_total_gb = round(float(mem_total) / (1024 ** 3), 2) if mem_total and mem_total != "未知" else None
|
||||
except:
|
||||
mem_total_gb = None
|
||||
|
||||
try:
|
||||
mem_used_gb = round(float(mem_used) / (1024 ** 3), 2) if mem_used and mem_used != "未知" else None
|
||||
except:
|
||||
mem_used_gb = None
|
||||
|
||||
return {
|
||||
"总内存 (GB)": mem_total_gb,
|
||||
"已用内存 (GB)": mem_used_gb
|
||||
}
|
||||
|
||||
class VolumeAvailableSensor(CoordinatorEntity, SensorEntity):
|
||||
"""存储卷剩余容量传感器(包含总容量和已用容量作为属性)"""
|
||||
|
||||
def __init__(self, coordinator, name, unique_id, icon, mount_point):
|
||||
super().__init__(coordinator)
|
||||
self._attr_name = name
|
||||
self._attr_unique_id = unique_id
|
||||
self._attr_icon = icon
|
||||
self.mount_point = mount_point
|
||||
|
||||
# 设备信息,归属到飞牛NAS系统
|
||||
self._attr_device_info = {
|
||||
"identifiers": {(DOMAIN, DEVICE_ID_NAS)},
|
||||
"name": "飞牛NAS系统监控",
|
||||
"manufacturer": "飞牛"
|
||||
}
|
||||
|
||||
self._attr_state_class = SensorStateClass.MEASUREMENT
|
||||
|
||||
@property
|
||||
def native_value(self):
|
||||
"""返回剩余容量(数值)"""
|
||||
system_data = self.coordinator.data.get("system", {})
|
||||
volumes = system_data.get("volumes", {})
|
||||
vol_info = volumes.get(self.mount_point, {})
|
||||
|
||||
avail_str = vol_info.get("available", "未知")
|
||||
if avail_str == "未知":
|
||||
return None
|
||||
|
||||
try:
|
||||
numeric_part = ''.join(filter(lambda x: x.isdigit() or x == '.', avail_str))
|
||||
return float(numeric_part)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
@property
|
||||
def native_unit_of_measurement(self):
|
||||
"""动态返回单位"""
|
||||
system_data = self.coordinator.data.get("system", {})
|
||||
volumes = system_data.get("volumes", {})
|
||||
vol_info = volumes.get(self.mount_point, {})
|
||||
|
||||
avail_str = vol_info.get("available", "")
|
||||
if avail_str.endswith("T") or avail_str.endswith("Ti"):
|
||||
return "TB"
|
||||
elif avail_str.endswith("G") or avail_str.endswith("Gi"):
|
||||
return "GB"
|
||||
elif avail_str.endswith("M") or avail_str.endswith("Mi"):
|
||||
return "MB"
|
||||
else:
|
||||
return None # 未知单位
|
||||
|
||||
@property
|
||||
def extra_state_attributes(self):
|
||||
system_data = self.coordinator.data.get("system", {})
|
||||
volumes = system_data.get("volumes", {})
|
||||
vol_info = volumes.get(self.mount_point, {})
|
||||
|
||||
return {
|
||||
"挂载点": self.mount_point,
|
||||
"文件系统": vol_info.get("filesystem", "未知"),
|
||||
"总容量": vol_info.get("size", "未知"),
|
||||
"已用容量": vol_info.get("used", "未知"),
|
||||
"使用率": vol_info.get("use_percent", "未知")
|
||||
}
|
||||
|
||||
|
||||
return attributes
|
@@ -58,15 +58,28 @@ class SystemManager:
|
||||
if backup_cpu_temp:
|
||||
system_info["cpu_temperature"] = backup_cpu_temp
|
||||
|
||||
# 新增:获取内存信息
|
||||
mem_info = await self.get_memory_info()
|
||||
system_info.update(mem_info)
|
||||
|
||||
# 新增:获取存储卷信息
|
||||
vol_info = await self.get_vol_usage()
|
||||
system_info["volumes"] = vol_info
|
||||
|
||||
return system_info
|
||||
|
||||
except Exception as e:
|
||||
self.logger.error("Error getting system info: %s", str(e))
|
||||
# 在异常处理中返回空数据
|
||||
return {
|
||||
"uptime_seconds": 0,
|
||||
"uptime": "未知",
|
||||
"cpu_temperature": "未知",
|
||||
"motherboard_temperature": "未知"
|
||||
"motherboard_temperature": "未知",
|
||||
"memory_total": "未知",
|
||||
"memory_used": "未知",
|
||||
"memory_available": "未知",
|
||||
"volumes": {}
|
||||
}
|
||||
|
||||
def save_sensor_data_for_debug(self, sensors_output: str):
|
||||
@@ -192,7 +205,7 @@ class SystemManager:
|
||||
if isinstance(temp_value, (int, float)):
|
||||
self.logger.debug("JSON中找到Tdie/Tctl温度: %s/%s = %.1f°C", key, subkey, temp_value)
|
||||
return f"{temp_value:.1f} °C"
|
||||
except Exception:
|
||||
except:
|
||||
pass
|
||||
except Exception as e:
|
||||
self.logger.warning("JSON解析失败: %s", str(e))
|
||||
@@ -368,11 +381,121 @@ class SystemManager:
|
||||
self.logger.warning("Using fallback motherboard temperature detection")
|
||||
return f"{avg_temp:.1f} °C"
|
||||
|
||||
# self.logger.warning("No motherboard temperature found in sensors output")
|
||||
return "未知"
|
||||
|
||||
|
||||
|
||||
async def get_memory_info(self) -> dict:
|
||||
"""获取内存使用信息"""
|
||||
try:
|
||||
# 使用 free 命令获取内存信息(-b 选项以字节为单位)
|
||||
mem_output = await self.coordinator.run_command("free -b")
|
||||
if not mem_output:
|
||||
return {}
|
||||
|
||||
# 解析输出
|
||||
lines = mem_output.splitlines()
|
||||
if len(lines) < 2:
|
||||
return {}
|
||||
|
||||
# 第二行是内存信息(Mem行)
|
||||
mem_line = lines[1].split()
|
||||
if len(mem_line) < 7:
|
||||
return {}
|
||||
|
||||
return {
|
||||
"memory_total": int(mem_line[1]),
|
||||
"memory_used": int(mem_line[2]),
|
||||
"memory_available": int(mem_line[6])
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
self.logger.error("获取内存信息失败: %s", str(e))
|
||||
return {}
|
||||
|
||||
async def get_vol_usage(self) -> dict:
|
||||
"""获取 /vol* 开头的存储卷使用信息"""
|
||||
try:
|
||||
# 优先使用字节单位
|
||||
df_output = await self.coordinator.run_command("df -B 1 /vol* 2>/dev/null")
|
||||
if df_output:
|
||||
return self.parse_df_bytes(df_output)
|
||||
|
||||
df_output = await self.coordinator.run_command("df -h /vol*")
|
||||
if df_output:
|
||||
return self.parse_df_human_readable(df_output)
|
||||
|
||||
return {}
|
||||
except Exception as e:
|
||||
self.logger.error("获取存储卷信息失败: %s", str(e))
|
||||
return {}
|
||||
|
||||
def parse_df_bytes(self, df_output: str) -> dict:
|
||||
volumes = {}
|
||||
for line in df_output.splitlines()[1:]:
|
||||
parts = line.split()
|
||||
if len(parts) < 6:
|
||||
continue
|
||||
|
||||
mount_point = parts[-1]
|
||||
# 只处理 /vol 开头的挂载点
|
||||
if not mount_point.startswith("/vol"):
|
||||
continue
|
||||
|
||||
try:
|
||||
size_bytes = int(parts[1])
|
||||
used_bytes = int(parts[2])
|
||||
avail_bytes = int(parts[3])
|
||||
use_percent = parts[4]
|
||||
|
||||
def bytes_to_human(b):
|
||||
for unit in ['', 'K', 'M', 'G', 'T']:
|
||||
if abs(b) < 1024.0:
|
||||
return f"{b:.1f}{unit}"
|
||||
b /= 1024.0
|
||||
return f"{b:.1f}P"
|
||||
|
||||
volumes[mount_point] = {
|
||||
"filesystem": parts[0],
|
||||
"size": bytes_to_human(size_bytes),
|
||||
"used": bytes_to_human(used_bytes),
|
||||
"available": bytes_to_human(avail_bytes),
|
||||
"use_percent": use_percent
|
||||
}
|
||||
except (ValueError, IndexError) as e:
|
||||
self.logger.debug("解析存储卷行失败: %s - %s", line, str(e))
|
||||
continue
|
||||
|
||||
return volumes
|
||||
|
||||
def parse_df_human_readable(self, df_output: str) -> dict:
|
||||
volumes = {}
|
||||
for line in df_output.splitlines()[1:]:
|
||||
parts = line.split()
|
||||
if len(parts) < 6:
|
||||
continue
|
||||
|
||||
mount_point = parts[-1]
|
||||
if not mount_point.startswith("/vol"):
|
||||
continue
|
||||
|
||||
try:
|
||||
size = parts[1]
|
||||
used = parts[2]
|
||||
avail = parts[3]
|
||||
use_percent = parts[4]
|
||||
|
||||
volumes[mount_point] = {
|
||||
"filesystem": parts[0],
|
||||
"size": size,
|
||||
"used": used,
|
||||
"available": avail,
|
||||
"use_percent": use_percent
|
||||
}
|
||||
except (ValueError, IndexError) as e:
|
||||
self.logger.debug("解析存储卷行失败: %s - %s", line, str(e))
|
||||
continue
|
||||
|
||||
return volumes
|
||||
|
||||
async def reboot_system(self):
|
||||
"""重启系统"""
|
||||
self.logger.info("Initiating system reboot...")
|
||||
@@ -380,7 +503,6 @@ class SystemManager:
|
||||
await self.coordinator.run_command("sudo reboot")
|
||||
self.logger.info("Reboot command sent")
|
||||
|
||||
# 更新系统状态为重启中
|
||||
if "system" in self.coordinator.data:
|
||||
self.coordinator.data["system"]["status"] = "rebooting"
|
||||
self.coordinator.async_update_listeners()
|
||||
@@ -395,7 +517,6 @@ class SystemManager:
|
||||
await self.coordinator.run_command("sudo shutdown -h now")
|
||||
self.logger.info("Shutdown command sent")
|
||||
|
||||
# 立即更新系统状态为关闭
|
||||
if "system" in self.coordinator.data:
|
||||
self.coordinator.data["system"]["status"] = "off"
|
||||
self.coordinator.async_update_listeners()
|
||||
|
Reference in New Issue
Block a user