后端增加电源控制接口

This commit is contained in:
2026-06-19 21:19:16 +08:00
parent 78b5898da2
commit 606d17d91d
+84
View File
@@ -693,3 +693,87 @@ async def control_device(control_data: dict, db: Session = Depends(get_db)):
except Exception as e: except Exception as e:
print(f"控制设备时发生错误: {e}") print(f"控制设备时发生错误: {e}")
raise HTTPException(status_code=500, detail=str(e)) raise HTTPException(status_code=500, detail=str(e))
# 电源控制API - 控制HVS和Scanner的供电
@app.post("/api/powerctrl")
async def power_control(power_data: dict):
"""
控制HVS和Scanner的供电
参数:
- device: 设备名称,可选值: 'hvs' 或 'scanner'
- action: 操作,可选值: 'on' (打开) 或 'off' (关闭) 或 'status' (查询状态)
"""
try:
device = power_data.get("device")
action = power_data.get("action")
if device is None or action is None:
raise HTTPException(status_code=400, detail="缺少必要参数: device 和 action")
# 验证设备类型
if device not in ['hvs', 'scanner']:
raise HTTPException(status_code=400, detail="device 必须是 'hvs' 或 'scanner'")
# 验证操作类型
if action not in ['on', 'off', 'status']:
raise HTTPException(status_code=400, detail="action 必须是 'on'、'off' 或 'status'")
# 定义GPIO引脚映射
gpio_pins = {
'hvs': 26,
'scanner': 17
}
pin = gpio_pins[device]
if action == 'status':
# 查询状态
result = subprocess.run(
['pinctrl', 'get', str(pin)],
capture_output=True,
text=True
)
if result.returncode != 0:
return {"device": device, "status": "unknown", "error": result.stderr}
output = result.stdout.strip()
# 解析状态: "17: op dl pn | lo" 表示输出低电平(打开)
# "17: op dh pn | hi" 表示输出高电平(关闭)
if 'dl' in output or 'lo' in output.lower():
status = 'on'
elif 'dh' in output or 'hi' in output.lower():
status = 'off'
else:
status = 'unknown'
return {"device": device, "status": status, "raw_output": output}
elif action == 'on':
# 打开供电: pinctrl set <pin> op pn dl
result = subprocess.run(
['pinctrl', 'set', str(pin), 'op', 'pn', 'dl'],
capture_output=True,
text=True
)
if result.returncode != 0:
raise HTTPException(status_code=500, detail=f"执行失败: {result.stderr}")
return {"device": device, "action": action, "status": "success"}
elif action == 'off':
# 关闭供电: pinctrl set <pin> op pn dh
result = subprocess.run(
['pinctrl', 'set', str(pin), 'op', 'pn', 'dh'],
capture_output=True,
text=True
)
if result.returncode != 0:
raise HTTPException(status_code=500, detail=f"执行失败: {result.stderr}")
return {"device": device, "action": action, "status": "success"}
except HTTPException:
raise
except Exception as e:
print(f"电源控制时发生错误: {e}")
raise HTTPException(status_code=500, detail=str(e))