update:补充音量太大声、太小声的意图动作

This commit is contained in:
hrz 2025-03-18 00:16:40 +08:00
parent 4342f87515
commit 7e785428ac
6 changed files with 124 additions and 55 deletions

View file

@ -35,10 +35,7 @@ log:
log_file: "server.log" log_file: "server.log"
# 设置数据文件路径 # 设置数据文件路径
data_dir: data data_dir: data
iot:
Speaker:
# 设置esp32的音量,范围0-100
volume: 80
xiaozhi: xiaozhi:
type: hello type: hello
version: 1 version: 1
@ -102,9 +99,6 @@ Intent:
- change_role - change_role
- get_weather - get_weather
# 是否使用iot_function_handler处理,开启后iot消息会自动注册到function_call中
use_iot_function_handler: false
Memory: Memory:
mem0ai: mem0ai:
type: mem0ai type: mem0ai

View file

@ -50,6 +50,7 @@ class FunctionHandler:
self.function_registry.register_function("play_music") self.function_registry.register_function("play_music")
self.function_registry.register_function("plugin_loader") self.function_registry.register_function("plugin_loader")
self.function_registry.register_function("get_time") self.function_registry.register_function("get_time")
self.function_registry.register_function("raise_and_lower_the_volume")
def register_config_functions(self): def register_config_functions(self):
"""注册配置中的函数,可以不同客户端使用不同的配置""" """注册配置中的函数,可以不同客户端使用不同的配置"""

View file

