62 lines
1.5 KiB
TypeScript
62 lines
1.5 KiB
TypeScript
import type { EventSubscription } from "expo-modules-core";
|
|
import { create } from "zustand";
|
|
|
|
import { fullFeedFixture } from "@/lib/ble/fixtures";
|
|
import { Ble, defaultBleState } from "@aris/ble";
|
|
import type { BleStatePayload } from "@aris/ble";
|
|
|
|
export type BleStoreState = BleStatePayload & {
|
|
isSupported: boolean;
|
|
isReady: boolean;
|
|
initialize: () => void;
|
|
setAdvertisingEnabled: (enabled: boolean) => void;
|
|
setWifiRequested: (requested: boolean) => void;
|
|
sendFixtureFeedNow: () => void;
|
|
};
|
|
|
|
let subscription: EventSubscription | null = null;
|
|
|
|
const noopSubscription: EventSubscription = {
|
|
remove: () => undefined,
|
|
};
|
|
|
|
export const useBleStore = create<BleStoreState>((set, get) => ({
|
|
...defaultBleState,
|
|
isSupported: Ble.isSupported,
|
|
isReady: false,
|
|
initialize: () => {
|
|
if (!Ble.isSupported || get().isReady) {
|
|
return;
|
|
}
|
|
const state = Ble.getState();
|
|
set({ ...state, isReady: true });
|
|
subscription?.remove();
|
|
subscription =
|
|
Ble.addStateListener?.((nextState) => {
|
|
set({ ...nextState });
|
|
}) ?? noopSubscription;
|
|
Ble.start();
|
|
},
|
|
setAdvertisingEnabled: (enabled) => {
|
|
if (!Ble.isSupported) {
|
|
return;
|
|
}
|
|
set({ advertisingEnabled: enabled });
|
|
Ble.setAdvertisingEnabled(enabled);
|
|
},
|
|
setWifiRequested: (requested) => {
|
|
if (!Ble.isSupported) {
|
|
return;
|
|
}
|
|
set({ wifiRequested: requested });
|
|
Ble.setWifiRequested(requested);
|
|
},
|
|
sendFixtureFeedNow: () => {
|
|
if (!Ble.isSupported) {
|
|
return;
|
|
}
|
|
const payload = JSON.stringify(fullFeedFixture);
|
|
Ble.sendOpaque(payload, 1);
|
|
},
|
|
}));
|