smart-home/smart-home-app/utils/alarmAutoSync.js
2026-02-26 09:16:34 +08:00

45 lines
1.3 KiB
JavaScript

import { getAllDevices } from '@/utils/deviceStore.js'
import { syncEsp32AlarmHistoryToCloud } from '@/utils/alarmSync.js'
const LAST_SYNC_KEY = 'alarm_cloud_last_sync_ms'
function pickDeviceUidForCloudSync() {
try {
const list = getAllDevices() || []
// 优先厨房主机,其次任意 host
const kitchen = list.find(d => d && d.type === 'host' && d.id === 'dev_host_2')
if (kitchen && kitchen.id) return String(kitchen.id)
const host = list.find(d => d && d.type === 'host' && d.id)
if (host && host.id) return String(host.id)
} catch (e) {}
return ''
}
export function shouldAutoSyncAlarmHistory({ minIntervalMs = 5 * 60 * 1000 } = {}) {
try {
const last = Number(uni.getStorageSync(LAST_SYNC_KEY) || 0)
if (last && Date.now() - last < minIntervalMs) return false
return true
} catch (e) {
return true
}
}
export async function autoSyncAlarmHistoryToCloud(options = {}) {
const { minIntervalMs = 5 * 60 * 1000 } = options
if (!shouldAutoSyncAlarmHistory({ minIntervalMs })) {
return { skipped: true, reason: 'throttled' }
}
const deviceUid = pickDeviceUidForCloudSync()
if (!deviceUid) {
return { skipped: true, reason: 'no_device_uid' }
}
const res = await syncEsp32AlarmHistoryToCloud({ deviceUid })
try {
uni.setStorageSync(LAST_SYNC_KEY, Date.now())
} catch (e) {}
return { skipped: false, deviceUid, result: res }
}