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

56 lines
2.0 KiB
JavaScript

import { getAlarmHistoryUrl } from '@/utils/esp32Client.js'
import { requestEsp32Api } from '@/utils/networkHelper.js'
import { uploadAlarmsBatch } from '@/utils/alarmCloudApi.js'
function parseAlarmTimestampMs(alarm) {
if (alarm && typeof alarm.timestampMs === 'number' && alarm.timestampMs > 0) {
return alarm.timestampMs
}
if (alarm && typeof alarm.timestamp_ms === 'number' && alarm.timestamp_ms > 0) {
return alarm.timestamp_ms
}
if (alarm && typeof alarm.timestamp === 'number' && alarm.timestamp > 0) {
return alarm.timestamp < 1000000000000 ? alarm.timestamp * 1000 : alarm.timestamp
}
return 0
}
export async function fetchEsp32AlarmHistoryRaw() {
const url = getAlarmHistoryUrl()
if (!url) {
throw new Error('ESP32 baseUrl not configured')
}
const resp = await requestEsp32Api({ url, method: 'GET' })
if (!(resp && resp.statusCode === 200 && resp.data && Array.isArray(resp.data.alarms))) {
throw new Error('Invalid ESP32 alarm history response')
}
return resp.data.alarms
}
export function mapEsp32AlarmsToCloudBatch({ alarms, deviceUid }) {
const duid = String(deviceUid || '').trim()
if (!duid) {
throw new Error('deviceUid is required for cloud sync')
}
return (alarms || []).map(a => {
const ts = parseAlarmTimestampMs(a)
return {
deviceUid: duid,
sourceEventId: duid + ':' + String(ts || ''),
alarmType: a && a.title ? String(a.title) : null,
level: a && a.level ? String(a.level) : null,
title: a && a.title ? String(a.title) : '报警',
message: a && (a.desc || a.message) ? String(a.desc || a.message) : null,
temp: (a && typeof a.temp === 'number') ? a.temp : (a && typeof a.temp === 'string' ? Number(a.temp) : null),
occurredAtMs: ts || null
}
})
}
export async function syncEsp32AlarmHistoryToCloud({ deviceUid }) {
const alarms = await fetchEsp32AlarmHistoryRaw()
const payload = mapEsp32AlarmsToCloudBatch({ alarms, deviceUid })
const resp = await uploadAlarmsBatch(payload)
return { esp32Count: alarms.length, cloudResponse: resp }
}