@ -6,15 +6,18 @@ from plugins_func.register import device_type_registry, register_function, Actio
TAG = __name__ TAG = __name__
logger = setup_logging() logger = setup_logging()
def wrap_async_function(async_func): def wrap_async_function(async_func):
"""包装异步函数为同步函数""" """包装异步函数为同步函数"""
def wrapper(*args, **kwargs): def wrapper(*args, **kwargs):
try: try:
# 获取连接对象(第一个参数) # 获取连接对象(第一个参数)
conn = args[0] conn = args[0]
if not hasattr(conn, 'loop'): if not hasattr(conn, 'loop'):
logger.bind(tag=TAG).error("Connection对象没有loop属性") logger.bind(tag=TAG).error("Connection对象没有loop属性")
return ActionResponse(Action.ERROR, "Connection对象没有loop属性", "执行操作时出错: Connection对象没有loop属性") return ActionResponse(Action.ERROR, "Connection对象没有loop属性",
"执行操作时出错: Connection对象没有loop属性")
# 使用conn对象中的事件循环 # 使用conn对象中的事件循环
loop = conn.loop loop = conn.loop
@ -25,16 +28,20 @@ def wrap_async_function(async_func):
except Exception as e: except Exception as e:
logger.bind(tag=TAG).error(f"运行异步函数时出错: {e}") logger.bind(tag=TAG).error(f"运行异步函数时出错: {e}")
return ActionResponse(Action.ERROR, str(e), f"执行操作时出错: {e}") return ActionResponse(Action.ERROR, str(e), f"执行操作时出错: {e}")
return wrapper return wrapper
def create_iot_function(device_name, method_name, method_info): def create_iot_function(device_name, method_name, method_info):
""" """
根据IOT设备描述生成通用的控制函数 根据IOT设备描述生成通用的控制函数
""" """
async def iot_control_function(conn, response_success=None, response_failure=None, **params): async def iot_control_function(conn, response_success=None, response_failure=None, **params):
try: try:
# 打印响应参数 # 打印响应参数
logger.bind(tag=TAG).info(f"控制函数接收到的响应参数: success='{response_success}', failure='{response_failure}'") logger.bind(tag=TAG).info(
f"控制函数接收到的响应参数: success='{response_success}', failure='{response_failure}'")
# 发送控制命令 # 发送控制命令
await send_iot_conn(conn, device_name, method_name, params) await send_iot_conn(conn, device_name, method_name, params)
@ -68,16 +75,20 @@ def create_iot_function(device_name, method_name, method_info):
response = response_failure response = response_failure
return ActionResponse(Action.ERROR, str(e), response) return ActionResponse(Action.ERROR, str(e), response)
return wrap_async_function(iot_control_function) return wrap_async_function(iot_control_function)
def create_iot_query_function(device_name, prop_name, prop_info): def create_iot_query_function(device_name, prop_name, prop_info):
""" """
根据IOT设备属性创建查询函数 根据IOT设备属性创建查询函数
""" """
async def iot_query_function(conn, response_success=None, response_failure=None): async def iot_query_function(conn, response_success=None, response_failure=None):
try: try:
# 打印响应参数 # 打印响应参数
logger.bind(tag=TAG).info(f"查询函数接收到的响应参数: success='{response_success}', failure='{response_failure}'") logger.bind(tag=TAG).info(
f"查询函数接收到的响应参数: success='{response_success}', failure='{response_failure}'")
value = await get_iot_status(conn, device_name, prop_name) value = await get_iot_status(conn, device_name, prop_name)
@ -99,8 +110,10 @@ def create_iot_query_function(device_name, prop_name, prop_info):
response = response_failure response = response_failure
return ActionResponse(Action.ERROR, str(e), response) return ActionResponse(Action.ERROR, str(e), response)
return wrap_async_function(iot_query_function) return wrap_async_function(iot_query_function)
async def update_state_by_method(conn, device_name, method_name, params): async def update_state_by_method(conn, device_name, method_name, params):
"""根据方法和参数自动更新设备状态""" """根据方法和参数自动更新设备状态"""
try: try:
@ -129,10 +142,12 @@ async def update_state_by_method(conn, device_name, method_name, params):
except Exception as e: except Exception as e:
logger.bind(tag=TAG).warning(f"自动更新状态失败: {e}") logger.bind(tag=TAG).warning(f"自动更新状态失败: {e}")
class IotDescriptor: class IotDescriptor:
""" """
A class to represent an IoT descriptor. A class to represent an IoT descriptor.
""" """
def __init__(self, name, description, properties, methods): def __init__(self, name, description, properties, methods):
self.name = name self.name = name
self.description = description self.description = description
@ -168,6 +183,7 @@ class IotDescriptor:
method[k]["value"] = "" method[k]["value"] = ""
self.methods.append(method) self.methods.append(method)
def register_device_type(descriptor): def register_device_type(descriptor):
"""注册设备类型及其功能""" """注册设备类型及其功能"""
device_name = descriptor["name"] device_name = descriptor["name"]
@ -255,9 +271,10 @@ def register_device_type(descriptor):
device_type_registry.register_device_type(type_id, functions) device_type_registry.register_device_type(type_id, functions)
return type_id return type_id
# 用于接受前端设备推送的搜索iot描述
async def handleIotDescriptors(conn, descriptors): async def handleIotDescriptors(conn, descriptors):
"""处理物联网描述""" """处理物联网描述"""
bUseIotFunctionHandler = conn.config.get("use_iot_function_handler", False)
functions_changed = False functions_changed = False
for descriptor in descriptors: for descriptor in descriptors:
@ -266,7 +283,7 @@ async def handleIotDescriptors(conn, descriptors):
descriptor["methods"]) descriptor["methods"])
conn.iot_descriptors[descriptor["name"]] = iot_descriptor conn.iot_descriptors[descriptor["name"]] = iot_descriptor
if bUseIotFunctionHandler: if conn.use_function_call_mode:
# 注册或获取设备类型 # 注册或获取设备类型
type_id = register_device_type(descriptor) type_id = register_device_type(descriptor)
device_functions = device_type_registry.get_device_functions(type_id) device_functions = device_type_registry.get_device_functions(type_id)
@ -285,13 +302,6 @@ async def handleIotDescriptors(conn, descriptors):
logger.bind(tag=TAG).info(f"设备类型: {type_id}") logger.bind(tag=TAG).info(f"设备类型: {type_id}")
logger.bind(tag=TAG).info(f"更新function描述列表完成,当前支持的函数: {func_names}") logger.bind(tag=TAG).info(f"更新function描述列表完成,当前支持的函数: {func_names}")
# 暂时从配置文件中设置音量,后期通过意图识别控制音量
default_iot_volume = 100
if "iot" in conn.config:
default_iot_volume = conn.config["iot"]["Speaker"]["volume"]
logger.bind(tag=TAG).info(f"服务端设置音量为{default_iot_volume}")
await send_iot_conn(conn, "Speaker", "SetVolume", {"volume": default_iot_volume})
await set_iot_status(conn, "Speaker", "volume", default_iot_volume)
async def handleIotStatus(conn, states): async def handleIotStatus(conn, states):
"""处理物联网状态""" """处理物联网状态"""
@ -310,6 +320,7 @@ async def handleIotStatus(conn, states):
break break
break break
async def get_iot_status(conn, name, property_name): async def get_iot_status(conn, name, property_name):
"""获取物联网状态""" """获取物联网状态"""
for key, value in conn.iot_descriptors.items(): for key, value in conn.iot_descriptors.items():
@ -320,6 +331,7 @@ async def get_iot_status(conn, name, property_name):
logger.bind(tag=TAG).warning(f"未找到设备 {name} 的属性 {property_name}") logger.bind(tag=TAG).warning(f"未找到设备 {name} 的属性 {property_name}")
return None return None
async def set_iot_status(conn, name, property_name, value): async def set_iot_status(conn, name, property_name, value):
"""设置物联网状态""" """设置物联网状态"""
for key, iot_descriptor in conn.iot_descriptors.items(): for key, iot_descriptor in conn.iot_descriptors.items():
@ -334,6 +346,7 @@ async def set_iot_status(conn, name, property_name, value):
return return
logger.bind(tag=TAG).warning(f"未找到设备 {name} 的属性 {property_name}") logger.bind(tag=TAG).warning(f"未找到设备 {name} 的属性 {property_name}")
async def send_iot_conn(conn, name, method_name, parameters): async def send_iot_conn(conn, name, method_name, parameters):
"""发送物联网指令""" """发送物联网指令"""
for key, value in conn.iot_descriptors.items(): for key, value in conn.iot_descriptors.items():

