-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathjune-client.ts
More file actions
More file actions
Latest commit
426 lines (398 loc) · 14.3 KB
/
Copy pathjune-client.ts
File metadata and controls
426 lines (398 loc) · 14.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
import { EventEmitter } from 'events';
import WebSocket from 'ws';
import {
JUNE_APP_VERSION,
JUNE_PLATFORM_VERSION,
JUNE_USER_AGENT,
} from './settings';
import {
fahrenheitToMilliC,
MC_CANCEL,
MC_KEEPALIVE,
MC_PREHEAT,
milliCToCelsius,
normalizeOvenConfig,
parseJuneTokenResponse,
NormalizedJuneConfig,
JuneOvenConfig,
signedFrame,
} from './protocol';
import { fetchJsonWithTimeout, isRetryableHttpStatus, JuneHttpError } from './http';
import { parseCameraFrame, parseProbeTelemetry, type JuneSnapshot } from './protocol-decode';
export interface JuneTelemetry {
currentTempC?: number;
targetTempC?: number;
active?: boolean;
ready?: boolean;
done?: boolean;
connectionState?: string;
probeC?: number;
probePresent?: boolean;
}
export { parseCameraFrame, parseProbeTelemetry } from './protocol-decode';
export type { JuneSnapshot } from './protocol-decode';
// A 10011 frame's pre-signed URL is valid ~300 s. Treat a cached snapshot as
// gone once it is close to expiry so idle live-view taps fail fast (with the
// placeholder) instead of spawning ffmpeg against a URL that now 403s.
const SNAPSHOT_TTL_MS = 240_000;
const RETRY_BASE_MS = 1_000;
const RETRY_MAX_MS = 120_000;
export function calculateRetryDelay(attempt: number, random = Math.random): number {
const exponential = Math.min(RETRY_MAX_MS, RETRY_BASE_MS * 2 ** Math.max(0, attempt - 1));
return Math.min(RETRY_MAX_MS, Math.round(exponential * (0.5 + random())));
}
export interface JuneClientEvents {
telemetry: [JuneTelemetry];
token: [{ accessToken: string; refreshToken: string }];
warning: [string];
}
interface PendingCommand {
resolve: (status: string | null) => void;
timer: NodeJS.Timeout;
}
export declare interface JuneClient {
on<U extends keyof JuneClientEvents>(event: U, listener: (...args: JuneClientEvents[U]) => void): this;
emit<U extends keyof JuneClientEvents>(event: U, ...args: JuneClientEvents[U]): boolean;
}
export class JuneClient extends EventEmitter {
public readonly config: NormalizedJuneConfig;
private ws?: WebSocket;
private keepalive?: NodeJS.Timeout;
private reconnect?: NodeJS.Timeout;
private startupRetry?: NodeJS.Timeout;
private reconnectAttempt = 0;
private startupAttempt = 0;
private statusPoll?: NodeJS.Timeout;
private connectPromise?: Promise<void>;
private refreshPromise?: Promise<void>;
private statusPromise?: Promise<void>;
private stopped = false;
private readonly pending = new Map<number, PendingCommand>();
private lastActive = false;
private lastCancelled = false;
private lastTargetTempC?: number;
private snapshot?: JuneSnapshot;
private snapshotAt = 0;
public get latestSnapshot(): JuneSnapshot | undefined {
if (this.snapshot && Date.now() - this.snapshotAt > SNAPSHOT_TTL_MS) {
return undefined;
}
return this.snapshot;
}
constructor(config: JuneOvenConfig, private readonly log: Pick<Console, 'debug' | 'warn' | 'error'> = console) {
super();
this.config = normalizeOvenConfig(config);
}
public async start(): Promise<void> {
this.stopped = false;
clearTimeout(this.startupRetry);
this.startupRetry = undefined;
try {
await this.refreshToken();
} catch (error) {
if (!this.stopped && this.isRetryableStartupError(error)) {
this.scheduleStartupRetry();
}
throw error;
}
this.startupAttempt = 0;
await this.fetchStatus().catch(error => this.warn(`Initial status failed: ${error.message}`));
if (this.stopped) {
// stop() ran while we were awaiting startup; don't install the poll it
// already tried to clear.
return;
}
void this.connect().catch(error => this.warn(`WebSocket connection failed: ${error.message}`));
this.statusPoll = setInterval(() => {
this.fetchStatus().catch(error => this.warn(`Status poll failed: ${error.message}`));
}, 60_000);
}
public stop(): void {
this.stopped = true;
clearInterval(this.keepalive);
clearInterval(this.statusPoll);
clearTimeout(this.reconnect);
this.reconnect = undefined;
clearTimeout(this.startupRetry);
this.startupRetry = undefined;
this.reconnectAttempt = 0;
this.startupAttempt = 0;
const socket = this.ws;
this.ws = undefined;
socket?.close();
for (const pending of this.pending.values()) {
clearTimeout(pending.timer);
pending.resolve(null);
}
this.pending.clear();
}
public async preheat(mode = this.config.defaultMode, tempF = this.config.defaultTempF): Promise<string | null> {
this.lastCancelled = false;
return this.sendCommand(MC_PREHEAT, { primitive_type: mode, temperature_cavity: fahrenheitToMilliC(tempF) });
}
});
this.ws.send(frame);
return ack;
}
private handleMessage(message: string): void {
let frame: { message_code?: number; data?: any };
try {
frame = JSON.parse(message);
} catch {
return;
}
const data = frame.data || {};
if (frame.message_code === 10020 && typeof data.request_order === 'number') {
const pending = this.pending.get(data.request_order);
if (pending) {
this.pending.delete(data.request_order);
clearTimeout(pending.timer);
pending.resolve(typeof data.status === 'string' ? data.status : null);
}
return;
}
if (frame.message_code === 10013) {
this.applyTelemetry({
currentTempC: typeof data.sensor_data?.cavity === 'number' ? milliCToCelsius(data.sensor_data.cavity) : undefined,
ready: typeof data.cook_state_data?.progress === 'number' && data.cook_state_data.progress >= 0.995,
...parseProbeTelemetry(data),
});
return;
}
if (frame.message_code === 10011) {
const snapshot = parseCameraFrame(data);
if (snapshot) {
this.snapshot = snapshot;
this.snapshotAt = Date.now();
}
return;
}
if (frame.message_code === 10015 || frame.message_code === 10016) {
const target = data.temperature_cavity ?? data.food?.plan?.steps?.find?.((step: { temperature_cavity?: number }) => typeof step.temperature_cavity === 'number')?.temperature_cavity;
this.applyTelemetry({ targetTempC: typeof target === 'number' ? milliCToCelsius(target) : undefined });
return;
}
if (frame.message_code === 10017 && data.type === 'cancelled') {
this.lastCancelled = true;
return;
}
if (frame.message_code === 10018) {
this.applyTelemetry({ active: data.state === 'active' });
}
}
private applyTelemetry(update: JuneTelemetry): void {
if (typeof update.targetTempC === 'number') {
this.lastTargetTempC = update.targetTempC;
}
if (typeof update.active === 'boolean') {
update.done = this.lastActive && !update.active && !this.lastCancelled;
this.lastActive = update.active;
if (update.active) {
this.lastCancelled = false;
}
}
if (typeof update.ready === 'boolean' && update.ready && typeof update.currentTempC === 'number' && typeof this.lastTargetTempC === 'number') {
update.ready = update.currentTempC + 1 >= this.lastTargetTempC;
}
this.emit('telemetry', update);
}
private warn(message: string): void {
this.log.warn(message);
this.emit('warning', message);
}
}