basically complete retrieving found peripherals.

This commit is contained in:
Vixalie
2025-02-28 13:20:27 +08:00
parent 63c7d49943
commit c6043b612f
3 changed files with 28 additions and 22 deletions

View File

@@ -2,7 +2,7 @@ import { invoke } from '@tauri-apps/api/core';
import { listen, UnlistenFn } from '@tauri-apps/api/event';
import { message } from '@tauri-apps/plugin-dialog';
import { atom, PrimitiveAtom, useSetAtom } from 'jotai';
import { atomFamily, atomWithRefresh } from 'jotai/utils';
import { atomFamily, atomWithRefresh, RESET } from 'jotai/utils';
import { FC, ReactNode, useEffect, useRef } from 'react';
export type Channels = 'a' | 'b';
@@ -18,7 +18,7 @@ type ChannelState = {
type PeripheralItem = {
id: string;
address: string;
represent: string;
represent: string | null;
isConnected: boolean;
rssi: number | null;
battery: number | null;
@@ -77,22 +77,24 @@ export const DeviceState = atomWithRefresh<DeviceState>(async (get) => {
battery: null,
};
});
export const FoundPeripherals = atomWithRefresh<PeripheralItem[]>(async (get) => {
try {
const peripherals = await invoke('found_peripherals');
return peripherals.map((peripheral: PeripheralItem) => ({
id: peripheral.id,
address: peripheral.address,
represent: peripheral.represent,
isConnected: peripheral.isConnected,
rssi: peripheral.rssi,
battery: peripheral.battery,
}));
} catch (e) {
console.error('[refresh found]', e);
}
return [];
});
export const FoundPeripherals = atom(
[] as PeripheralItem[],
(get, set, item: PeripheralItem | typeof RESET) => {
if (item === RESET) {
void set(FoundPeripherals, []);
} else {
void set(FoundPeripherals, (prev) => {
const foundIndex = prev.findIndex((i) => i.id === item.id);
if (foundIndex !== -1) {
prev[foundIndex] = item;
} else {
prev.push(item);
}
return prev;
});
}
},
);
const Channels: Record<Channels, PrimitiveAtom<ChannelState>> = {
a: atomWithRefresh<ChannelState>(async (get) => {
try {
@@ -164,7 +166,9 @@ const EstimWatchProvider: FC<{ children?: ReactNode }> = ({ children }) => {
try {
unlistenBle.current = await listen('central_state_updated', () => refreshBle());
unlistenDevice.current = await listen('peripheral_connected', () => refreshDevice());
unlistenPreipherals.current = await listen('peripherals_found', () => refreshPeripherals());
unlistenPreipherals.current = await listen('peripheral_found', (event) => {
refreshPeripherals(event.payload);
});
unlistenChannelA.current = await listen('channel_a_updated', () => refreshChannelA());
unlistenChannelB.current = await listen('channel_b_updated', () => refreshChannelB());
await invoke('activate_central_adapter');