mirror of
https://github.com/xiaochao99/fn_nas
synced 2025-12-25 14:27:12 +00:00
Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fcb46f429c | ||
|
|
4ae0b74e78 | ||
|
|
fd079c4ddf | ||
|
|
9e799c8948 | ||
|
|
31ffc24e6a | ||
|
|
905bbf9c96 |
@@ -33,7 +33,7 @@
|
||||
1. 进入**HACS商店**
|
||||
2. 添加自定义存储库:
|
||||
```shell
|
||||
https://github.com/anxms/fn_nas
|
||||
https://github.com/xiaochao99/fn_nas
|
||||
```
|
||||
3. 搜索"飞牛NAS",点击下载
|
||||
4. **重启Home Assistant服务**
|
||||
|
||||
72
custom_components/fn_nas/binary_sensor.py
Normal file
72
custom_components/fn_nas/binary_sensor.py
Normal file
@@ -0,0 +1,72 @@
|
||||
import logging
|
||||
from homeassistant.components.binary_sensor import BinarySensorEntity, BinarySensorDeviceClass
|
||||
from homeassistant.helpers.update_coordinator import CoordinatorEntity
|
||||
from .const import (
|
||||
DOMAIN, HDD_HEALTH, DEVICE_ID_NAS, DATA_UPDATE_COORDINATOR
|
||||
)
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
async def async_setup_entry(hass, config_entry, async_add_entities):
|
||||
domain_data = hass.data[DOMAIN][config_entry.entry_id]
|
||||
coordinator = domain_data[DATA_UPDATE_COORDINATOR]
|
||||
|
||||
entities = []
|
||||
existing_ids = set()
|
||||
|
||||
# 添加硬盘健康状态二元传感器
|
||||
for disk in coordinator.data.get("disks", []):
|
||||
health_uid = f"{config_entry.entry_id}_{disk['device']}_health_binary"
|
||||
if health_uid not in existing_ids:
|
||||
entities.append(
|
||||
DiskHealthBinarySensor(
|
||||
coordinator,
|
||||
disk["device"],
|
||||
f"硬盘 {disk.get('model', '未知')} 健康状态",
|
||||
health_uid,
|
||||
disk
|
||||
)
|
||||
)
|
||||
existing_ids.add(health_uid)
|
||||
|
||||
async_add_entities(entities)
|
||||
|
||||
|
||||
class DiskHealthBinarySensor(CoordinatorEntity, BinarySensorEntity):
|
||||
def __init__(self, coordinator, device_id, name, unique_id, disk_info):
|
||||
super().__init__(coordinator)
|
||||
self.device_id = device_id
|
||||
self._attr_name = name
|
||||
self._attr_unique_id = unique_id
|
||||
self.disk_info = disk_info
|
||||
self._attr_device_info = {
|
||||
"identifiers": {(DOMAIN, f"disk_{device_id}")},
|
||||
"name": disk_info.get("model", "未知硬盘"),
|
||||
"manufacturer": "硬盘设备",
|
||||
"via_device": (DOMAIN, DEVICE_ID_NAS)
|
||||
}
|
||||
self._attr_device_class = BinarySensorDeviceClass.PROBLEM
|
||||
|
||||
@property
|
||||
def is_on(self):
|
||||
"""返回True表示有问题,False表示正常"""
|
||||
for disk in self.coordinator.data.get("disks", []):
|
||||
if disk["device"] == self.device_id:
|
||||
health = disk.get("health", "未知")
|
||||
# 将健康状态映射为二元状态
|
||||
if health in ["正常", "良好", "OK", "ok", "good", "Good"]:
|
||||
return False # 正常状态
|
||||
elif health in ["警告", "异常", "错误", "warning", "Warning", "error", "Error", "bad", "Bad"]:
|
||||
return True # 有问题状态
|
||||
else:
|
||||
# 未知状态也视为有问题
|
||||
return True
|
||||
return True # 默认视为有问题
|
||||
|
||||
@property
|
||||
def icon(self):
|
||||
"""根据状态返回图标"""
|
||||
if self.is_on:
|
||||
return "mdi:alert-circle" # 有问题时显示警告图标
|
||||
else:
|
||||
return "mdi:check-circle" # 正常时显示对勾图标
|
||||
@@ -18,7 +18,7 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
|
||||
# 1. 添加NAS重启按钮
|
||||
entities.append(RebootButton(coordinator, config_entry.entry_id))
|
||||
|
||||
# 2. 添加虚拟机重启按钮
|
||||
# 2. 添加虚拟机重启按钮和强制关机按钮
|
||||
if "vms" in coordinator.data:
|
||||
for vm in coordinator.data["vms"]:
|
||||
entities.append(
|
||||
@@ -29,6 +29,14 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
|
||||
config_entry.entry_id
|
||||
)
|
||||
)
|
||||
entities.append(
|
||||
VMDestroyButton(
|
||||
coordinator,
|
||||
vm["name"],
|
||||
vm.get("title", vm["name"]),
|
||||
config_entry.entry_id
|
||||
)
|
||||
)
|
||||
|
||||
# 3. 添加Docker容器重启按钮(如果启用了Docker功能)
|
||||
if enable_docker and "docker_containers" in coordinator.data:
|
||||
@@ -163,3 +171,48 @@ class DockerContainerRestartButton(CoordinatorEntity, ButtonEntity):
|
||||
"操作类型": "重启容器",
|
||||
"提示": "重启操作可能需要一些时间完成"
|
||||
}
|
||||
|
||||
class VMDestroyButton(CoordinatorEntity, ButtonEntity):
|
||||
def __init__(self, coordinator, vm_name, vm_title, entry_id):
|
||||
super().__init__(coordinator)
|
||||
self.vm_name = vm_name
|
||||
self.vm_title = vm_title
|
||||
self._attr_name = f"{vm_title} 强制关机"
|
||||
self._attr_unique_id = f"{entry_id}_flynas_vm_{vm_name}_destroy"
|
||||
self._attr_device_info = {
|
||||
"identifiers": {(DOMAIN, f"vm_{vm_name}")},
|
||||
"name": vm_title,
|
||||
"via_device": (DOMAIN, DEVICE_ID_NAS)
|
||||
}
|
||||
self._attr_icon = "mdi:power-off" # 使用关机图标
|
||||
|
||||
self.vm_manager = coordinator.vm_manager if hasattr(coordinator, 'vm_manager') else None
|
||||
|
||||
async def async_press(self):
|
||||
"""强制关机虚拟机"""
|
||||
if not self.vm_manager:
|
||||
_LOGGER.error("vm_manager不可用,无法强制关机虚拟机 %s", self.vm_name)
|
||||
return
|
||||
|
||||
try:
|
||||
success = await self.vm_manager.control_vm(self.vm_name, "destroy")
|
||||
if success:
|
||||
# 更新状态为"强制关机中"
|
||||
for vm in self.coordinator.data["vms"]:
|
||||
if vm["name"] == self.vm_name:
|
||||
vm["state"] = "destroying"
|
||||
self.async_write_ha_state()
|
||||
|
||||
# 在下次更新时恢复实际状态
|
||||
self.coordinator.async_add_listener(self.async_write_ha_state)
|
||||
except Exception as e:
|
||||
_LOGGER.error("强制关机虚拟机时出错: %s", str(e), exc_info=True)
|
||||
|
||||
@property
|
||||
def extra_state_attributes(self):
|
||||
return {
|
||||
"虚拟机名称": self.vm_name,
|
||||
"操作类型": "强制关机",
|
||||
"警告": "此操作会强制关闭虚拟机,可能导致数据丢失",
|
||||
"提示": "仅在虚拟机无法正常关机时使用此功能"
|
||||
}
|
||||
@@ -3,6 +3,7 @@ from homeassistant.const import Platform
|
||||
DOMAIN = "fn_nas"
|
||||
PLATFORMS = [
|
||||
Platform.SENSOR,
|
||||
Platform.BINARY_SENSOR,
|
||||
Platform.SWITCH,
|
||||
Platform.BUTTON
|
||||
]
|
||||
|
||||
@@ -36,96 +36,124 @@ class DiskManager:
|
||||
self.logger.debug("No match found for patterns: %s", patterns)
|
||||
return default
|
||||
|
||||
async def check_disk_active(self, device: str, window: int = 30) -> bool:
|
||||
def _format_capacity(self, capacity_str: str) -> str:
|
||||
"""将容量字符串格式化为GB或TB格式"""
|
||||
if not capacity_str or capacity_str == "未知":
|
||||
return "未知"
|
||||
|
||||
try:
|
||||
# 处理逗号分隔的数字(如 "1,000,204,886,016 bytes")
|
||||
capacity_str = capacity_str.replace(',', '')
|
||||
|
||||
# 提取数字和单位
|
||||
import re
|
||||
# 匹配数字和单位(如 "500 GB", "1.0 TB", "1000204886016 bytes", "1,000,204,886,016 bytes")
|
||||
match = re.search(r'(\d+(?:\.\d+)?)\s*([KMGT]?B|bytes?)', capacity_str, re.IGNORECASE)
|
||||
if not match:
|
||||
# 如果没有匹配到单位,尝试直接提取数字
|
||||
numbers = re.findall(r'\d+', capacity_str)
|
||||
if numbers:
|
||||
# 取最大的数字(通常是容量值)
|
||||
value = float(max(numbers, key=len))
|
||||
bytes_value = value # 假设为字节
|
||||
else:
|
||||
return capacity_str
|
||||
else:
|
||||
value = float(match.group(1))
|
||||
unit = match.group(2).upper()
|
||||
|
||||
# 转换为字节
|
||||
if unit in ['B', 'BYTE', 'BYTES']:
|
||||
bytes_value = value
|
||||
elif unit in ['KB', 'KIB']:
|
||||
bytes_value = value * 1024
|
||||
elif unit in ['MB', 'MIB']:
|
||||
bytes_value = value * 1024 * 1024
|
||||
elif unit in ['GB', 'GIB']:
|
||||
bytes_value = value * 1024 * 1024 * 1024
|
||||
elif unit in ['TB', 'TIB']:
|
||||
bytes_value = value * 1024 * 1024 * 1024 * 1024
|
||||
else:
|
||||
bytes_value = value # 默认假设为字节
|
||||
|
||||
# 转换为合适的单位
|
||||
if bytes_value >= 1024**4: # 1 TB
|
||||
return f"{bytes_value / (1024**4):.1f} TB"
|
||||
elif bytes_value >= 1024**3: # 1 GB
|
||||
return f"{bytes_value / (1024**3):.1f} GB"
|
||||
elif bytes_value >= 1024**2: # 1 MB
|
||||
return f"{bytes_value / (1024**2):.1f} MB"
|
||||
elif bytes_value >= 1024: # 1 KB
|
||||
return f"{bytes_value / 1024:.1f} KB"
|
||||
else:
|
||||
return f"{bytes_value:.1f} B"
|
||||
|
||||
except Exception as e:
|
||||
self.logger.debug(f"格式化容量失败: {capacity_str}, 错误: {e}")
|
||||
return capacity_str
|
||||
|
||||
async def check_disk_active(self, device: str, window: int = 30, current_status: str = None) -> bool:
|
||||
"""检查硬盘在指定时间窗口内是否有活动"""
|
||||
try:
|
||||
stat_path = f"/sys/block/{device}/stat"
|
||||
# 首先检查硬盘当前状态
|
||||
if current_status is None:
|
||||
current_status = await self.get_disk_activity(device)
|
||||
else:
|
||||
self.logger.debug(f"使用传入的状态: {device} = {current_status}")
|
||||
|
||||
# 读取当前统计文件
|
||||
stat_output = await self.coordinator.run_command(f"cat {stat_path} 2>/dev/null")
|
||||
if not stat_output:
|
||||
self.logger.debug(f"无法读取 {stat_path},默认返回活跃状态")
|
||||
return True
|
||||
|
||||
# 解析统计信息
|
||||
stats = stat_output.split()
|
||||
if len(stats) < 11:
|
||||
self.logger.debug(f"无效的统计信息格式:{stat_output}")
|
||||
return True
|
||||
|
||||
try:
|
||||
# /sys/block/{device}/stat 字段说明:
|
||||
# 0: read I/Os requests 读请求次数
|
||||
# 1: read I/Os merged 读请求合并次数
|
||||
# 2: read sectors 读扇区数
|
||||
# 3: read ticks 读操作耗时(ms)
|
||||
# 4: write I/Os requests 写请求次数
|
||||
# 5: write I/Os merged 写请求合并次数
|
||||
# 6: write sectors 写扇区数
|
||||
# 7: write ticks 写操作耗时(ms)
|
||||
# 8: in_flight 当前进行中的I/O请求数
|
||||
# 9: io_ticks I/O活动时间(ms)
|
||||
# 10: time_in_queue 队列中的总时间(ms)
|
||||
|
||||
current_stats = {
|
||||
'read_ios': int(stats[0]),
|
||||
'write_ios': int(stats[4]),
|
||||
'in_flight': int(stats[8]),
|
||||
'io_ticks': int(stats[9])
|
||||
}
|
||||
|
||||
# 如果当前有正在进行的I/O操作,直接返回活跃状态
|
||||
if current_stats['in_flight'] > 0:
|
||||
self.logger.debug(f"磁盘 {device} 有正在进行的I/O操作: {current_stats['in_flight']}")
|
||||
self.disk_io_stats_cache[device] = current_stats
|
||||
return True
|
||||
|
||||
# 检查是否有缓存的统计信息
|
||||
cached_stats = self.disk_io_stats_cache.get(device)
|
||||
|
||||
if cached_stats:
|
||||
# 比较I/O请求次数的变化
|
||||
read_ios_diff = current_stats['read_ios'] - cached_stats['read_ios']
|
||||
write_ios_diff = current_stats['write_ios'] - cached_stats['write_ios']
|
||||
io_ticks_diff = current_stats['io_ticks'] - cached_stats['io_ticks']
|
||||
|
||||
self.logger.debug(f"磁盘 {device} I/O变化: 读={read_ios_diff}, 写={write_ios_diff}, 活动时间={io_ticks_diff}ms")
|
||||
|
||||
# 如果在检测窗口内有I/O活动,认为磁盘活跃
|
||||
if read_ios_diff > 0 or write_ios_diff > 0 or io_ticks_diff > 100: # 100ms内的活动
|
||||
self.logger.debug(f"磁盘 {device} 在窗口期内有I/O活动")
|
||||
self.disk_io_stats_cache[device] = current_stats
|
||||
return True
|
||||
|
||||
# 检查io_ticks是否表明最近有活动
|
||||
# io_ticks是累积值,如果在合理范围内增长,说明有轻微活动
|
||||
if io_ticks_diff > 0 and io_ticks_diff < window * 1000: # 在窗口时间内的轻微活动
|
||||
self.logger.debug(f"磁盘 {device} 有轻微I/O活动")
|
||||
self.disk_io_stats_cache[device] = current_stats
|
||||
return True
|
||||
else:
|
||||
# 首次检测,保存当前状态并认为活跃
|
||||
self.logger.debug(f"磁盘 {device} 首次检测,保存统计信息")
|
||||
self.disk_io_stats_cache[device] = current_stats
|
||||
return True
|
||||
|
||||
# 更新缓存
|
||||
self.disk_io_stats_cache[device] = current_stats
|
||||
|
||||
# 检查硬盘电源状态
|
||||
power_state = await self.get_disk_power_state(device)
|
||||
if power_state in ["standby", "sleep", "idle"]:
|
||||
self.logger.debug(f"磁盘 {device} 处于省电状态: {power_state}")
|
||||
return False
|
||||
|
||||
# 所有检查都通过,返回非活跃状态
|
||||
self.logger.debug(f"磁盘 {device} 判定为非活跃状态")
|
||||
# 如果硬盘处于休眠状态,直接返回非活跃
|
||||
if current_status == "休眠中":
|
||||
self.logger.debug(f"硬盘 {device} 处于休眠状态,不执行详细检测")
|
||||
return False
|
||||
|
||||
except (ValueError, IndexError) as e:
|
||||
self.logger.debug(f"解析统计信息失败: {e}")
|
||||
# 如果硬盘处于空闲状态,检查是否有近期活动
|
||||
if current_status == "空闲中":
|
||||
# 检查缓存的统计信息来判断近期活动
|
||||
stat_path = f"/sys/block/{device}/stat"
|
||||
stat_output = await self.coordinator.run_command(f"cat {stat_path} 2>/dev/null")
|
||||
|
||||
if stat_output:
|
||||
stats = stat_output.split()
|
||||
if len(stats) >= 11:
|
||||
try:
|
||||
current_read_ios = int(stats[0])
|
||||
current_write_ios = int(stats[4])
|
||||
current_io_ticks = int(stats[9])
|
||||
|
||||
cached_stats = self.disk_io_stats_cache.get(device)
|
||||
if cached_stats:
|
||||
read_diff = current_read_ios - cached_stats.get('read_ios', 0)
|
||||
write_diff = current_write_ios - cached_stats.get('write_ios', 0)
|
||||
io_ticks_diff = current_io_ticks - cached_stats.get('io_ticks', 0)
|
||||
|
||||
# 如果在最近30秒内有I/O活动,认为硬盘活跃
|
||||
if read_diff > 0 or write_diff > 0 or io_ticks_diff > 100:
|
||||
self.logger.debug(f"硬盘 {device} 近期有I/O活动,需要更新信息")
|
||||
return True
|
||||
|
||||
# 更新缓存
|
||||
self.disk_io_stats_cache[device] = {
|
||||
'read_ios': current_read_ios,
|
||||
'write_ios': current_write_ios,
|
||||
'io_ticks': current_io_ticks
|
||||
}
|
||||
|
||||
except (ValueError, IndexError):
|
||||
pass
|
||||
|
||||
# 如果硬盘空闲且没有近期活动,使用缓存信息
|
||||
self.logger.debug(f"硬盘 {device} 处于空闲状态且无近期活动,使用缓存信息")
|
||||
return False
|
||||
|
||||
# 如果硬盘处于活动中,返回活跃状态
|
||||
if current_status == "活动中":
|
||||
self.logger.debug(f"硬盘 {device} 处于活动中,执行详细检测")
|
||||
return True
|
||||
|
||||
# 默认情况下返回活跃状态
|
||||
self.logger.debug(f"硬盘 {device} 状态未知,默认执行详细检测")
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
self.logger.error(f"检测硬盘活动状态失败: {str(e)}")
|
||||
return True # 出错时默认执行检测
|
||||
@@ -161,12 +189,13 @@ class DiskManager:
|
||||
async def get_disk_activity(self, device: str) -> str:
|
||||
"""获取硬盘活动状态(活动中/空闲中/休眠中)"""
|
||||
try:
|
||||
# 先检查电源状态
|
||||
# 先检查电源状态 - 这是最可靠的休眠检测方法
|
||||
power_state = await self.get_disk_power_state(device)
|
||||
if power_state in ["standby", "sleep"]:
|
||||
self.logger.debug(f"硬盘 {device} 电源状态为 {power_state},判定为休眠中")
|
||||
return "休眠中"
|
||||
|
||||
# 检查最近的I/O活动
|
||||
# 检查最近的I/O活动 - 使用非侵入性方式
|
||||
stat_path = f"/sys/block/{device}/stat"
|
||||
stat_output = await self.coordinator.run_command(f"cat {stat_path} 2>/dev/null")
|
||||
|
||||
@@ -175,9 +204,11 @@ class DiskManager:
|
||||
if len(stats) >= 11:
|
||||
try:
|
||||
in_flight = int(stats[8]) # 当前进行中的I/O
|
||||
io_ticks = int(stats[9]) # I/O活动时间(ms)
|
||||
|
||||
# 如果有正在进行的I/O,返回活动中
|
||||
if in_flight > 0:
|
||||
self.logger.debug(f"硬盘 {device} 有进行中的I/O操作: {in_flight}")
|
||||
return "活动中"
|
||||
|
||||
# 检查缓存的统计信息来判断近期活动
|
||||
@@ -188,18 +219,64 @@ class DiskManager:
|
||||
|
||||
read_diff = current_read_ios - cached_stats.get('read_ios', 0)
|
||||
write_diff = current_write_ios - cached_stats.get('write_ios', 0)
|
||||
io_ticks_diff = io_ticks - cached_stats.get('io_ticks', 0)
|
||||
|
||||
if read_diff > 0 or write_diff > 0:
|
||||
# 如果在最近30秒内有I/O活动,认为硬盘活动中
|
||||
if read_diff > 0 or write_diff > 0 or io_ticks_diff > 100: # 100ms内的活动
|
||||
self.logger.debug(f"硬盘 {device} 近期有I/O活动: 读={read_diff}, 写={write_diff}, 活动时间={io_ticks_diff}ms")
|
||||
|
||||
# 更新缓存统计信息
|
||||
self.disk_io_stats_cache[device] = {
|
||||
'read_ios': current_read_ios,
|
||||
'write_ios': current_write_ios,
|
||||
'in_flight': in_flight,
|
||||
'io_ticks': io_ticks
|
||||
}
|
||||
return "活动中"
|
||||
else:
|
||||
# 首次检测,保存当前状态并认为活跃
|
||||
self.logger.debug(f"硬盘 {device} 首次检测,保存统计信息")
|
||||
self.disk_io_stats_cache[device] = {
|
||||
'read_ios': int(stats[0]),
|
||||
'write_ios': int(stats[4]),
|
||||
'in_flight': in_flight,
|
||||
'io_ticks': io_ticks
|
||||
}
|
||||
return "活动中" # 首次检测默认返回活动中
|
||||
|
||||
except (ValueError, IndexError):
|
||||
pass
|
||||
# 更新缓存统计信息
|
||||
self.disk_io_stats_cache[device] = {
|
||||
'read_ios': int(stats[0]),
|
||||
'write_ios': int(stats[4]),
|
||||
'in_flight': in_flight,
|
||||
'io_ticks': io_ticks
|
||||
}
|
||||
|
||||
return "空闲中"
|
||||
# 如果没有活动,返回空闲中
|
||||
self.logger.debug(f"硬盘 {device} 处于空闲状态")
|
||||
return "空闲中"
|
||||
|
||||
except (ValueError, IndexError) as e:
|
||||
self.logger.debug(f"解析硬盘 {device} 统计信息失败: {e}")
|
||||
return "活动中" # 出错时默认返回活动中,避免中断休眠
|
||||
|
||||
# 如果无法获取统计信息,检查硬盘是否可访问
|
||||
try:
|
||||
# 尝试读取设备信息,如果成功说明硬盘可访问
|
||||
test_output = await self.coordinator.run_command(f"ls -la /dev/{device} 2>/dev/null")
|
||||
if test_output and device in test_output:
|
||||
self.logger.debug(f"硬盘 {device} 可访问但无统计信息,默认返回活动中")
|
||||
return "活动中"
|
||||
else:
|
||||
self.logger.debug(f"硬盘 {device} 不可访问,可能处于休眠状态")
|
||||
return "休眠中"
|
||||
except:
|
||||
self.logger.debug(f"硬盘 {device} 检测失败,默认返回活动中")
|
||||
return "活动中"
|
||||
|
||||
except Exception as e:
|
||||
self.logger.error(f"获取硬盘 {device} 状态失败: {str(e)}", exc_info=True)
|
||||
return "未知"
|
||||
return "活动中" # 出错时默认返回活动中,避免中断休眠
|
||||
|
||||
async def get_disks_info(self) -> list[dict]:
|
||||
disks = []
|
||||
@@ -268,31 +345,31 @@ class DiskManager:
|
||||
disks.append(disk_info)
|
||||
continue
|
||||
|
||||
# 检查硬盘是否活跃
|
||||
is_active = await self.check_disk_active(device, window=30)
|
||||
# 检查硬盘是否活跃,传入当前状态确保一致性
|
||||
is_active = await self.check_disk_active(device, window=30, current_status=status)
|
||||
if not is_active:
|
||||
self.logger.debug(f"硬盘 {device} 处于非活跃状态,使用上一次获取的信息")
|
||||
|
||||
# 优先使用缓存的完整信息
|
||||
if cached_info:
|
||||
disk_info.update({
|
||||
"model": cached_info.get("model", "未检测"),
|
||||
"serial": cached_info.get("serial", "未检测"),
|
||||
"capacity": cached_info.get("capacity", "未检测"),
|
||||
"health": cached_info.get("health", "未检测"),
|
||||
"temperature": cached_info.get("temperature", "未检测"),
|
||||
"power_on_hours": cached_info.get("power_on_hours", "未检测"),
|
||||
"model": cached_info.get("model", "未知"),
|
||||
"serial": cached_info.get("serial", "未知"),
|
||||
"capacity": cached_info.get("capacity", "未知"),
|
||||
"health": cached_info.get("health", "未知"),
|
||||
"temperature": cached_info.get("temperature", "未知"),
|
||||
"power_on_hours": cached_info.get("power_on_hours", "未知"),
|
||||
"attributes": cached_info.get("attributes", {})
|
||||
})
|
||||
else:
|
||||
# 如果没有缓存信息,使用默认值
|
||||
disk_info.update({
|
||||
"model": "未检测",
|
||||
"serial": "未检测",
|
||||
"capacity": "未检测",
|
||||
"health": "未检测",
|
||||
"temperature": "未检测",
|
||||
"power_on_hours": "未检测",
|
||||
"model": "未知",
|
||||
"serial": "未知",
|
||||
"capacity": "未知",
|
||||
"health": "未知",
|
||||
"temperature": "未知",
|
||||
"power_on_hours": "未知",
|
||||
"attributes": {}
|
||||
})
|
||||
|
||||
@@ -336,31 +413,45 @@ class DiskManager:
|
||||
|
||||
async def _get_full_disk_info(self, disk_info, device_path):
|
||||
"""获取硬盘的完整信息(模型、序列号、健康状态等)"""
|
||||
# 获取基本信息
|
||||
# 获取基本信息 - 首先尝试NVMe格式
|
||||
info_output = await self.coordinator.run_command(f"smartctl -i {device_path}")
|
||||
self.logger.debug("smartctl -i output for %s: %s", disk_info["device"], info_output[:200] + "..." if len(info_output) > 200 else info_output)
|
||||
|
||||
# 模型
|
||||
# 检查是否为NVMe设备
|
||||
is_nvme = "nvme" in disk_info["device"].lower()
|
||||
|
||||
# 模型 - 增强NVMe支持
|
||||
disk_info["model"] = self.extract_value(
|
||||
info_output,
|
||||
[
|
||||
r"Device Model:\s*(.+)",
|
||||
r"Model(?: Family)?\s*:\s*(.+)",
|
||||
r"Model\s*Number:\s*(.+)"
|
||||
r"Model\s*Number:\s*(.+)",
|
||||
r"Product:\s*(.+)", # NVMe格式
|
||||
r"Model Number:\s*(.+)", # NVMe格式
|
||||
]
|
||||
)
|
||||
|
||||
# 序列号
|
||||
# 序列号 - 增强NVMe支持
|
||||
disk_info["serial"] = self.extract_value(
|
||||
info_output,
|
||||
r"Serial Number\s*:\s*(.+)"
|
||||
[
|
||||
r"Serial Number\s*:\s*(.+)",
|
||||
r"Serial Number:\s*(.+)", # NVMe格式
|
||||
r"Serial\s*:\s*(.+)", # NVMe格式
|
||||
]
|
||||
)
|
||||
|
||||
# 容量
|
||||
disk_info["capacity"] = self.extract_value(
|
||||
info_output,
|
||||
r"User Capacity:\s*([^[]+)"
|
||||
)
|
||||
# 容量 - 增强NVMe支持并转换为GB/TB格式
|
||||
capacity_patterns = [
|
||||
r"User Capacity:\s*([^[]+)",
|
||||
r"Namespace 1 Size/Capacity:\s*([^[]+)", # NVMe格式
|
||||
r"Total NVM Capacity:\s*([^[]+)", # NVMe格式
|
||||
r"Capacity:\s*([^[]+)", # NVMe格式
|
||||
]
|
||||
|
||||
raw_capacity = self.extract_value(info_output, capacity_patterns)
|
||||
disk_info["capacity"] = self._format_capacity(raw_capacity)
|
||||
|
||||
# 健康状态
|
||||
health_output = await self.coordinator.run_command(f"smartctl -H {device_path}")
|
||||
@@ -437,6 +528,46 @@ class DiskManager:
|
||||
# 改进的通电时间检测逻辑 - 处理特殊格式
|
||||
power_on_hours = "未知"
|
||||
|
||||
# 检查是否为NVMe设备
|
||||
is_nvme = "nvme" in disk_info["device"].lower()
|
||||
|
||||
# 方法0:NVMe设备的通电时间提取(优先处理)
|
||||
if is_nvme:
|
||||
# NVMe格式的通电时间提取 - 支持带逗号的数字格式
|
||||
nvme_patterns = [
|
||||
r"Power On Hours\s*:\s*([\d,]+)", # 支持带逗号的数字格式(如 "6,123")
|
||||
r"Power On Time\s*:\s*([\d,]+)", # NVMe备用格式
|
||||
r"Power on hours\s*:\s*([\d,]+)", # 小写格式
|
||||
r"Power on time\s*:\s*([\d,]+)", # 小写格式
|
||||
]
|
||||
|
||||
for pattern in nvme_patterns:
|
||||
match = re.search(pattern, data_output, re.IGNORECASE)
|
||||
if match:
|
||||
try:
|
||||
# 处理带逗号的数字格式(如 "6,123")
|
||||
hours_str = match.group(1).replace(',', '')
|
||||
hours = int(hours_str)
|
||||
power_on_hours = f"{hours} 小时"
|
||||
self.logger.debug("Found NVMe power_on_hours via pattern %s: %s", pattern, power_on_hours)
|
||||
break
|
||||
except:
|
||||
continue
|
||||
|
||||
# 如果还没找到,尝试在SMART数据部分查找
|
||||
if power_on_hours == "未知":
|
||||
# 查找SMART数据部分中的Power On Hours
|
||||
smart_section_match = re.search(r"SMART/Health Information.*?Power On Hours\s*:\s*([\d,]+)",
|
||||
data_output, re.IGNORECASE | re.DOTALL)
|
||||
if smart_section_match:
|
||||
try:
|
||||
hours_str = smart_section_match.group(1).replace(',', '')
|
||||
hours = int(hours_str)
|
||||
power_on_hours = f"{hours} 小时"
|
||||
self.logger.debug("Found NVMe power_on_hours in SMART section: %s", power_on_hours)
|
||||
except:
|
||||
pass
|
||||
|
||||
# 方法1:提取属性9的RAW_VALUE(处理特殊格式)
|
||||
attr9_match = re.search(
|
||||
r"^\s*9\s+Power_On_Hours\b[^\n]+\s+(\d+)h(?:\+(\d+)m(?:\+(\d+)\.\d+s)?)?",
|
||||
@@ -474,7 +605,7 @@ class DiskManager:
|
||||
[
|
||||
# 精确匹配属性9行
|
||||
r"^\s*9\s+Power_On_Hours\b[^\n]+\s+(\d+)\s*$",
|
||||
|
||||
r"^\s*9\s+Power On Hours\b[^\n]+\s+(\d+)h(?:\+(\d+)m(?:\+(\d+)\.\d+s)?)?",
|
||||
# 通用匹配模式
|
||||
r"9\s+Power_On_Hours\b.*?(\d+)\b",
|
||||
r"Power_On_Hours\b.*?(\d+)\b",
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
{
|
||||
"domain": "fn_nas",
|
||||
"name": "飞牛NAS",
|
||||
"version": "1.3.7",
|
||||
"documentation": "https://github.com/anxms/fn_nas",
|
||||
"version": "1.3.9",
|
||||
"documentation": "https://github.com/xiaochao99/fn_nas",
|
||||
"dependencies": [],
|
||||
"codeowners": ["@anxms"],
|
||||
"codeowners": ["@xiaochao99"],
|
||||
"requirements": ["asyncssh>=2.13.1"],
|
||||
"iot_class": "local_polling",
|
||||
"config_flow": true
|
||||
|
||||
@@ -3,8 +3,8 @@ from homeassistant.components.sensor import SensorEntity, SensorDeviceClass, Sen
|
||||
from homeassistant.helpers.update_coordinator import CoordinatorEntity
|
||||
from homeassistant.const import UnitOfTemperature
|
||||
from .const import (
|
||||
DOMAIN, HDD_TEMP, HDD_HEALTH, HDD_STATUS, SYSTEM_INFO, ICON_DISK,
|
||||
ICON_TEMPERATURE, ICON_HEALTH, ATTR_DISK_MODEL, ATTR_SERIAL_NO,
|
||||
DOMAIN, HDD_TEMP, HDD_STATUS, SYSTEM_INFO, ICON_DISK,
|
||||
ICON_TEMPERATURE, ATTR_DISK_MODEL, ATTR_SERIAL_NO,
|
||||
ATTR_POWER_ON_HOURS, ATTR_TOTAL_CAPACITY, ATTR_HEALTH_STATUS,
|
||||
DEVICE_ID_NAS, DATA_UPDATE_COORDINATOR
|
||||
)
|
||||
@@ -38,22 +38,7 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
|
||||
)
|
||||
existing_ids.add(temp_uid)
|
||||
|
||||
# 健康状态传感器
|
||||
health_uid = f"{config_entry.entry_id}_{disk['device']}_health"
|
||||
if health_uid not in existing_ids:
|
||||
entities.append(
|
||||
DiskSensor(
|
||||
coordinator,
|
||||
disk["device"],
|
||||
HDD_HEALTH,
|
||||
f"硬盘 {disk.get('model', '未知')} 健康状态",
|
||||
health_uid,
|
||||
None,
|
||||
ICON_HEALTH,
|
||||
disk
|
||||
)
|
||||
)
|
||||
existing_ids.add(health_uid)
|
||||
|
||||
|
||||
# 硬盘状态传感器
|
||||
status_uid = f"{config_entry.entry_id}_{disk['device']}_status"
|
||||
@@ -302,7 +287,7 @@ class DiskSensor(CoordinatorEntity, SensorEntity):
|
||||
if disk["device"] == self.device_id:
|
||||
if self.sensor_type == HDD_TEMP:
|
||||
temp = disk.get("temperature")
|
||||
if temp is None or temp == "未知" or temp == "未检测":
|
||||
if temp is None or temp == "未知":
|
||||
return None
|
||||
if isinstance(temp, str):
|
||||
try:
|
||||
@@ -314,11 +299,7 @@ class DiskSensor(CoordinatorEntity, SensorEntity):
|
||||
elif isinstance(temp, (int, float)):
|
||||
return temp
|
||||
return None
|
||||
elif self.sensor_type == HDD_HEALTH:
|
||||
health = disk.get("health", "未知")
|
||||
if health == "未检测":
|
||||
return "未检测"
|
||||
return health if health != "未知" else "未知状态"
|
||||
|
||||
elif self.sensor_type == HDD_STATUS:
|
||||
return disk.get("status", "未知")
|
||||
return None
|
||||
|
||||
@@ -213,29 +213,84 @@ class SystemManager:
|
||||
for i, line in enumerate(lines):
|
||||
line_lower = line.lower().strip()
|
||||
|
||||
# 主板温度关键词
|
||||
# 主板温度关键词 - 扩展关键词列表
|
||||
if any(keyword in line_lower for keyword in [
|
||||
"motherboard", "mobo", "mb", "system", "chipset",
|
||||
"ambient", "temp1:", "temp2:", "temp3:", "systin"
|
||||
"ambient", "temp1:", "temp2:", "temp3:", "systin",
|
||||
"acpitz", "thermal", "pch", "platform", "board",
|
||||
"sys", "thermal zone", "acpi", "isa"
|
||||
]) and not any(cpu_keyword in line_lower for cpu_keyword in [
|
||||
"cpu", "core", "package", "processor", "tctl", "tdie"
|
||||
]) and not any(exclude in line_lower for exclude in ["fan", "rpm"]):
|
||||
|
||||
self._debug_log(f"找到可能的主板温度行: {line}")
|
||||
|
||||
# 多种温度格式匹配
|
||||
temp_value = None
|
||||
|
||||
# 格式1: +45.0°C (high = +80.0°C, crit = +95.0°C)
|
||||
if '+' in line and '°c' in line_lower:
|
||||
try:
|
||||
temp_match = line.split('+')[1].split('°')[0].strip()
|
||||
temp = float(temp_match)
|
||||
# 主板温度通常在15-70度之间
|
||||
if 15 <= temp <= 70:
|
||||
self._info_log(f"从sensors提取主板温度: {temp:.1f}°C")
|
||||
return f"{temp:.1f} °C"
|
||||
else:
|
||||
self._debug_log(f"主板温度值超出合理范围: {temp:.1f}°C")
|
||||
except (ValueError, IndexError) as e:
|
||||
self._debug_log(f"解析主板温度失败: {e}")
|
||||
continue
|
||||
temp_value = float(temp_match)
|
||||
except (ValueError, IndexError):
|
||||
pass
|
||||
|
||||
# 格式2: 45.0°C
|
||||
if temp_value is None and '°c' in line_lower:
|
||||
try:
|
||||
# 查找数字后跟°C的模式
|
||||
import re
|
||||
temp_match = re.search(r'(\d+\.?\d*)\s*°c', line_lower)
|
||||
if temp_match:
|
||||
temp_value = float(temp_match.group(1))
|
||||
except (ValueError, AttributeError):
|
||||
pass
|
||||
|
||||
# 格式3: 45.0 C (没有°符号)
|
||||
if temp_value is None and (' c' in line_lower or 'c ' in line_lower):
|
||||
try:
|
||||
# 查找数字后跟C的模式
|
||||
import re
|
||||
temp_match = re.search(r'(\d+\.?\d*)\s*c', line_lower)
|
||||
if temp_match:
|
||||
temp_value = float(temp_match.group(1))
|
||||
except (ValueError, AttributeError):
|
||||
pass
|
||||
|
||||
if temp_value is not None:
|
||||
# 主板温度通常在15-70度之间,但放宽范围到10-80度
|
||||
if 10 <= temp_value <= 80:
|
||||
# 存储候选值,不立即返回
|
||||
import re
|
||||
if not hasattr(self, '_temp_candidates'):
|
||||
self._temp_candidates = []
|
||||
self._temp_candidates.append((temp_value, line))
|
||||
self._debug_log(f"找到有效主板温度候选: {temp_value:.1f}°C")
|
||||
else:
|
||||
self._debug_log(f"主板温度值超出合理范围: {temp_value:.1f}°C")
|
||||
continue
|
||||
|
||||
# 处理候选值
|
||||
if hasattr(self, '_temp_candidates') and self._temp_candidates:
|
||||
# 优先选择温度在25-45度之间的值(典型主板温度)
|
||||
ideal_candidates = [t for t in self._temp_candidates if 25 <= t[0] <= 45]
|
||||
if ideal_candidates:
|
||||
best_temp = ideal_candidates[0][0] # 取第一个理想候选值
|
||||
else:
|
||||
# 如果没有理想值,取第一个候选值
|
||||
best_temp = self._temp_candidates[0][0]
|
||||
|
||||
self._info_log(f"从sensors提取主板温度: {best_temp:.1f}°C")
|
||||
# 清理候选值
|
||||
delattr(self, '_temp_candidates')
|
||||
return f"{best_temp:.1f} °C"
|
||||
|
||||
# 如果没有找到主板温度,尝试备用方法
|
||||
self._debug_log("尝试备用方法获取主板温度")
|
||||
mobo_temp = self._extract_mobo_temp_fallback(sensors_output)
|
||||
if mobo_temp != "未知":
|
||||
return mobo_temp
|
||||
|
||||
self._warning_log("未在sensors输出中找到主板温度")
|
||||
return "未知"
|
||||
@@ -244,9 +299,58 @@ class SystemManager:
|
||||
self._error_log(f"解析sensors主板温度输出失败: {e}")
|
||||
return "未知"
|
||||
|
||||
def _extract_mobo_temp_fallback(self, sensors_output: str) -> str:
|
||||
"""备用方法获取主板温度"""
|
||||
try:
|
||||
lines = sensors_output.split('\n')
|
||||
|
||||
# 方法1: 查找非CPU的温度传感器
|
||||
for line in lines:
|
||||
line_lower = line.lower().strip()
|
||||
|
||||
# 跳过明显的CPU相关行
|
||||
if any(cpu_keyword in line_lower for cpu_keyword in [
|
||||
"cpu", "core", "package", "processor", "tctl", "tdie"
|
||||
]):
|
||||
continue
|
||||
|
||||
# 查找温度值
|
||||
if '°c' in line_lower or ' c' in line_lower:
|
||||
# 尝试提取温度值
|
||||
import re
|
||||
temp_match = re.search(r'(\d+\.?\d*)\s*[°]?\s*c', line_lower)
|
||||
if temp_match:
|
||||
temp_value = float(temp_match.group(1))
|
||||
if 15 <= temp_value <= 60: # 主板温度合理范围
|
||||
self._info_log(f"通过备用方法获取主板温度: {temp_value:.1f}°C")
|
||||
return f"{temp_value:.1f} °C"
|
||||
|
||||
# 方法2: 查找hwmon设备中的主板温度
|
||||
for i, line in enumerate(lines):
|
||||
line_lower = line.lower()
|
||||
if "hwmon" in line_lower and "temp" in line_lower:
|
||||
# 检查接下来的几行是否有温度值
|
||||
for j in range(i+1, min(i+5, len(lines))):
|
||||
next_line = lines[j].lower()
|
||||
if '°c' in next_line or ' c' in next_line:
|
||||
import re
|
||||
temp_match = re.search(r'(\d+\.?\d*)\s*[°]?\s*c', next_line)
|
||||
if temp_match:
|
||||
temp_value = float(temp_match.group(1))
|
||||
if 15 <= temp_value <= 60:
|
||||
self._info_log(f"通过hwmon获取主板温度: {temp_value:.1f}°C")
|
||||
return f"{temp_value:.1f} °C"
|
||||
|
||||
return "未知"
|
||||
|
||||
except Exception as e:
|
||||
self._debug_log(f"备用方法获取主板温度失败: {e}")
|
||||
return "未知"
|
||||
|
||||
def format_uptime(self, seconds: float) -> str:
|
||||
"""格式化运行时间为易读格式"""
|
||||
try:
|
||||
days, remainder = divmod(seconds, 86400)
|
||||
days, remainder = divmod(seconds, 86400)
|
||||
hours, remainder = divmod(remainder, 3600)
|
||||
minutes, seconds = divmod(remainder, 60)
|
||||
|
||||
@@ -84,7 +84,7 @@ class VMManager:
|
||||
|
||||
async def control_vm(self, vm_name, action):
|
||||
"""控制虚拟机操作"""
|
||||
valid_actions = ["start", "shutdown", "reboot"]
|
||||
valid_actions = ["start", "shutdown", "reboot", "destroy"]
|
||||
if action not in valid_actions:
|
||||
raise ValueError(f"无效操作: {action}")
|
||||
|
||||
|
||||
Reference in New Issue
Block a user