feat: 实现readingRecord
This commit is contained in:
@ -8,12 +8,15 @@
|
||||
} from '$lib/stores/serial/serial.ui';
|
||||
import { serialOptions } from '$lib/stores/serial/serial.options';
|
||||
import SerialParamSelect from './SerialParamSelect.svelte';
|
||||
import { addRecord, readingRecord } from '$lib/stores/record/record';
|
||||
import { get } from 'svelte/store';
|
||||
|
||||
import { toast } from 'svelte-sonner';
|
||||
|
||||
import { Button } from '$lib/components/ui/button';
|
||||
|
||||
import { getSerialContext } from '$lib/serial/serial.store';
|
||||
import { startReadLoop } from '$lib/serial';
|
||||
|
||||
const serial = getSerialContext();
|
||||
const serialState = serial.state;
|
||||
@ -36,6 +39,46 @@
|
||||
{ value: '2', label: '2' },
|
||||
];
|
||||
|
||||
function concatUint8(a: Uint8Array, b: Uint8Array) {
|
||||
const out = new Uint8Array(a.length + b.length);
|
||||
out.set(a, 0);
|
||||
out.set(b, a.length);
|
||||
return out;
|
||||
}
|
||||
|
||||
function appendReadingChunk(chunk: Uint8Array) {
|
||||
readingRecord.update((current) => {
|
||||
// ① 还没有 readingRecord → 新建
|
||||
if (!current) {
|
||||
return {
|
||||
id: crypto.randomUUID(),
|
||||
type: 'read',
|
||||
data: chunk,
|
||||
timestamp: Date.now(),
|
||||
display: 'ascii',
|
||||
};
|
||||
}
|
||||
|
||||
// ② 已存在 → 追加数据
|
||||
return {
|
||||
...current,
|
||||
data: concatUint8(current.data, chunk),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function finalizeReadingRecord() {
|
||||
const record = get(readingRecord);
|
||||
if (!record) return;
|
||||
|
||||
addRecord(record);
|
||||
readingRecord.set(undefined);
|
||||
}
|
||||
|
||||
function isRecordFinished(chunk: Uint8Array) {
|
||||
return chunk.includes(0x0a); // '\n'
|
||||
}
|
||||
|
||||
async function connect() {
|
||||
await serial.requestPort();
|
||||
await serial.openPort($serialOptions);
|
||||
@ -44,6 +87,19 @@
|
||||
} else {
|
||||
toast.success('串口连接成功');
|
||||
}
|
||||
await startReadLoop(
|
||||
(chunk) => {
|
||||
appendReadingChunk(chunk);
|
||||
if (isRecordFinished(chunk)) {
|
||||
console.log('Received chunk:', chunk);
|
||||
finalizeReadingRecord();
|
||||
}
|
||||
},
|
||||
(err) => {
|
||||
console.error('Read loop error:', err);
|
||||
toast.error(`读取数据失败: ${err}`);
|
||||
}
|
||||
);
|
||||
}
|
||||
</script>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user