本流为开门回家根据光线是否开灯以及AI说出回家欢迎词的流,AI为通义千问,可以自行申请KEY,免费的。
1、流程图
2、函数代码
// ====================== [安全数据解构] ======================
const update_time = formatDate(new Date()); // 更新时间并格式化
// 使用安全解构提取数据,设置默认值防止未定义错误
const {
whoAtHome: {
attributes:{
who_detail:{
who_home_recently: recentlyHome // 家庭成员最近回家状态
}
}
},
timeFormat: {
attributes: { // 问候语配置
greet: {
helloWord // 时段问候语
}
}
},
washerDoor = '', // 洗衣机门状态
washer = '', // 洗衣机运行状态
washer_data: { timeSinceChangedMs: washerSinceTime = 0 }, // 洗衣机状态变更时间
clothesHanger: clothesHangerStatus = "closed", // 晾衣架状态
clothesHanger_data: { timeSinceChangedMs: clothesHangerSinceTime = 0 } // 晾衣架变更时间
} = msg || {};
// ====================== [生成设备提醒] ======================
// 洗衣机提醒:门关闭且停止运行
const washerNotice = createDeviceNotice(
washerDoor === "off" && washer === "off",
"洗衣机衣服已洗好%s,请及时晾晒!",
formatDuration(washerSinceTime)
);
// 晾衣架提醒:升起超过6小时(21600000毫秒)
const clothesHangerNotice = createDeviceNotice(
clothesHangerStatus === "open" && clothesHangerSinceTime >= 21600000,
"阳台衣物已晾晒%s,请及时收起!",
formatDuration(clothesHangerSinceTime)
);
// 定义条件数组
const specificGreetings = ["下午好!", "晚上好!", "晚安!"];
var aiGreeting = msg.payload.choices[0].message.content || "欢迎主人回家!";
// ====================== [构建消息内容] ======================
// 组合通知内容(过滤空值后拼接)
const content = [
recentlyHome && `${recentlyHome},${helloWord}`, // 回家成员问候
aiGreeting, // 时段问候
washerNotice, // 洗衣机提醒
clothesHangerNotice // 晾衣架提醒
].filter(Boolean).join("\n"); // 移除空值,增加换行
// ====================== [返回结果] ======================
// 构造最终消息对象
msg = {
notifyTitle: "🏠欢迎回家", // 消息标题
voice: content, // 语音播报内容
notify: `${update_time}\n${content}`, // 通知内容
notifyId: 1006 // 通知类型ID
};
return msg;
// ====================== [设备提醒生成函数] ======================
function createDeviceNotice(condition, template, ...values) {
if (!condition) return '';
return values.reduce((acc, val) =>
acc.replace(/%s/, val != null ? val.toString() : ""), template);
}
// ====================== [时间格式化函数] ======================
function formatDuration(ms) {
if (typeof ms !== "number" || ms < 0) return "0分钟";
const seconds = Math.floor(ms / 1000);
const days = Math.floor(seconds / 86400);
const hours = Math.floor((seconds % 86400) / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
// 智能显示策略:
// 1. 优先显示天数
// 2. 无天数时显示小时+分钟
// 3. 无小时时仅显示分钟
return (
days > 0 ? `${days}天${hours}小时` :
hours > 0 ? `${hours}小时${minutes}分钟` : `${minutes}分钟` );
}
//===============时间格式转换函数==============//
function formatDate(now) {
var time = now.toLocaleString("zh-CN", {
timeZone: "Asia/Shanghai",
hour12: false,
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit"
});
return time.replace(/\//g, "-");
}
3、下载地址
|