View file

@ -22,7 +22,7 @@ class TTSProvider(TTSProviderBase):
self.cut_punc = config.get("cut_punc","") self.cut_punc = config.get("cut_punc","")
self.speed = config.get("speed", 1.0) self.speed = config.get("speed", 1.0)
self.inp_refs = config.get("inp_refs",[]) self.inp_refs = config.get("inp_refs",[])
self.sample_steps = config.get("inp_refs",32) self.sample_steps = config.get("sample_steps",32)
self.if_sr = config.get("if_sr",False) self.if_sr = config.get("if_sr",False)

View file

@ -112,7 +112,6 @@ def get_music_files(music_dir, music_ext):
def initialize_music_handler(conn): def initialize_music_handler(conn):
global MUSIC_CACHE global MUSIC_CACHE
if MUSIC_CACHE == {}: if MUSIC_CACHE == {}:
logger.bind(tag=TAG).info(f"实例化音乐:")
if "music" in conn.config: if "music" in conn.config:
MUSIC_CACHE["music_config"] = conn.config["music"] MUSIC_CACHE["music_config"] = conn.config["music"]
MUSIC_CACHE["music_dir"] = os.path.abspath( MUSIC_CACHE["music_dir"] = os.path.abspath(

View file

@ -0,0 +1,62 @@
from config.logger import setup_logging
from plugins_func.register import register_function, ToolType, ActionResponse, Action
from core.handle.iotHandle import get_iot_status, send_iot_conn
import asyncio
TAG = __name__
logger = setup_logging()
raise_and_lower_the_volume_function_desc = {
"type": "function",
"function": {
"name": "raise_and_lower_the_volume",
"description": "用户觉得声音过高或过低,或者用户想提高或降低音量。比如用户说太大声了,参数为:lower,比如用户说提高音量,参数为:raise",
"parameters": {
"type": "object",
"properties": {
"action": {
"type": "string",
"description": "动作名称,要么是raise,要么是lower"
}
},
"required": ["action"]
}
}
}
@register_function('raise_and_lower_the_volume', raise_and_lower_the_volume_function_desc, ToolType.IOT_CTL)
def raise_and_lower_the_volume(conn, action: str):
"""
获取当前设备音量
"""
future = asyncio.run_coroutine_threadsafe(
_raise_and_lower_the_volume(conn, action),
conn.loop
)
try:
new_volume = future.result() # 同步等待异步操作完成
logger.bind(tag=TAG).info(f"音量操作完成: {new_volume}")
response = f"音量已调整到{new_volume}"
except Exception as e:
logger.bind(tag=TAG).error(f"音量操作失败: {e}")
response = f"音量调整失败: {e}"
return ActionResponse(action=Action.RESPONSE, result="指令已接收", response=response)
async def _raise_and_lower_the_volume(conn, action):
volume = await get_iot_status(conn, "Speaker", "volume")
if action == 'raise':
volume += 10
elif action == 'lower':
volume -= 10
# 限制音量范围在0到100之间
if volume < 0:
volume = 0
elif volume > 100:
volume = 100
await send_iot_conn(conn, "Speaker", "SetVolume", {"volume": volume})
return volume