import { LightHA } from "../../src/index.ts"; import { config } from "../app.ts"; import { app } from "../app.ts"; import dayjs from 'dayjs'; export const lightHA = new LightHA({ token: config.HAAS_TOKEN || '', homeassistantURL: config.HAAS_URL }); const mi = config.HAAS_MI_ENTITY_ID || 'text.xiaomi_lx06_9e08_execute_text_directive'; type CallHaReult = { entity_id?: string; runTime?: number; message?: string; } export const callText = async (text: string): Promise => { const command = text?.trim().slice(0, 20); type ParseCommand = { type?: '打开' | '关闭', appName?: string, command?: string, } let obj: ParseCommand = {}; if (command.startsWith('打开')) { obj.appName = command.replace('打开', '').trim(); obj.type = '打开'; } else if (command.startsWith('关闭')) { obj.appName = command.replace('关闭', '').trim(); obj.type = '关闭'; } let endTime = Date.now(); let result: CallHaReult = {}; if (obj.type) { try { const search = await lightHA.searchLight(obj.appName || ''); console.log('searchTime', Date.now() - endTime); if (search.id) { result.entity_id = search.id; await lightHA.runService({ entity_id: search.id, service: obj.type === '打开' ? 'turn_on' : 'turn_off' }); } else if (search.hasMore) { const [first] = search.result; await lightHA.runService({ entity_id: first.entity_id, service: obj.type === '打开' ? 'turn_on' : 'turn_off' }); result.entity_id = first.entity_id; } else { if (mi) { result.message = '使用小爱音箱控制'; await lightHA.text.executeTextDirective(mi, text); } else { console.log('未找到对应设备:', obj.appName); result.message = `未找到对应设备: ${obj.appName}`; } } console.log('解析到控制指令', obj); } catch (e) { console.error('控制失败', e); } } else { result.message = '无法解析控制指令,必须以 "打开 xxx" 或 "关闭 xxx" 开头'; } result.runTime = Date.now() - endTime; return result; } app.route({ path: 'ha', key: 'ha-call', description: 'Home Assistant 控制指令', }).define(async (ctx) => { const text = ctx.query?.text || '' if (!text) { ctx.throw(400, '缺少 text 参数'); } const res = await callText(text); ctx.body = { content: '指令已发送', result: res, timestamp: dayjs().format() }; }).addTo(app)