@cldmv/node-android-tv-remote 1.5.5 → 2.1.0

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