在信号发生器控制脚本中,错误处理是确保系统稳定性和可维护性的关键环节。以下是针对信号发生器脚本的错误处理机制设计,涵盖异常捕获、日志记录、重试机制、设备状态检查等核心方法,并提供Python和C++的代码示例。
python
import
time
from
your_signal_generator_lib
import
SignalGenerator, DeviceError
def
safe_configure_channel(sg, channel, freq, amp):
try:
sg.set_frequency(channel, freq)
sg.set_amplitude(channel, amp)
except
DeviceError
as
e:
print(f"Channel
{channel}配置失败:
{str(e)}")
# 可选:记录日志或触发报警
except
ValueError
as
e:
print(f"参数错误 (Channel
{channel}):
{str(e)}")
except
Exception
as
e:
print(f"未知错误 (Channel
{channel}):
{str(e)}")
raise# 重新抛出异常或处理
# 使用示例
sg = SignalGenerator("192.168.1.100")
try:
safe_configure_channel(sg,
1,
10e6, -5)# 正常配置
safe_configure_channel(sg,
2,
1e9,
0)
# 可能触发参数越界
except
Exception
as
e:
print(f"脚本终止:
{str(e)}")
python
import
time
from
threading
import
Lock
def
configure_with_retry(sg, channel, freq, amp, max_retries=3, timeout=5
):
lock = Lock()# 避免多线程竞争
for
attempt
in
range(max_retries):
try:
with
lock:
sg.set_frequency(channel, freq, timeout=timeout)
sg.set_amplitude(channel, amp, timeout=timeout)
return
True# 成功则退出
except
DeviceError
as
e:
print(f"Attempt
{attempt +
1}
failed:
{str(e)}")
time.sleep(1)# 等待后重试
except
TimeoutError:
print("设备响应超时,重置连接...")
sg.reconnect()# 假设有重连方法
return
False# 所有重试失败
# 使用示例
if
not
configure_with_retry(sg,
1,
5e6, -10):
print("配置失败,执行备用方案...")
python
import
logging
# 配置日志
logging.basicConfig(
filename="signal_generator.log",
level=logging.ERROR,
format="%(asctime)s - %(levelname)s - %(message)s"
)
def
log_and_raise(error_msg):
logging.error(error_msg)
raise
RuntimeError(error_msg)
try:
sg.set_frequency(1,
1e10)# 故意触发错误
except
ValueError
as
e:
log_and_raise(f"严重参数错误:
{str(e)}")
cpp
#include
#include
#include
#include
"signal_generator.h"
std::mutex sg_mutex;
void
safeConfigureChannel
(SignalGenerator& sg,
int
channel,
double
freq,
double
amp)
{
try
{
std::lock_guard
lock
(sg_mutex)
;
if
(freq > sg.getMaxFrequency()) {
throw
std::out_of_range("Frequency exceeds device limit");
}
sg.setFrequency(channel, freq);
sg.setAmplitude(channel, amp);
}
catch
(const
std::exception& e) {
std::cerr <<
"Error (Channel "
<"): "
<what() <
// 可选:记录到文件或触发回调
}
}
// 使用示例
int
main
()
{
SignalGenerator
sg
("192.168.1.100")
;
try
{
safeConfigureChannel(sg,
1,
1e6,
-10);
safeConfigureChannel(sg,
2,
1e10,
0);// 触发异常
}
catch
(...) {
std::cerr <<
"Unhandled exception in main"
<
}
return
0;
}
cpp
#include
#include
bool
configureWithRetry
(SignalGenerator& sg,
int
channel,
double
freq,
double
amp,
int
maxRetries =
3)
{
for
(int
i =
0; i
try
{
std::lock_guard
lock
(sg_mutex)
;
if
(!sg.isConnected()) {
sg.reconnect();// 尝试重连
}
sg.setFrequency(channel, freq);
sg.setAmplitude(channel, amp);
return
true;
}
catch
(const
std::exception& e) {
std::cerr <<
"Attempt "
<1
<<
" failed: "
<what() <
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
return
false;
}
python
def
monitor_and_recover(sg, check_interval=60
):
while
True:
try:
status = sg.get_status()
if
"ERROR"
in
status:
print("检测到设备错误,尝试恢复...")
sg.reset()
time.sleep(10)# 等待设备重启
except
Exception
as
e:
print(f"监控线程异常:
{str(e)}")
time.sleep(check_interval)
# 在后台启动监控线程
import
threading
threading.Thread(target=monitor_and_recover, args=(sg,), daemon=True).start()
python
from
contextlib
import
contextmanager
@contextmanager
def
signal_generator_session(sg):
try:
yield
sg
except
DeviceError
as
e:
print(f"操作失败:
{str(e)}")
sg.disconnect()
raise
finally:
sg.disconnect()# 确保资源释放
# 使用示例
with
signal_generator_session(SignalGenerator("192.168.1.100"))
as
sg:
sg.set_frequency(1,
1e6)
try/finally
或上下文管理器确保设备连接释放。
try/except
、日志模块和上下文管理器实现健壮性。
通过完善的错误处理,信号发生器脚本可以从偶发故障中自动恢复,显著提升自动化测试或生产环境的可靠性。