Files
WebTools/src/workers/crc.worker.ts
T

53 lines
1.9 KiB
TypeScript

import { calculateCrcHexInput, calculateCrcReport, type CrcWorkerRequest, type CrcWorkerResponse } from '@/lib/crcWorker'
import { getFirmwareFormat, MAX_FIRMWARE_FILE_SIZE, parseFirmwareContent } from '@/lib/firmware'
import type { DataBlock } from '@/lib/intelHex'
const workerScope = globalThis as unknown as {
onmessage: ((event: MessageEvent<CrcWorkerRequest>) => void) | null
postMessage(message: CrcWorkerResponse): void
}
let firmwareBlocks: DataBlock[] | undefined
workerScope.onmessage = async (event) => {
const request = event.data
try {
if (request.type === 'parse') {
if (request.file.size === 0) throw new Error('文件为空')
if (request.file.size > MAX_FIRMWARE_FILE_SIZE) throw new Error('文件不能超过 64 MiB')
const format = getFirmwareFormat(request.file.name)
const content = format === 'Intel HEX'
? await request.file.text()
: new Uint8Array(await request.file.arrayBuffer())
const parsed = parseFirmwareContent(request.file.name, content)
firmwareBlocks = parsed.blocks
workerScope.postMessage({
type: 'parsed',
id: request.id,
format: parsed.format,
totalBytes: parsed.totalBytes,
blockCount: parsed.blocks.length,
warnings: parsed.warnings,
})
return
}
if (request.type === 'calculate-hex') {
workerScope.postMessage({
type: 'calculated-hex',
id: request.id,
...calculateCrcHexInput(request.input, request.parameters),
})
return
}
if (!firmwareBlocks) throw new Error('请先选择 BIN 或 Intel HEX 文件')
workerScope.postMessage({ type: 'calculated', id: request.id, ...calculateCrcReport(firmwareBlocks, request.parameters) })
} catch (reason) {
workerScope.postMessage({
type: 'error',
id: request.id,
operation: request.type,
error: reason instanceof Error ? reason.message : 'CRC 计算失败',
})
}
}