/** * 扫描流程接口封装。 * 后端实现见 HardwareWeb/Controllers/ScanController.cs: * POST /api/scan/start -> { scanId, totalPoints } * POST /api/scan/abort -> { aborted } * GET /api/scan/current -> ScanProgress * GET /api/scan/latest -> ScanRun * GET /api/scan/{scanId} -> ScanRun */ export interface ScanProgress { scanId: string phase: string pointIndex: number totalPoints: number completedPoints: number percent: number message: string stageX: number stageY: number stageMoving: boolean updatedAt: string } export interface ScanSegment { deviceIndex: number serialNumber: string wavelengthStart: number wavelengthEnd: number pointCount: number } export interface ScanElement { symbol: string name: string intensityLevel: string abundance: number rawAbundance: number verdict: string maxIntensity: number matchedWavelength: number matchedLines: number } export interface ScanPointResult { index: number pixelX: number pixelY: number stageX: number stageY: number succeeded: boolean error: string | null wavelengths: number[] spectrum: number[] segments: ScanSegment[] elements: ScanElement[] temperature: number electronDensity: number acquiredAt: string } export interface ScanRun { scanId: string status: string startedAt: string finishedAt: string | null error: string | null totalPoints: number completedPoints: number imageWidth: number imageHeight: number imageMimeType: string | null imageBase64: string | null points: ScanPointResult[] } export interface ScanStartResult { scanId: string totalPoints: number } /** 历史列表中的一条扫描记录(不含图片与光谱数据)。 */ export interface ScanHistoryItem { scanId: string status: string startedAt: string finishedAt: string | null totalPoints: number completedPoints: number error: string | null } const API_BASE = (import.meta.env.VITE_API_BASE ?? '').replace(/\/$/, '') const DEFAULT_TIMEOUT = 15000 const START_TIMEOUT = 60000 const RESULT_TIMEOUT = 30000 export class ScanApiError extends Error { readonly status: number constructor(message: string, status = 0) { super(message) this.name = 'ScanApiError' this.status = status } } async function request( path: string, init?: RequestInit, timeout = DEFAULT_TIMEOUT, ): Promise { const controller = new AbortController() const timer = window.setTimeout(() => controller.abort(), timeout) try { const response = await fetch(`${API_BASE}${path}`, { ...init, cache: 'no-store', signal: controller.signal, headers: { Accept: 'application/json', ...(init?.headers ?? {}), }, }) if (!response.ok) { let detail = `HTTP ${response.status}` try { const body = (await response.json()) as { message?: string; error?: string } detail = body.message ?? body.error ?? detail } catch { // 非 JSON 响应时保留状态码 } throw new ScanApiError(detail, response.status) } return (await response.json()) as T } catch (error) { if (error instanceof ScanApiError) throw error if (error instanceof DOMException && error.name === 'AbortError') { throw new ScanApiError('扫描服务响应超时') } throw new ScanApiError( error instanceof Error ? error.message : '无法连接扫描服务', ) } finally { window.clearTimeout(timer) } } /** 开始一次扫描(后台任务,立即返回)。 */ export function startScan(): Promise { return request( '/api/scan/start', { method: 'POST' }, START_TIMEOUT, ) } /** 中止当前扫描:停止流程、丢弃数据并回零。 */ export function abortScan(): Promise<{ aborted: boolean }> { return request<{ aborted: boolean }>('/api/scan/abort', { method: 'POST' }) } export function getCurrentScan(): Promise { return request('/api/scan/current') } export function getScan(scanId: string): Promise { return request( `/api/scan/${encodeURIComponent(scanId)}`, undefined, RESULT_TIMEOUT, ) } export function getLatestScan(): Promise { return request('/api/scan/latest', undefined, RESULT_TIMEOUT) } /** 历史扫描记录列表(按开始时间倒序)。 */ export function getScanHistory(limit = 100): Promise { return request(`/api/scan/history?limit=${limit}`) } /** 删除一条历史扫描记录及其采样点。 */ export function deleteScan(scanId: string): Promise<{ deleted: boolean }> { return request<{ deleted: boolean }>( `/api/scan/${encodeURIComponent(scanId)}`, { method: 'DELETE' }, ) } export function getStageHubUrl(): string { return `${API_BASE}/stageHub` }