74 lines
2.5 KiB
Python
74 lines
2.5 KiB
Python
import grpc
|
|
from typing import Tuple
|
|
|
|
from . import generated
|
|
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
|
|
|
|
def _create_command_header(self):
|
|
"""创建命令头"""
|
|
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:
|
|
request = generated.microphone_service_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:
|
|
request = generated.microphone_service_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:
|
|
request = generated.microphone_service_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 |