cmvr-es-cli/cmvr/micphone_client.py
2025-08-25 10:34:44 +08:00

94 lines
3.4 KiB
Python

import grpc
from typing import Tuple
from .enums import CMVRErrorCode
from .models import MicState
class MicphoneClient:
"""麦克风客户端"""
def __init__(self, device_id: str, stub):
self.device_id = device_id
self.stub = stub
self.generated = None # 推迟导入
def _import_generated(self):
"""推迟导入 generated"""
if self.generated is None:
try:
# 从正确的路径导入生成的模块
from generated.cmvr.api import common_pb2, microphone_command_pb2
self.generated = type('GeneratedModules', (), {
'common_pb2': common_pb2,
'microphone_command_pb2': microphone_command_pb2
})
except ImportError as e:
print(f"导入生成的模块失败: {e}")
print("请确保已生成 protobuf 代码")
raise
return self.generated
def _create_command_header(self):
"""创建命令头"""
generated = self._import_generated()
header = generated.common_pb2.CommandHeader.Request()
header.device_id = self.device_id
header.timestamp.GetCurrentTime()
return header
def get_status(self) -> Tuple[CMVRErrorCode, MicState]:
"""获取麦克风状态"""
try:
generated = self._import_generated()
request = generated.microphone_command_pb2.GetMicStateCommand.Request()
request.header.CopyFrom(self._create_command_header())
response = self.stub.GetStatus(request)
if not response.header.success:
return CMVRErrorCode.CMVR_RPC_FAILED, MicState()
state = MicState(
is_initialized=response.state.is_initialized,
is_running=response.state.is_running,
is_recording=response.state.is_recording,
volume=response.state.volume,
error_message=response.state.error_message
)
return CMVRErrorCode.CMVR_SUCCESS, state
except grpc.RpcError as e:
print(f"获取麦克风状态失败: {e}")
return CMVRErrorCode.CMVR_RPC_FAILED, MicState()
def start_record(self, audio_path: str) -> CMVRErrorCode:
"""开始录音"""
try:
generated = self._import_generated()
request = generated.microphone_command_pb2.StartMicRecordingCommand.Request()
request.header.CopyFrom(self._create_command_header())
request.file_path = audio_path
response = self.stub.StartRecord(request)
return CMVRErrorCode.CMVR_SUCCESS if response.header.success else CMVRErrorCode.CMVR_RPC_FAILED
except grpc.RpcError as e:
print(f"开始录音失败: {e}")
return CMVRErrorCode.CMVR_RPC_FAILED
def stop_record(self) -> CMVRErrorCode:
"""停止录音"""
try:
generated = self._import_generated()
request = generated.microphone_command_pb2.StopMicRecordingCommand.Request()
request.header.CopyFrom(self._create_command_header())
response = self.stub.StopRecord(request)
return CMVRErrorCode.CMVR_SUCCESS if response.header.success else CMVRErrorCode.CMVR_RPC_FAILED
except grpc.RpcError as e:
print(f"停止录音失败: {e}")
return CMVRErrorCode.CMVR_RPC_FAILED