mirror of
https://github.com/xiaochao99/fn_nas
synced 2025-12-26 14:57:12 +00:00
Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
035a7e7413 | ||
|
|
41d4e4cc0d | ||
|
|
fcb46f429c | ||
|
|
4ae0b74e78 | ||
|
|
fd079c4ddf |
@@ -33,7 +33,7 @@
|
|||||||
1. 进入**HACS商店**
|
1. 进入**HACS商店**
|
||||||
2. 添加自定义存储库:
|
2. 添加自定义存储库:
|
||||||
```shell
|
```shell
|
||||||
https://github.com/anxms/fn_nas
|
https://github.com/xiaochao99/fn_nas
|
||||||
```
|
```
|
||||||
3. 搜索"飞牛NAS",点击下载
|
3. 搜索"飞牛NAS",点击下载
|
||||||
4. **重启Home Assistant服务**
|
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" # 正常时显示对勾图标
|
||||||
@@ -3,7 +3,7 @@ from homeassistant.components.button import ButtonEntity
|
|||||||
from homeassistant.helpers.entity import EntityCategory
|
from homeassistant.helpers.entity import EntityCategory
|
||||||
from homeassistant.helpers.update_coordinator import CoordinatorEntity
|
from homeassistant.helpers.update_coordinator import CoordinatorEntity
|
||||||
from .const import (
|
from .const import (
|
||||||
DOMAIN, DATA_UPDATE_COORDINATOR, DEVICE_ID_NAS, CONF_ENABLE_DOCKER
|
DOMAIN, DATA_UPDATE_COORDINATOR, DEVICE_ID_NAS, CONF_ENABLE_DOCKER, DEVICE_ID_ZFS
|
||||||
)
|
)
|
||||||
|
|
||||||
_LOGGER = logging.getLogger(__name__)
|
_LOGGER = logging.getLogger(__name__)
|
||||||
@@ -52,6 +52,19 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# 4. 添加ZFS存储池scrub按钮
|
||||||
|
if "zpools" in coordinator.data:
|
||||||
|
for zpool in coordinator.data["zpools"]:
|
||||||
|
safe_name = zpool["name"].replace(" ", "_").replace("/", "_").replace(".", "_")
|
||||||
|
entities.append(
|
||||||
|
ZpoolScrubButton(
|
||||||
|
coordinator,
|
||||||
|
zpool["name"],
|
||||||
|
safe_name,
|
||||||
|
config_entry.entry_id
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
async_add_entities(entities)
|
async_add_entities(entities)
|
||||||
|
|
||||||
class RebootButton(CoordinatorEntity, ButtonEntity):
|
class RebootButton(CoordinatorEntity, ButtonEntity):
|
||||||
@@ -215,4 +228,52 @@ class VMDestroyButton(CoordinatorEntity, ButtonEntity):
|
|||||||
"操作类型": "强制关机",
|
"操作类型": "强制关机",
|
||||||
"警告": "此操作会强制关闭虚拟机,可能导致数据丢失",
|
"警告": "此操作会强制关闭虚拟机,可能导致数据丢失",
|
||||||
"提示": "仅在虚拟机无法正常关机时使用此功能"
|
"提示": "仅在虚拟机无法正常关机时使用此功能"
|
||||||
|
}
|
||||||
|
|
||||||
|
class ZpoolScrubButton(CoordinatorEntity, ButtonEntity):
|
||||||
|
def __init__(self, coordinator, zpool_name, safe_name, entry_id):
|
||||||
|
super().__init__(coordinator)
|
||||||
|
self.zpool_name = zpool_name
|
||||||
|
self.safe_name = safe_name
|
||||||
|
self._attr_name = f"ZFS {zpool_name} 数据检查"
|
||||||
|
self._attr_unique_id = f"{entry_id}_zpool_{safe_name}_scrub"
|
||||||
|
self._attr_device_info = {
|
||||||
|
"identifiers": {(DOMAIN, DEVICE_ID_ZFS)},
|
||||||
|
"name": "ZFS存储池",
|
||||||
|
"via_device": (DOMAIN, DEVICE_ID_NAS)
|
||||||
|
}
|
||||||
|
self._attr_icon = "mdi:harddisk-check"
|
||||||
|
|
||||||
|
@property
|
||||||
|
def available(self):
|
||||||
|
"""检查按钮是否可用(当scrub进行中时不可点击)"""
|
||||||
|
scrub_status = self.coordinator.data.get("scrub_status", {}).get(self.zpool_name, {})
|
||||||
|
return not scrub_status.get("scrub_in_progress", False)
|
||||||
|
|
||||||
|
async def async_press(self):
|
||||||
|
"""执行ZFS存储池数据一致性检查"""
|
||||||
|
try:
|
||||||
|
# 检查是否已经有scrub在进行中
|
||||||
|
scrub_status = self.coordinator.data.get("scrub_status", {}).get(self.zpool_name, {})
|
||||||
|
if scrub_status.get("scrub_in_progress", False):
|
||||||
|
self.coordinator.logger.warning(f"ZFS存储池 {self.zpool_name} 已在进行数据一致性检查")
|
||||||
|
return
|
||||||
|
|
||||||
|
success = await self.coordinator.scrub_zpool(self.zpool_name)
|
||||||
|
if success:
|
||||||
|
self.coordinator.logger.info(f"ZFS存储池 {self.zpool_name} 数据一致性检查启动成功")
|
||||||
|
# 立即刷新状态以更新按钮状态
|
||||||
|
await self.coordinator.async_request_refresh()
|
||||||
|
else:
|
||||||
|
self.coordinator.logger.error(f"ZFS存储池 {self.zpool_name} 数据一致性检查启动失败")
|
||||||
|
except Exception as e:
|
||||||
|
self.coordinator.logger.error(f"启动ZFS存储池 {self.zpool_name} 数据一致性检查时出错: {str(e)}", exc_info=True)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def extra_state_attributes(self):
|
||||||
|
return {
|
||||||
|
"存储池名称": self.zpool_name,
|
||||||
|
"操作类型": "数据一致性检查",
|
||||||
|
"说明": "对ZFS存储池执行数据完整性和一致性验证",
|
||||||
|
"提示": "此操作可能需要较长时间完成,建议在低峰期执行"
|
||||||
}
|
}
|
||||||
@@ -3,6 +3,7 @@ from homeassistant.const import Platform
|
|||||||
DOMAIN = "fn_nas"
|
DOMAIN = "fn_nas"
|
||||||
PLATFORMS = [
|
PLATFORMS = [
|
||||||
Platform.SENSOR,
|
Platform.SENSOR,
|
||||||
|
Platform.BINARY_SENSOR,
|
||||||
Platform.SWITCH,
|
Platform.SWITCH,
|
||||||
Platform.BUTTON
|
Platform.BUTTON
|
||||||
]
|
]
|
||||||
@@ -32,7 +33,8 @@ HDD_HEALTH = "health"
|
|||||||
HDD_STATUS = "status"
|
HDD_STATUS = "status"
|
||||||
SYSTEM_INFO = "system"
|
SYSTEM_INFO = "system"
|
||||||
FAN_SPEED = "fan_speed"
|
FAN_SPEED = "fan_speed"
|
||||||
UPS_INFO = "ups_info"
|
UPS_INFO = "ups_info"
|
||||||
|
ZFS_POOL = "zfs_pool"
|
||||||
|
|
||||||
ATTR_DISK_MODEL = "硬盘型号"
|
ATTR_DISK_MODEL = "硬盘型号"
|
||||||
ATTR_SERIAL_NO = "序列号"
|
ATTR_SERIAL_NO = "序列号"
|
||||||
@@ -48,8 +50,28 @@ ICON_TEMPERATURE = "mdi:thermometer"
|
|||||||
ICON_HEALTH = "mdi:heart-pulse"
|
ICON_HEALTH = "mdi:heart-pulse"
|
||||||
ICON_POWER = "mdi:power"
|
ICON_POWER = "mdi:power"
|
||||||
ICON_RESTART = "mdi:restart"
|
ICON_RESTART = "mdi:restart"
|
||||||
|
ICON_ZFS = "mdi:harddisk-plus"
|
||||||
|
|
||||||
# 设备标识符常量
|
# 设备标识符常量
|
||||||
DEVICE_ID_NAS = "flynas_nas_system"
|
DEVICE_ID_NAS = "flynas_nas_system"
|
||||||
DEVICE_ID_UPS = "flynas_ups"
|
DEVICE_ID_UPS = "flynas_ups"
|
||||||
CONF_NETWORK_MACS = "network_macs"
|
DEVICE_ID_ZFS = "flynas_zfs"
|
||||||
|
CONF_NETWORK_MACS = "network_macs"
|
||||||
|
|
||||||
|
# ZFS相关常量
|
||||||
|
ATTR_ZPOOL_NAME = "存储池名称"
|
||||||
|
ATTR_ZPOOL_HEALTH = "健康状态"
|
||||||
|
ATTR_ZPOOL_SIZE = "总大小"
|
||||||
|
ATTR_ZPOOL_ALLOC = "已使用"
|
||||||
|
ATTR_ZPOOL_FREE = "可用空间"
|
||||||
|
ATTR_ZPOOL_CAPACITY = "使用率"
|
||||||
|
ATTR_ZPOOL_FRAGMENTATION = "碎片率"
|
||||||
|
ATTR_ZPOOL_CKPOINT = "检查点"
|
||||||
|
ATTR_ZPOOL_EXPANDSZ = "扩展大小"
|
||||||
|
ATTR_ZPOOL_DEDUP = "重复数据删除率"
|
||||||
|
ATTR_ZPOOL_SCRUB_STATUS = "检查状态"
|
||||||
|
ATTR_ZPOOL_SCRUB_PROGRESS = "检查进度"
|
||||||
|
ATTR_ZPOOL_SCRUB_SCAN_RATE = "扫描速度"
|
||||||
|
ATTR_ZPOOL_SCRUB_TIME_REMAINING = "剩余时间"
|
||||||
|
ATTR_ZPOOL_SCRUB_ISSUED = "已发出数据"
|
||||||
|
ATTR_ZPOOL_SCRUB_REPAIRED = "已修复数据"
|
||||||
@@ -79,7 +79,9 @@ class FlynasCoordinator(DataUpdateCoordinator):
|
|||||||
},
|
},
|
||||||
"ups": {},
|
"ups": {},
|
||||||
"vms": [],
|
"vms": [],
|
||||||
"docker_containers": []
|
"docker_containers": [],
|
||||||
|
"zpools": [],
|
||||||
|
"scrub_status": {}
|
||||||
}
|
}
|
||||||
|
|
||||||
def _debug_log(self, message: str):
|
def _debug_log(self, message: str):
|
||||||
@@ -385,6 +387,18 @@ class FlynasCoordinator(DataUpdateCoordinator):
|
|||||||
disks = await self.disk_manager.get_disks_info()
|
disks = await self.disk_manager.get_disks_info()
|
||||||
self._debug_log(f"磁盘信息获取完成,数量: {len(disks)}")
|
self._debug_log(f"磁盘信息获取完成,数量: {len(disks)}")
|
||||||
|
|
||||||
|
self._debug_log("开始获取ZFS存储池信息...")
|
||||||
|
zpools = await self.disk_manager.get_zpools()
|
||||||
|
self._debug_log(f"ZFS存储池信息获取完成,数量: {len(zpools)}")
|
||||||
|
|
||||||
|
# 获取所有ZFS存储池的scrub状态
|
||||||
|
scrub_status = {}
|
||||||
|
for zpool in zpools:
|
||||||
|
self._debug_log(f"开始获取存储池 {zpool['name']} 的scrub状态...")
|
||||||
|
scrub_info = await self.disk_manager.get_zpool_status(zpool['name'])
|
||||||
|
scrub_status[zpool['name']] = scrub_info
|
||||||
|
self._debug_log(f"存储池 {zpool['name']} scrub状态获取完成")
|
||||||
|
|
||||||
self._debug_log("开始获取UPS信息...")
|
self._debug_log("开始获取UPS信息...")
|
||||||
ups_info = await self.ups_manager.get_ups_info()
|
ups_info = await self.ups_manager.get_ups_info()
|
||||||
self._debug_log("UPS信息获取完成")
|
self._debug_log("UPS信息获取完成")
|
||||||
@@ -416,7 +430,9 @@ class FlynasCoordinator(DataUpdateCoordinator):
|
|||||||
"system": {**system, "status": status},
|
"system": {**system, "status": status},
|
||||||
"ups": ups_info,
|
"ups": ups_info,
|
||||||
"vms": vms,
|
"vms": vms,
|
||||||
"docker_containers": docker_containers
|
"docker_containers": docker_containers,
|
||||||
|
"zpools": zpools,
|
||||||
|
"scrub_status": scrub_status
|
||||||
}
|
}
|
||||||
|
|
||||||
self._debug_log(f"数据更新完成: disks={len(disks)}, vms={len(vms)}, containers={len(docker_containers)}")
|
self._debug_log(f"数据更新完成: disks={len(disks)}, vms={len(vms)}, containers={len(docker_containers)}")
|
||||||
@@ -437,6 +453,24 @@ class FlynasCoordinator(DataUpdateCoordinator):
|
|||||||
async def reboot_system(self):
|
async def reboot_system(self):
|
||||||
"""重启系统 - 委托给SystemManager"""
|
"""重启系统 - 委托给SystemManager"""
|
||||||
return await self.system_manager.reboot_system()
|
return await self.system_manager.reboot_system()
|
||||||
|
|
||||||
|
async def scrub_zpool(self, pool_name: str) -> bool:
|
||||||
|
"""执行ZFS存储池数据一致性检查"""
|
||||||
|
try:
|
||||||
|
self._debug_log(f"开始对ZFS存储池 {pool_name} 执行scrub操作")
|
||||||
|
command = f"zpool scrub {pool_name}"
|
||||||
|
result = await self.run_command(command)
|
||||||
|
|
||||||
|
if result and not result.lower().startswith("cannot"):
|
||||||
|
self._debug_log(f"ZFS存储池 {pool_name} scrub操作启动成功")
|
||||||
|
return True
|
||||||
|
else:
|
||||||
|
self.logger.error(f"ZFS存储池 {pool_name} scrub操作失败: {result}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
self.logger.error(f"执行ZFS存储池 {pool_name} scrub操作时出错: {str(e)}", exc_info=True)
|
||||||
|
return False
|
||||||
|
|
||||||
class UPSDataUpdateCoordinator(DataUpdateCoordinator):
|
class UPSDataUpdateCoordinator(DataUpdateCoordinator):
|
||||||
def __init__(self, hass: HomeAssistant, config, main_coordinator):
|
def __init__(self, hass: HomeAssistant, config, main_coordinator):
|
||||||
|
|||||||
@@ -92,11 +92,14 @@ class DiskManager:
|
|||||||
self.logger.debug(f"格式化容量失败: {capacity_str}, 错误: {e}")
|
self.logger.debug(f"格式化容量失败: {capacity_str}, 错误: {e}")
|
||||||
return capacity_str
|
return capacity_str
|
||||||
|
|
||||||
async def check_disk_active(self, device: str, window: int = 30) -> bool:
|
async def check_disk_active(self, device: str, window: int = 30, current_status: str = None) -> bool:
|
||||||
"""检查硬盘在指定时间窗口内是否有活动"""
|
"""检查硬盘在指定时间窗口内是否有活动"""
|
||||||
try:
|
try:
|
||||||
# 首先检查硬盘当前状态
|
# 首先检查硬盘当前状态
|
||||||
current_status = await self.get_disk_activity(device)
|
if current_status is None:
|
||||||
|
current_status = await self.get_disk_activity(device)
|
||||||
|
else:
|
||||||
|
self.logger.debug(f"使用传入的状态: {device} = {current_status}")
|
||||||
|
|
||||||
# 如果硬盘处于休眠状态,直接返回非活跃
|
# 如果硬盘处于休眠状态,直接返回非活跃
|
||||||
if current_status == "休眠中":
|
if current_status == "休眠中":
|
||||||
@@ -138,8 +141,8 @@ class DiskManager:
|
|||||||
except (ValueError, IndexError):
|
except (ValueError, IndexError):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
# 如果硬盘空闲且没有近期活动,返回非活跃
|
# 如果硬盘空闲且没有近期活动,使用缓存信息
|
||||||
self.logger.debug(f"硬盘 {device} 处于空闲状态且无近期活动,不执行详细检测")
|
self.logger.debug(f"硬盘 {device} 处于空闲状态且无近期活动,使用缓存信息")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# 如果硬盘处于活动中,返回活跃状态
|
# 如果硬盘处于活动中,返回活跃状态
|
||||||
@@ -186,9 +189,10 @@ class DiskManager:
|
|||||||
async def get_disk_activity(self, device: str) -> str:
|
async def get_disk_activity(self, device: str) -> str:
|
||||||
"""获取硬盘活动状态(活动中/空闲中/休眠中)"""
|
"""获取硬盘活动状态(活动中/空闲中/休眠中)"""
|
||||||
try:
|
try:
|
||||||
# 先检查电源状态
|
# 先检查电源状态 - 这是最可靠的休眠检测方法
|
||||||
power_state = await self.get_disk_power_state(device)
|
power_state = await self.get_disk_power_state(device)
|
||||||
if power_state in ["standby", "sleep"]:
|
if power_state in ["standby", "sleep"]:
|
||||||
|
self.logger.debug(f"硬盘 {device} 电源状态为 {power_state},判定为休眠中")
|
||||||
return "休眠中"
|
return "休眠中"
|
||||||
|
|
||||||
# 检查最近的I/O活动 - 使用非侵入性方式
|
# 检查最近的I/O活动 - 使用非侵入性方式
|
||||||
@@ -256,9 +260,19 @@ class DiskManager:
|
|||||||
self.logger.debug(f"解析硬盘 {device} 统计信息失败: {e}")
|
self.logger.debug(f"解析硬盘 {device} 统计信息失败: {e}")
|
||||||
return "活动中" # 出错时默认返回活动中,避免中断休眠
|
return "活动中" # 出错时默认返回活动中,避免中断休眠
|
||||||
|
|
||||||
# 如果无法获取统计信息,默认返回活动中
|
# 如果无法获取统计信息,检查硬盘是否可访问
|
||||||
self.logger.debug(f"无法获取硬盘 {device} 的统计信息,默认返回活动中")
|
try:
|
||||||
return "活动中"
|
# 尝试读取设备信息,如果成功说明硬盘可访问
|
||||||
|
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:
|
except Exception as e:
|
||||||
self.logger.error(f"获取硬盘 {device} 状态失败: {str(e)}", exc_info=True)
|
self.logger.error(f"获取硬盘 {device} 状态失败: {str(e)}", exc_info=True)
|
||||||
@@ -331,31 +345,31 @@ class DiskManager:
|
|||||||
disks.append(disk_info)
|
disks.append(disk_info)
|
||||||
continue
|
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:
|
if not is_active:
|
||||||
self.logger.debug(f"硬盘 {device} 处于非活跃状态,使用上一次获取的信息")
|
self.logger.debug(f"硬盘 {device} 处于非活跃状态,使用上一次获取的信息")
|
||||||
|
|
||||||
# 优先使用缓存的完整信息
|
# 优先使用缓存的完整信息
|
||||||
if cached_info:
|
if cached_info:
|
||||||
disk_info.update({
|
disk_info.update({
|
||||||
"model": cached_info.get("model", "未检测"),
|
"model": cached_info.get("model", "未知"),
|
||||||
"serial": cached_info.get("serial", "未检测"),
|
"serial": cached_info.get("serial", "未知"),
|
||||||
"capacity": cached_info.get("capacity", "未检测"),
|
"capacity": cached_info.get("capacity", "未知"),
|
||||||
"health": cached_info.get("health", "未检测"),
|
"health": cached_info.get("health", "未知"),
|
||||||
"temperature": cached_info.get("temperature", "未检测"),
|
"temperature": cached_info.get("temperature", "未知"),
|
||||||
"power_on_hours": cached_info.get("power_on_hours", "未检测"),
|
"power_on_hours": cached_info.get("power_on_hours", "未知"),
|
||||||
"attributes": cached_info.get("attributes", {})
|
"attributes": cached_info.get("attributes", {})
|
||||||
})
|
})
|
||||||
else:
|
else:
|
||||||
# 如果没有缓存信息,使用默认值
|
# 如果没有缓存信息,使用默认值
|
||||||
disk_info.update({
|
disk_info.update({
|
||||||
"model": "未检测",
|
"model": "未知",
|
||||||
"serial": "未检测",
|
"serial": "未知",
|
||||||
"capacity": "未检测",
|
"capacity": "未知",
|
||||||
"health": "未检测",
|
"health": "未知",
|
||||||
"temperature": "未检测",
|
"temperature": "未知",
|
||||||
"power_on_hours": "未检测",
|
"power_on_hours": "未知",
|
||||||
"attributes": {}
|
"attributes": {}
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -412,7 +426,7 @@ class DiskManager:
|
|||||||
[
|
[
|
||||||
r"Device Model:\s*(.+)",
|
r"Device Model:\s*(.+)",
|
||||||
r"Model(?: Family)?\s*:\s*(.+)",
|
r"Model(?: Family)?\s*:\s*(.+)",
|
||||||
r"Model\s*Number:\s*(.+)",
|
r"Model Number:\s*(.+)",
|
||||||
r"Product:\s*(.+)", # NVMe格式
|
r"Product:\s*(.+)", # NVMe格式
|
||||||
r"Model Number:\s*(.+)", # NVMe格式
|
r"Model Number:\s*(.+)", # NVMe格式
|
||||||
]
|
]
|
||||||
@@ -430,10 +444,10 @@ class DiskManager:
|
|||||||
|
|
||||||
# 容量 - 增强NVMe支持并转换为GB/TB格式
|
# 容量 - 增强NVMe支持并转换为GB/TB格式
|
||||||
capacity_patterns = [
|
capacity_patterns = [
|
||||||
r"User Capacity:\s*([^[]+)",
|
r"User Capacity:\s*([^\[]+)",
|
||||||
r"Namespace 1 Size/Capacity:\s*([^[]+)", # NVMe格式
|
r"Namespace 1 Size/Capacity:\s*([^\[]+)", # NVMe格式
|
||||||
r"Total NVM Capacity:\s*([^[]+)", # NVMe格式
|
r"Total NVM Capacity:\s*([^\[]+)", # NVMe格式
|
||||||
r"Capacity:\s*([^[]+)", # NVMe格式
|
r"Capacity:\s*([^\[]+)", # NVMe格式
|
||||||
]
|
]
|
||||||
|
|
||||||
raw_capacity = self.extract_value(info_output, capacity_patterns)
|
raw_capacity = self.extract_value(info_output, capacity_patterns)
|
||||||
@@ -637,7 +651,7 @@ class DiskManager:
|
|||||||
# 添加额外属性:温度历史记录
|
# 添加额外属性:温度历史记录
|
||||||
temp_history = {}
|
temp_history = {}
|
||||||
# 提取属性194的温度历史
|
# 提取属性194的温度历史
|
||||||
temp194_match = re.search(r"194\s+Temperature_Celsius+.*?\(\s*([\d\s]+)$", data_output)
|
temp194_match = re.search(r"194\s+Temperature_Celsius+.*?(\s*[\d\s]+)$", data_output)
|
||||||
if temp194_match:
|
if temp194_match:
|
||||||
try:
|
try:
|
||||||
values = [int(x) for x in temp194_match.group(1).split()]
|
values = [int(x) for x in temp194_match.group(1).split()]
|
||||||
@@ -652,4 +666,199 @@ class DiskManager:
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
# 保存额外属性
|
# 保存额外属性
|
||||||
disk_info["attributes"] = temp_history
|
disk_info["attributes"] = temp_history
|
||||||
|
|
||||||
|
async def get_zpools(self) -> list[dict]:
|
||||||
|
"""获取ZFS存储池信息"""
|
||||||
|
zpools = []
|
||||||
|
try:
|
||||||
|
self.logger.debug("Fetching ZFS pool list...")
|
||||||
|
# 使用zpool list获取存储池信息(包含所有字段)
|
||||||
|
zpool_output = await self.coordinator.run_command("zpool list 2>/dev/null || echo 'NO_ZPOOL'")
|
||||||
|
self.logger.debug("zpool list output: %s", zpool_output)
|
||||||
|
|
||||||
|
if "NO_ZPOOL" in zpool_output or "command not found" in zpool_output.lower():
|
||||||
|
self.logger.info("系统未安装ZFS或没有ZFS存储池")
|
||||||
|
return []
|
||||||
|
|
||||||
|
# 解析zpool list输出
|
||||||
|
lines = zpool_output.splitlines()
|
||||||
|
# 跳过标题行,从第二行开始解析
|
||||||
|
for line in lines[1:]: # 跳过第一行标题
|
||||||
|
if line.strip():
|
||||||
|
# 分割制表符或连续空格
|
||||||
|
parts = re.split(r'\s+', line.strip())
|
||||||
|
if len(parts) >= 11: # 根据实际输出有11个字段
|
||||||
|
pool_info = {
|
||||||
|
"name": parts[0],
|
||||||
|
"size": parts[1],
|
||||||
|
"alloc": parts[2],
|
||||||
|
"free": parts[3],
|
||||||
|
"ckpoint": parts[4] if parts[4] != "-" else "",
|
||||||
|
"expand_sz": parts[5] if parts[5] != "-" else "",
|
||||||
|
"frag": parts[6] if parts[6] != "-" else "0%",
|
||||||
|
"capacity": parts[7],
|
||||||
|
"dedup": parts[8],
|
||||||
|
"health": parts[9],
|
||||||
|
"altroot": parts[10] if parts[10] != "-" else ""
|
||||||
|
}
|
||||||
|
|
||||||
|
zpools.append(pool_info)
|
||||||
|
self.logger.debug("Found ZFS pool: %s", pool_info["name"])
|
||||||
|
|
||||||
|
self.logger.info("Found %d ZFS pools", len(zpools))
|
||||||
|
return zpools
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
self.logger.error("Failed to get ZFS pool info: %s", str(e), exc_info=True)
|
||||||
|
return []
|
||||||
|
|
||||||
|
async def get_zpool_status(self, pool_name: str) -> dict:
|
||||||
|
"""获取ZFS存储池的详细状态信息,包括scrub进度"""
|
||||||
|
try:
|
||||||
|
self.logger.debug(f"Getting ZFS pool status for {pool_name}")
|
||||||
|
status_output = await self.coordinator.run_command(f"zpool status {pool_name} 2>/dev/null || echo 'NO_POOL'")
|
||||||
|
|
||||||
|
if "NO_POOL" in status_output or "command not found" in status_output.lower():
|
||||||
|
self.logger.debug(f"ZFS pool {pool_name} not found")
|
||||||
|
return {"scrub_in_progress": False}
|
||||||
|
|
||||||
|
# 解析scrub信息
|
||||||
|
scrub_info = self._parse_scrub_info(status_output)
|
||||||
|
return scrub_info
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
self.logger.error(f"Failed to get ZFS pool status for {pool_name}: {str(e)}", exc_info=True)
|
||||||
|
return {"scrub_in_progress": False}
|
||||||
|
|
||||||
|
def _parse_scrub_info(self, status_output: str) -> dict:
|
||||||
|
"""解析zpool status中的scrub信息"""
|
||||||
|
scrub_info = {
|
||||||
|
"scrub_in_progress": False,
|
||||||
|
"scrub_status": "无检查",
|
||||||
|
"scrub_progress": "0%",
|
||||||
|
"scan_rate": "0/s",
|
||||||
|
"time_remaining": "",
|
||||||
|
"scanned": "0",
|
||||||
|
"issued": "0",
|
||||||
|
"repaired": "0",
|
||||||
|
"scrub_start_time": ""
|
||||||
|
}
|
||||||
|
|
||||||
|
lines = status_output.split('\n')
|
||||||
|
has_scan_section = False
|
||||||
|
|
||||||
|
# 首先判断是否有scan段(这是判断scrub进行中的关键)
|
||||||
|
for line in lines:
|
||||||
|
line = line.strip()
|
||||||
|
if line.startswith('scan:'):
|
||||||
|
has_scan_section = True
|
||||||
|
break
|
||||||
|
|
||||||
|
# 如果没有scan段,直接返回无检查状态
|
||||||
|
if not has_scan_section:
|
||||||
|
return scrub_info
|
||||||
|
|
||||||
|
# 解析scan段的内容
|
||||||
|
in_scan_section = False
|
||||||
|
for line in lines:
|
||||||
|
line = line.strip()
|
||||||
|
|
||||||
|
# 检查是否进入scan部分
|
||||||
|
if line.startswith('scan:'):
|
||||||
|
in_scan_section = True
|
||||||
|
scrub_info["scrub_in_progress"] = True # 有scan段就表示在进行中
|
||||||
|
scan_line = line[5:].strip() # 去掉'scan:'
|
||||||
|
|
||||||
|
# 检查scrub具体状态
|
||||||
|
if 'scrub in progress' in scan_line or 'scrub resilvering' in scan_line:
|
||||||
|
scrub_info["scrub_status"] = "检查进行中"
|
||||||
|
scrub_info["scrub_progress"] = "0.1%" # 刚开始,显示微小进度表示进行中
|
||||||
|
|
||||||
|
# 解析开始时间
|
||||||
|
if 'since' in scan_line:
|
||||||
|
time_part = scan_line.split('since')[-1].strip()
|
||||||
|
scrub_info["scrub_start_time"] = time_part
|
||||||
|
|
||||||
|
elif 'scrub repaired' in scan_line or 'scrub completed' in scan_line:
|
||||||
|
scrub_info["scrub_status"] = "检查完成"
|
||||||
|
scrub_info["scrub_in_progress"] = False
|
||||||
|
elif 'scrub canceled' in scan_line:
|
||||||
|
scrub_info["scrub_status"] = "检查已取消"
|
||||||
|
scrub_info["scrub_in_progress"] = False
|
||||||
|
elif 'scrub paused' in scan_line:
|
||||||
|
scrub_info["scrub_status"] = "检查已暂停"
|
||||||
|
scrub_info["scrub_in_progress"] = False
|
||||||
|
else:
|
||||||
|
# 有scan段但没有具体状态说明,默认为进行中
|
||||||
|
scrub_info["scrub_status"] = "检查进行中"
|
||||||
|
scrub_info["scrub_progress"] = "0.1%"
|
||||||
|
|
||||||
|
continue
|
||||||
|
|
||||||
|
# 如果在scan部分,解析详细信息
|
||||||
|
if in_scan_section and line and not line.startswith('config'):
|
||||||
|
# 解析进度信息,例如: "2.10T / 2.10T scanned, 413G / 2.10T issued at 223M/s"
|
||||||
|
if 'scanned' in line and 'issued' in line:
|
||||||
|
parts = line.split(',')
|
||||||
|
|
||||||
|
# 解析扫描进度
|
||||||
|
if len(parts) >= 1:
|
||||||
|
scanned_part = parts[0].strip()
|
||||||
|
if ' / ' in scanned_part:
|
||||||
|
scanned_data = scanned_part.split(' / ')[0].strip()
|
||||||
|
total_data = scanned_part.split(' / ')[1].split()[0].strip()
|
||||||
|
scrub_info["scanned"] = f"{scanned_data}/{total_data}"
|
||||||
|
|
||||||
|
# 解析发出的数据
|
||||||
|
if len(parts) >= 2:
|
||||||
|
issued_part = parts[1].strip()
|
||||||
|
if ' / ' in issued_part:
|
||||||
|
issued_data = issued_part.split(' / ')[0].strip()
|
||||||
|
total_issued = issued_part.split(' / ')[1].split()[0].strip()
|
||||||
|
scrub_info["issued"] = f"{issued_data}/{total_issued}"
|
||||||
|
|
||||||
|
# 解析扫描速度
|
||||||
|
if 'at' in line:
|
||||||
|
speed_part = line.split('at')[-1].strip().split()[0]
|
||||||
|
scrub_info["scan_rate"] = speed_part
|
||||||
|
|
||||||
|
# 解析进度百分比和剩余时间
|
||||||
|
elif '%' in line and 'done' in line:
|
||||||
|
# 例如: "644M repaired, 19.23% done, 02:12:38 to go"
|
||||||
|
if '%' in line:
|
||||||
|
progress_match = re.search(r'(\d+\.?\d*)%', line)
|
||||||
|
if progress_match:
|
||||||
|
scrub_info["scrub_progress"] = f"{progress_match.group(1)}%"
|
||||||
|
|
||||||
|
if 'repaired' in line:
|
||||||
|
repaired_match = re.search(r'([\d.]+[KMGT]?).*repaired', line)
|
||||||
|
if repaired_match:
|
||||||
|
scrub_info["repaired"] = repaired_match.group(1)
|
||||||
|
|
||||||
|
if 'to go' in line:
|
||||||
|
time_match = re.search(r'(\d{2}:\d{2}:\d{2})\s+to\s+go', line)
|
||||||
|
if time_match:
|
||||||
|
scrub_info["time_remaining"] = time_match.group(1)
|
||||||
|
|
||||||
|
# 如果遇到空行或新章节,退出scan部分
|
||||||
|
elif line == '' or line.startswith('config'):
|
||||||
|
break
|
||||||
|
|
||||||
|
return scrub_info
|
||||||
|
|
||||||
|
def _format_bytes(self, bytes_value: int) -> str:
|
||||||
|
"""将字节数格式化为易读的格式"""
|
||||||
|
try:
|
||||||
|
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} B"
|
||||||
|
except Exception:
|
||||||
|
return f"{bytes_value} B"
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"domain": "fn_nas",
|
"domain": "fn_nas",
|
||||||
"name": "飞牛NAS",
|
"name": "飞牛NAS",
|
||||||
"version": "1.3.8",
|
"version": "1.4.0",
|
||||||
"documentation": "https://github.com/xiaochao99/fn_nas",
|
"documentation": "https://github.com/xiaochao99/fn_nas",
|
||||||
"dependencies": [],
|
"dependencies": [],
|
||||||
"codeowners": ["@xiaochao99"],
|
"codeowners": ["@xiaochao99"],
|
||||||
|
|||||||
@@ -3,10 +3,16 @@ from homeassistant.components.sensor import SensorEntity, SensorDeviceClass, Sen
|
|||||||
from homeassistant.helpers.update_coordinator import CoordinatorEntity
|
from homeassistant.helpers.update_coordinator import CoordinatorEntity
|
||||||
from homeassistant.const import UnitOfTemperature
|
from homeassistant.const import UnitOfTemperature
|
||||||
from .const import (
|
from .const import (
|
||||||
DOMAIN, HDD_TEMP, HDD_HEALTH, HDD_STATUS, SYSTEM_INFO, ICON_DISK,
|
DOMAIN, HDD_TEMP, HDD_STATUS, SYSTEM_INFO, ICON_DISK,
|
||||||
ICON_TEMPERATURE, ICON_HEALTH, ATTR_DISK_MODEL, ATTR_SERIAL_NO,
|
ICON_TEMPERATURE, ATTR_DISK_MODEL, ATTR_SERIAL_NO,
|
||||||
ATTR_POWER_ON_HOURS, ATTR_TOTAL_CAPACITY, ATTR_HEALTH_STATUS,
|
ATTR_POWER_ON_HOURS, ATTR_TOTAL_CAPACITY, ATTR_HEALTH_STATUS,
|
||||||
DEVICE_ID_NAS, DATA_UPDATE_COORDINATOR
|
DEVICE_ID_NAS, DATA_UPDATE_COORDINATOR, ZFS_POOL, ICON_ZFS,
|
||||||
|
ATTR_ZPOOL_NAME, ATTR_ZPOOL_HEALTH, ATTR_ZPOOL_SIZE,
|
||||||
|
ATTR_ZPOOL_ALLOC, ATTR_ZPOOL_FREE, ATTR_ZPOOL_CAPACITY,
|
||||||
|
ATTR_ZPOOL_FRAGMENTATION, ATTR_ZPOOL_CKPOINT, ATTR_ZPOOL_EXPANDSZ,
|
||||||
|
ATTR_ZPOOL_DEDUP, ATTR_ZPOOL_SCRUB_STATUS, ATTR_ZPOOL_SCRUB_PROGRESS,
|
||||||
|
ATTR_ZPOOL_SCRUB_SCAN_RATE, ATTR_ZPOOL_SCRUB_TIME_REMAINING,
|
||||||
|
ATTR_ZPOOL_SCRUB_ISSUED, ATTR_ZPOOL_SCRUB_REPAIRED, DEVICE_ID_ZFS
|
||||||
)
|
)
|
||||||
|
|
||||||
_LOGGER = logging.getLogger(__name__)
|
_LOGGER = logging.getLogger(__name__)
|
||||||
@@ -38,22 +44,7 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
|
|||||||
)
|
)
|
||||||
existing_ids.add(temp_uid)
|
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"
|
status_uid = f"{config_entry.entry_id}_{disk['device']}_status"
|
||||||
@@ -244,6 +235,77 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
|
|||||||
)
|
)
|
||||||
existing_ids.add(sensor_uid)
|
existing_ids.add(sensor_uid)
|
||||||
|
|
||||||
|
# 添加ZFS存储池传感器
|
||||||
|
if "zpools" in coordinator.data:
|
||||||
|
for zpool in coordinator.data["zpools"]:
|
||||||
|
safe_name = zpool["name"].replace(" ", "_").replace("/", "_").replace(".", "_")
|
||||||
|
|
||||||
|
# ZFS存储池健康状态传感器
|
||||||
|
health_uid = f"{config_entry.entry_id}_zpool_{safe_name}_health"
|
||||||
|
if health_uid not in existing_ids:
|
||||||
|
entities.append(
|
||||||
|
ZFSPoolSensor(
|
||||||
|
coordinator,
|
||||||
|
zpool["name"],
|
||||||
|
"health",
|
||||||
|
f"ZFS {zpool['name']} 健康状态",
|
||||||
|
health_uid,
|
||||||
|
None,
|
||||||
|
ICON_ZFS,
|
||||||
|
zpool
|
||||||
|
)
|
||||||
|
)
|
||||||
|
existing_ids.add(health_uid)
|
||||||
|
|
||||||
|
# ZFS存储池容量使用率传感器
|
||||||
|
capacity_uid = f"{config_entry.entry_id}_zpool_{safe_name}_capacity"
|
||||||
|
if capacity_uid not in existing_ids:
|
||||||
|
entities.append(
|
||||||
|
ZFSPoolSensor(
|
||||||
|
coordinator,
|
||||||
|
zpool["name"],
|
||||||
|
"capacity",
|
||||||
|
f"ZFS {zpool['name']} 使用率",
|
||||||
|
capacity_uid,
|
||||||
|
"%",
|
||||||
|
ICON_ZFS,
|
||||||
|
zpool,
|
||||||
|
device_class=SensorDeviceClass.POWER_FACTOR,
|
||||||
|
state_class=SensorStateClass.MEASUREMENT
|
||||||
|
)
|
||||||
|
)
|
||||||
|
existing_ids.add(capacity_uid)
|
||||||
|
|
||||||
|
# ZFS存储池总大小传感器
|
||||||
|
size_uid = f"{config_entry.entry_id}_zpool_{safe_name}_size"
|
||||||
|
if size_uid not in existing_ids:
|
||||||
|
entities.append(
|
||||||
|
ZFSPoolSensor(
|
||||||
|
coordinator,
|
||||||
|
zpool["name"],
|
||||||
|
"size",
|
||||||
|
f"ZFS {zpool['name']} 容量",
|
||||||
|
size_uid,
|
||||||
|
None, # 动态确定单位
|
||||||
|
ICON_ZFS,
|
||||||
|
zpool
|
||||||
|
)
|
||||||
|
)
|
||||||
|
existing_ids.add(size_uid)
|
||||||
|
|
||||||
|
# ZFS存储池scrub进度传感器
|
||||||
|
scrub_uid = f"{config_entry.entry_id}_zpool_{safe_name}_scrub"
|
||||||
|
if scrub_uid not in existing_ids:
|
||||||
|
entities.append(
|
||||||
|
ZFSScrubSensor(
|
||||||
|
coordinator,
|
||||||
|
zpool["name"],
|
||||||
|
f"ZFS {zpool['name']} 检查进度",
|
||||||
|
scrub_uid
|
||||||
|
)
|
||||||
|
)
|
||||||
|
existing_ids.add(scrub_uid)
|
||||||
|
|
||||||
# 添加剩余内存传感器
|
# 添加剩余内存传感器
|
||||||
mem_available_uid = f"{config_entry.entry_id}_memory_available"
|
mem_available_uid = f"{config_entry.entry_id}_memory_available"
|
||||||
if mem_available_uid not in existing_ids:
|
if mem_available_uid not in existing_ids:
|
||||||
@@ -302,7 +364,7 @@ class DiskSensor(CoordinatorEntity, SensorEntity):
|
|||||||
if disk["device"] == self.device_id:
|
if disk["device"] == self.device_id:
|
||||||
if self.sensor_type == HDD_TEMP:
|
if self.sensor_type == HDD_TEMP:
|
||||||
temp = disk.get("temperature")
|
temp = disk.get("temperature")
|
||||||
if temp is None or temp == "未知" or temp == "未检测":
|
if temp is None or temp == "未知":
|
||||||
return None
|
return None
|
||||||
if isinstance(temp, str):
|
if isinstance(temp, str):
|
||||||
try:
|
try:
|
||||||
@@ -314,11 +376,7 @@ class DiskSensor(CoordinatorEntity, SensorEntity):
|
|||||||
elif isinstance(temp, (int, float)):
|
elif isinstance(temp, (int, float)):
|
||||||
return temp
|
return temp
|
||||||
return None
|
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:
|
elif self.sensor_type == HDD_STATUS:
|
||||||
return disk.get("status", "未知")
|
return disk.get("status", "未知")
|
||||||
return None
|
return None
|
||||||
@@ -329,6 +387,28 @@ class DiskSensor(CoordinatorEntity, SensorEntity):
|
|||||||
return SensorDeviceClass.TEMPERATURE
|
return SensorDeviceClass.TEMPERATURE
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
@property
|
||||||
|
def native_unit_of_measurement(self):
|
||||||
|
"""动态返回单位(仅对size类型传感器)"""
|
||||||
|
if self.sensor_type != "size":
|
||||||
|
return self._attr_native_unit_of_measurement
|
||||||
|
|
||||||
|
# 对于size类型传感器,根据实际数据确定单位
|
||||||
|
for zpool in self.coordinator.data.get("zpools", []):
|
||||||
|
if zpool["name"] == self.zpool_name:
|
||||||
|
size_str = zpool.get("size", "")
|
||||||
|
if size_str.endswith("T") or size_str.endswith("Ti"):
|
||||||
|
return "TB"
|
||||||
|
elif size_str.endswith("G") or size_str.endswith("Gi"):
|
||||||
|
return "GB"
|
||||||
|
elif size_str.endswith("M") or size_str.endswith("Mi"):
|
||||||
|
return "MB"
|
||||||
|
elif size_str.endswith("K") or size_str.endswith("Ki"):
|
||||||
|
return "KB"
|
||||||
|
else:
|
||||||
|
return "GB" # 默认单位
|
||||||
|
return "GB" # 默认单位
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def extra_state_attributes(self):
|
def extra_state_attributes(self):
|
||||||
return {
|
return {
|
||||||
@@ -602,6 +682,28 @@ class MemoryAvailableSensor(CoordinatorEntity, SensorEntity):
|
|||||||
except (TypeError, ValueError):
|
except (TypeError, ValueError):
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
@property
|
||||||
|
def native_unit_of_measurement(self):
|
||||||
|
"""动态返回单位(仅对size类型传感器)"""
|
||||||
|
if self.sensor_type != "size":
|
||||||
|
return self._attr_native_unit_of_measurement
|
||||||
|
|
||||||
|
# 对于size类型传感器,根据实际数据确定单位
|
||||||
|
for zpool in self.coordinator.data.get("zpools", []):
|
||||||
|
if zpool["name"] == self.zpool_name:
|
||||||
|
size_str = zpool.get("size", "")
|
||||||
|
if size_str.endswith("T") or size_str.endswith("Ti"):
|
||||||
|
return "TB"
|
||||||
|
elif size_str.endswith("G") or size_str.endswith("Gi"):
|
||||||
|
return "GB"
|
||||||
|
elif size_str.endswith("M") or size_str.endswith("Mi"):
|
||||||
|
return "MB"
|
||||||
|
elif size_str.endswith("K") or size_str.endswith("Ki"):
|
||||||
|
return "KB"
|
||||||
|
else:
|
||||||
|
return "GB" # 默认单位
|
||||||
|
return "GB" # 默认单位
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def extra_state_attributes(self):
|
def extra_state_attributes(self):
|
||||||
"""返回总内存和已用内存(GB)以及原始字节值"""
|
"""返回总内存和已用内存(GB)以及原始字节值"""
|
||||||
@@ -692,6 +794,158 @@ class VolumeAvailableSensor(CoordinatorEntity, SensorEntity):
|
|||||||
"已用容量": vol_info.get("used", "未知"),
|
"已用容量": vol_info.get("used", "未知"),
|
||||||
"使用率": vol_info.get("use_percent", "未知")
|
"使用率": vol_info.get("use_percent", "未知")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
class ZFSPoolSensor(CoordinatorEntity, SensorEntity):
|
||||||
|
"""ZFS存储池传感器"""
|
||||||
|
|
||||||
|
def __init__(self, coordinator, zpool_name, sensor_type, name, unique_id, unit, icon, zpool_info, device_class=None, state_class=None):
|
||||||
|
super().__init__(coordinator)
|
||||||
|
self.zpool_name = zpool_name
|
||||||
|
self.sensor_type = sensor_type
|
||||||
|
self._attr_name = name
|
||||||
|
self._attr_unique_id = unique_id
|
||||||
|
self._attr_native_unit_of_measurement = unit
|
||||||
|
self._attr_icon = icon
|
||||||
|
self.zpool_info = zpool_info
|
||||||
|
self._attr_device_info = {
|
||||||
|
"identifiers": {(DOMAIN, DEVICE_ID_ZFS)},
|
||||||
|
"name": "ZFS存储池",
|
||||||
|
"via_device": (DOMAIN, DEVICE_ID_NAS)
|
||||||
|
}
|
||||||
|
|
||||||
|
# 设置设备类和状态类(如果提供)
|
||||||
|
if device_class:
|
||||||
|
self._attr_device_class = device_class
|
||||||
|
if state_class:
|
||||||
|
self._attr_state_class = state_class
|
||||||
|
|
||||||
|
@property
|
||||||
|
def native_value(self):
|
||||||
|
"""返回传感器的值"""
|
||||||
|
for zpool in self.coordinator.data.get("zpools", []):
|
||||||
|
if zpool["name"] == self.zpool_name:
|
||||||
|
if self.sensor_type == "health":
|
||||||
|
# 健康状态中英文映射
|
||||||
|
health_map = {
|
||||||
|
"ONLINE": "在线",
|
||||||
|
"DEGRADED": "降级",
|
||||||
|
"FAULTED": "故障",
|
||||||
|
"OFFLINE": "离线",
|
||||||
|
"REMOVED": "已移除",
|
||||||
|
"UNAVAIL": "不可用"
|
||||||
|
}
|
||||||
|
return health_map.get(zpool.get("health", "UNKNOWN"), zpool.get("health", "未知"))
|
||||||
|
elif self.sensor_type == "capacity":
|
||||||
|
# 返回使用率数值(去掉百分号)
|
||||||
|
capacity = zpool.get("capacity", "0%")
|
||||||
|
try:
|
||||||
|
return float(capacity.replace("%", ""))
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
elif self.sensor_type == "size":
|
||||||
|
# 返回总大小的数值部分
|
||||||
|
size = zpool.get("size", "0")
|
||||||
|
try:
|
||||||
|
# 提取数字部分
|
||||||
|
import re
|
||||||
|
match = re.search(r'([\d.]+)', size)
|
||||||
|
if match:
|
||||||
|
return float(match.group(1))
|
||||||
|
return None
|
||||||
|
except (ValueError, AttributeError):
|
||||||
|
return None
|
||||||
|
return None
|
||||||
|
|
||||||
|
@property
|
||||||
|
def native_unit_of_measurement(self):
|
||||||
|
"""动态返回单位(仅对size类型传感器)"""
|
||||||
|
if self.sensor_type != "size":
|
||||||
|
return self._attr_native_unit_of_measurement
|
||||||
|
|
||||||
return attributes
|
# 对于size类型传感器,根据实际数据确定单位
|
||||||
|
for zpool in self.coordinator.data.get("zpools", []):
|
||||||
|
if zpool["name"] == self.zpool_name:
|
||||||
|
size_str = zpool.get("size", "")
|
||||||
|
if size_str.endswith("T") or size_str.endswith("Ti"):
|
||||||
|
return "TB"
|
||||||
|
elif size_str.endswith("G") or size_str.endswith("Gi"):
|
||||||
|
return "GB"
|
||||||
|
elif size_str.endswith("M") or size_str.endswith("Mi"):
|
||||||
|
return "MB"
|
||||||
|
elif size_str.endswith("K") or size_str.endswith("Ki"):
|
||||||
|
return "KB"
|
||||||
|
else:
|
||||||
|
return "GB" # 默认单位
|
||||||
|
return "GB" # 默认单位
|
||||||
|
|
||||||
|
@property
|
||||||
|
def extra_state_attributes(self):
|
||||||
|
"""返回额外的状态属性"""
|
||||||
|
for zpool in self.coordinator.data.get("zpools", []):
|
||||||
|
if zpool["name"] == self.zpool_name:
|
||||||
|
return {
|
||||||
|
ATTR_ZPOOL_NAME: zpool.get("name", "未知"),
|
||||||
|
ATTR_ZPOOL_HEALTH: zpool.get("health", "未知"),
|
||||||
|
ATTR_ZPOOL_SIZE: zpool.get("size", "未知"),
|
||||||
|
ATTR_ZPOOL_ALLOC: zpool.get("alloc", "未知"),
|
||||||
|
ATTR_ZPOOL_FREE: zpool.get("free", "未知"),
|
||||||
|
ATTR_ZPOOL_CAPACITY: zpool.get("capacity", "未知"),
|
||||||
|
ATTR_ZPOOL_FRAGMENTATION: zpool.get("frag", "未知"),
|
||||||
|
ATTR_ZPOOL_CKPOINT: zpool.get("ckpoint", "") if zpool.get("ckpoint") != "" else "无",
|
||||||
|
ATTR_ZPOOL_EXPANDSZ: zpool.get("expand_sz", "") if zpool.get("expand_sz") != "" else "无",
|
||||||
|
ATTR_ZPOOL_DEDUP: zpool.get("dedup", "未知"),
|
||||||
|
"根路径": zpool.get("altroot", "") if zpool.get("altroot") != "" else "默认"
|
||||||
|
}
|
||||||
|
return {}
|
||||||
|
|
||||||
|
class ZFSScrubSensor(CoordinatorEntity, SensorEntity):
|
||||||
|
"""ZFS存储池scrub进度传感器"""
|
||||||
|
|
||||||
|
def __init__(self, coordinator, zpool_name, name, unique_id):
|
||||||
|
super().__init__(coordinator)
|
||||||
|
self.zpool_name = zpool_name
|
||||||
|
self._attr_name = name
|
||||||
|
self._attr_unique_id = unique_id
|
||||||
|
self._attr_native_unit_of_measurement = "%"
|
||||||
|
self._attr_icon = "mdi:progress-check"
|
||||||
|
self._attr_device_info = {
|
||||||
|
"identifiers": {(DOMAIN, DEVICE_ID_ZFS)},
|
||||||
|
"name": "ZFS存储池",
|
||||||
|
"via_device": (DOMAIN, DEVICE_ID_NAS)
|
||||||
|
}
|
||||||
|
self._attr_device_class = SensorDeviceClass.POWER_FACTOR
|
||||||
|
self._attr_state_class = SensorStateClass.MEASUREMENT
|
||||||
|
self.scrub_cache = {}
|
||||||
|
|
||||||
|
@property
|
||||||
|
def native_value(self):
|
||||||
|
"""返回scrub进度百分比"""
|
||||||
|
# 获取scrub状态信息
|
||||||
|
scrub_info = self.coordinator.data.get("scrub_status", {}).get(self.zpool_name, {})
|
||||||
|
progress_str = scrub_info.get("scrub_progress", "0%")
|
||||||
|
|
||||||
|
try:
|
||||||
|
# 提取数字部分
|
||||||
|
if progress_str and progress_str != "0%":
|
||||||
|
return float(progress_str.replace("%", ""))
|
||||||
|
return 0.0
|
||||||
|
except (ValueError, AttributeError):
|
||||||
|
return 0.0
|
||||||
|
|
||||||
|
@property
|
||||||
|
def extra_state_attributes(self):
|
||||||
|
"""返回scrub详细状态信息"""
|
||||||
|
scrub_info = self.coordinator.data.get("scrub_status", {}).get(self.zpool_name, {})
|
||||||
|
|
||||||
|
return {
|
||||||
|
ATTR_ZPOOL_NAME: self.zpool_name,
|
||||||
|
ATTR_ZPOOL_SCRUB_STATUS: scrub_info.get("scrub_status", "无检查"),
|
||||||
|
ATTR_ZPOOL_SCRUB_PROGRESS: scrub_info.get("scrub_progress", "0%"),
|
||||||
|
ATTR_ZPOOL_SCRUB_SCAN_RATE: scrub_info.get("scan_rate", "0/s"),
|
||||||
|
ATTR_ZPOOL_SCRUB_TIME_REMAINING: scrub_info.get("time_remaining", ""),
|
||||||
|
ATTR_ZPOOL_SCRUB_ISSUED: scrub_info.get("issued", "0"),
|
||||||
|
ATTR_ZPOOL_SCRUB_REPAIRED: scrub_info.get("repaired", "0"),
|
||||||
|
"开始时间": scrub_info.get("scrub_start_time", ""),
|
||||||
|
"扫描数据": scrub_info.get("scanned", "0"),
|
||||||
|
"检查进行中": scrub_info.get("scrub_in_progress", False)
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user