// 环境监控 API: 走后端 /api/mihome/* (凭证/token 不出前端) import { api, getApiBase, getToken } from './client.js' // 状态: 授权 + 家庭(设备) + 电量 + 最新样本 + 缺日 + 统计可用性 // force=true 让后端跳过 5 分钟认证缓存, 立刻回真实授权状态 export async function getMihomeStatus(force) { return api('/mihome/status' + (force ? '?force=1' : '')) } // 历史: range = today | month | year export async function getMihomeHistory(did, range) { return api('/mihome/device/' + encodeURIComponent(did) + '/history?range=' + encodeURIComponent(range)) } // 改别名 (alias 传空串 = 清空) export async function setMihomeAlias(did, alias) { return api('/mihome/device/' + encodeURIComponent(did), { method: 'PUT', body: { alias } }) } // 立即同步 export async function syncMihome() { return api('/mihome/sync', { method: 'POST' }) } // 重授权 export async function startMihomeAuth() { return api('/mihome/reauthorize', { method: 'POST' }) } export async function getMihomeAuthStatus() { return api('/mihome/reauthorize/status') } export async function cancelMihomeAuth() { return api('/mihome/reauthorize/cancel', { method: 'POST' }) } // 二维码图片: 后端接口在 authRequired 后面, 而 无法带 Authorization 头, // 直接塞地址会 401 (二维码位置一片空白). 这里用 fetch 带 JWT 取回二进制, 再转 blob URL 给 . export async function fetchMihomeQrImage() { const token = getToken() const res = await fetch(getApiBase() + '/api/mihome/reauthorize/qr-image', { headers: token ? { Authorization: 'Bearer ' + token } : {}, cache: 'no-store', }) if (!res.ok) { const data = await res.json().catch(() => ({})) throw new Error(data.error || '二维码加载失败 (' + res.status + ')') } const blob = await res.blob() return URL.createObjectURL(blob) }