修改streamer服务的部分实现

This commit is contained in:
GuanYuankai 2025-10-22 15:31:10 +08:00
parent 7a40c9a7f3
commit e3ff3bd050
5 changed files with 14 additions and 40 deletions

View File

@ -117,7 +117,7 @@ target_link_libraries(test PRIVATE
add_executable(edge_streamer
src/streamer/main.cpp
src/streamer/main_streamer.cpp
)
#

View File

@ -85,7 +85,12 @@ RUN ldconfig
RUN rm -rf /var/lib/apt/lists/*
COPY piper_models/ /app/piper_models/
USER dev
RUN pip install --no-cache-dir --user -i https://mirrors.aliyun.com/pypi/simple/ piper-tts onvif-zeep python-nmap
RUN pip install --no-cache-dir --user -i https://mirrors.aliyun.com/pypi/simple/ \
piper-tts \
onvif-zeep \
python-nmap \
psutil \
paramiko
RUN echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bash_profile
USER dev
CMD ["/bin/bash"]

View File

@ -7,9 +7,9 @@ from typing import List, Set, Union, Dict
import time
import os
from urllib.parse import urlparse
from collections import defaultdict # 导入 defaultdict 以简化camera_lock下的操作
import json
from collections import defaultdict
# --- Global Variables for thread-safe access ---
active_ips: Set[str] = set()
found_cameras: Dict[str, Dict[str, str]] = defaultdict(dict) # 使用defaultdict简化内层字典的初始化
ip_lock = threading.Lock()
@ -27,24 +27,19 @@ COMMON_CAMERA_PORTS = [
37777, # Dahua primary port
37778, # Dahua secondary port
8002, # Often used for camera APIs or secondary streams
# Add more ports if you know specific ones for your camera brands
]
SSH_PORTS = [22] # Potential SSH access for some cameras
# --- Imports for ONVIF Discovery ---
ONVIF_AVAILABLE = False
try:
import psutil # For getting all network interfaces
import onvif # The package 'onvif-zeep' installs the 'onvif' module
# Attempt to import specific discovery module first, as it's the intended way.
# If this fails, the ONVIF_AVAILABLE flag will be set to False.
import psutil
import onvif
try:
from onvif import discovery
from onvif import discovery
_discovery_method = discovery.find_device
print("ONVIF: Using onvif.discovery.find_device for discovery.")
except (ImportError, AttributeError):
# Fallback: check if the top-level 'onvif' module has a discover method
if hasattr(onvif, 'discover') and callable(onvif.discover):
_discovery_method = onvif.discover
print("ONVIF: Using top-level onvif.discover() for discovery.")
@ -60,12 +55,11 @@ except ImportError as e:
print(f" Please ensure 'psutil' and 'onvif-zeep' are installed:")
print(f" pip install psutil onvif-zeep")
print(f" ONVIF discovery will be skipped.")
# If psutil is not available, we can still do single network scanning later
try:
import psutil
except ImportError:
psutil = None # Mark psutil as not available
_discovery_method = None # Ensure it's None if ONVIF is unavailable
psutil = None
_discovery_method = None
# --- Imports for SSH service detection ---
@ -112,8 +106,6 @@ def get_all_local_networks() -> List[str]:
netmask = snic.netmask
if ip_address and netmask and ip_address != '127.0.0.1':
try:
# Calculate the network address using the IP and netmask
# ipaddress module can handle this directly from address and netmask
network_obj = ipaddress.IPv4Network(f"{ip_address}/{netmask}", strict=False)
networks.add(str(network_obj))
except ipaddress.AddressValueError as e:
@ -136,17 +128,13 @@ def onvif_discovery_task() -> None:
print("ONVIF: Starting discovery. This may take a few seconds...")
try:
# Use the determined discovery method
discovered_device_xaddrs: List[str] = _discovery_method(timeout=5)
# Ensure raw_xaddrs is a list before iteration
if not isinstance(discovered_device_xaddrs, list):
discovered_device_xaddrs = [discovered_device_xaddrs] if discovered_device_xaddrs else []
discovered_ips_via_onvif = []
for xaddr in discovered_device_xaddrs:
try:
# Extract IP from the XAddr URL
parsed_url = urlparse(xaddr)
device_ip = parsed_url.hostname
if device_ip and device_ip not in discovered_ips_via_onvif:
@ -176,7 +164,6 @@ def check_socket(ip: str, port: int, timeout: float = 0.5) -> bool:
except (socket.timeout, ConnectionRefusedError, OSError):
return False
except Exception as e:
# print(f"Error checking {ip}:{port}: {e}") # Uncomment for debugging
return False
def check_ssh_banner(ip: str, port: int, timeout: float = 0.5) -> Union[str, bool]:
@ -193,14 +180,11 @@ def check_ssh_banner(ip: str, port: int, timeout: float = 0.5) -> Union[str, boo
except (paramiko.SSHException, socket.error, socket.timeout):
return False
except Exception as e:
# print(f"Error getting SSH banner from {ip}:{port}: {e}") # Uncomment for debugging
return False
def service_scan_task(ip: str) -> None:
"""Scans common camera ports and SSH ports on a given IP and updates found_cameras."""
# Try ONVIF specific ports (80, 554, 8000, 8080) for detailed service if available
for port in COMMON_CAMERA_PORTS:
if check_socket(ip, port):
with camera_lock:
@ -228,7 +212,6 @@ def main():
start_time = time.time()
print("--- Starting Network Camera Discovery on RK3588 ---")
# Get local IP address (for display)
local_ip = get_local_ip()
print(f"Local IP Address: {local_ip}")

View File

@ -8,8 +8,6 @@
namespace SystemMonitor {
// --- 核心工具函数实现 (私有成员) ---
std::string SystemMonitor::readFile(const std::string& filePath) const {
std::ifstream file(filePath);
if (!file.is_open()) return "";
@ -27,8 +25,6 @@ std::string SystemMonitor::execCommand(const char* cmd) const {
return result;
}
// --- 数据采集接口实现 ---
SystemInfo SystemMonitor::getSystemInfo() const {
SystemInfo info;
struct utsname uname_info;
@ -51,7 +47,6 @@ std::vector<StorageDevice> SystemMonitor::getStorageInfo() const {
std::stringstream line_stream(line);
if (line_stream >> dev.filesystem >> dev.totalSize >> dev.usedSize >> dev.availableSize >> dev.usePercentage >> std::ws &&
std::getline(line_stream, dev.mountPoint)) {
// 简单的类型推断
dev.type = (dev.filesystem.find('/') != std::string::npos) ? "overlay" : "physical";
devices.push_back(dev);
}
@ -65,20 +60,14 @@ MemoryInfo SystemMonitor::getMemoryInfo() const {
std::istringstream stream(meminfo_content);
std::string line;
// 遍历/proc/meminfo的每一行
while (std::getline(stream, line)) {
// 查找并解析总内存
if (line.rfind("MemTotal:", 0) == 0) {
std::sscanf(line.c_str(), "MemTotal: %lu kB", &info.total_kb);
}
// 查找并解析可用内存 (MemAvailable通常比MemFree更准确)
else if (line.rfind("MemAvailable:", 0) == 0) {
std::sscanf(line.c_str(), "MemAvailable: %lu kB", &info.available_kb);
}
}
// 如果系统中没有 MemAvailable 字段 (非常老的内核), 则将 available_kb 设为0
// 我们的 web_server 代码会处理这种情况
return info;
}
@ -120,7 +109,6 @@ CpuUtilization SystemMonitor::getCpuUtilization(int interval_ms) const {
uint64_t current_idle = idle + iowait;
uint64_t current_total = current_idle + user + nice + system + irq + softirq + steal;
// 只有在有历史数据时才计算
if (prev_total_ > 0) {
uint64_t total_d = current_total - prev_total_;
uint64_t idle_d = current_idle - prev_idle_;
@ -129,11 +117,9 @@ CpuUtilization SystemMonitor::getCpuUtilization(int interval_ms) const {
}
}
// 更新历史数据以备下次调用
prev_idle_ = current_idle;
prev_total_ = current_total;
// 第一次调用时返回0但已经记录了初始状态
return util;
}