@cldmv/node-android-tv-remote 2.1.9 → 2.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1895 +0,0 @@
1
- /**
2
- *
3
- * @Project: @cldmv/node-android-tv-remote
4
- * @Filename: /src/lib/android-tv-remote.mjs
5
- * @Date: 2025-10-15T10:19:05-07:00 (1760548745)
6
- * @Author: Nate Corcoran <CLDMV>
7
- * @Email: <Shinrai@users.noreply.github.com>
8
- * -----
9
- * @Last modified by: Nate Corcoran <CLDMV> (Shinrai@users.noreply.github.com)
10
- * @Last modified time: 2026-10-02T12:16:15-07:00 (1790968575)
11
- * -----
12
- * @Copyright: Copyright (c) 2013-2026 Catalyzed Motivation Inc. All rights reserved.
13
- *
14
- */
15
-
16
- /**
17
- * Android TV Remote module - Event-driven ADB remote control for Android TV devices.
18
- *
19
- * @module android-tv-remote
20
- *
21
- * @description
22
- * This module provides an event-driven interface for controlling Android TV devices via ADB.
23
- * All operations emit events instead of console logging, allowing for better integration
24
- * and programmatic handling of device communication.
25
- *
26
- * @example
27
- * // ESM usage with event handling
28
- * import createRemote from "@cldmv/node-android-tv-remote";
29
- *
30
- * const remote = createRemote({ ip: "192.168.1.100" });
31
- *
32
- * // Listen for log events
33
- * remote.on('log', (data) => {
34
- * console.log(`[${data.level}] ${data.message}`, data.source);
35
- * });
36
- *
37
- * // Listen for errors
38
- * remote.on('error', (data) => {
39
- * console.error(`Error from ${data.source}:`, data.error.message);
40
- * });
41
- *
42
- * // Use the remote
43
- * await remote.press.home();
44
- *
45
- * @example
46
- * // Static create method
47
- * import { createAndroidTVRemote } from "@cldmv/node-android-tv-remote";
48
- *
49
- * const remote = await createAndroidTVRemote({ ip: "192.168.1.100" });
50
- * remote.on('log', console.log);
51
- * await remote.press.play();
52
- */
53
-
54
- /**
55
- * Configuration object for Android TV Remote.
56
- * @typedef {Object} RemoteConfig
57
- * @property {string} ip - The IP address of the device.
58
- * @property {number} [port=5555] - The port for ADB connection.
59
- * @property {string} [inputDevice="/dev/input/event0"] - The input device path.
60
- * @property {boolean} [autoConnect=true] - Whether to auto-connect on command.
61
- * @property {boolean} [autoDisconnect=false] - Whether to auto-disconnect after inactivity.
62
- * @property {number} [disconnectTimeout=10] - Inactivity timeout in seconds before disconnecting.
63
- * @property {boolean} [maintainConnection=true] - Whether to maintain the ADB connection with a heartbeat.
64
- * @property {number} [heartbeatInterval=30000] - Heartbeat interval in ms (default 30s).
65
- * @property {number} [connectionCheckInterval=30000] - Interval in ms for periodic connection checks (default 30s).
66
- * @property {number} [connectTimeout=10000] - Timeout in ms for ADB connection attempts (default 10s).
67
- * @property {boolean} [quiet=true] - Suppress log events if true (errors are always emitted).
68
- */
69
-
70
- /**
71
- * Log event data structure.
72
- * @typedef {Object} LogEventData
73
- * @property {string} level - Log level: 'info', 'warn', 'error', 'debug'.
74
- * @property {string} message - Log message.
75
- * @property {string} source - Source of the log message (e.g., 'connect', 'disconnect', 'setSettings').
76
- * @property {string} timestamp - ISO timestamp of when the log was created.
77
- * @property {any} [data] - Optional additional data related to the log.
78
- */
79
-
80
- /**
81
- * Error event data structure.
82
- * @typedef {Object} ErrorEventData
83
- * @property {Error} error - The error object that was thrown.
84
- * @property {string} source - Source of the error (e.g., 'connect', 'disconnect', 'adb').
85
- * @property {string} message - Human-readable error message.
86
- * @property {string} timestamp - ISO timestamp of when the error occurred.
87
- */
88
-
89
- /**
90
- * Android TV Remote instance with event emission capabilities.
91
- * @typedef {Object} Remote
92
- * @property {function(string=): Promise<void>} setSettings - Configure or retrieve Android TV settings for optimal remote operation.
93
- * @property {function(function(Error=, any=)=): Promise<void>|undefined} connect - Connect to the device. Supports both promise and callback styles.
94
- * @property {function(function(Error=, any=)=): Promise<void>|undefined} disconnect - Disconnect from the device. Supports both promise and callback styles.
95
- * @property {function(number, function(Error=, any=)=): Promise<void>|undefined} inputKeycode - Send a keycode to the device. Supports both promise and callback styles.
96
- * @property {function(): Promise<boolean>} reboot - Reboots the device using ADB's native reboot method.
97
- * @property {function(Object=): Promise<ReadableStream|void>} screencap - Takes a screenshot with optional resizing and file saving.
98
- * @property {function(number=): Promise<boolean>} waitBootComplete - Waits until device has finished booting (default 60s timeout).
99
- * @property {function(boolean=): Promise<"connected"|"disconnected"|"unknown">} getConnectionStatus - Returns the current connection status; optionally performs a live check.
100
- * @property {boolean} isConnected - True if the module believes it is connected (internal state, not a live check).
101
- * @property {Object} press - Remote control key functions for Android TV remotes.
102
- * @property {Object} keyboard - Keyboard interface for all keys, with text and keycode fallback.
103
- * @property {Object} keyboard.key - Contains all key functions.
104
- * @property {Object} keyboard.key.shift - Contains all shifted key functions.
105
- *
106
- * @property {function(string, Function): Remote} on - Add event listener. Returns remote instance for chaining.
107
- * @property {function(string, Function): Remote} off - Remove event listener. Returns remote instance for chaining.
108
- * @property {function(string, Function): Remote} once - Add one-time event listener. Returns remote instance for chaining.
109
- * @property {function(string, ...any): boolean} emit - Emit an event. Returns true if event had listeners.
110
- *
111
- * @fires Remote#log - Emitted for informational messages, warnings, and debug info.
112
- * @fires Remote#error - Emitted when errors occur during ADB operations.
113
- * @fires Remote#screencap-start - Emitted when screenshot capture begins.
114
- * @fires Remote#screencap-captured - Emitted when raw screenshot is captured.
115
- * @fires Remote#screencap-processing - Emitted when image processing begins.
116
- * @fires Remote#screencap-ready - Emitted when final processed stream is ready.
117
- * @fires Remote#screencap-saved - Emitted when screenshot is saved to file.
118
- * @fires Remote#screencap-complete - Emitted when entire screenshot operation is complete.
119
- *
120
- * @example
121
- * // Event handling examples
122
- * remote.on('log', (data) => {
123
- * if (data.level === 'error') {
124
- * console.error(`ERROR [${data.source}]: ${data.message}`);
125
- * } else if (data.level === 'warn') {
126
- * console.warn(`WARN [${data.source}]: ${data.message}`);
127
- * } else {
128
- * console.log(`INFO [${data.source}]: ${data.message}`);
129
- * }
130
- * });
131
- *
132
- * remote.on('error', (data) => {
133
- * console.error(`FATAL ERROR from ${data.source}:`);
134
- * console.error(data.error.stack || data.error.message);
135
- *
136
- * // Handle specific error types
137
- * if (data.error.message.includes('device unauthorized')) {
138
- * console.log('Please authorize ADB on your Android TV device');
139
- * }
140
- * });
141
- */
142
-
143
- import adbkit from "@devicefarmer/adbkit";
144
- import { EventEmitter } from "events";
145
- import { debuglog } from "node:util";
146
- import { createWriteStream } from "fs";
147
- import sharp from "sharp";
148
- // @devicefarmer/adbkit is plain CJS (`exports.default` / `exports.Adb` both
149
- // getter re-exports of the same class). Under plain Node's ESM/CJS interop,
150
- // the default import resolves to `module.exports` (so `.Adb` holds the
151
- // class); under Vite/Rollup-based CJS interop (e.g. vitest with the module
152
- // inlined), the default import unwraps straight to the class itself. Cover
153
- // both shapes rather than assuming one.
154
- const Adb = adbkit.Adb ?? adbkit;
155
-
156
- /**
157
- * Wraps an async function to support both promise and callback styles.
158
- * @internal
159
- * @param {Function} fn - The async function to wrap.
160
- * @returns {Function} A function supporting both promise and callback usage.
161
- */
162
- function wrapAsync(fn) {
163
- return function (...args) {
164
- const cb = typeof args[args.length - 1] === "function" ? args.pop() : null;
165
- const p = fn.apply(this, args);
166
- if (cb) {
167
- p.then((result) => cb(null, result)).catch((err) => cb(err));
168
- } else {
169
- return p;
170
- }
171
- };
172
- }
173
-
174
- /**
175
- * Debug channel for errors no "error" listener is attached to.
176
- * Enable with NODE_DEBUG=android-tv-remote.
177
- * @private
178
- */
179
- const debug = debuglog("android-tv-remote");
180
-
181
- /**
182
- * Create the event channel for one remote instance. Every remote gets its own
183
- * EventEmitter, so listeners on one remote never see another remote's events.
184
- * @private
185
- * @returns {{ emitter: EventEmitter, emitLog: Function, emitError: Function, handleDisconnectError: Function }}
186
- */
187
- function createEventChannel() {
188
- const emitter = new EventEmitter();
189
-
190
- /**
191
- * Emit a log event with structured data.
192
- * @private
193
- * @param {string} level - Log level (info, warn, error, debug).
194
- * @param {string} message - Log message.
195
- * @param {string} [source] - Source of the log message.
196
- * @param {any} [data] - Additional data to include.
197
- */
198
- function emitLog(level, message, source = "android-tv-remote", data = null) {
199
- emitter.emit("log", {
200
- level,
201
- message,
202
- source,
203
- timestamp: new Date().toISOString(),
204
- ...(data && { data })
205
- });
206
- }
207
-
208
- /**
209
- * Emit an error event with structured data.
210
- * @private
211
- * @param {Error} error - The error object.
212
- * @param {string} [source] - Source of the error.
213
- * @param {string} [message] - Additional error message.
214
- */
215
- function emitError(error, source = "android-tv-remote", message = null) {
216
- // Filter out libspng/PNG processing errors that occur after disconnection
217
- // These are common when background operations try to process data after disconnect
218
- const errorMsg = error.message || "";
219
- if (errorMsg.includes("libspng") || errorMsg.includes("pngload_buffer") || errorMsg.includes("read error")) {
220
- // Log as debug instead of error to avoid noise
221
- emitLog("debug", `PNG processing error (likely post-disconnect): ${errorMsg}`, source);
222
- return;
223
- }
224
-
225
- const payload = {
226
- error,
227
- source,
228
- message: message || error.message,
229
- timestamp: new Date().toISOString()
230
- };
231
-
232
- // EventEmitter throws when "error" is emitted with no listener, which would crash
233
- // the consumer's process. Without a listener, route the error to the log channel
234
- // (and NODE_DEBUG=android-tv-remote) instead; the failing operation still rejects
235
- // or resolves with the error, so it is never silently lost.
236
- if (emitter.listenerCount("error") > 0) {
237
- emitter.emit("error", payload);
238
- return;
239
- }
240
- debug("unhandled error from %s: %s", source, payload.message);
241
- emitLog("error", payload.message, source, { error });
242
- }
243
-
244
- /**
245
- * Handles disconnect and connection errors, emits helpful messages.
246
- * Also provides onboarding steps for common authentication and connection issues.
247
- * @private
248
- * @param {Error} err - The error object.
249
- * @example
250
- * try {
251
- * // ...code that may throw
252
- * } catch (err) {
253
- * handleDisconnectError(err);
254
- * }
255
- */
256
-
257
- function handleDisconnectError(err) {
258
- emitError(err, "handleDisconnectError");
259
-
260
- if (err.message && (err.message.includes("device unauthorized") || err.message.includes("failed to authenticate"))) {
261
- emitError(err, "handleDisconnectError", "Device unauthorized - authentication required");
262
- emitLog(
263
- "error",
264
- "Your device is unauthorized or failed to authenticate. Please check your TV and accept the authorization dialog to allow this system to connect via ADB.",
265
- "handleDisconnectError"
266
- );
267
- emitLog(
268
- "info",
269
- "If you do not see a prompt, try disconnecting and reconnecting the device, or reboot your TV.",
270
- "handleDisconnectError"
271
- );
272
- emitLog(
273
- "info",
274
- "If the problem persists, remove the device from the list of authorized ADB devices in Developer Options and try again.",
275
- "handleDisconnectError"
276
- );
277
- emitLog(
278
- "info",
279
- "Tip: In Developer Options on your TV, try toggling 'ADB Debugging' off and then back on. This often resolves authentication issues.",
280
- "handleDisconnectError"
281
- );
282
- }
283
-
284
- if (err.message && (err.message.includes("actively refused") || err.message.includes("No connection could be made"))) {
285
- emitError(err, "handleDisconnectError", "Connection refused - ADB not enabled");
286
- emitLog(
287
- "error",
288
- "The device refused the connection. To enable ADB, follow these steps on your Android TV or Fire TV:",
289
- "handleDisconnectError"
290
- );
291
- emitLog("info", "1. Open Settings > Device Preferences > About (or My Fire TV > About)", "handleDisconnectError");
292
- emitLog("info", "2. Scroll to 'Build' and press OK 7 times to enable Developer Options", "handleDisconnectError");
293
- emitLog("info", "3. Go back to Settings > Device Preferences > Developer Options", "handleDisconnectError");
294
- emitLog(
295
- "info",
296
- "4. Enable 'Developer Options' if needed, then enable 'ADB Debugging' and 'Apps from Unknown Sources'",
297
- "handleDisconnectError"
298
- );
299
- emitLog("info", "5. Ensure your TV and computer are on the same network", "handleDisconnectError");
300
- emitLog("info", "6. On your computer, run: adb connect <device-ip>:5555", "handleDisconnectError");
301
- emitLog("info", "7. Accept the authorization prompt on your TV", "handleDisconnectError");
302
- emitLog("info", "If you do not see 'Developer Options', repeat step 2 until it appears.", "handleDisconnectError");
303
- }
304
-
305
- return err;
306
- }
307
-
308
- return { emitter, emitLog, emitError, handleDisconnectError };
309
- }
310
-
311
- /**
312
- * Android keycodes mapping loaded from JSON file.
313
- * @internal
314
- * @type {Object.<string, number>}
315
- * @see https://developer.android.com/reference/android/view/KeyEvent
316
- */
317
- import keycodes from "../data/keycodes.json" with { type: "json" };
318
- import keyboardKeys from "../data/keyboard-keys.json" with { type: "json" };
319
-
320
- /**
321
- * Gets the shifted character for a given key.
322
- * @private
323
- * @param {string} keyName - The key name
324
- * @param {string} char - The original character
325
- * @returns {string} The shifted character
326
- */
327
- function getShiftedCharacter(keyName, char) {
328
- // Handle letters - convert to uppercase
329
- if (/^[a-z]$/.test(char)) {
330
- return char.toUpperCase();
331
- }
332
-
333
- // Handle shifted symbols
334
- const shiftMap = {
335
- "1": "!",
336
- "2": "@",
337
- "3": "#",
338
- "4": "$",
339
- "5": "%",
340
- "6": "^",
341
- "7": "&",
342
- "8": "*",
343
- "9": "(",
344
- "0": ")",
345
- "-": "_",
346
- "=": "+",
347
- "[": "{",
348
- "]": "}",
349
- "\\": "|",
350
- ";": ":",
351
- "'": '"',
352
- ",": "<",
353
- ".": ">",
354
- "/": "?",
355
- "`": "~"
356
- };
357
-
358
- return shiftMap[char] || char;
359
- }
360
-
361
- /**
362
- * Remote keys mapping loaded from JSON file.
363
- * @internal
364
- * @type {string[]}
365
- */
366
- import remoteKeys from "../data/remote-keys.json" with { type: "json" };
367
-
368
- /**
369
- * Factory function to create a ready-to-use Remote instance.
370
- * @function
371
- * @public
372
- * @param {RemoteConfig} config - Configuration for the remote.
373
- * @returns {Promise<Remote>} A promise that resolves to a ready-to-use remote instance
374
- */
375
- export default async function createRemote(config) {
376
- // Ensure config is an object and has the required 'ip' property
377
- if (!config || typeof config !== "object" || !config.ip) {
378
- throw new Error("Missing required 'ip' property in RemoteConfig.");
379
- }
380
- const ip = config.ip;
381
- const port = config.port || 5555;
382
- const inputDevice = config.inputDevice || "/dev/input/event0";
383
- const host = ip + ":" + port;
384
- const connectTimeout = typeof config.connectTimeout === "number" ? config.connectTimeout : 10000;
385
- const client = Adb.createClient({
386
- timeout: connectTimeout
387
- });
388
- const device = client.getDevice(host);
389
- // Per-instance event channel: listeners are scoped to this remote.
390
- const { emitter, emitLog, emitError, handleDisconnectError } = createEventChannel();
391
- let connected = false;
392
- let backgroundOperations = new Set();
393
-
394
- /**
395
- * Local emitError function that has access to connection state
396
- * @private
397
- * @param {Error} error - The error object
398
- * @param {string} [source] - Source of the error
399
- * @param {string} [message] - Additional error message
400
- */
401
- function localEmitError(error, source = "android-tv-remote", message = null) {
402
- // Filter out libspng/PNG processing errors that occur after disconnection
403
- const errorMsg = error.message || "";
404
- if (!connected && (errorMsg.includes("libspng") || errorMsg.includes("pngload_buffer") || errorMsg.includes("read error"))) {
405
- // Log as debug instead of error to avoid noise
406
- emitLog("debug", `PNG processing error (post-disconnect): ${errorMsg}`, source);
407
- return;
408
- }
409
-
410
- // Use global emitError for other cases
411
- emitError(error, source, message);
412
- }
413
-
414
- const autoConnect = config.autoConnect !== false; // default true
415
- const autoDisconnect = config.autoDisconnect === true; // default false
416
- const disconnectTimeout = typeof config.disconnectTimeout === "number" ? config.disconnectTimeout : 10;
417
- const connectionCheckInterval = typeof config.connectionCheckInterval === "number" ? config.connectionCheckInterval : 10000;
418
- let connectionCheckTimer = null;
419
- let disconnectTimer = null;
420
- const quiet = config.quiet !== false; // default true
421
- const maintainConnection = config.maintainConnection !== false; // default true
422
- const heartbeatInterval = typeof config.heartbeatInterval === "number" ? config.heartbeatInterval : 20000;
423
- let heartbeatTimer = null;
424
-
425
- /**
426
- * On initialization, check if already connected to the device and set internal state.
427
- * This ensures the internal state is correct if the device is already connected.
428
- * Expose a promise (initPromise) that resolves or rejects based on the result.
429
- */
430
- const INIT_TIMEOUT_MS = 7000;
431
-
432
- /**
433
- * Internal resolve/reject for initPromise, always defined as functions.
434
- */
435
- let initPromiseResolve;
436
- let initPromiseReject;
437
-
438
- /**
439
- * Promise that resolves if initial auto-connect succeeds, or rejects if it fails.
440
- * Now includes a timeout to prevent hanging forever if ADB never responds.
441
- * @type {Promise<void>}
442
- * @example
443
- * remote.initPromise.then(() => { ... }).catch((err) => { ... });
444
- */
445
- const realInitPromise = new Promise((resolve, reject) => {
446
- initPromiseResolve = resolve;
447
- initPromiseReject = reject;
448
- if (!autoConnect) {
449
- // Skip initialization if autoConnect is disabled
450
- initPromiseResolve(undefined);
451
- return;
452
- }
453
- (async () => {
454
- try {
455
- const status = await getConnectionStatus(true);
456
- if (status === "connected") {
457
- connected = true;
458
- if (!quiet) emitLog("info", `Already connected to ${host} (on init)`, "initPromise");
459
- startHeartbeat();
460
- initPromiseResolve(undefined);
461
- } else {
462
- // Try to connect if not already connected
463
- await connect();
464
- if (connected) {
465
- initPromiseResolve(undefined);
466
- } else {
467
- const error = new Error("Failed to connect to device on initialization.");
468
- emitError(error, "initPromise", "Auto-connect failed during initialization");
469
- initPromiseReject(error);
470
- }
471
- }
472
- } catch (e) {
473
- emitError(e instanceof Error ? e : new Error(String(e)), "initPromise", "Exception during initialization");
474
- initPromiseReject(e);
475
- }
476
- })();
477
- });
478
-
479
- const initPromise = Promise.race([
480
- realInitPromise,
481
- new Promise((_, reject) => {
482
- setTimeout(() => {
483
- reject(new Error("ADB initPromise timed out"));
484
- }, INIT_TIMEOUT_MS);
485
- })
486
- ]);
487
- // Callers who never look at initPromise must not get an unhandled rejection (which
488
- // crashes Node.js) when auto-connect fails; awaiting it still rejects as before.
489
- initPromise.catch(() => {});
490
-
491
- /**
492
- * Resets the disconnect timer if autoDisconnect is enabled.
493
- * Disconnects after inactivity if enabled.
494
- * @private
495
- */
496
- function resetDisconnectTimer() {
497
- if (!autoDisconnect) return;
498
- if (disconnectTimer) clearTimeout(disconnectTimer);
499
- disconnectTimer = setTimeout(() => {
500
- if (connected) disconnect();
501
- }, disconnectTimeout * 1000);
502
- }
503
-
504
- /**
505
- * Starts the heartbeat timer to maintain the ADB connection.
506
- * Periodically sends a shell command to keep the connection alive.
507
- * Also starts the periodic connection check for auto-reconnect.
508
- * @private
509
- */
510
- function startHeartbeat() {
511
- if (!maintainConnection) return;
512
- if (heartbeatTimer) clearInterval(heartbeatTimer);
513
- heartbeatTimer = setInterval(() => {
514
- if (!connected) return;
515
- // Send a no-op shell command to keep the connection alive
516
- device.shell("echo heartbeat").catch(() => {});
517
- }, heartbeatInterval);
518
- startConnectionCheck();
519
- }
520
-
521
- /**
522
- * Starts the periodic connection check. If disconnected, attempts to reconnect.
523
- * Ensures persistent, self-healing ADB connection.
524
- * @private
525
- */
526
- function startConnectionCheck() {
527
- if (connectionCheckTimer) clearInterval(connectionCheckTimer);
528
- connectionCheckTimer = setInterval(async () => {
529
- if (!connected) return;
530
- try {
531
- const devices = await client.listDevices();
532
- const deviceId = host;
533
- const found = devices.some((d) => d.id === deviceId);
534
- if (!found) {
535
- emitLog("warn", `Device ${deviceId} not found in adb devices list. Attempting reconnect...`, "connectionCheck");
536
- connected = false;
537
- await connect();
538
- }
539
- } catch (err) {
540
- const error = err instanceof Error ? err : new Error(String(err));
541
- emitLog("warn", `Error checking device connection: ${error.message}`, "connectionCheck");
542
- }
543
- }, connectionCheckInterval);
544
- }
545
-
546
- /**
547
- * Stops the heartbeat and connection check timers.
548
- * @private
549
- */
550
- function stopHeartbeat() {
551
- if (heartbeatTimer) {
552
- clearInterval(heartbeatTimer);
553
- heartbeatTimer = null;
554
- }
555
- if (connectionCheckTimer) {
556
- clearInterval(connectionCheckTimer);
557
- connectionCheckTimer = null;
558
- }
559
- }
560
-
561
- /**
562
- * Ensures connection if autoConnect is enabled.
563
- * Used internally before sending commands.
564
- * @internal
565
- * @returns {Promise<void>}
566
- */
567
- function ensureConnected() {
568
- if (!autoConnect) return Promise.resolve();
569
- if (connected) return Promise.resolve();
570
- return connect();
571
- }
572
-
573
- /**
574
- * Connects to the ADB device if not already connected.
575
- * Checks the internal connection state before connecting.
576
- * @returns {Promise<void>}
577
- * @example
578
- * await remote.connect(); // Only connects if not already connected
579
- */
580
- function connect() {
581
- if (connected) {
582
- if (!quiet) emitLog("info", `Already connected to ${host}`, "connect");
583
- return Promise.resolve();
584
- }
585
- return client
586
- .connect(ip, port)
587
- .then(() => {
588
- connected = true;
589
- if (!quiet) emitLog("info", `Connected to ${host}`, "connect");
590
- startHeartbeat();
591
- })
592
- .catch((err) => {
593
- if (err.message && err.message.includes("already connected")) {
594
- if (!quiet) emitLog("warn", "Device already connected", "connect");
595
- connected = true;
596
- startHeartbeat();
597
- return true;
598
- }
599
- return handleDisconnectError(err);
600
- });
601
- }
602
- const connectWrapped = wrapAsync(connect);
603
-
604
- /**
605
- * Disconnects from the ADB device and stops heartbeat/connection check.
606
- * Handles already-disconnected state gracefully.
607
- * @internal
608
- * @returns {Promise<void>}
609
- */
610
- async function disconnect() {
611
- if (disconnectTimer) {
612
- clearTimeout(disconnectTimer);
613
- disconnectTimer = null;
614
- }
615
- stopHeartbeat();
616
-
617
- // Wait for all background operations to complete before disconnecting
618
- if (backgroundOperations.size > 0) {
619
- if (!quiet)
620
- emitLog("info", `🔄 [DISCONNECT] Waiting for ${backgroundOperations.size} background operations to complete...`, "disconnect");
621
- const waitStartTime = performance.now();
622
- try {
623
- await Promise.allSettled([...backgroundOperations]);
624
- const waitEndTime = performance.now();
625
- if (!quiet)
626
- emitLog(
627
- "info",
628
- `✅ [DISCONNECT] All background operations completed in ${(waitEndTime - waitStartTime).toFixed(2)}ms`,
629
- "disconnect"
630
- );
631
- } catch (error) {
632
- const waitEndTime = performance.now();
633
- emitLog(
634
- "warn",
635
- `⚠️ [DISCONNECT] Some background operations failed after ${(waitEndTime - waitStartTime).toFixed(2)}ms: ${error.message}`,
636
- "disconnect"
637
- );
638
- }
639
- } else {
640
- if (!quiet) emitLog("info", `✅ [DISCONNECT] No background operations to wait for`, "disconnect");
641
- }
642
-
643
- try {
644
- await client.disconnect(ip, port);
645
- connected = false;
646
- if (!quiet) emitLog("info", `Disconnected from ${host}`, "disconnect");
647
- return true;
648
- } catch (err) {
649
- if (err.message && err.message.includes("disconnected")) {
650
- if (!quiet) emitLog("warn", "Device already disconnected before explicit disconnect call", "disconnect");
651
- connected = false;
652
- return true;
653
- }
654
- return handleDisconnectError(err);
655
- }
656
- }
657
- const disconnectWrapped = wrapAsync(disconnect);
658
-
659
- /**
660
- * Sends a keycode to the device, auto-connects/disconnects as needed.
661
- * @internal
662
- * @param {number} code - The Android keycode to send.
663
- * @returns {Promise<any>}
664
- */
665
- function inputKeycode(code) {
666
- return ensureConnected().then(() => {
667
- resetDisconnectTimer();
668
- return device.shell("input keyevent " + code);
669
- });
670
- }
671
- const inputKeycodeWrapped = wrapAsync(inputKeycode);
672
-
673
- /**
674
- * Sends a long press keycode to the device, auto-connects/disconnects as needed.
675
- * @internal
676
- * @param {number} code - The Android keycode to send as a long press.
677
- * @returns {Promise<any>}
678
- */
679
- function inputKeycodeLongPress(code) {
680
- const cmd = "sendevent " + inputDevice + " 1 " + code + " 1 && " + "sleep 1 && " + "sendevent " + inputDevice + " 1 " + code + " 0";
681
- return ensureConnected().then(() => {
682
- resetDisconnectTimer();
683
- return device.shell(cmd);
684
- });
685
- }
686
- const inputKeycodeLongPressWrapped = wrapAsync(inputKeycodeLongPress);
687
-
688
- /**
689
- * Sends text input to the device, auto-connects/disconnects as needed.
690
- * @internal
691
- * @param {string} text - The text to input.
692
- * @returns {Promise<any>}
693
- */
694
- function inputText(text) {
695
- const escaped = text.replace(/ /g, "%s");
696
- return ensureConnected().then(() => {
697
- resetDisconnectTimer();
698
- return device.shell('input text "' + escaped + '"');
699
- });
700
- }
701
- const inputTextWrapped = wrapAsync(inputText);
702
-
703
- /**
704
- * Returns the current connection status as tracked by the module.
705
- * Optionally performs a live check against adb devices if requested.
706
- * Also updates the internal connected state if a live check is performed.
707
- * @public
708
- * @param {boolean} [liveCheck=false] - If true, checks adb devices for actual connection.
709
- * @returns {Promise<"connected"|"disconnected"|"unknown">}
710
- * @example
711
- * await remote.getConnectionStatus();
712
- * await remote.getConnectionStatus(true); // live check
713
- */
714
- async function getConnectionStatus(liveCheck = false) {
715
- if (!liveCheck) {
716
- return connected ? "connected" : "disconnected";
717
- }
718
- try {
719
- const devices = await client.listDevices();
720
- const deviceId = host;
721
- const found = devices.some((d) => d.id === deviceId);
722
- connected = found; // Keep internal state in sync with live check
723
- return found ? "connected" : "disconnected";
724
- } catch {
725
- connected = false;
726
- return "unknown";
727
- }
728
- }
729
-
730
- /**
731
- * Returns true if the module believes it is connected to the device.
732
- * This is a fast check of internal state, not a live ADB query.
733
- * @public
734
- * @returns {boolean}
735
- * @example
736
- * if (remote.isConnected) { ... }
737
- */
738
- function isConnected() {
739
- return !!connected;
740
- }
741
-
742
- /**
743
- * Returns a list of all available keyboard key function names on the live API (keyboard.key).
744
- * This inspects the actual keyboard.key object, so it always matches the real API surface, including all aliases and dynamic keys.
745
- * @returns {string[]}
746
- * @example
747
- * remote.getKeyboardKeys();
748
- */
749
- function getKeyboardKeys() {
750
- // 'this' is not bound, so we must access the constructed keyboard.key object
751
- // Only return the top-level key names (not .keycode or .shift)
752
- if (!this || !this.keyboard || !this.keyboard.key) return [];
753
- return Object.keys(this.keyboard.key).filter((k) => typeof this.keyboard.key[k] === "function");
754
- }
755
-
756
- /**
757
- * Returns a list of all available press command names on the live API (press object), including aliases and dynamic keys.
758
- * This inspects the actual press object, so it always matches the real API surface.
759
- * @returns {string[]}
760
- * @example
761
- * remote.getPressCommands();
762
- */
763
- function getPressCommands() {
764
- if (!this || !this.press) return [];
765
- return Object.keys(this.press).filter((k) => k !== "long" && typeof this.press[k] === "function");
766
- }
767
-
768
- /**
769
- * Variable to store the last screencap data (PNG buffer) after processing.
770
- * Updated every time screencap or thumbnail is called, regardless of options.
771
- * @type {Buffer|null}
772
- */
773
- let lastScreencapData = null;
774
-
775
- const remoteApi = {
776
- /**
777
- * Promise that resolves if initial auto-connect succeeds, or rejects if it fails.
778
- * @type {Promise<void>}
779
- * @example
780
- * remote.initPromise.then(() => { ... }).catch((err) => { ... });
781
- */
782
- initPromise,
783
-
784
- /**
785
- * Add event listener.
786
- * @public
787
- * @param {string} event - Event name.
788
- * @param {Function} listener - Event listener function.
789
- * @returns {Object} This remote instance for chaining.
790
- * @example
791
- * remote.on('log', (data) => console.log(data));
792
- * remote.on('error', (data) => console.error(data));
793
- */
794
- on(event, listener) {
795
- emitter.on(event, listener);
796
- return remoteApi;
797
- },
798
-
799
- /**
800
- * Remove event listener.
801
- * @public
802
- * @param {string} event - Event name.
803
- * @param {Function} listener - Event listener function.
804
- * @returns {Object} This remote instance for chaining.
805
- * @example
806
- * remote.off('log', logHandler);
807
- */
808
- off(event, listener) {
809
- emitter.off(event, listener);
810
- return remoteApi;
811
- },
812
-
813
- /**
814
- * Add one-time event listener.
815
- * @public
816
- * @param {string} event - Event name.
817
- * @param {Function} listener - Event listener function.
818
- * @returns {Object} This remote instance for chaining.
819
- * @example
820
- * remote.once('log', (data) => console.log('First log:', data));
821
- */
822
- once(event, listener) {
823
- emitter.once(event, listener);
824
- return remoteApi;
825
- },
826
-
827
- /**
828
- * Emit an event.
829
- * @public
830
- * @param {string} event - Event name.
831
- * @param {...any} args - Event arguments.
832
- * @returns {boolean} True if event had listeners.
833
- * @example
834
- * remote.emit('custom-event', { data: 'example' });
835
- */
836
- emit(event, ...args) {
837
- return emitter.emit(event, ...args);
838
- },
839
- /**
840
- * Returns the current connection status as tracked by the module, or does a live check if requested.
841
- * @function
842
- * @param {boolean} [liveCheck=false] - If true, checks adb devices for actual connection.
843
- * @returns {Promise<"connected"|"disconnected"|"unknown">}
844
- * @example
845
- * await remote.getConnectionStatus();
846
- * await remote.getConnectionStatus(true); // live check
847
- */
848
- getConnectionStatus,
849
- /**
850
- * Returns a list of all available keyboard key function names on the live API (keyboard.key).
851
- * @returns {string[]}
852
- * @example
853
- * remote.getKeyboardKeys();
854
- */
855
- getKeyboardKeys() {
856
- return getKeyboardKeys.call(remoteApi);
857
- },
858
- /**
859
- * Returns a list of all available press command names on the live API (press object), including aliases and dynamic keys.
860
- * @returns {string[]}
861
- * @example
862
- * remote.getPressCommands();
863
- */
864
- getPressCommands() {
865
- return getPressCommands.call(remoteApi);
866
- },
867
- /**
868
- * Returns true if the module believes it is connected to the device.
869
- * @readonly
870
- * @type {boolean}
871
- * @example
872
- * if (remote.isConnected) { ... }
873
- */
874
- get isConnected() {
875
- return isConnected();
876
- },
877
-
878
- /**
879
- * Returns the last screencap data (PNG stream) captured by screencap() or thumbnail().
880
- * Updated every time a screenshot is taken, regardless of options used.
881
- * @readonly
882
- * @type {ReadableStream|null}
883
- * @example
884
- * await remote.screencap({ filepath: './screenshot.png' });
885
- * console.log('Last screencap stream:', remote.lastScreencapData);
886
- *
887
- * // Use the cached stream data
888
- * if (remote.lastScreencapData) {
889
- * remote.lastScreencapData.pipe(someOtherStream);
890
- * }
891
- */
892
- get lastScreencapData() {
893
- return lastScreencapData;
894
- },
895
- /**
896
- * Configure or retrieve Android TV settings for optimal remote operation.
897
- * Handles power management, display settings, and system configuration.
898
- * @public
899
- * @param {string} [mode='set'] - 'get' to retrieve settings, 'set' to configure settings
900
- * @fires Remote#log - Emitted with settings operation results
901
- * @fires Remote#error - Emitted if settings operations fail
902
- * @example
903
- * await remote.setSettings(); // Set all optimal settings
904
- * await remote.setSettings('get'); // Get current settings values
905
- */
906
- async setSettings(mode = "set") {
907
- try {
908
- emitLog("info", `=== ${mode === "set" ? "Configuring" : "Retrieving"} Android TV settings ===`, "setSettings");
909
-
910
- await ensureConnected();
911
-
912
- // Core settings for power management and display
913
- const coreSettings = [
914
- { ns: "system", key: "screen_off_timeout", value: 2147483647 },
915
- { ns: "secure", key: "sleep_timeout", value: 0 },
916
- { ns: "global", key: "stay_on_while_plugged_in", value: 3 }
917
- ];
918
-
919
- // Process core settings
920
- for (const item of coreSettings) {
921
- const cmd = mode === "set" ? `settings put ${item.ns} ${item.key} ${item.value}` : `settings get ${item.ns} ${item.key}`;
922
-
923
- const result = await device.shell(cmd).then(Adb.util.readAll);
924
-
925
- if (!quiet) {
926
- if (mode === "set") {
927
- emitLog("info", `Set ${item.ns} ${item.key} to ${item.value}`, "setSettings");
928
- } else {
929
- emitLog("info", `${item.ns} ${item.key}: ${result.toString().trim()}`, "setSettings");
930
- }
931
- }
932
- }
933
-
934
- // Additional settings (only applied in set mode)
935
- if (mode === "set") {
936
- emitLog("info", "Setting additional display and power settings", "setSettings");
937
-
938
- const additionalSettings = [
939
- "settings put system screen_brightness_mode 0", // Manual brightness
940
- "settings put system screen_brightness 255", // Max brightness
941
- "svc power stayon true" // Stay on while plugged
942
- ];
943
-
944
- for (const cmd of additionalSettings) {
945
- if (!quiet) emitLog("info", `Running: ${cmd}`, "setSettings");
946
- await device.shell(cmd);
947
- }
948
- }
949
-
950
- emitLog("info", `✅ Android TV settings ${mode === "set" ? "configured" : "retrieved"} successfully`, "setSettings");
951
- } catch (error) {
952
- localEmitError(error, "setSettings", `Failed to ${mode === "set" ? "configure" : "retrieve"} Android TV settings`);
953
- throw error;
954
- }
955
- },
956
-
957
- /**
958
- * Ensures the Android TV device is awake and responsive.
959
- * Performs comprehensive power state checking and correction.
960
- * @public
961
- * @returns {Promise<boolean>} Returns true if device is awake and ready
962
- * @fires Remote#log - Emitted with power state and wake-up process information
963
- * @fires Remote#error - Emitted if wake-up process fails
964
- * @example
965
- * await remote.ensureAwake();
966
- */
967
- async ensureAwake() {
968
- try {
969
- emitLog("info", "=== Starting ensureAwake sequence ===", "ensureAwake");
970
-
971
- await ensureConnected();
972
-
973
- // Helper function to parse power state from dumpsys output
974
- const parsePowerState = (output) => {
975
- const mIsPoweredMatch = output.match(/^\s*mIsPowered=([a-zA-Z0-9]+)/m);
976
- const mWakefulnessMatch = output.match(/^\s*mWakefulness=([a-zA-Z0-9]+)/m);
977
- const mDisplayReadyMatch = output.match(/^\s*mDisplayReady=([a-zA-Z0-9]+)/m);
978
- return {
979
- mIsPowered: mIsPoweredMatch ? mIsPoweredMatch[1] : "unknown",
980
- mWakefulness: mWakefulnessMatch ? mWakefulnessMatch[1] : "unknown",
981
- mDisplayReady: mDisplayReadyMatch ? mDisplayReadyMatch[1] : "unknown"
982
- };
983
- };
984
-
985
- // Helper function to get current power state
986
- const getCurrentPowerState = async () => {
987
- const output = await device
988
- .shell("dumpsys power")
989
- .then(Adb.util.readAll)
990
- .then((b) => b.toString());
991
- return parsePowerState(output);
992
- };
993
-
994
- // Helper function to emit power state
995
- const emitPowerState = (parsed, context = "") => {
996
- const prefix = context ? `${context} ` : "";
997
- emitLog("info", `${prefix}Power State:`, "ensureAwake");
998
- emitLog("info", ` mIsPowered: ${parsed.mIsPowered}`, "ensureAwake");
999
- emitLog("info", ` mWakefulness: ${parsed.mWakefulness}`, "ensureAwake");
1000
- emitLog("info", ` mDisplayReady: ${parsed.mDisplayReady}`, "ensureAwake");
1001
- };
1002
-
1003
- // Check initial power state
1004
- const initialPowerState = await getCurrentPowerState();
1005
- emitPowerState(initialPowerState, "Initial");
1006
-
1007
- // Determine what commands need to be sent
1008
- const commandsToSend = [];
1009
-
1010
- if (initialPowerState.mIsPowered !== "true") {
1011
- emitLog("info", `Device not powered (${initialPowerState.mIsPowered}), will send POWER keycode`, "ensureAwake");
1012
- commandsToSend.push({ keycode: keycodes.power, reason: "power on device" });
1013
- } else {
1014
- emitLog("info", "✅ Device already powered", "ensureAwake");
1015
- }
1016
-
1017
- if (initialPowerState.mWakefulness !== "Awake") {
1018
- emitLog("info", `Device not awake (${initialPowerState.mWakefulness}), will send WAKEUP keycode`, "ensureAwake");
1019
- commandsToSend.push({ keycode: keycodes.wakeUp, reason: "wake up device" });
1020
- } else {
1021
- emitLog("info", "✅ Device already awake", "ensureAwake");
1022
- }
1023
-
1024
- if (initialPowerState.mDisplayReady !== "true") {
1025
- emitLog("info", `Display not ready (${initialPowerState.mDisplayReady}), will send POWER keycode`, "ensureAwake");
1026
- commandsToSend.push({ keycode: keycodes.power, reason: "ensure display ready" });
1027
- } else {
1028
- emitLog("info", "✅ Display already ready", "ensureAwake");
1029
- }
1030
-
1031
- // Send required commands
1032
- if (commandsToSend.length > 0) {
1033
- emitLog("info", `Sending ${commandsToSend.length} keycode(s)...`, "ensureAwake");
1034
-
1035
- for (const cmd of commandsToSend) {
1036
- emitLog("info", `Sending keycode ${cmd.keycode} to ${cmd.reason}`, "ensureAwake");
1037
- await inputKeycode(cmd.keycode);
1038
-
1039
- // Brief delay between commands
1040
- await new Promise((resolve) => setTimeout(resolve, 500));
1041
- }
1042
-
1043
- // Wait for commands to take effect
1044
- emitLog("info", "Waiting for commands to take effect...", "ensureAwake");
1045
- await new Promise((resolve) => setTimeout(resolve, 3000));
1046
- }
1047
-
1048
- // Verify final state
1049
- const finalPowerState = await getCurrentPowerState();
1050
- emitPowerState(finalPowerState, "Final");
1051
-
1052
- // Check for persistent issues
1053
- const issues = [];
1054
- if (finalPowerState.mIsPowered !== "true") {
1055
- issues.push(`Device still not powered: ${finalPowerState.mIsPowered}`);
1056
- }
1057
- if (finalPowerState.mWakefulness !== "Awake") {
1058
- issues.push(`Device still not awake: ${finalPowerState.mWakefulness}`);
1059
- }
1060
- if (finalPowerState.mDisplayReady !== "true") {
1061
- issues.push(`Display still not ready: ${finalPowerState.mDisplayReady}`);
1062
- }
1063
-
1064
- if (issues.length === 0) {
1065
- emitLog("info", "🎉 ensureAwake completed successfully - device is fully ready", "ensureAwake");
1066
- return true;
1067
- } else {
1068
- // Log warnings for persistent issues
1069
- for (const issue of issues) {
1070
- emitLog("warn", issue, "ensureAwake");
1071
- }
1072
-
1073
- // Only throw error if critical issues persist
1074
- emitError(
1075
- new Error(`ensureAwake failed with ${issues.length} persistent issue(s): ${issues.join(", ")}`),
1076
- "ensureAwake",
1077
- "Device may not be fully responsive"
1078
- );
1079
- return false;
1080
- }
1081
- } catch (error) {
1082
- emitError(error, "ensureAwake", "Failed to ensure device is awake");
1083
- throw error;
1084
- }
1085
- },
1086
-
1087
- /**
1088
- * Connect to the device. Supports both promise and callback styles.
1089
- * @public
1090
- * @param {function(Error=, any=)=} [cb]
1091
- * @returns {Promise|undefined}
1092
- * @fires Remote#log - Emitted with connection status information
1093
- * @fires Remote#error - Emitted if connection fails or ADB errors occur
1094
- * @example
1095
- * await remote.connect();
1096
- * remote.connect((err) => { ... });
1097
- */
1098
- connect:
1099
- /**
1100
- * @type {(cb?: (err?: Error, result?: any) => any) => Promise<any> | undefined}
1101
- */ (connectWrapped),
1102
-
1103
- /**
1104
- * Disconnect from the device. Supports both promise and callback styles.
1105
- * @public
1106
- * @param {function(Error=, any=)=} [cb]
1107
- * @returns {Promise|undefined}
1108
- * @fires Remote#log - Emitted with disconnection status information
1109
- * @fires Remote#error - Emitted if disconnection fails
1110
- * @example
1111
- * await remote.disconnect();
1112
- * remote.disconnect((err) => { ... });
1113
- */
1114
- disconnect:
1115
- /**
1116
- * @type {(cb?: (err?: Error, result?: any) => any) => Promise<any> | undefined}
1117
- */ (disconnectWrapped),
1118
-
1119
- /**
1120
- * Send a keycode. Supports both promise and callback styles.
1121
- * @public
1122
- * @param {number} code
1123
- * @param {function(Error=, any=)=} [cb]
1124
- * @returns {Promise|undefined}
1125
- * @example
1126
- * await remote.inputKeycode(23);
1127
- * remote.inputKeycode(23, (err) => { ... });
1128
- */
1129
- inputKeycode:
1130
- /**
1131
- * @type {(code: number, cb?: (err?: Error, result?: any) => any) => Promise<any> | undefined}
1132
- */ (inputKeycodeWrapped),
1133
-
1134
- /**
1135
- * Reboots the Android TV device using ADB's native reboot method.
1136
- * @public
1137
- * @returns {Promise<boolean>} Returns true when reboot command was sent successfully
1138
- * @fires Remote#log - Emitted with reboot operation status and warnings
1139
- * @fires Remote#error - Emitted if reboot operation fails
1140
- * @example
1141
- * await remote.reboot(); // Reboots the device
1142
- */
1143
- async reboot() {
1144
- try {
1145
- emitLog("info", "=== Starting device reboot ===", "reboot");
1146
-
1147
- // Ensure we're connected before sending reboot command
1148
- await ensureConnected();
1149
-
1150
- emitLog("info", "Sending reboot command to device", "reboot");
1151
-
1152
- // Use the native device.reboot() method with timeout handling
1153
- let result;
1154
- try {
1155
- result = await device.reboot();
1156
- emitLog("info", `✅ Reboot command completed normally`, "reboot");
1157
- } catch (timeoutError) {
1158
- // Socket timeout is expected during reboot - device becomes unresponsive
1159
- if (timeoutError.message && timeoutError.message.includes("timeout")) {
1160
- emitLog("info", "✅ Reboot command sent (connection timeout is expected during reboot)", "reboot");
1161
- result = true; // Treat timeout as success
1162
- } else {
1163
- // Re-throw non-timeout errors
1164
- throw timeoutError;
1165
- }
1166
- }
1167
- emitLog("warn", "Device will reboot shortly and connection will be lost", "reboot");
1168
-
1169
- // Wait a moment for command to take effect, then disconnect
1170
- setTimeout(() => {
1171
- emitLog("info", "Device should be rebooting now - connection will be terminated", "reboot");
1172
- // Force disconnect after reboot
1173
- connected = false;
1174
- stopHeartbeat();
1175
- }, 1000);
1176
-
1177
- emitLog("info", "=== Device reboot initiated ===", "reboot");
1178
- return result;
1179
- } catch (error) {
1180
- emitError(error, "reboot", "Failed to reboot device");
1181
-
1182
- // Provide helpful error messages for common issues
1183
- if (error.message && error.message.includes("unauthorized")) {
1184
- emitLog("error", "Device unauthorized - ensure ADB debugging is enabled and device is authorized", "reboot");
1185
- } else if (error.message && error.message.includes("device not found")) {
1186
- emitLog("error", "Device not found - check IP address and ADB connection", "reboot");
1187
- } else if (error.message && error.message.includes("permission")) {
1188
- emitLog("error", "Permission denied - reboot may require root access on some devices", "reboot");
1189
- } else if (error.message && error.message.includes("timeout")) {
1190
- emitLog("warn", "Reboot command timed out - this may be normal behavior during reboot", "reboot");
1191
- }
1192
-
1193
- throw error;
1194
- }
1195
- },
1196
-
1197
- /**
1198
- * Takes a screenshot of the Android TV device screen in PNG format with optional resizing and file saving.
1199
- * @public
1200
- * @param {Object} [options={}] - Screenshot options
1201
- * @param {number} [options.width] - Target width for resizing (optional)
1202
- * @param {number} [options.height] - Target height for resizing (optional)
1203
- * @param {string} [options.filepath] - File path to save screenshot (optional)
1204
- * @returns {Promise<ReadableStream|void>} Returns PNG stream if no filepath, void if saved to file
1205
- * @fires Remote#screencap-start - Emitted when screenshot capture begins
1206
- * @fires Remote#screencap-captured - Emitted when raw screenshot is captured
1207
- * @fires Remote#screencap-processing - Emitted when image processing begins
1208
- * @fires Remote#screencap-ready - Emitted when final processed stream is ready
1209
- * @fires Remote#screencap-saved - Emitted when screenshot is saved to file
1210
- * @fires Remote#screencap-complete - Emitted when entire operation is complete
1211
- * @fires Remote#log - Emitted with screenshot operation status
1212
- * @fires Remote#error - Emitted if screenshot operation fails
1213
- * @example
1214
- * // Basic screenshot - returns stream
1215
- * const pngStream = await remote.screencap();
1216
- *
1217
- * // Screenshot with resizing
1218
- * const resizedStream = await remote.screencap({ width: 1280, height: 720 });
1219
- *
1220
- * // Screenshot saved to file
1221
- * await remote.screencap({ filepath: './screenshot.png' });
1222
- *
1223
- * // Screenshot with resizing and file save
1224
- * await remote.screencap({ width: 640, height: 360, filepath: './thumb.png' });
1225
- *
1226
- * // Event-driven usage (non-blocking)
1227
- * remote.screencap({ width: 1280, filepath: './shot.png' });
1228
- * remote.on('screencap-complete', (data) => {
1229
- * console.log('Screenshot ready:', data.filepath);
1230
- * });
1231
- */
1232
- async screencap(options = {}) {
1233
- const startTime = performance.now();
1234
- const { width, height, filepath } = options;
1235
-
1236
- try {
1237
- emitLog("info", "=== Taking device screenshot ===", "screencap");
1238
-
1239
- // Emit start event
1240
- emitter.emit("screencap-start", {
1241
- timestamp: new Date().toISOString(),
1242
- options: { width, height, filepath }
1243
- });
1244
-
1245
- // Ensure we're connected before taking screenshot
1246
- await ensureConnected();
1247
-
1248
- emitLog("info", "Capturing screenshot using native screencap utility", "screencap");
1249
-
1250
- // Use the native device.screencap() method which should return PNG
1251
- const screencapStream = await device.screencap();
1252
- const captureTime = performance.now();
1253
-
1254
- emitLog("info", `✅ Screenshot captured successfully (${(captureTime - startTime).toFixed(2)}ms)`, "screencap");
1255
-
1256
- // Emit captured event
1257
- emitter.emit("screencap-captured", {
1258
- timestamp: new Date().toISOString(),
1259
- captureTime: captureTime - startTime
1260
- });
1261
-
1262
- // Determine if we need Sharp processing (only for resizing)
1263
- const needsSharpProcessing = width || height;
1264
-
1265
- // Handle file save without processing (direct PNG stream to file)
1266
- if (filepath && !needsSharpProcessing) {
1267
- const backgroundOperation = (async () => {
1268
- try {
1269
- const fileOpStartTime = performance.now();
1270
-
1271
- emitLog("info", `💾 [BACKGROUND] Starting direct save to: ${filepath}`, "screencap");
1272
-
1273
- // Direct pipe: ADB PNG stream -> File (no Sharp processing)
1274
- const directPipeStartTime = performance.now();
1275
- const writeStream = createWriteStream(filepath);
1276
-
1277
- // Store the raw PNG stream for user access
1278
- lastScreencapData = screencapStream;
1279
-
1280
- emitLog("info", `🔄 [BACKGROUND] Piping stream to file...`, "screencap");
1281
- screencapStream.pipe(writeStream);
1282
-
1283
- emitLog("info", `⏳ [BACKGROUND] Waiting for write stream to finish...`, "screencap");
1284
- await new Promise((resolve, reject) => {
1285
- writeStream.on("finish", () => {
1286
- emitLog("info", `✅ [BACKGROUND] Write stream finished for ${filepath}`, "screencap");
1287
- resolve();
1288
- });
1289
- writeStream.on("error", (err) => {
1290
- emitLog("error", `❌ [BACKGROUND] Write stream error for ${filepath}: ${err.message}`, "screencap");
1291
- reject(err);
1292
- });
1293
- });
1294
-
1295
- const directPipeTime = performance.now() - directPipeStartTime;
1296
- const totalFileOpTime = performance.now() - fileOpStartTime;
1297
- const totalTime = performance.now() - startTime;
1298
-
1299
- emitLog("info", `✅ Screenshot saved directly to ${filepath}`, "screencap");
1300
- emitLog("info", `⚡ Direct pipe timing: ${directPipeTime.toFixed(2)}ms (no Sharp processing!)`, "screencap");
1301
-
1302
- // Emit saved event with timing
1303
- emitter.emit("screencap-saved", {
1304
- timestamp: new Date().toISOString(),
1305
- filepath,
1306
- timing: {
1307
- adbStream: captureTime - startTime,
1308
- directPipe: directPipeTime,
1309
- fileOperation: totalFileOpTime,
1310
- total: totalTime
1311
- }
1312
- });
1313
-
1314
- // Emit complete event
1315
- emitter.emit("screencap-complete", {
1316
- timestamp: new Date().toISOString(),
1317
- filepath,
1318
- processed: false,
1319
- timing: {
1320
- adbStream: captureTime - startTime,
1321
- directPipe: directPipeTime,
1322
- fileOperation: totalFileOpTime,
1323
- total: totalTime
1324
- }
1325
- });
1326
- } catch (saveError) {
1327
- emitLog("error", `💥 [BACKGROUND] Direct pipe error: ${saveError.message}`, "screencap");
1328
- localEmitError(saveError, "screencap", `Failed to save screenshot directly to ${filepath}: ${saveError.message}`);
1329
- } finally {
1330
- emitLog("info", `🧹 [BACKGROUND] Cleaning up background operation for ${filepath}`, "screencap");
1331
- backgroundOperations.delete(backgroundOperation);
1332
- }
1333
- })();
1334
-
1335
- backgroundOperations.add(backgroundOperation);
1336
- emitLog("info", "Direct PNG pipe started in background", "screencap");
1337
- return; // Don't return a stream when saving to file
1338
- }
1339
-
1340
- if (!needsSharpProcessing && !filepath) {
1341
- // Store the raw PNG stream for user access
1342
- lastScreencapData = screencapStream;
1343
-
1344
- // Return raw stream if no processing or file save needed
1345
- emitLog("info", "Raw PNG stream ready (no processing needed)", "screencap");
1346
- emitter.emit("screencap-ready", {
1347
- timestamp: new Date().toISOString(),
1348
- processed: false,
1349
- totalTime: captureTime - startTime
1350
- });
1351
- emitter.emit("screencap-complete", {
1352
- timestamp: new Date().toISOString(),
1353
- totalTime: captureTime - startTime,
1354
- processed: false
1355
- });
1356
- return screencapStream;
1357
- }
1358
-
1359
- // Process the image
1360
- emitLog("info", "Processing screenshot image...", "screencap");
1361
- emitter.emit("screencap-processing", {
1362
- timestamp: new Date().toISOString(),
1363
- width,
1364
- height,
1365
- filepath
1366
- });
1367
-
1368
- const processStartTime = performance.now();
1369
-
1370
- // Create Sharp transform pipeline
1371
- let sharpTransform = sharp();
1372
-
1373
- // Apply resizing if width or height specified
1374
- if (width || height) {
1375
- const resizeOptions = {
1376
- fit: "inside", // Maintain aspect ratio
1377
- withoutEnlargement: true // Don't upscale
1378
- };
1379
- if (width) resizeOptions.width = width;
1380
- if (height) resizeOptions.height = height;
1381
-
1382
- sharpTransform = sharpTransform.resize(resizeOptions);
1383
- emitLog("info", `Resizing to ${width || "auto"}x${height || "auto"}`, "screencap");
1384
- }
1385
-
1386
- // Ensure PNG format with fastest compression settings
1387
- sharpTransform = sharpTransform.png({
1388
- compressionLevel: 1, // Fastest compression (0-9, lower = faster)
1389
- progressive: false // Disable progressive encoding
1390
- });
1391
-
1392
- if (filepath) {
1393
- // Background process handles saving and updates lastScreencapData when done
1394
- const backgroundOperation = (async () => {
1395
- try {
1396
- const fileOpStartTime = performance.now();
1397
- const writeStream = createWriteStream(filepath);
1398
-
1399
- // Process and save data, collecting it for lastScreencapData
1400
- const chunks = [];
1401
- const processedStream = screencapStream.pipe(sharpTransform);
1402
-
1403
- await new Promise((resolve, reject) => {
1404
- processedStream.on("data", (chunk) => {
1405
- chunks.push(chunk);
1406
- writeStream.write(chunk);
1407
- });
1408
-
1409
- processedStream.on("end", () => {
1410
- writeStream.end();
1411
- // Save processed data to lastScreencapData when done
1412
- lastScreencapData = Buffer.concat(chunks);
1413
-
1414
- const totalFileOpTime = performance.now() - fileOpStartTime;
1415
- const totalTime = performance.now() - startTime;
1416
-
1417
- emitLog("info", `✅ Screenshot saved to ${filepath}`, "screencap");
1418
- emitLog("info", `⏱️ File save timing: ${totalFileOpTime.toFixed(2)}ms, Total: ${totalTime.toFixed(2)}ms`, "screencap");
1419
-
1420
- emitter.emit("screencap-saved", {
1421
- timestamp: new Date().toISOString(),
1422
- filepath,
1423
- timing: { fileOperation: totalFileOpTime, total: totalTime }
1424
- });
1425
-
1426
- emitter.emit("screencap-complete", {
1427
- timestamp: new Date().toISOString(),
1428
- filepath,
1429
- processed: true,
1430
- width,
1431
- height,
1432
- timing: { fileOperation: totalFileOpTime, total: totalTime }
1433
- });
1434
-
1435
- resolve();
1436
- });
1437
-
1438
- processedStream.on("error", (error) => {
1439
- reject(error);
1440
- });
1441
- });
1442
- } catch (saveError) {
1443
- // Show full error details for debugging
1444
- emitLog("error", `💥 [BACKGROUND SHARP] File save error: ${saveError.message}`, "screencap");
1445
- emitLog("error", `💥 [BACKGROUND SHARP] Error stack: ${saveError.stack}`, "screencap");
1446
-
1447
- // Only suppress specific libspng/PNG processing errors that occur after disconnection
1448
- if (
1449
- !connected &&
1450
- saveError.message &&
1451
- (saveError.message.includes("libspng") ||
1452
- saveError.message.includes("pngload_buffer") ||
1453
- saveError.message.includes("read error"))
1454
- ) {
1455
- emitLog("debug", `PNG processing error after disconnection (suppressed): ${filepath}`, "screencap");
1456
- } else {
1457
- // Emit all other errors with full details
1458
- localEmitError(saveError, "screencap", `Failed to save screenshot to ${filepath}: ${saveError.message}`);
1459
- }
1460
- } finally {
1461
- // Remove from background operations when complete
1462
- emitLog("info", `🧹 [BACKGROUND SHARP] Cleaning up background operation for ${filepath}`, "screencap");
1463
- backgroundOperations.delete(backgroundOperation);
1464
- }
1465
- })();
1466
-
1467
- // Track the background operation
1468
- backgroundOperations.add(backgroundOperation);
1469
- emitLog("info", "Screenshot processing started in background", "screencap");
1470
- return; // Don't return a stream when saving to file
1471
- } else {
1472
- // Return processed stream
1473
- const processedStream = screencapStream.pipe(sharpTransform);
1474
- const processEndTime = performance.now();
1475
-
1476
- const streamCaptureTime = captureTime - startTime;
1477
- const sharpProcessTime = processEndTime - processStartTime;
1478
- const totalTime = processEndTime - startTime;
1479
-
1480
- // Debug timing variables
1481
- emitLog(
1482
- "debug",
1483
- `🔍 Timing variables: captureTime=${captureTime}, startTime=${startTime}, processEndTime=${processEndTime}, processStartTime=${processStartTime}`,
1484
- "screencap"
1485
- );
1486
-
1487
- emitLog("info", `PNG stream processed and ready`, "screencap");
1488
- try {
1489
- emitLog(
1490
- "info",
1491
- `⏱️ Timing breakdown: Capture=${streamCaptureTime.toFixed(2)}ms, Sharp=${sharpProcessTime.toFixed(2)}ms, Total=${totalTime.toFixed(2)}ms`,
1492
- "screencap"
1493
- );
1494
- } catch (timingError) {
1495
- emitLog(
1496
- "error",
1497
- `⚠️ Timing log error in stream processing: ${timingError.message}. Variables: streamCaptureTime=${streamCaptureTime}, sharpProcessTime=${sharpProcessTime}, totalTime=${totalTime}`,
1498
- "screencap"
1499
- );
1500
- }
1501
-
1502
- // Emit ready event
1503
- emitter.emit("screencap-ready", {
1504
- timestamp: new Date().toISOString(),
1505
- processed: true,
1506
- width,
1507
- height,
1508
- timing: {
1509
- capture: streamCaptureTime,
1510
- sharpProcess: sharpProcessTime,
1511
- total: totalTime
1512
- }
1513
- });
1514
-
1515
- // Emit complete event
1516
- emitter.emit("screencap-complete", {
1517
- timestamp: new Date().toISOString(),
1518
- processed: true,
1519
- width,
1520
- height,
1521
- timing: {
1522
- capture: streamCaptureTime,
1523
- sharpProcess: sharpProcessTime,
1524
- total: totalTime
1525
- }
1526
- });
1527
-
1528
- // Store the processed stream for user access
1529
- lastScreencapData = processedStream;
1530
-
1531
- return processedStream;
1532
- }
1533
- } catch (error) {
1534
- localEmitError(error, "screencap", "Failed to capture screenshot");
1535
-
1536
- // Provide helpful error messages for common issues
1537
- if (error.message && error.message.includes("unauthorized")) {
1538
- emitLog("error", "Device unauthorized - ensure ADB debugging is enabled and device is authorized", "screencap");
1539
- } else if (error.message && error.message.includes("device not found")) {
1540
- emitLog("error", "Device not found - check IP address and ADB connection", "screencap");
1541
- } else if (error.message && error.message.includes("screencap")) {
1542
- emitLog("warn", "Screencap utility may not be available - automatic fallback to framebuffer attempted", "screencap");
1543
- } else if (error.message && error.message.includes("ENOENT")) {
1544
- emitLog("error", `File path error: ${error.message}`, "screencap");
1545
- }
1546
-
1547
- throw error;
1548
- }
1549
- },
1550
-
1551
- /**
1552
- * Takes a thumbnail screenshot with default width of 240px.
1553
- * @public
1554
- * @param {Object} [options={}] - Thumbnail options
1555
- * @param {number} [options.width=240] - Target width for thumbnail (default: 240)
1556
- * @param {number} [options.height] - Target height for thumbnail (optional)
1557
- * @param {string} [options.filepath] - File path to save thumbnail (optional)
1558
- * @returns {Promise<ReadableStream|void>} Returns PNG stream if no filepath, void if saved to file
1559
- * @fires Remote#screencap-start - Emitted when thumbnail capture begins
1560
- * @fires Remote#screencap-captured - Emitted when raw screenshot is captured
1561
- * @fires Remote#screencap-processing - Emitted when image processing begins
1562
- * @fires Remote#screencap-ready - Emitted when final processed stream is ready
1563
- * @fires Remote#screencap-saved - Emitted when thumbnail is saved to file
1564
- * @fires Remote#screencap-complete - Emitted when entire thumbnail operation is complete
1565
- * @fires Remote#log - Emitted with thumbnail operation status
1566
- * @fires Remote#error - Emitted if thumbnail operation fails
1567
- * @example
1568
- * // Basic thumbnail with default 240px width
1569
- * const thumbnailStream = await remote.thumbnail();
1570
- *
1571
- * // Thumbnail with custom dimensions
1572
- * const customThumb = await remote.thumbnail({ width: 320, height: 180 });
1573
- *
1574
- * // Thumbnail saved to file
1575
- * await remote.thumbnail({ filepath: './thumb.png' });
1576
- *
1577
- * // Thumbnail with custom size and file save
1578
- * await remote.thumbnail({ width: 160, height: 90, filepath: './small-thumb.png' });
1579
- */
1580
- async thumbnail(options = {}) {
1581
- // Set default width to 240 if not specified
1582
- const thumbnailOptions = {
1583
- width: 240,
1584
- ...options
1585
- };
1586
-
1587
- emitLog("info", `📸 Taking thumbnail screenshot (${thumbnailOptions.width}x${thumbnailOptions.height || "auto"})`, "thumbnail");
1588
-
1589
- // Call screencap with thumbnail options
1590
- return await this.screencap(thumbnailOptions);
1591
- },
1592
-
1593
- /**
1594
- * Waits until the Android TV device has finished booting.
1595
- * @public
1596
- * @param {number} [timeout=60000] - Maximum time to wait in milliseconds (default: 60 seconds)
1597
- * @returns {Promise<boolean>} Returns true when device has completed booting
1598
- * @fires Remote#log - Emitted with boot monitoring status
1599
- * @fires Remote#error - Emitted if boot monitoring fails
1600
- * @example
1601
- * await remote.waitBootComplete(); // Wait with default 60 second timeout
1602
- * await remote.waitBootComplete(120000); // Wait up to 2 minutes
1603
- */
1604
- async waitBootComplete(timeout = 60000) {
1605
- try {
1606
- emitLog("info", "=== Waiting for device boot completion ===", "waitBootComplete");
1607
-
1608
- // Ensure we're connected before monitoring boot status
1609
- await ensureConnected();
1610
-
1611
- emitLog("info", `Monitoring boot status (timeout: ${timeout}ms)`, "waitBootComplete");
1612
-
1613
- // Use the native device.waitBootComplete() method
1614
- const result = await device.waitBootComplete();
1615
-
1616
- emitLog("info", "✅ Device boot completed successfully", "waitBootComplete");
1617
- emitLog("info", "Device is now ready for operations", "waitBootComplete");
1618
-
1619
- return result;
1620
- } catch (error) {
1621
- emitError(error, "waitBootComplete", "Failed while waiting for boot completion");
1622
-
1623
- // Provide helpful error messages for common issues
1624
- if (error.message && error.message.includes("unauthorized")) {
1625
- emitLog("error", "Device unauthorized - ensure ADB debugging is enabled and device is authorized", "waitBootComplete");
1626
- } else if (error.message && error.message.includes("device not found")) {
1627
- emitLog("error", "Device not found - check IP address and ADB connection", "waitBootComplete");
1628
- } else if (error.message && error.message.includes("timeout")) {
1629
- emitLog("error", `Boot completion timeout after ${timeout}ms - device may still be starting`, "waitBootComplete");
1630
- } else if (error.message && error.message.includes("connection")) {
1631
- emitLog("error", "Connection lost while waiting for boot completion", "waitBootComplete");
1632
- }
1633
-
1634
- throw error;
1635
- }
1636
- },
1637
-
1638
- /**
1639
- * All remote key functions support both promise and callback styles.
1640
- * @public
1641
- */
1642
- press: (() => {
1643
- /**
1644
- * Dynamically generated remote control key functions for Android TV remotes.
1645
- * Keys are loaded from remote-keys.json. Color buttons are excluded.
1646
- * @namespace press
1647
- */
1648
- const obj = {};
1649
- const longObj = {};
1650
- remoteKeys.forEach((key) => {
1651
- /**
1652
- * Sends the corresponding keycode for this remote key.
1653
- * @returns {Promise<any>}
1654
- * @example
1655
- * press.home();
1656
- */
1657
- obj[key] = wrapAsync(function () {
1658
- // Special handling for ok/select
1659
- if (key === "ok" || key === "select") {
1660
- return inputKeycode(keycodes.dpadCenter || keycodes.ok);
1661
- }
1662
- // Map up/down/left/right to dpad keycodes
1663
- if (key === "up") {
1664
- return inputKeycode(keycodes.dpadUp);
1665
- }
1666
- if (key === "down") {
1667
- return inputKeycode(keycodes.dpadDown);
1668
- }
1669
- if (key === "left") {
1670
- return inputKeycode(keycodes.dpadLeft);
1671
- }
1672
- if (key === "right") {
1673
- return inputKeycode(keycodes.dpadRight);
1674
- }
1675
- // Special handling for play/pause
1676
- if (key === "play") {
1677
- return inputKeycode(keycodes.mediaPlay || keycodes.playPause);
1678
- }
1679
- if (key === "pause") {
1680
- return inputKeycode(keycodes.mediaPause || keycodes.playPause);
1681
- }
1682
- if (key === "volumeMute" || key === "mute") {
1683
- return inputKeycode(keycodes.volumeMute || keycodes.mute);
1684
- }
1685
- if (key === "input") {
1686
- return inputKeycode(keycodes.tvInput);
1687
- }
1688
- if (key.startsWith("number")) {
1689
- // e.g. number0
1690
- const num = key.replace("number", "");
1691
- return inputKeycode(keycodes[num]);
1692
- }
1693
- return inputKeycode(keycodes[key]);
1694
- });
1695
-
1696
- /**
1697
- * Sends the corresponding keycode for this remote key as a long press.
1698
- * @returns {Promise<any>}
1699
- * @example
1700
- * press.long.home();
1701
- */
1702
- longObj[key] = wrapAsync(function () {
1703
- if (key === "ok" || key === "select") {
1704
- return inputKeycodeLongPressWrapped(keycodes.dpadCenter || keycodes.ok);
1705
- }
1706
- if (key === "up") {
1707
- return inputKeycodeLongPressWrapped(keycodes.dpadUp);
1708
- }
1709
- if (key === "down") {
1710
- return inputKeycodeLongPressWrapped(keycodes.dpadDown);
1711
- }
1712
- if (key === "left") {
1713
- return inputKeycodeLongPressWrapped(keycodes.dpadLeft);
1714
- }
1715
- if (key === "right") {
1716
- return inputKeycodeLongPressWrapped(keycodes.dpadRight);
1717
- }
1718
- if (key === "play") {
1719
- return inputKeycodeLongPressWrapped(keycodes.mediaPlay || keycodes.playPause);
1720
- }
1721
- if (key === "pause") {
1722
- return inputKeycodeLongPressWrapped(keycodes.mediaPause || keycodes.playPause);
1723
- }
1724
- if (key === "volumeMute" || key === "mute") {
1725
- return inputKeycodeLongPressWrapped(keycodes.volumeMute || keycodes.mute);
1726
- }
1727
- if (key === "input") {
1728
- return inputKeycodeLongPressWrapped(keycodes.tvInput);
1729
- }
1730
- if (key.startsWith("number")) {
1731
- const num = key.replace("number", "");
1732
- return inputKeycodeLongPressWrapped(keycodes[num]);
1733
- }
1734
- return inputKeycodeLongPressWrapped(keycodes[key]);
1735
- });
1736
- });
1737
- // Robust aliasing: always add if dpad keys exist in keycodes
1738
- // if (typeof obj.dpadUp === "function" || keycodes.dpadUp) obj.up = obj.dpadUp;
1739
- // if (typeof obj.dpadDown === "function" || keycodes.dpadDown) obj.down = obj.dpadDown;
1740
- // if (typeof obj.dpadLeft === "function" || keycodes.dpadLeft) obj.left = obj.dpadLeft;
1741
- // if (typeof obj.dpadRight === "function" || keycodes.dpadRight) obj.right = obj.dpadRight;
1742
- // if (typeof obj.dpadCenter === "function" || keycodes.dpadCenter) obj.ok = obj.dpadCenter;
1743
- // if (typeof longObj.dpadUp === "function") longObj.up = longObj.dpadUp;
1744
- // if (typeof longObj.dpadDown === "function") longObj.down = longObj.dpadDown;
1745
- // if (typeof longObj.dpadLeft === "function") longObj.left = longObj.dpadLeft;
1746
- // if (typeof longObj.dpadRight === "function") longObj.right = longObj.dpadRight;
1747
- // if (typeof longObj.dpadCenter === "function") longObj.ok = longObj.dpadCenter;
1748
- obj.long = longObj;
1749
- return obj;
1750
- })(),
1751
-
1752
- /**
1753
- * Keyboard interface for all keys, with text and keycode fallback.
1754
- * @public
1755
- */
1756
- keyboard: {
1757
- /**
1758
- * Sends text input to the device.
1759
- * @public
1760
- * @param {string} text - The text to input.
1761
- * @returns {Promise<any>}
1762
- * @example
1763
- * keyboard.text('hello');
1764
- */
1765
- text: inputTextWrapped,
1766
-
1767
- /**
1768
- * Key subobject: callable and contains all key functions.
1769
- */
1770
- key: Object.assign(
1771
- wrapAsync(function (keyName, options) {
1772
- options = options || {};
1773
- if (!keyboardKeys[keyName]) {
1774
- const error = new Error("Unknown keyboard key: " + keyName);
1775
- emitError(error, "keyboard.key", `Unknown keyboard key: ${keyName}`);
1776
- return Promise.reject(error);
1777
- }
1778
- if (!options.forceKeycode) {
1779
- // Send as text character
1780
- return inputText(keyboardKeys[keyName]);
1781
- }
1782
- // Fallback to keycode if exists
1783
- if (keycodes[keyName]) {
1784
- return inputKeycode(keycodes[keyName]);
1785
- }
1786
- const error = new Error("No keycode available for key: " + keyName);
1787
- emitError(error, "keyboard.key", `No keycode available for key: ${keyName}`);
1788
- return Promise.reject(error);
1789
- }),
1790
- {
1791
- // Dynamically add all keyboard key functions and .keycode subobject
1792
- ...(() => {
1793
- const keyFns = {};
1794
- Object.keys(keyboardKeys).forEach((keyName) => {
1795
- /**
1796
- * Sends this key using inputText or keycode fallback.
1797
- * @returns {Promise<any>}
1798
- * @example
1799
- * keyboard.key.a();
1800
- */
1801
- keyFns[keyName] = wrapAsync(function (options) {
1802
- options = options || {};
1803
- if (!options.forceKeycode) {
1804
- return inputText(keyboardKeys[keyName]);
1805
- }
1806
- if (keycodes[keyName]) {
1807
- return inputKeycode(keycodes[keyName]);
1808
- }
1809
- const error = new Error("No keycode available for key: " + keyName);
1810
- emitError(error, "keyboard.key", `No keycode available for key: ${keyName}`);
1811
- return Promise.reject(error);
1812
- });
1813
- /**
1814
- * Sends this key using keycode only.
1815
- * @returns {Promise<any>}
1816
- * @example
1817
- * keyboard.key.a.keycode();
1818
- */
1819
- if (keycodes[keyName]) {
1820
- keyFns[keyName].keycode = wrapAsync(function () {
1821
- return inputKeycode(keycodes[keyName]);
1822
- });
1823
- }
1824
- });
1825
- return keyFns;
1826
- })(),
1827
-
1828
- /**
1829
- * Shift subobject for shifted keys.
1830
- */
1831
- shift: (() => {
1832
- const shiftFns = {};
1833
- Object.keys(keyboardKeys).forEach((keyName) => {
1834
- const char = keyboardKeys[keyName];
1835
- const shiftedChar = getShiftedCharacter(keyName, char);
1836
-
1837
- // Only create shift function if the character actually changes when shifted
1838
- if (shiftedChar !== char) {
1839
- /**
1840
- * Sends this key with shift using inputText (shifted character).
1841
- * Note: No keycode method available for shift variants since Android
1842
- * ADB doesn't support sending multiple keycodes simultaneously.
1843
- * @returns {Promise<any>}
1844
- * @example
1845
- * keyboard.key.shift.a(); // Sends "A"
1846
- */
1847
- shiftFns[keyName] = wrapAsync(function () {
1848
- // Send shifted character as text
1849
- return inputText(shiftedChar);
1850
- });
1851
- }
1852
- });
1853
- return shiftFns;
1854
- })()
1855
- }
1856
- )
1857
- }
1858
- };
1859
-
1860
- // Handle initialization if autoConnect is enabled
1861
- if (autoConnect) {
1862
- try {
1863
- // Wait for initialization to complete
1864
- await realInitPromise;
1865
- } catch (error) {
1866
- // If initialization fails, still return the remote but emit error
1867
- emitError(error, "createRemote", "Auto-connect failed during initialization");
1868
- }
1869
- }
1870
-
1871
- return remoteApi;
1872
- }
1873
-
1874
- /**
1875
- * Create and return a ready-to-use Android TV Remote instance.
1876
- * @public
1877
- * @param {RemoteConfig} config - Configuration for the remote.
1878
- * @returns {Promise<Remote>} Resolves with a ready remote instance.
1879
- *
1880
- * @description
1881
- * Alias for createRemote() - both functions now return ready-to-use remote instances.
1882
- *
1883
- * @example
1884
- * // ESM with event handling
1885
- * const remote = await createAndroidTVRemote({ ip: "192.168.1.100" });
1886
- * remote.on('log', (data) => console.log(data));
1887
- * remote.on('error', (data) => console.error(data));
1888
- */
1889
- export async function createAndroidTVRemote(config) {
1890
- // Now createRemote is async and handles initialization internally
1891
- return await createRemote(config);
1892
- }
1893
-
1894
- // Add static create method to the default export
1895
- createRemote.create = createAndroidTVRemote;