forked from Blendman974/faceclaw
Initial publishable release
This commit is contained in:
commit
6e442e7faa
120 files changed
+750769
No files matched your search
@@ -0,0 +1,64 @@
|
||||
import { Utils } from "@nativescript/core";
|
||||
|
||||
declare const com: any;
|
||||
|
||||
export type DiscoveredDevice = {
|
||||
address: string;
|
||||
name: string;
|
||||
role: "left" | "right" | "ring";
|
||||
source: "paired" | "scan";
|
||||
};
|
||||
|
||||
export type DiscoveredAddressSet = {
|
||||
left: string;
|
||||
right: string;
|
||||
ring: string;
|
||||
summary: string;
|
||||
};
|
||||
|
||||
export class DeviceDiscoveryBridge {
|
||||
private readonly discovery: any;
|
||||
|
||||
constructor() {
|
||||
const context = Utils.android.getApplicationContext();
|
||||
if (!context) throw new Error("Android application context unavailable");
|
||||
this.discovery = new com.faceclaw.app.FaceclawDeviceDiscovery(context);
|
||||
}
|
||||
|
||||
async getBondedCandidates(): Promise<DiscoveredDevice[]> {
|
||||
return parseCandidates(String(this.discovery.getBondedCandidatesJson()));
|
||||
}
|
||||
|
||||
async scanCandidates(timeoutMs = 6000): Promise<DiscoveredDevice[]> {
|
||||
return parseCandidates(String(this.discovery.scanCandidatesJson(timeoutMs)));
|
||||
}
|
||||
}
|
||||
|
||||
export function buildAddressSet(candidates: DiscoveredDevice[]): DiscoveredAddressSet {
|
||||
const latestForRole = new Map<DiscoveredDevice["role"], DiscoveredDevice>();
|
||||
for (const candidate of candidates) {
|
||||
latestForRole.set(candidate.role, candidate);
|
||||
}
|
||||
const selected = {
|
||||
left: latestForRole.get("left")?.address ?? "",
|
||||
right: latestForRole.get("right")?.address ?? "",
|
||||
ring: latestForRole.get("ring")?.address ?? "",
|
||||
};
|
||||
const lines = candidates.map((candidate) => `${candidate.role}: ${candidate.name} ${candidate.address}`);
|
||||
return {
|
||||
...selected,
|
||||
summary: lines.length ? lines.join("\n") : "No matching devices found.",
|
||||
};
|
||||
}
|
||||
|
||||
function parseCandidates(json: string): DiscoveredDevice[] {
|
||||
const raw = JSON.parse(json) as Array<Record<string, unknown>>;
|
||||
return raw
|
||||
.map((item) => ({
|
||||
address: String(item.address ?? ""),
|
||||
name: String(item.name ?? ""),
|
||||
role: String(item.role ?? "") as DiscoveredDevice["role"],
|
||||
source: String(item.source ?? "") as DiscoveredDevice["source"],
|
||||
}))
|
||||
.filter((item) => !!item.address && (item.role === "left" || item.role === "right" || item.role === "ring"));
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { Utils } from "@nativescript/core";
|
||||
|
||||
declare const com: any;
|
||||
|
||||
export type EvenAppNotificationState = {
|
||||
notificationAccessEnabled: boolean;
|
||||
evenNotificationActive: boolean;
|
||||
};
|
||||
|
||||
export function readEvenAppNotificationState(): EvenAppNotificationState {
|
||||
if (!global.isAndroid) {
|
||||
return { notificationAccessEnabled: false, evenNotificationActive: false };
|
||||
}
|
||||
const context = Utils.android.getApplicationContext();
|
||||
if (!context) {
|
||||
return { notificationAccessEnabled: false, evenNotificationActive: false };
|
||||
}
|
||||
const detector = com.faceclaw.app.FaceclawEvenAppDetector;
|
||||
return {
|
||||
notificationAccessEnabled: Boolean(detector.isNotificationAccessEnabled(context)),
|
||||
evenNotificationActive: Boolean(detector.isEvenNotificationActive(context)),
|
||||
};
|
||||
}
|
||||
|
||||
export function openEvenAppSettings(): void {
|
||||
if (!global.isAndroid) return;
|
||||
const context = Utils.android.getApplicationContext();
|
||||
if (context) {
|
||||
com.faceclaw.app.FaceclawEvenAppDetector.openEvenAppSettings(context);
|
||||
}
|
||||
}
|
||||
|
||||
export function openNotificationAccessSettings(): void {
|
||||
if (!global.isAndroid) return;
|
||||
const context = Utils.android.getApplicationContext();
|
||||
if (context) {
|
||||
com.faceclaw.app.FaceclawEvenAppDetector.openNotificationAccessSettings(context);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
import { Utils } from "@nativescript/core";
|
||||
|
||||
declare const com: any;
|
||||
|
||||
type NotificationListener = (address: string, characteristicUuid: string, data: Uint8Array) => void;
|
||||
type ConnectionListener = (address: string, connected: boolean) => void;
|
||||
|
||||
function toUint8Array(bytes: ArrayLike<number> | null | undefined): Uint8Array {
|
||||
if (!bytes) return new Uint8Array(0);
|
||||
const out = new Uint8Array(bytes.length);
|
||||
for (let i = 0; i < bytes.length; i++) {
|
||||
out[i] = bytes[i]! & 0xff;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function toJavaByteArray(bytes: Uint8Array): number[] {
|
||||
const out = Array.create("byte", bytes.length) as number[];
|
||||
for (let i = 0; i < bytes.length; i++) {
|
||||
const value = bytes[i]!;
|
||||
out[i] = value > 127 ? value - 256 : value;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function toJavaByteList(frames: Uint8Array[]): any {
|
||||
const list = new java.util.ArrayList();
|
||||
for (const frame of frames) {
|
||||
list.add(toJavaByteArray(frame));
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
export class FaceclawBleBridge {
|
||||
private readonly manager: any;
|
||||
private readonly notificationListeners = new Set<NotificationListener>();
|
||||
private readonly connectionListeners = new Set<ConnectionListener>();
|
||||
private readonly listenerProxy: any;
|
||||
|
||||
constructor() {
|
||||
const context = Utils.android.getApplicationContext();
|
||||
if (!context) throw new Error("Android application context unavailable");
|
||||
|
||||
this.manager = new com.faceclaw.app.FaceclawBleManager(context);
|
||||
this.listenerProxy = new com.faceclaw.app.FaceclawBleListener({
|
||||
onNotification: (address: string, characteristicUuid: string, data: ArrayLike<number>) => {
|
||||
const bytes = toUint8Array(data);
|
||||
for (const listener of this.notificationListeners) {
|
||||
listener(String(address), String(characteristicUuid), bytes);
|
||||
}
|
||||
},
|
||||
onConnectionStateChange: (address: string, connected: boolean) => {
|
||||
for (const listener of this.connectionListeners) {
|
||||
listener(String(address), Boolean(connected));
|
||||
}
|
||||
},
|
||||
});
|
||||
this.manager.setListener(this.listenerProxy);
|
||||
}
|
||||
|
||||
onNotification(listener: NotificationListener): () => void {
|
||||
this.notificationListeners.add(listener);
|
||||
return () => {
|
||||
this.notificationListeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
onConnectionStateChange(listener: ConnectionListener): () => void {
|
||||
this.connectionListeners.add(listener);
|
||||
return () => {
|
||||
this.connectionListeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
async connect(address: string, timeoutMs: number): Promise<void> {
|
||||
if (!this.manager.connect(address, timeoutMs)) {
|
||||
throw new Error(`connect failed: ${address}`);
|
||||
}
|
||||
}
|
||||
|
||||
async requestMtu(address: string, mtu: number, timeoutMs: number): Promise<void> {
|
||||
if (!this.manager.requestMtu(address, mtu, timeoutMs)) {
|
||||
throw new Error(`requestMtu failed: ${address}`);
|
||||
}
|
||||
}
|
||||
|
||||
async requestConnectionPriority(address: string, priority: number): Promise<void> {
|
||||
if (!this.manager.requestConnectionPriority(address, priority)) {
|
||||
throw new Error(`requestConnectionPriority failed: ${address} ${priority}`);
|
||||
}
|
||||
}
|
||||
|
||||
async discoverServices(address: string, timeoutMs: number): Promise<void> {
|
||||
if (!this.manager.discoverServices(address, timeoutMs)) {
|
||||
throw new Error(`discoverServices failed: ${address}`);
|
||||
}
|
||||
}
|
||||
|
||||
async enableNotifications(
|
||||
address: string,
|
||||
characteristicUuid: string,
|
||||
enable: boolean,
|
||||
timeoutMs: number,
|
||||
): Promise<void> {
|
||||
if (!this.manager.enableNotifications(address, characteristicUuid, enable, timeoutMs)) {
|
||||
throw new Error(`enableNotifications failed: ${address} ${characteristicUuid}`);
|
||||
}
|
||||
}
|
||||
|
||||
async writeCharacteristic(
|
||||
address: string,
|
||||
characteristicUuid: string,
|
||||
data: Uint8Array,
|
||||
writeType: number,
|
||||
timeoutMs: number,
|
||||
): Promise<void> {
|
||||
if (!this.manager.write(address, characteristicUuid, toJavaByteArray(data), writeType, timeoutMs)) {
|
||||
throw new Error(`write failed: ${address} ${characteristicUuid}`);
|
||||
}
|
||||
}
|
||||
|
||||
async writeCharacteristicFrames(
|
||||
address: string,
|
||||
characteristicUuid: string,
|
||||
frames: Uint8Array[],
|
||||
writeType: number,
|
||||
timeoutMs: number,
|
||||
allowFallback: boolean,
|
||||
interFrameDelayMs: number,
|
||||
): Promise<void> {
|
||||
if (
|
||||
!this.manager.writeFrames(
|
||||
address,
|
||||
characteristicUuid,
|
||||
toJavaByteList(frames),
|
||||
writeType,
|
||||
timeoutMs,
|
||||
allowFallback,
|
||||
interFrameDelayMs,
|
||||
)
|
||||
) {
|
||||
throw new Error(`write frames failed: ${address} ${characteristicUuid}`);
|
||||
}
|
||||
}
|
||||
|
||||
async queueCharacteristicFrames(
|
||||
address: string,
|
||||
characteristicUuid: string,
|
||||
frames: Uint8Array[],
|
||||
writeType: number,
|
||||
timeoutMs: number,
|
||||
allowFallback: boolean,
|
||||
interFrameDelayMs: number,
|
||||
): Promise<void> {
|
||||
if (
|
||||
!this.manager.queueWriteFrames(
|
||||
address,
|
||||
characteristicUuid,
|
||||
toJavaByteList(frames),
|
||||
writeType,
|
||||
timeoutMs,
|
||||
allowFallback,
|
||||
interFrameDelayMs,
|
||||
)
|
||||
) {
|
||||
throw new Error(`queue write frames failed: ${address} ${characteristicUuid}`);
|
||||
}
|
||||
}
|
||||
|
||||
async disconnect(address: string): Promise<void> {
|
||||
this.manager.disconnect(address);
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
this.manager.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
import { Utils } from "@nativescript/core";
|
||||
|
||||
declare const com: any;
|
||||
|
||||
export type CommunicatorPhase =
|
||||
| "disconnected"
|
||||
| "connecting"
|
||||
| "connected"
|
||||
| "retrying"
|
||||
| "disconnecting";
|
||||
|
||||
export type CommunicatorState = {
|
||||
phase: CommunicatorPhase;
|
||||
status: string;
|
||||
};
|
||||
|
||||
export type HeadsetBatteryState = {
|
||||
battery: number;
|
||||
chargingStatus: number;
|
||||
};
|
||||
|
||||
export type RawInputEvent =
|
||||
| {
|
||||
kind: "list-click";
|
||||
containerName: string;
|
||||
eventType: number;
|
||||
eventSource: number;
|
||||
systemExitReasonCode: number;
|
||||
}
|
||||
| {
|
||||
kind: "text-click";
|
||||
containerName: string;
|
||||
eventType: number;
|
||||
eventSource: number;
|
||||
systemExitReasonCode: number;
|
||||
}
|
||||
| {
|
||||
kind: "sys-event";
|
||||
containerName: string;
|
||||
eventType: number;
|
||||
eventSource: number;
|
||||
systemExitReasonCode: number;
|
||||
};
|
||||
|
||||
function toJavaByteArray(bytes: Uint8Array): number[] {
|
||||
const out = Array.create("byte", bytes.length) as number[];
|
||||
for (let i = 0; i < bytes.length; i++) {
|
||||
const value = bytes[i]!;
|
||||
out[i] = value > 127 ? value - 256 : value;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export class FaceclawCommunicatorBridge {
|
||||
private readonly communicator: any;
|
||||
private readonly listenerProxy: any;
|
||||
private readonly logListeners = new Set<(line: string) => void>();
|
||||
private readonly stateListeners = new Set<(state: CommunicatorState) => void>();
|
||||
private readonly ringListeners = new Set<(event: RawInputEvent) => void>();
|
||||
private readonly batteryListeners = new Set<(state: HeadsetBatteryState) => void>();
|
||||
private readonly evenAppConflictListeners = new Set<(message: string) => void>();
|
||||
|
||||
constructor(addresses: { right: string; left: string; ring?: string }) {
|
||||
const context = Utils.android.getApplicationContext();
|
||||
if (!context) throw new Error("Android application context unavailable");
|
||||
|
||||
this.communicator = new com.faceclaw.app.FaceclawBleCommunicator(
|
||||
context,
|
||||
addresses.right,
|
||||
addresses.left,
|
||||
addresses.ring ?? "",
|
||||
);
|
||||
this.listenerProxy = new com.faceclaw.app.FaceclawBleCommunicatorListener({
|
||||
onLog: (line: string) => {
|
||||
for (const listener of this.logListeners) {
|
||||
listener(String(line));
|
||||
}
|
||||
},
|
||||
onStateChange: (phase: string, status: string) => {
|
||||
const state = {
|
||||
phase: String(phase) as CommunicatorPhase,
|
||||
status: String(status),
|
||||
};
|
||||
for (const listener of this.stateListeners) {
|
||||
listener(state);
|
||||
}
|
||||
},
|
||||
onRingEvent: (
|
||||
kind: string,
|
||||
containerName: string,
|
||||
eventType: number,
|
||||
eventSource: number,
|
||||
systemExitReasonCode: number,
|
||||
) => {
|
||||
const event = {
|
||||
kind: String(kind) as RawInputEvent["kind"],
|
||||
containerName: String(containerName),
|
||||
eventType: Number(eventType),
|
||||
eventSource: Number(eventSource),
|
||||
systemExitReasonCode: Number(systemExitReasonCode),
|
||||
};
|
||||
for (const listener of this.ringListeners) {
|
||||
listener(event);
|
||||
}
|
||||
},
|
||||
onBatteryState: (headsetBattery: number, headsetCharging: number) => {
|
||||
const state = {
|
||||
battery: Number(headsetBattery),
|
||||
chargingStatus: Number(headsetCharging),
|
||||
};
|
||||
for (const listener of this.batteryListeners) {
|
||||
listener(state);
|
||||
}
|
||||
},
|
||||
onEvenAppConflict: (message: string) => {
|
||||
for (const listener of this.evenAppConflictListeners) {
|
||||
listener(String(message));
|
||||
}
|
||||
},
|
||||
});
|
||||
this.communicator.setListener(this.listenerProxy);
|
||||
}
|
||||
|
||||
onLog(listener: (line: string) => void): () => void {
|
||||
this.logListeners.add(listener);
|
||||
return () => this.logListeners.delete(listener);
|
||||
}
|
||||
|
||||
onStateChange(listener: (state: CommunicatorState) => void): () => void {
|
||||
this.stateListeners.add(listener);
|
||||
return () => this.stateListeners.delete(listener);
|
||||
}
|
||||
|
||||
onRingEvent(listener: (event: RawInputEvent) => void): () => void {
|
||||
this.ringListeners.add(listener);
|
||||
return () => this.ringListeners.delete(listener);
|
||||
}
|
||||
|
||||
onBatteryState(listener: (state: HeadsetBatteryState) => void): () => void {
|
||||
this.batteryListeners.add(listener);
|
||||
return () => this.batteryListeners.delete(listener);
|
||||
}
|
||||
|
||||
onEvenAppConflict(listener: (message: string) => void): () => void {
|
||||
this.evenAppConflictListeners.add(listener);
|
||||
return () => this.evenAppConflictListeners.delete(listener);
|
||||
}
|
||||
|
||||
async start(): Promise<void> {
|
||||
this.communicator.start();
|
||||
}
|
||||
|
||||
async submitDashboardImage(tileBmps: Uint8Array[], fingerprint: string): Promise<void> {
|
||||
if (tileBmps.length !== 4) {
|
||||
throw new Error(`expected 4 dashboard tiles, got ${tileBmps.length}`);
|
||||
}
|
||||
this.communicator.submitDashboardImage4(
|
||||
toJavaByteArray(tileBmps[0]!),
|
||||
toJavaByteArray(tileBmps[1]!),
|
||||
toJavaByteArray(tileBmps[2]!),
|
||||
toJavaByteArray(tileBmps[3]!),
|
||||
fingerprint,
|
||||
);
|
||||
}
|
||||
|
||||
async disconnect(): Promise<void> {
|
||||
this.communicator.disconnect();
|
||||
}
|
||||
|
||||
async sendShutdown(exitMode = 0): Promise<boolean> {
|
||||
return Boolean(this.communicator.sendShutdown(exitMode));
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
this.communicator.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { Utils } from "@nativescript/core";
|
||||
|
||||
declare const com: any;
|
||||
|
||||
function getContext(): android.content.Context {
|
||||
const context = Utils.android.getApplicationContext();
|
||||
if (!context) throw new Error("Android application context unavailable");
|
||||
return context;
|
||||
}
|
||||
|
||||
function createIntent(action: string, text?: string): android.content.Intent {
|
||||
const context = getContext();
|
||||
const intent = new android.content.Intent(context, com.faceclaw.app.FaceclawForegroundService.class);
|
||||
intent.setAction(action);
|
||||
if (text) {
|
||||
intent.putExtra(com.faceclaw.app.FaceclawForegroundService.EXTRA_TEXT, text);
|
||||
}
|
||||
return intent;
|
||||
}
|
||||
|
||||
export function startForegroundNotification(text: string): void {
|
||||
if (!global.isAndroid) return;
|
||||
const context = getContext();
|
||||
const intent = createIntent(com.faceclaw.app.FaceclawForegroundService.ACTION_START, text);
|
||||
androidx.core.content.ContextCompat.startForegroundService(context, intent);
|
||||
}
|
||||
|
||||
export function updateForegroundNotification(text: string): void {
|
||||
if (!global.isAndroid) return;
|
||||
const context = getContext();
|
||||
context.startService(createIntent(com.faceclaw.app.FaceclawForegroundService.ACTION_UPDATE, text));
|
||||
}
|
||||
|
||||
export function stopForegroundNotification(): void {
|
||||
if (!global.isAndroid) return;
|
||||
const context = getContext();
|
||||
context.startService(createIntent(com.faceclaw.app.FaceclawForegroundService.ACTION_STOP));
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { ImageSource, Screen, Utils } from "@nativescript/core";
|
||||
|
||||
import { type GrayImage } from "../graphics/image";
|
||||
|
||||
const PREVIEW_BRIGHTEN_GAMMA = 0.7;
|
||||
|
||||
export function grayImageToPreviewSource(image: GrayImage): ImageSource | null {
|
||||
if (!global.isAndroid) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const colors = Array.create("int", image.width * image.height) as number[];
|
||||
for (let i = 0; i < image.pixels.length; i++) {
|
||||
const gray = brightenForPreview(image.pixels[i] ?? 0);
|
||||
colors[i] = (255 << 24) | (gray << 16) | (gray << 8) | gray;
|
||||
}
|
||||
|
||||
const bitmap = android.graphics.Bitmap.createBitmap(
|
||||
colors,
|
||||
image.width,
|
||||
image.height,
|
||||
android.graphics.Bitmap.Config.ARGB_8888,
|
||||
);
|
||||
const targetWidth = Math.max(1, Math.round(Utils.layout.toDevicePixels(Screen.mainScreen.widthDIPs)));
|
||||
const targetHeight = Math.max(1, Math.round((targetWidth * image.height) / image.width));
|
||||
const scaledBitmap =
|
||||
bitmap.getWidth() === targetWidth && bitmap.getHeight() === targetHeight
|
||||
? bitmap
|
||||
: android.graphics.Bitmap.createScaledBitmap(bitmap, targetWidth, targetHeight, false);
|
||||
return new ImageSource(scaledBitmap);
|
||||
}
|
||||
|
||||
function brightenForPreview(gray: number): number {
|
||||
const normalized = Math.max(0, Math.min(255, gray)) / 255;
|
||||
return Math.max(0, Math.min(255, Math.round(255 * Math.pow(normalized, PREVIEW_BRIGHTEN_GAMMA))));
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
import { Utils } from "@nativescript/core";
|
||||
|
||||
declare const com: any;
|
||||
|
||||
export type MediaPlaybackState =
|
||||
| "notification-access-required"
|
||||
| "idle"
|
||||
| "playing"
|
||||
| "paused"
|
||||
| "buffering"
|
||||
| "stopped"
|
||||
| "unknown";
|
||||
|
||||
export type MediaControllerState = {
|
||||
available: boolean;
|
||||
accessEnabled: boolean;
|
||||
packageName: string;
|
||||
playbackState: MediaPlaybackState;
|
||||
title: string;
|
||||
artist: string;
|
||||
album: string;
|
||||
status: string;
|
||||
canPlayPause: boolean;
|
||||
canSkipNext: boolean;
|
||||
canSkipPrevious: boolean;
|
||||
};
|
||||
|
||||
const DEFAULT_MEDIA_STATE: MediaControllerState = {
|
||||
available: false,
|
||||
accessEnabled: false,
|
||||
packageName: "",
|
||||
playbackState: "idle",
|
||||
title: "",
|
||||
artist: "",
|
||||
album: "",
|
||||
status: "Media controller unavailable.",
|
||||
canPlayPause: false,
|
||||
canSkipNext: false,
|
||||
canSkipPrevious: false,
|
||||
};
|
||||
|
||||
export class FaceclawMediaControllerBridge {
|
||||
private readonly stateListeners = new Set<(state: MediaControllerState) => void>();
|
||||
private controller: any | null = null;
|
||||
private listenerProxy: any | null = null;
|
||||
private state: MediaControllerState = { ...DEFAULT_MEDIA_STATE };
|
||||
private started = false;
|
||||
|
||||
onStateChange(listener: (state: MediaControllerState) => void): () => void {
|
||||
this.stateListeners.add(listener);
|
||||
listener(this.snapshot());
|
||||
return () => this.stateListeners.delete(listener);
|
||||
}
|
||||
|
||||
snapshot(): MediaControllerState {
|
||||
return { ...this.state };
|
||||
}
|
||||
|
||||
async start(): Promise<void> {
|
||||
if (this.started || !global.isAndroid) return;
|
||||
this.ensureController();
|
||||
this.started = true;
|
||||
this.controller?.start();
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
if (!this.started || !global.isAndroid) return;
|
||||
this.started = false;
|
||||
this.controller?.stop();
|
||||
}
|
||||
|
||||
async playPause(): Promise<void> {
|
||||
this.ensureController();
|
||||
this.controller?.playPause();
|
||||
}
|
||||
|
||||
async skipNext(): Promise<void> {
|
||||
this.ensureController();
|
||||
this.controller?.skipNext();
|
||||
}
|
||||
|
||||
async skipPrevious(): Promise<void> {
|
||||
this.ensureController();
|
||||
this.controller?.skipPrevious();
|
||||
}
|
||||
|
||||
openNotificationAccessSettings(): void {
|
||||
this.ensureController();
|
||||
this.controller?.openNotificationAccessSettings();
|
||||
}
|
||||
|
||||
private ensureController(): void {
|
||||
if (!global.isAndroid || this.controller) return;
|
||||
const context = Utils.android.getApplicationContext();
|
||||
if (!context) {
|
||||
throw new Error("Android application context unavailable");
|
||||
}
|
||||
this.controller = new com.faceclaw.app.FaceclawMediaController(context);
|
||||
this.listenerProxy = new com.faceclaw.app.FaceclawMediaControllerListener({
|
||||
onStateChange: (
|
||||
playbackState: string,
|
||||
packageName: string,
|
||||
title: string,
|
||||
artist: string,
|
||||
album: string,
|
||||
canPlayPause: boolean,
|
||||
canSkipNext: boolean,
|
||||
canSkipPrevious: boolean,
|
||||
accessEnabled: boolean,
|
||||
status: string,
|
||||
) => {
|
||||
this.state = {
|
||||
available: Boolean(title || artist || album || packageName) || String(playbackState) !== "idle",
|
||||
accessEnabled: Boolean(accessEnabled),
|
||||
packageName: String(packageName),
|
||||
playbackState: normalizePlaybackState(String(playbackState)),
|
||||
title: String(title),
|
||||
artist: String(artist),
|
||||
album: String(album),
|
||||
status: String(status),
|
||||
canPlayPause: Boolean(canPlayPause),
|
||||
canSkipNext: Boolean(canSkipNext),
|
||||
canSkipPrevious: Boolean(canSkipPrevious),
|
||||
};
|
||||
for (const listener of this.stateListeners) {
|
||||
listener(this.snapshot());
|
||||
}
|
||||
},
|
||||
});
|
||||
this.controller.setListener(this.listenerProxy);
|
||||
}
|
||||
}
|
||||
|
||||
function normalizePlaybackState(value: string): MediaPlaybackState {
|
||||
switch (value) {
|
||||
case "notification-access-required":
|
||||
case "idle":
|
||||
case "playing":
|
||||
case "paused":
|
||||
case "buffering":
|
||||
case "stopped":
|
||||
return value;
|
||||
default:
|
||||
return "unknown";
|
||||
}
|
||||
}
|
||||
|
||||
export const mediaControllerBridge = new FaceclawMediaControllerBridge();
|
||||
@@ -0,0 +1,411 @@
|
||||
import { loadNightscoutSettings } from "../ui/dashboard-settings";
|
||||
|
||||
export type NightscoutPoint = {
|
||||
timestampMs: number;
|
||||
sgv: number;
|
||||
};
|
||||
|
||||
export type NightscoutCarbEvent = {
|
||||
timestampMs: number;
|
||||
carbs: number;
|
||||
};
|
||||
|
||||
export type NightscoutBolusEvent = {
|
||||
timestampMs: number;
|
||||
insulin: number;
|
||||
};
|
||||
|
||||
export type NightscoutBasalEvent = {
|
||||
timestampMs: number;
|
||||
durationMinutes: number;
|
||||
rate: number;
|
||||
};
|
||||
|
||||
export type NightscoutState = {
|
||||
available: boolean;
|
||||
status: string;
|
||||
units: string;
|
||||
history: NightscoutPoint[];
|
||||
latest: NightscoutPoint | null;
|
||||
delta: number | null;
|
||||
direction: string;
|
||||
iob: number | null;
|
||||
cob: number | null;
|
||||
cageTimestampMs: number | null;
|
||||
pumpStatus: string;
|
||||
openapsStatusShort: string;
|
||||
carbs: NightscoutCarbEvent[];
|
||||
boluses: NightscoutBolusEvent[];
|
||||
basal: NightscoutBasalEvent[];
|
||||
lastUpdatedMs: number | null;
|
||||
configurationMissing: boolean;
|
||||
};
|
||||
|
||||
type NightscoutEntryResponse = {
|
||||
sgv?: unknown;
|
||||
date?: unknown;
|
||||
direction?: unknown;
|
||||
};
|
||||
|
||||
type NightscoutDeviceStatusResponse = {
|
||||
openaps?: {
|
||||
iob?: {
|
||||
iob?: unknown;
|
||||
timestamp?: unknown;
|
||||
mills?: unknown;
|
||||
};
|
||||
suggested?: {
|
||||
COB?: unknown;
|
||||
timestamp?: unknown;
|
||||
mills?: unknown;
|
||||
};
|
||||
enacted?: {
|
||||
COB?: unknown;
|
||||
timestamp?: unknown;
|
||||
mills?: unknown;
|
||||
};
|
||||
};
|
||||
pump?: {
|
||||
clock?: unknown;
|
||||
reservoir?: unknown;
|
||||
battery?: {
|
||||
voltage?: unknown;
|
||||
status?: unknown;
|
||||
};
|
||||
status?: {
|
||||
status?: unknown;
|
||||
bolusing?: unknown;
|
||||
suspended?: unknown;
|
||||
timestamp?: unknown;
|
||||
};
|
||||
};
|
||||
created_at?: unknown;
|
||||
};
|
||||
|
||||
type NightscoutStatusResponse = {
|
||||
settings?: {
|
||||
units?: unknown;
|
||||
};
|
||||
};
|
||||
|
||||
type NightscoutTreatmentResponse = {
|
||||
created_at?: unknown;
|
||||
timestamp?: unknown;
|
||||
eventType?: unknown;
|
||||
carbs?: unknown;
|
||||
insulin?: unknown;
|
||||
absolute?: unknown;
|
||||
rate?: unknown;
|
||||
duration?: unknown;
|
||||
};
|
||||
|
||||
const NIGHTSCOUT_REFRESH_MS = 60_000;
|
||||
const NIGHTSCOUT_HISTORY_COUNT = 30;
|
||||
const NIGHTSCOUT_GRAPH_WINDOW_MS = 2 * 60 * 60 * 1000;
|
||||
const NIGHTSCOUT_TREATMENT_LOOKBACK_MS = 3 * 60 * 60 * 1000;
|
||||
|
||||
const DEFAULT_NIGHTSCOUT_STATE: NightscoutState = {
|
||||
available: false,
|
||||
status: "Nightscout unavailable.",
|
||||
units: "mg/dL",
|
||||
history: [],
|
||||
latest: null,
|
||||
delta: null,
|
||||
direction: "",
|
||||
iob: null,
|
||||
cob: null,
|
||||
cageTimestampMs: null,
|
||||
pumpStatus: "",
|
||||
openapsStatusShort: "--",
|
||||
carbs: [],
|
||||
boluses: [],
|
||||
basal: [],
|
||||
lastUpdatedMs: null,
|
||||
configurationMissing: true,
|
||||
};
|
||||
|
||||
export class NightscoutBridge {
|
||||
private readonly listeners = new Set<(state: NightscoutState) => void>();
|
||||
private state: NightscoutState = { ...DEFAULT_NIGHTSCOUT_STATE };
|
||||
private refreshHandle: ReturnType<typeof setInterval> | null = null;
|
||||
private refreshInFlight: Promise<void> | null = null;
|
||||
|
||||
onStateChange(listener: (state: NightscoutState) => void): () => void {
|
||||
this.listeners.add(listener);
|
||||
listener(this.snapshot());
|
||||
return () => this.listeners.delete(listener);
|
||||
}
|
||||
|
||||
snapshot(): NightscoutState {
|
||||
return {
|
||||
...this.state,
|
||||
history: this.state.history.map((point) => ({ ...point })),
|
||||
latest: this.state.latest ? { ...this.state.latest } : null,
|
||||
carbs: this.state.carbs.map((event) => ({ ...event })),
|
||||
boluses: this.state.boluses.map((event) => ({ ...event })),
|
||||
basal: this.state.basal.map((event) => ({ ...event })),
|
||||
};
|
||||
}
|
||||
|
||||
async start(): Promise<void> {
|
||||
if (this.refreshHandle) {
|
||||
await this.refreshNow();
|
||||
return;
|
||||
}
|
||||
await this.refreshNow();
|
||||
this.refreshHandle = setInterval(() => {
|
||||
void this.refreshNow();
|
||||
}, NIGHTSCOUT_REFRESH_MS);
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
if (this.refreshHandle) {
|
||||
clearInterval(this.refreshHandle);
|
||||
this.refreshHandle = null;
|
||||
}
|
||||
await this.refreshInFlight?.catch(() => {});
|
||||
}
|
||||
|
||||
async refreshNow(): Promise<void> {
|
||||
if (this.refreshInFlight) {
|
||||
return this.refreshInFlight;
|
||||
}
|
||||
this.refreshInFlight = this.refresh();
|
||||
try {
|
||||
await this.refreshInFlight;
|
||||
} finally {
|
||||
this.refreshInFlight = null;
|
||||
}
|
||||
}
|
||||
|
||||
private async refresh(): Promise<void> {
|
||||
try {
|
||||
const nowMs = Date.now();
|
||||
const settings = loadNightscoutSettings();
|
||||
if (!settings.siteUrl || !settings.apiToken) {
|
||||
this.state = {
|
||||
...DEFAULT_NIGHTSCOUT_STATE,
|
||||
status: "Configure Nightscout site URL and API token.",
|
||||
configurationMissing: true,
|
||||
};
|
||||
this.emit();
|
||||
return;
|
||||
}
|
||||
const treatmentStartIso = new Date(nowMs - NIGHTSCOUT_TREATMENT_LOOKBACK_MS).toISOString();
|
||||
const tokenQuery = `token=${encodeURIComponent(settings.apiToken)}`;
|
||||
const [entries, deviceStatus, status, treatments, siteChanges] = await Promise.all([
|
||||
fetchJson<NightscoutEntryResponse[]>(
|
||||
`${settings.siteUrl}/api/v1/entries.json?count=${NIGHTSCOUT_HISTORY_COUNT}&${tokenQuery}`,
|
||||
),
|
||||
fetchJson<NightscoutDeviceStatusResponse[]>(
|
||||
`${settings.siteUrl}/api/v1/devicestatus.json?count=1&${tokenQuery}`,
|
||||
),
|
||||
fetchJson<NightscoutStatusResponse>(
|
||||
`${settings.siteUrl}/api/v1/status.json?${tokenQuery}`,
|
||||
),
|
||||
fetchJson<NightscoutTreatmentResponse[]>(
|
||||
`${settings.siteUrl}/api/v1/treatments.json?find%5Bcreated_at%5D%5B%24gte%5D=${encodeURIComponent(treatmentStartIso)}&${tokenQuery}`,
|
||||
),
|
||||
fetchJson<NightscoutTreatmentResponse[]>(
|
||||
`${settings.siteUrl}/api/v1/treatments.json?find%5BeventType%5D=Site%20Change&count=1&${tokenQuery}`,
|
||||
),
|
||||
]);
|
||||
|
||||
const history = (entries ?? [])
|
||||
.map((entry) => ({
|
||||
timestampMs: Number(entry.date ?? 0),
|
||||
sgv: Number(entry.sgv ?? NaN),
|
||||
direction: typeof entry.direction === "string" ? entry.direction : "",
|
||||
}))
|
||||
.filter((entry) => Number.isFinite(entry.timestampMs) && Number.isFinite(entry.sgv))
|
||||
.sort((a, b) => a.timestampMs - b.timestampMs);
|
||||
|
||||
const latest = history.at(-1) ?? null;
|
||||
const previous = history.length >= 2 ? history[history.length - 2]! : null;
|
||||
const latestDirection = latest ? (entries?.[0]?.direction as string | undefined) ?? "" : "";
|
||||
const latestDeviceStatus = deviceStatus?.[0];
|
||||
const iob = Number((latestDeviceStatus?.openaps?.iob?.iob as number | undefined) ?? NaN);
|
||||
const cob = firstFiniteNumber(
|
||||
latestDeviceStatus?.openaps?.suggested?.COB,
|
||||
latestDeviceStatus?.openaps?.enacted?.COB,
|
||||
);
|
||||
const loopTimestampMs = Math.max(
|
||||
parseTimestampMs(latestDeviceStatus?.openaps?.suggested?.mills ?? latestDeviceStatus?.openaps?.suggested?.timestamp),
|
||||
parseTimestampMs(latestDeviceStatus?.openaps?.enacted?.mills ?? latestDeviceStatus?.openaps?.enacted?.timestamp),
|
||||
parseTimestampMs(latestDeviceStatus?.openaps?.iob?.mills ?? latestDeviceStatus?.openaps?.iob?.timestamp),
|
||||
);
|
||||
const pumpStatus = formatPumpStatus(latestDeviceStatus, nowMs);
|
||||
const parsedTreatments = parseTreatments(treatments ?? [], nowMs);
|
||||
const latestSiteChange = parseTimestampMs(siteChanges?.[0]?.created_at ?? siteChanges?.[0]?.timestamp);
|
||||
|
||||
this.state = {
|
||||
available: latest !== null,
|
||||
status: latest ? "Nightscout updated." : "No Nightscout glucose entries.",
|
||||
units: typeof status?.settings?.units === "string" ? status.settings.units : "mg/dL",
|
||||
history: history.map(({ timestampMs, sgv }) => ({ timestampMs, sgv })),
|
||||
latest: latest ? { timestampMs: latest.timestampMs, sgv: latest.sgv } : null,
|
||||
delta: latest && previous ? latest.sgv - previous.sgv : null,
|
||||
direction: latestDirection,
|
||||
iob: Number.isFinite(iob) ? iob : null,
|
||||
cob,
|
||||
cageTimestampMs: latestSiteChange > 0 ? latestSiteChange : null,
|
||||
pumpStatus,
|
||||
openapsStatusShort: loopTimestampMs > 0 ? formatElapsedShort(nowMs - loopTimestampMs) : "--",
|
||||
carbs: parsedTreatments.carbs,
|
||||
boluses: parsedTreatments.boluses,
|
||||
basal: parsedTreatments.basal,
|
||||
lastUpdatedMs: nowMs,
|
||||
configurationMissing: false,
|
||||
};
|
||||
this.emit();
|
||||
} catch (error) {
|
||||
const message = (error as Error)?.message ?? String(error);
|
||||
this.state = {
|
||||
...this.state,
|
||||
available: this.state.latest !== null,
|
||||
status: `Nightscout refresh failed: ${message}`,
|
||||
};
|
||||
this.emit();
|
||||
}
|
||||
}
|
||||
|
||||
private emit(): void {
|
||||
const snapshot = this.snapshot();
|
||||
for (const listener of this.listeners) {
|
||||
listener(snapshot);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchJson<T>(url: string): Promise<T> {
|
||||
const response = await fetch(url);
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}`);
|
||||
}
|
||||
return (await response.json()) as T;
|
||||
}
|
||||
|
||||
function parseTreatments(treatments: NightscoutTreatmentResponse[], nowMs: number): {
|
||||
carbs: NightscoutCarbEvent[];
|
||||
boluses: NightscoutBolusEvent[];
|
||||
basal: NightscoutBasalEvent[];
|
||||
} {
|
||||
const windowStartMs = nowMs - NIGHTSCOUT_TREATMENT_LOOKBACK_MS;
|
||||
const carbs: NightscoutCarbEvent[] = [];
|
||||
const boluses: NightscoutBolusEvent[] = [];
|
||||
const basal: NightscoutBasalEvent[] = [];
|
||||
|
||||
for (const treatment of treatments) {
|
||||
const timestampMs = parseTimestampMs(treatment.created_at ?? treatment.timestamp);
|
||||
if (timestampMs <= 0 || timestampMs < windowStartMs || timestampMs > nowMs) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const carbValue = firstFiniteNumber(treatment.carbs);
|
||||
if (carbValue !== null && carbValue > 0) {
|
||||
carbs.push({ timestampMs, carbs: carbValue });
|
||||
}
|
||||
|
||||
const insulinValue = firstFiniteNumber(treatment.insulin);
|
||||
if (insulinValue !== null && insulinValue > 0) {
|
||||
boluses.push({ timestampMs, insulin: insulinValue });
|
||||
}
|
||||
|
||||
const eventType = typeof treatment.eventType === "string" ? treatment.eventType : "";
|
||||
const basalRate = firstFiniteNumber(treatment.absolute, treatment.rate);
|
||||
const durationMinutes = firstFiniteNumber(treatment.duration);
|
||||
if ((eventType === "Temp Basal" || basalRate !== null) && basalRate !== null && durationMinutes !== null && durationMinutes > 0) {
|
||||
basal.push({ timestampMs, rate: basalRate, durationMinutes });
|
||||
}
|
||||
}
|
||||
|
||||
carbs.sort((a, b) => a.timestampMs - b.timestampMs);
|
||||
boluses.sort((a, b) => a.timestampMs - b.timestampMs);
|
||||
basal.sort((a, b) => a.timestampMs - b.timestampMs);
|
||||
return { carbs, boluses, basal };
|
||||
}
|
||||
|
||||
function parseTimestampMs(value: unknown): number {
|
||||
if (typeof value === "number" && Number.isFinite(value)) {
|
||||
return value;
|
||||
}
|
||||
if (typeof value === "string") {
|
||||
const asNumber = Number(value);
|
||||
if (Number.isFinite(asNumber) && asNumber > 0) {
|
||||
return asNumber;
|
||||
}
|
||||
const parsed = Date.parse(value);
|
||||
if (Number.isFinite(parsed)) {
|
||||
return parsed;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
function firstFiniteNumber(...values: unknown[]): number | null {
|
||||
for (const value of values) {
|
||||
const numeric = Number(value);
|
||||
if (Number.isFinite(numeric)) {
|
||||
return numeric;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function formatPumpStatus(status: NightscoutDeviceStatusResponse | undefined, nowMs: number): string {
|
||||
if (!status?.pump) {
|
||||
return "--";
|
||||
}
|
||||
const reservoir = firstFiniteNumber(status.pump.reservoir);
|
||||
const voltage = firstFiniteNumber(status.pump.battery?.voltage);
|
||||
const commTimestampMs = Math.max(
|
||||
parseTimestampMs(status.pump.status?.timestamp),
|
||||
parseTimestampMs(status.pump.clock),
|
||||
parseTimestampMs(status.created_at),
|
||||
);
|
||||
const stateLabel = summarizePumpState(status);
|
||||
const parts: string[] = [];
|
||||
if (reservoir !== null) {
|
||||
parts.push(`${Math.round(reservoir)}U`);
|
||||
}
|
||||
if (voltage !== null) {
|
||||
parts.push(`${voltage.toFixed(2)}v`);
|
||||
}
|
||||
if (commTimestampMs > 0) {
|
||||
parts.push(`${formatElapsedShort(nowMs - commTimestampMs)} ago`);
|
||||
}
|
||||
if (stateLabel) {
|
||||
parts.push(stateLabel);
|
||||
}
|
||||
return parts.join(" ") || "--";
|
||||
}
|
||||
|
||||
function summarizePumpState(status: NightscoutDeviceStatusResponse): string {
|
||||
if (status.pump?.status?.suspended === true) {
|
||||
return "suspended";
|
||||
}
|
||||
if (status.pump?.status?.bolusing === true) {
|
||||
return "bolusing";
|
||||
}
|
||||
if (typeof status.pump?.status?.status === "string" && status.pump.status.status.trim()) {
|
||||
return status.pump.status.status.trim();
|
||||
}
|
||||
if (typeof status.pump?.battery?.status === "string" && status.pump.battery.status.trim()) {
|
||||
return status.pump.battery.status.trim();
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
function formatElapsedShort(elapsedMs: number): string {
|
||||
const minutes = Math.max(0, Math.round(elapsedMs / 60_000));
|
||||
if (minutes < 60) {
|
||||
return `${minutes}m`;
|
||||
}
|
||||
const hours = Math.round(minutes / 60);
|
||||
if (hours < 48) {
|
||||
return `${hours}h`;
|
||||
}
|
||||
return `${Math.round(hours / 24)}d`;
|
||||
}
|
||||
|
||||
export const nightscoutBridge = new NightscoutBridge();
|
||||
@@ -0,0 +1,52 @@
|
||||
import { GrayImage } from "../graphics/image";
|
||||
|
||||
declare const com: any;
|
||||
|
||||
const ICON_SIZE = 24;
|
||||
const ICON_CACHE_MS = 5_000;
|
||||
|
||||
let cachedIcons: GrayImage[] = [];
|
||||
let cachedAtMs = 0;
|
||||
|
||||
export function readActiveNotificationIcons(maxIcons: number): GrayImage[] {
|
||||
if (!global.isAndroid || maxIcons <= 0) return [];
|
||||
|
||||
const now = Date.now();
|
||||
if (now - cachedAtMs < ICON_CACHE_MS) {
|
||||
return cachedIcons.map(cloneGrayImage);
|
||||
}
|
||||
|
||||
const bytes = toUint8Array(
|
||||
com.faceclaw.app.FaceclawMediaNotificationListenerService.getActiveNotificationIconGrays(
|
||||
ICON_SIZE,
|
||||
maxIcons,
|
||||
),
|
||||
);
|
||||
const iconByteLength = ICON_SIZE * ICON_SIZE;
|
||||
const iconCount = Math.floor(bytes.length / iconByteLength);
|
||||
const icons: GrayImage[] = [];
|
||||
for (let index = 0; index < iconCount; index++) {
|
||||
const icon = new GrayImage(ICON_SIZE, ICON_SIZE, 0);
|
||||
icon.pixels.set(bytes.subarray(index * iconByteLength, (index + 1) * iconByteLength));
|
||||
icons.push(icon);
|
||||
}
|
||||
|
||||
cachedIcons = icons;
|
||||
cachedAtMs = now;
|
||||
return icons.map(cloneGrayImage);
|
||||
}
|
||||
|
||||
function toUint8Array(bytes: ArrayLike<number> | null | undefined): Uint8Array {
|
||||
if (!bytes) return new Uint8Array(0);
|
||||
const out = new Uint8Array(bytes.length);
|
||||
for (let i = 0; i < bytes.length; i++) {
|
||||
out[i] = bytes[i]! & 0xff;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function cloneGrayImage(image: GrayImage): GrayImage {
|
||||
const clone = new GrayImage(image.width, image.height, 0);
|
||||
clone.pixels.set(image.pixels);
|
||||
return clone;
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { Utils } from "@nativescript/core";
|
||||
|
||||
declare const android: any;
|
||||
|
||||
export type PhoneBatteryState = {
|
||||
battery: number | null;
|
||||
charging: boolean | null;
|
||||
};
|
||||
|
||||
export function readPhoneBatteryState(): PhoneBatteryState {
|
||||
if (!global.isAndroid) {
|
||||
return { battery: null, charging: null };
|
||||
}
|
||||
const context = Utils.android.getApplicationContext();
|
||||
if (!context) {
|
||||
return { battery: null, charging: null };
|
||||
}
|
||||
|
||||
const filter = new android.content.IntentFilter(android.content.Intent.ACTION_BATTERY_CHANGED);
|
||||
const intent = context.registerReceiver(null, filter);
|
||||
if (!intent) {
|
||||
return { battery: null, charging: null };
|
||||
}
|
||||
|
||||
const level = Number(intent.getIntExtra(android.os.BatteryManager.EXTRA_LEVEL, -1));
|
||||
const scale = Number(intent.getIntExtra(android.os.BatteryManager.EXTRA_SCALE, -1));
|
||||
const status = Number(intent.getIntExtra(android.os.BatteryManager.EXTRA_STATUS, -1));
|
||||
const charging =
|
||||
status === android.os.BatteryManager.BATTERY_STATUS_CHARGING ||
|
||||
status === android.os.BatteryManager.BATTERY_STATUS_FULL;
|
||||
|
||||
return {
|
||||
battery: level >= 0 && scale > 0 ? Math.round((level * 100) / scale) : null,
|
||||
charging,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user