From 606d17d91df87ef6b3a920d1c839c5ecd12b609e Mon Sep 17 00:00:00 2001 From: leon Date: Fri, 19 Jun 2026 21:19:16 +0800 Subject: [PATCH] =?UTF-8?q?=E5=90=8E=E7=AB=AF=E5=A2=9E=E5=8A=A0=E7=94=B5?= =?UTF-8?q?=E6=BA=90=E6=8E=A7=E5=88=B6=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/main.py | 84 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) diff --git a/backend/main.py b/backend/main.py index ed62bc0..3510c84 100644 --- a/backend/main.py +++ b/backend/main.py @@ -693,3 +693,87 @@ async def control_device(control_data: dict, db: Session = Depends(get_db)): except Exception as e: print(f"控制设备时发生错误: {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 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 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))