@cldmv/node-android-tv-remote 2.0.0 → 2.1.7

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,49 +1,51 @@
1
1
  /**
2
+ *
2
3
  * @Project: @cldmv/node-android-tv-remote
3
4
  * @Filename: /src/lib/android-tv-remote.mjs
4
- * @Date: 2025-10-15 10:19:05 -07:00 (1760548745)
5
- * @Author: Nate Hyson <CLDMV>
5
+ * @Date: 2025-10-15T10:19:05-07:00 (1760548745)
6
+ * @Author: Nate Corcoran <CLDMV>
6
7
  * @Email: <Shinrai@users.noreply.github.com>
7
8
  * -----
8
- * @Last modified by: Nate Hyson <CLDMV> (Shinrai@users.noreply.github.com)
9
- * @Last modified time: 2025-10-15 11:13:38 -07:00 (1760552018)
9
+ * @Last modified by: Nate Corcoran <CLDMV> (Shinrai@users.noreply.github.com)
10
+ * @Last modified time: 2026-10-02T12:16:15-07:00 (1790968575)
10
11
  * -----
11
- * @Copyright: Copyright (c) 2013-2025 Catalyzed Motivation Inc. All rights reserved.
12
+ * @Copyright: Copyright (c) 2013-2026 Catalyzed Motivation Inc. All rights reserved.
13
+ *
12
14
  */
13
15
 
14
16
  /**
15
17
  * Android TV Remote module - Event-driven ADB remote control for Android TV devices.
16
- *
18
+ *
17
19
  * @module android-tv-remote
18
- *
20
+ *
19
21
  * @description
20
22
  * This module provides an event-driven interface for controlling Android TV devices via ADB.
21
23
  * All operations emit events instead of console logging, allowing for better integration
22
24
  * and programmatic handling of device communication.
23
- *
25
+ *
24
26
  * @example
25
27
  * // ESM usage with event handling
26
28
  * import createRemote from "@cldmv/node-android-tv-remote";
27
- *
29
+ *
28
30
  * const remote = createRemote({ ip: "192.168.1.100" });
29
- *
31
+ *
30
32
  * // Listen for log events
31
33
  * remote.on('log', (data) => {
32
34
  * console.log(`[${data.level}] ${data.message}`, data.source);
33
35
  * });
34
- *
36
+ *
35
37
  * // Listen for errors
36
38
  * remote.on('error', (data) => {
37
39
  * console.error(`Error from ${data.source}:`, data.error.message);
38
40
  * });
39
- *
41
+ *
40
42
  * // Use the remote
41
43
  * await remote.press.home();
42
- *
44
+ *
43
45
  * @example
44
46
  * // Static create method
45
47
  * import { createAndroidTVRemote } from "@cldmv/node-android-tv-remote";
46
- *
48
+ *
47
49
  * const remote = await createAndroidTVRemote({ ip: "192.168.1.100" });
48
50
  * remote.on('log', console.log);
49
51
  * await remote.press.play();
@@ -70,7 +72,7 @@
70
72
  * @typedef {Object} LogEventData
71
73
  * @property {string} level - Log level: 'info', 'warn', 'error', 'debug'.
72
74
  * @property {string} message - Log message.
73
- * @property {string} source - Source of the log message (e.g., 'connect', 'disconnect', 'handleSettings').
75
+ * @property {string} source - Source of the log message (e.g., 'connect', 'disconnect', 'setSettings').
74
76
  * @property {string} timestamp - ISO timestamp of when the log was created.
75
77
  * @property {any} [data] - Optional additional data related to the log.
76
78
  */
@@ -87,25 +89,34 @@
87
89
  /**
88
90
  * Android TV Remote instance with event emission capabilities.
89
91
  * @typedef {Object} Remote
90
- * @property {function(string, boolean=): Promise<void>} handleSettings - Get or set Android settings via ADB.
92
+ * @property {function(string=): Promise<void>} setSettings - Configure or retrieve Android TV settings for optimal remote operation.
91
93
  * @property {function(function(Error=, any=)=): Promise<void>|undefined} connect - Connect to the device. Supports both promise and callback styles.
92
94
  * @property {function(function(Error=, any=)=): Promise<void>|undefined} disconnect - Disconnect from the device. Supports both promise and callback styles.
93
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).
94
99
  * @property {function(boolean=): Promise<"connected"|"disconnected"|"unknown">} getConnectionStatus - Returns the current connection status; optionally performs a live check.
95
100
  * @property {boolean} isConnected - True if the module believes it is connected (internal state, not a live check).
96
101
  * @property {Object} press - Remote control key functions for Android TV remotes.
97
102
  * @property {Object} keyboard - Keyboard interface for all keys, with text and keycode fallback.
98
103
  * @property {Object} keyboard.key - Contains all key functions.
99
104
  * @property {Object} keyboard.key.shift - Contains all shifted key functions.
100
- *
105
+ *
101
106
  * @property {function(string, Function): Remote} on - Add event listener. Returns remote instance for chaining.
102
107
  * @property {function(string, Function): Remote} off - Remove event listener. Returns remote instance for chaining.
103
108
  * @property {function(string, Function): Remote} once - Add one-time event listener. Returns remote instance for chaining.
104
109
  * @property {function(string, ...any): boolean} emit - Emit an event. Returns true if event had listeners.
105
- *
110
+ *
106
111
  * @fires Remote#log - Emitted for informational messages, warnings, and debug info.
107
112
  * @fires Remote#error - Emitted when errors occur during ADB operations.
108
- *
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
+ *
109
120
  * @example
110
121
  * // Event handling examples
111
122
  * remote.on('log', (data) => {
@@ -117,11 +128,11 @@
117
128
  * console.log(`INFO [${data.source}]: ${data.message}`);
118
129
  * }
119
130
  * });
120
- *
131
+ *
121
132
  * remote.on('error', (data) => {
122
133
  * console.error(`FATAL ERROR from ${data.source}:`);
123
134
  * console.error(data.error.stack || data.error.message);
124
- *
135
+ *
125
136
  * // Handle specific error types
126
137
  * if (data.error.message.includes('device unauthorized')) {
127
138
  * console.log('Please authorize ADB on your Android TV device');
@@ -131,7 +142,15 @@
131
142
 
132
143
  import adbkit from "@devicefarmer/adbkit";
133
144
  import { EventEmitter } from "events";
134
- const Adb = adbkit.Adb;
145
+ import { createWriteStream } from "fs";
146
+ import sharp from "sharp";
147
+ // @devicefarmer/adbkit is plain CJS (`exports.default` / `exports.Adb` both
148
+ // getter re-exports of the same class). Under plain Node's ESM/CJS interop,
149
+ // the default import resolves to `module.exports` (so `.Adb` holds the
150
+ // class); under Vite/Rollup-based CJS interop (e.g. vitest with the module
151
+ // inlined), the default import unwraps straight to the class itself. Cover
152
+ // both shapes rather than assuming one.
153
+ const Adb = adbkit.Adb ?? adbkit;
135
154
 
136
155
  /**
137
156
  * Wraps an async function to support both promise and callback styles.
@@ -171,7 +190,7 @@ function emitLog(level, message, source = "android-tv-remote", data = null) {
171
190
  ...(data && { data })
172
191
  });
173
192
  }
174
-
193
+
175
194
  /**
176
195
  * Emit an error event with structured data.
177
196
  * @private
@@ -180,6 +199,15 @@ function emitLog(level, message, source = "android-tv-remote", data = null) {
180
199
  * @param {string} [message] - Additional error message.
181
200
  */
182
201
  function emitError(error, source = "android-tv-remote", message = null) {
202
+ // Filter out libspng/PNG processing errors that occur after disconnection
203
+ // These are common when background operations try to process data after disconnect
204
+ const errorMsg = error.message || "";
205
+ if (errorMsg.includes("libspng") || errorMsg.includes("pngload_buffer") || errorMsg.includes("read error")) {
206
+ // Log as debug instead of error to avoid noise
207
+ emitLog("debug", `PNG processing error (likely post-disconnect): ${errorMsg}`, source);
208
+ return;
209
+ }
210
+
183
211
  emitter.emit("error", {
184
212
  error,
185
213
  source,
@@ -187,7 +215,7 @@ function emitError(error, source = "android-tv-remote", message = null) {
187
215
  timestamp: new Date().toISOString()
188
216
  });
189
217
  }
190
-
218
+
191
219
  /**
192
220
  * Handles disconnect and connection errors, emits helpful messages.
193
221
  * Also provides onboarding steps for common authentication and connection issues.
@@ -206,25 +234,49 @@ function handleDisconnectError(err) {
206
234
 
207
235
  if (err.message && (err.message.includes("device unauthorized") || err.message.includes("failed to authenticate"))) {
208
236
  emitError(err, "handleDisconnectError", "Device unauthorized - authentication required");
209
- 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");
210
- emitLog("info", "If you do not see a prompt, try disconnecting and reconnecting the device, or reboot your TV.", "handleDisconnectError");
211
- emitLog("info", "If the problem persists, remove the device from the list of authorized ADB devices in Developer Options and try again.", "handleDisconnectError");
212
- emitLog("info", "Tip: In Developer Options on your TV, try toggling 'ADB Debugging' off and then back on. This often resolves authentication issues.", "handleDisconnectError");
237
+ emitLog(
238
+ "error",
239
+ "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.",
240
+ "handleDisconnectError"
241
+ );
242
+ emitLog(
243
+ "info",
244
+ "If you do not see a prompt, try disconnecting and reconnecting the device, or reboot your TV.",
245
+ "handleDisconnectError"
246
+ );
247
+ emitLog(
248
+ "info",
249
+ "If the problem persists, remove the device from the list of authorized ADB devices in Developer Options and try again.",
250
+ "handleDisconnectError"
251
+ );
252
+ emitLog(
253
+ "info",
254
+ "Tip: In Developer Options on your TV, try toggling 'ADB Debugging' off and then back on. This often resolves authentication issues.",
255
+ "handleDisconnectError"
256
+ );
213
257
  }
214
-
258
+
215
259
  if (err.message && (err.message.includes("actively refused") || err.message.includes("No connection could be made"))) {
216
260
  emitError(err, "handleDisconnectError", "Connection refused - ADB not enabled");
217
- emitLog("error", "The device refused the connection. To enable ADB, follow these steps on your Android TV or Fire TV:", "handleDisconnectError");
261
+ emitLog(
262
+ "error",
263
+ "The device refused the connection. To enable ADB, follow these steps on your Android TV or Fire TV:",
264
+ "handleDisconnectError"
265
+ );
218
266
  emitLog("info", "1. Open Settings > Device Preferences > About (or My Fire TV > About)", "handleDisconnectError");
219
267
  emitLog("info", "2. Scroll to 'Build' and press OK 7 times to enable Developer Options", "handleDisconnectError");
220
268
  emitLog("info", "3. Go back to Settings > Device Preferences > Developer Options", "handleDisconnectError");
221
- emitLog("info", "4. Enable 'Developer Options' if needed, then enable 'ADB Debugging' and 'Apps from Unknown Sources'", "handleDisconnectError");
269
+ emitLog(
270
+ "info",
271
+ "4. Enable 'Developer Options' if needed, then enable 'ADB Debugging' and 'Apps from Unknown Sources'",
272
+ "handleDisconnectError"
273
+ );
222
274
  emitLog("info", "5. Ensure your TV and computer are on the same network", "handleDisconnectError");
223
275
  emitLog("info", "6. On your computer, run: adb connect <device-ip>:5555", "handleDisconnectError");
224
276
  emitLog("info", "7. Accept the authorization prompt on your TV", "handleDisconnectError");
225
277
  emitLog("info", "If you do not see 'Developer Options', repeat step 2 until it appears.", "handleDisconnectError");
226
278
  }
227
-
279
+
228
280
  return err;
229
281
  }
230
282
 
@@ -235,6 +287,48 @@ function handleDisconnectError(err) {
235
287
  * @see https://developer.android.com/reference/android/view/KeyEvent
236
288
  */
237
289
  import keycodes from "../data/keycodes.json" with { type: "json" };
290
+ import keyboardKeys from "../data/keyboard-keys.json" with { type: "json" };
291
+
292
+ /**
293
+ * Gets the shifted character for a given key.
294
+ * @private
295
+ * @param {string} keyName - The key name
296
+ * @param {string} char - The original character
297
+ * @returns {string} The shifted character
298
+ */
299
+ function getShiftedCharacter(keyName, char) {
300
+ // Handle letters - convert to uppercase
301
+ if (/^[a-z]$/.test(char)) {
302
+ return char.toUpperCase();
303
+ }
304
+
305
+ // Handle shifted symbols
306
+ const shiftMap = {
307
+ "1": "!",
308
+ "2": "@",
309
+ "3": "#",
310
+ "4": "$",
311
+ "5": "%",
312
+ "6": "^",
313
+ "7": "&",
314
+ "8": "*",
315
+ "9": "(",
316
+ "0": ")",
317
+ "-": "_",
318
+ "=": "+",
319
+ "[": "{",
320
+ "]": "}",
321
+ "\\": "|",
322
+ ";": ":",
323
+ "'": '"',
324
+ ",": "<",
325
+ ".": ">",
326
+ "/": "?",
327
+ "`": "~"
328
+ };
329
+
330
+ return shiftMap[char] || char;
331
+ }
238
332
 
239
333
  /**
240
334
  * Remote keys mapping loaded from JSON file.
@@ -244,13 +338,13 @@ import keycodes from "../data/keycodes.json" with { type: "json" };
244
338
  import remoteKeys from "../data/remote-keys.json" with { type: "json" };
245
339
 
246
340
  /**
247
- * Factory function to create a Remote instance.
341
+ * Factory function to create a ready-to-use Remote instance.
248
342
  * @function
249
343
  * @public
250
344
  * @param {RemoteConfig} config - Configuration for the remote.
251
- * @returns {Remote}
345
+ * @returns {Promise<Remote>} A promise that resolves to a ready-to-use remote instance
252
346
  */
253
- export default function createRemote(config) {
347
+ export default async function createRemote(config) {
254
348
  // Ensure config is an object and has the required 'ip' property
255
349
  if (!config || typeof config !== "object" || !config.ip) {
256
350
  throw new Error("Missing required 'ip' property in RemoteConfig.");
@@ -265,6 +359,28 @@ export default function createRemote(config) {
265
359
  });
266
360
  const device = client.getDevice(host);
267
361
  let connected = false;
362
+ let backgroundOperations = new Set();
363
+
364
+ /**
365
+ * Local emitError function that has access to connection state
366
+ * @private
367
+ * @param {Error} error - The error object
368
+ * @param {string} [source] - Source of the error
369
+ * @param {string} [message] - Additional error message
370
+ */
371
+ function localEmitError(error, source = "android-tv-remote", message = null) {
372
+ // Filter out libspng/PNG processing errors that occur after disconnection
373
+ const errorMsg = error.message || "";
374
+ if (!connected && (errorMsg.includes("libspng") || errorMsg.includes("pngload_buffer") || errorMsg.includes("read error"))) {
375
+ // Log as debug instead of error to avoid noise
376
+ emitLog("debug", `PNG processing error (post-disconnect): ${errorMsg}`, source);
377
+ return;
378
+ }
379
+
380
+ // Use global emitError for other cases
381
+ emitError(error, source, message);
382
+ }
383
+
268
384
  const autoConnect = config.autoConnect !== false; // default true
269
385
  const autoDisconnect = config.autoDisconnect === true; // default false
270
386
  const disconnectTimeout = typeof config.disconnectTimeout === "number" ? config.disconnectTimeout : 10;
@@ -458,27 +574,52 @@ export default function createRemote(config) {
458
574
  * @internal
459
575
  * @returns {Promise<void>}
460
576
  */
461
- function disconnect() {
577
+ async function disconnect() {
462
578
  if (disconnectTimer) {
463
579
  clearTimeout(disconnectTimer);
464
580
  disconnectTimer = null;
465
581
  }
466
582
  stopHeartbeat();
467
- return client
468
- .disconnect(ip, port)
469
- .then(() => {
583
+
584
+ // Wait for all background operations to complete before disconnecting
585
+ if (backgroundOperations.size > 0) {
586
+ if (!quiet)
587
+ emitLog("info", `🔄 [DISCONNECT] Waiting for ${backgroundOperations.size} background operations to complete...`, "disconnect");
588
+ const waitStartTime = performance.now();
589
+ try {
590
+ await Promise.allSettled([...backgroundOperations]);
591
+ const waitEndTime = performance.now();
592
+ if (!quiet)
593
+ emitLog(
594
+ "info",
595
+ `✅ [DISCONNECT] All background operations completed in ${(waitEndTime - waitStartTime).toFixed(2)}ms`,
596
+ "disconnect"
597
+ );
598
+ } catch (error) {
599
+ const waitEndTime = performance.now();
600
+ emitLog(
601
+ "warn",
602
+ `⚠️ [DISCONNECT] Some background operations failed after ${(waitEndTime - waitStartTime).toFixed(2)}ms: ${error.message}`,
603
+ "disconnect"
604
+ );
605
+ }
606
+ } else {
607
+ if (!quiet) emitLog("info", `✅ [DISCONNECT] No background operations to wait for`, "disconnect");
608
+ }
609
+
610
+ try {
611
+ await client.disconnect(ip, port);
612
+ connected = false;
613
+ if (!quiet) emitLog("info", `Disconnected from ${host}`, "disconnect");
614
+ return true;
615
+ } catch (err) {
616
+ if (err.message && err.message.includes("disconnected")) {
617
+ if (!quiet) emitLog("warn", "Device already disconnected before explicit disconnect call", "disconnect");
470
618
  connected = false;
471
- if (!quiet) emitLog("info", `Disconnected from ${host}`, "disconnect");
472
619
  return true;
473
- })
474
- .catch((err) => {
475
- if (err.message && err.message.includes("disconnected")) {
476
- if (!quiet) emitLog("warn", "Device already disconnected before explicit disconnect call", "disconnect");
477
- connected = false;
478
- return true;
479
- }
480
- return handleDisconnectError(err);
481
- });
620
+ }
621
+ return handleDisconnectError(err);
622
+ }
482
623
  }
483
624
  const disconnectWrapped = wrapAsync(disconnect);
484
625
 
@@ -526,26 +667,6 @@ export default function createRemote(config) {
526
667
  }
527
668
  const inputTextWrapped = wrapAsync(inputText);
528
669
 
529
- const keyboardKeys = {};
530
- const keyboardShiftKeys = {};
531
-
532
- for (let i = 0; i < 26; i++) {
533
- const letter = String.fromCharCode(97 + i);
534
- const code = 29 + i;
535
- keyboardKeys[letter] = ((code) => () => inputKeycode(code))(code);
536
- keyboardShiftKeys[letter] = ((code) => () => {
537
- return inputKeycode(keycodes.shiftLeft).then(() => inputKeycode(code));
538
- })(code);
539
- }
540
-
541
- keyboardKeys.enter = () => inputKeycode(keycodes.enter);
542
- keyboardKeys.space = () => inputKeycode(keycodes.space);
543
- keyboardKeys.del = () => inputKeycode(keycodes.del);
544
-
545
- keyboardShiftKeys.enter = () => {
546
- return inputKeycode(keycodes.shiftLeft).then(() => inputKeycode(keycodes.enter));
547
- };
548
-
549
670
  /**
550
671
  * Returns the current connection status as tracked by the module.
551
672
  * Optionally performs a live check against adb devices if requested.
@@ -611,6 +732,13 @@ export default function createRemote(config) {
611
732
  return Object.keys(this.press).filter((k) => k !== "long" && typeof this.press[k] === "function");
612
733
  }
613
734
 
735
+ /**
736
+ * Variable to store the last screencap data (PNG buffer) after processing.
737
+ * Updated every time screencap or thumbnail is called, regardless of options.
738
+ * @type {Buffer|null}
739
+ */
740
+ let lastScreencapData = null;
741
+
614
742
  const remoteApi = {
615
743
  /**
616
744
  * Promise that resolves if initial auto-connect succeeds, or rejects if it fails.
@@ -619,7 +747,7 @@ export default function createRemote(config) {
619
747
  * remote.initPromise.then(() => { ... }).catch((err) => { ... });
620
748
  */
621
749
  initPromise,
622
-
750
+
623
751
  /**
624
752
  * Add event listener.
625
753
  * @public
@@ -634,7 +762,7 @@ export default function createRemote(config) {
634
762
  emitter.on(event, listener);
635
763
  return remoteApi;
636
764
  },
637
-
765
+
638
766
  /**
639
767
  * Remove event listener.
640
768
  * @public
@@ -648,7 +776,7 @@ export default function createRemote(config) {
648
776
  emitter.off(event, listener);
649
777
  return remoteApi;
650
778
  },
651
-
779
+
652
780
  /**
653
781
  * Add one-time event listener.
654
782
  * @public
@@ -662,7 +790,7 @@ export default function createRemote(config) {
662
790
  emitter.once(event, listener);
663
791
  return remoteApi;
664
792
  },
665
-
793
+
666
794
  /**
667
795
  * Emit an event.
668
796
  * @public
@@ -713,64 +841,214 @@ export default function createRemote(config) {
713
841
  get isConnected() {
714
842
  return isConnected();
715
843
  },
844
+
716
845
  /**
717
- * Get or set Android settings via ADB.
846
+ * Returns the last screencap data (PNG stream) captured by screencap() or thumbnail().
847
+ * Updated every time a screenshot is taken, regardless of options used.
848
+ * @readonly
849
+ * @type {ReadableStream|null}
850
+ * @example
851
+ * await remote.screencap({ filepath: './screenshot.png' });
852
+ * console.log('Last screencap stream:', remote.lastScreencapData);
853
+ *
854
+ * // Use the cached stream data
855
+ * if (remote.lastScreencapData) {
856
+ * remote.lastScreencapData.pipe(someOtherStream);
857
+ * }
858
+ */
859
+ get lastScreencapData() {
860
+ return lastScreencapData;
861
+ },
862
+ /**
863
+ * Configure or retrieve Android TV settings for optimal remote operation.
864
+ * Handles power management, display settings, and system configuration.
718
865
  * @public
719
- * @param {string} mode - 'get' or 'set'.
720
- * @param {boolean} [overrideQuiet] - Optionally override the quiet flag for this call.
721
- * @returns {Promise<void>}
722
- * @fires Remote#log - Emitted with settings operation status and results
866
+ * @param {string} [mode='set'] - 'get' to retrieve settings, 'set' to configure settings
867
+ * @fires Remote#log - Emitted with settings operation results
723
868
  * @fires Remote#error - Emitted if settings operations fail
724
869
  * @example
725
- * remote.handleSettings('get', false);
870
+ * await remote.setSettings(); // Set all optimal settings
871
+ * await remote.setSettings('get'); // Get current settings values
726
872
  */
727
- handleSettings(mode, overrideQuiet) {
728
- const keys = [
729
- { ns: "system", key: "screen_off_timeout", value: 2147483647 },
730
- { ns: "secure", key: "sleep_timeout", value: 0 },
731
- { ns: "global", key: "stay_on_while_plugged_in", value: 3 }
732
- ];
733
- const useQuiet = typeof overrideQuiet === "boolean" ? overrideQuiet : quiet;
734
- return client
735
- .connect(ip, port)
736
- .then(() => {
737
- if (!useQuiet) emitLog("info", `Connected to ${host}`, "handleSettings");
738
- let chain = Promise.resolve();
739
- keys.forEach((item) => {
740
- chain = chain.then(() => {
741
- let cmd;
742
- if (mode === "set") {
743
- cmd = `settings put ${item.ns} ${item.key} ${item.value}`;
744
- } else {
745
- cmd = `settings get ${item.ns} ${item.key}`;
746
- }
747
- return device
748
- .shell(cmd)
749
- .then(Adb.util.readAll)
750
- .then((result) => {
751
- if (!useQuiet) {
752
- if (mode === "set") {
753
- emitLog("info", `Set ${item.ns} ${item.key} to ${item.value}`, "handleSettings");
754
- } else {
755
- emitLog("info", `${item.ns} ${item.key}: ${result.toString().trim()}`, "handleSettings");
756
- }
757
- }
758
- });
759
- });
760
- });
761
- return chain;
762
- })
763
- .then(() => client.disconnect(ip, port))
764
- .then(() => {
765
- if (!useQuiet) emitLog("info", "Disconnected cleanly", "handleSettings");
766
- })
767
- .catch((err) => {
768
- if (err.message && err.message.includes("disconnected")) {
769
- if (!useQuiet) emitLog("warn", "Device already disconnected before explicit disconnect call", "handleSettings");
770
- } else {
771
- return handleDisconnectError(err);
873
+ async setSettings(mode = "set") {
874
+ try {
875
+ emitLog("info", `=== ${mode === "set" ? "Configuring" : "Retrieving"} Android TV settings ===`, "setSettings");
876
+
877
+ await ensureConnected();
878
+
879
+ // Core settings for power management and display
880
+ const coreSettings = [
881
+ { ns: "system", key: "screen_off_timeout", value: 2147483647 },
882
+ { ns: "secure", key: "sleep_timeout", value: 0 },
883
+ { ns: "global", key: "stay_on_while_plugged_in", value: 3 }
884
+ ];
885
+
886
+ // Process core settings
887
+ for (const item of coreSettings) {
888
+ const cmd = mode === "set" ? `settings put ${item.ns} ${item.key} ${item.value}` : `settings get ${item.ns} ${item.key}`;
889
+
890
+ const result = await device.shell(cmd).then(Adb.util.readAll);
891
+
892
+ if (!quiet) {
893
+ if (mode === "set") {
894
+ emitLog("info", `Set ${item.ns} ${item.key} to ${item.value}`, "setSettings");
895
+ } else {
896
+ emitLog("info", `${item.ns} ${item.key}: ${result.toString().trim()}`, "setSettings");
897
+ }
772
898
  }
773
- });
899
+ }
900
+
901
+ // Additional settings (only applied in set mode)
902
+ if (mode === "set") {
903
+ emitLog("info", "Setting additional display and power settings", "setSettings");
904
+
905
+ const additionalSettings = [
906
+ "settings put system screen_brightness_mode 0", // Manual brightness
907
+ "settings put system screen_brightness 255", // Max brightness
908
+ "svc power stayon true" // Stay on while plugged
909
+ ];
910
+
911
+ for (const cmd of additionalSettings) {
912
+ if (!quiet) emitLog("info", `Running: ${cmd}`, "setSettings");
913
+ await device.shell(cmd);
914
+ }
915
+ }
916
+
917
+ emitLog("info", `✅ Android TV settings ${mode === "set" ? "configured" : "retrieved"} successfully`, "setSettings");
918
+ } catch (error) {
919
+ localEmitError(error, "setSettings", `Failed to ${mode === "set" ? "configure" : "retrieve"} Android TV settings`);
920
+ throw error;
921
+ }
922
+ },
923
+
924
+ /**
925
+ * Ensures the Android TV device is awake and responsive.
926
+ * Performs comprehensive power state checking and correction.
927
+ * @public
928
+ * @returns {Promise<boolean>} Returns true if device is awake and ready
929
+ * @fires Remote#log - Emitted with power state and wake-up process information
930
+ * @fires Remote#error - Emitted if wake-up process fails
931
+ * @example
932
+ * await remote.ensureAwake();
933
+ */
934
+ async ensureAwake() {
935
+ try {
936
+ emitLog("info", "=== Starting ensureAwake sequence ===", "ensureAwake");
937
+
938
+ await ensureConnected();
939
+
940
+ // Helper function to parse power state from dumpsys output
941
+ const parsePowerState = (output) => {
942
+ const mIsPoweredMatch = output.match(/^\s*mIsPowered=([a-zA-Z0-9]+)/m);
943
+ const mWakefulnessMatch = output.match(/^\s*mWakefulness=([a-zA-Z0-9]+)/m);
944
+ const mDisplayReadyMatch = output.match(/^\s*mDisplayReady=([a-zA-Z0-9]+)/m);
945
+ return {
946
+ mIsPowered: mIsPoweredMatch ? mIsPoweredMatch[1] : "unknown",
947
+ mWakefulness: mWakefulnessMatch ? mWakefulnessMatch[1] : "unknown",
948
+ mDisplayReady: mDisplayReadyMatch ? mDisplayReadyMatch[1] : "unknown"
949
+ };
950
+ };
951
+
952
+ // Helper function to get current power state
953
+ const getCurrentPowerState = async () => {
954
+ const output = await device
955
+ .shell("dumpsys power")
956
+ .then(Adb.util.readAll)
957
+ .then((b) => b.toString());
958
+ return parsePowerState(output);
959
+ };
960
+
961
+ // Helper function to emit power state
962
+ const emitPowerState = (parsed, context = "") => {
963
+ const prefix = context ? `${context} ` : "";
964
+ emitLog("info", `${prefix}Power State:`, "ensureAwake");
965
+ emitLog("info", ` mIsPowered: ${parsed.mIsPowered}`, "ensureAwake");
966
+ emitLog("info", ` mWakefulness: ${parsed.mWakefulness}`, "ensureAwake");
967
+ emitLog("info", ` mDisplayReady: ${parsed.mDisplayReady}`, "ensureAwake");
968
+ };
969
+
970
+ // Check initial power state
971
+ const initialPowerState = await getCurrentPowerState();
972
+ emitPowerState(initialPowerState, "Initial");
973
+
974
+ // Determine what commands need to be sent
975
+ const commandsToSend = [];
976
+
977
+ if (initialPowerState.mIsPowered !== "true") {
978
+ emitLog("info", `Device not powered (${initialPowerState.mIsPowered}), will send POWER keycode`, "ensureAwake");
979
+ commandsToSend.push({ keycode: keycodes.power, reason: "power on device" });
980
+ } else {
981
+ emitLog("info", "✅ Device already powered", "ensureAwake");
982
+ }
983
+
984
+ if (initialPowerState.mWakefulness !== "Awake") {
985
+ emitLog("info", `Device not awake (${initialPowerState.mWakefulness}), will send WAKEUP keycode`, "ensureAwake");
986
+ commandsToSend.push({ keycode: keycodes.wakeUp, reason: "wake up device" });
987
+ } else {
988
+ emitLog("info", "✅ Device already awake", "ensureAwake");
989
+ }
990
+
991
+ if (initialPowerState.mDisplayReady !== "true") {
992
+ emitLog("info", `Display not ready (${initialPowerState.mDisplayReady}), will send POWER keycode`, "ensureAwake");
993
+ commandsToSend.push({ keycode: keycodes.power, reason: "ensure display ready" });
994
+ } else {
995
+ emitLog("info", "✅ Display already ready", "ensureAwake");
996
+ }
997
+
998
+ // Send required commands
999
+ if (commandsToSend.length > 0) {
1000
+ emitLog("info", `Sending ${commandsToSend.length} keycode(s)...`, "ensureAwake");
1001
+
1002
+ for (const cmd of commandsToSend) {
1003
+ emitLog("info", `Sending keycode ${cmd.keycode} to ${cmd.reason}`, "ensureAwake");
1004
+ await inputKeycode(cmd.keycode);
1005
+
1006
+ // Brief delay between commands
1007
+ await new Promise((resolve) => setTimeout(resolve, 500));
1008
+ }
1009
+
1010
+ // Wait for commands to take effect
1011
+ emitLog("info", "Waiting for commands to take effect...", "ensureAwake");
1012
+ await new Promise((resolve) => setTimeout(resolve, 3000));
1013
+ }
1014
+
1015
+ // Verify final state
1016
+ const finalPowerState = await getCurrentPowerState();
1017
+ emitPowerState(finalPowerState, "Final");
1018
+
1019
+ // Check for persistent issues
1020
+ const issues = [];
1021
+ if (finalPowerState.mIsPowered !== "true") {
1022
+ issues.push(`Device still not powered: ${finalPowerState.mIsPowered}`);
1023
+ }
1024
+ if (finalPowerState.mWakefulness !== "Awake") {
1025
+ issues.push(`Device still not awake: ${finalPowerState.mWakefulness}`);
1026
+ }
1027
+ if (finalPowerState.mDisplayReady !== "true") {
1028
+ issues.push(`Display still not ready: ${finalPowerState.mDisplayReady}`);
1029
+ }
1030
+
1031
+ if (issues.length === 0) {
1032
+ emitLog("info", "🎉 ensureAwake completed successfully - device is fully ready", "ensureAwake");
1033
+ return true;
1034
+ } else {
1035
+ // Log warnings for persistent issues
1036
+ for (const issue of issues) {
1037
+ emitLog("warn", issue, "ensureAwake");
1038
+ }
1039
+
1040
+ // Only throw error if critical issues persist
1041
+ emitError(
1042
+ new Error(`ensureAwake failed with ${issues.length} persistent issue(s): ${issues.join(", ")}`),
1043
+ "ensureAwake",
1044
+ "Device may not be fully responsive"
1045
+ );
1046
+ return false;
1047
+ }
1048
+ } catch (error) {
1049
+ emitError(error, "ensureAwake", "Failed to ensure device is awake");
1050
+ throw error;
1051
+ }
774
1052
  },
775
1053
 
776
1054
  /**
@@ -784,9 +1062,10 @@ export default function createRemote(config) {
784
1062
  * await remote.connect();
785
1063
  * remote.connect((err) => { ... });
786
1064
  */
787
- connect: /**
788
- * @type {(cb?: (err?: Error, result?: any) => any) => Promise<any> | undefined}
789
- */ (connectWrapped),
1065
+ connect:
1066
+ /**
1067
+ * @type {(cb?: (err?: Error, result?: any) => any) => Promise<any> | undefined}
1068
+ */ (connectWrapped),
790
1069
 
791
1070
  /**
792
1071
  * Disconnect from the device. Supports both promise and callback styles.
@@ -799,9 +1078,10 @@ export default function createRemote(config) {
799
1078
  * await remote.disconnect();
800
1079
  * remote.disconnect((err) => { ... });
801
1080
  */
802
- disconnect: /**
803
- * @type {(cb?: (err?: Error, result?: any) => any) => Promise<any> | undefined}
804
- */ (disconnectWrapped),
1081
+ disconnect:
1082
+ /**
1083
+ * @type {(cb?: (err?: Error, result?: any) => any) => Promise<any> | undefined}
1084
+ */ (disconnectWrapped),
805
1085
 
806
1086
  /**
807
1087
  * Send a keycode. Supports both promise and callback styles.
@@ -813,9 +1093,514 @@ export default function createRemote(config) {
813
1093
  * await remote.inputKeycode(23);
814
1094
  * remote.inputKeycode(23, (err) => { ... });
815
1095
  */
816
- inputKeycode: /**
817
- * @type {(code: number, cb?: (err?: Error, result?: any) => any) => Promise<any> | undefined}
818
- */ (inputKeycodeWrapped),
1096
+ inputKeycode:
1097
+ /**
1098
+ * @type {(code: number, cb?: (err?: Error, result?: any) => any) => Promise<any> | undefined}
1099
+ */ (inputKeycodeWrapped),
1100
+
1101
+ /**
1102
+ * Reboots the Android TV device using ADB's native reboot method.
1103
+ * @public
1104
+ * @returns {Promise<boolean>} Returns true when reboot command was sent successfully
1105
+ * @fires Remote#log - Emitted with reboot operation status and warnings
1106
+ * @fires Remote#error - Emitted if reboot operation fails
1107
+ * @example
1108
+ * await remote.reboot(); // Reboots the device
1109
+ */
1110
+ async reboot() {
1111
+ try {
1112
+ emitLog("info", "=== Starting device reboot ===", "reboot");
1113
+
1114
+ // Ensure we're connected before sending reboot command
1115
+ await ensureConnected();
1116
+
1117
+ emitLog("info", "Sending reboot command to device", "reboot");
1118
+
1119
+ // Use the native device.reboot() method with timeout handling
1120
+ let result;
1121
+ try {
1122
+ result = await device.reboot();
1123
+ emitLog("info", `✅ Reboot command completed normally`, "reboot");
1124
+ } catch (timeoutError) {
1125
+ // Socket timeout is expected during reboot - device becomes unresponsive
1126
+ if (timeoutError.message && timeoutError.message.includes("timeout")) {
1127
+ emitLog("info", "✅ Reboot command sent (connection timeout is expected during reboot)", "reboot");
1128
+ result = true; // Treat timeout as success
1129
+ } else {
1130
+ // Re-throw non-timeout errors
1131
+ throw timeoutError;
1132
+ }
1133
+ }
1134
+ emitLog("warn", "Device will reboot shortly and connection will be lost", "reboot");
1135
+
1136
+ // Wait a moment for command to take effect, then disconnect
1137
+ setTimeout(() => {
1138
+ emitLog("info", "Device should be rebooting now - connection will be terminated", "reboot");
1139
+ // Force disconnect after reboot
1140
+ connected = false;
1141
+ stopHeartbeat();
1142
+ }, 1000);
1143
+
1144
+ emitLog("info", "=== Device reboot initiated ===", "reboot");
1145
+ return result;
1146
+ } catch (error) {
1147
+ emitError(error, "reboot", "Failed to reboot device");
1148
+
1149
+ // Provide helpful error messages for common issues
1150
+ if (error.message && error.message.includes("unauthorized")) {
1151
+ emitLog("error", "Device unauthorized - ensure ADB debugging is enabled and device is authorized", "reboot");
1152
+ } else if (error.message && error.message.includes("device not found")) {
1153
+ emitLog("error", "Device not found - check IP address and ADB connection", "reboot");
1154
+ } else if (error.message && error.message.includes("permission")) {
1155
+ emitLog("error", "Permission denied - reboot may require root access on some devices", "reboot");
1156
+ } else if (error.message && error.message.includes("timeout")) {
1157
+ emitLog("warn", "Reboot command timed out - this may be normal behavior during reboot", "reboot");
1158
+ }
1159
+
1160
+ throw error;
1161
+ }
1162
+ },
1163
+
1164
+ /**
1165
+ * Takes a screenshot of the Android TV device screen in PNG format with optional resizing and file saving.
1166
+ * @public
1167
+ * @param {Object} [options={}] - Screenshot options
1168
+ * @param {number} [options.width] - Target width for resizing (optional)
1169
+ * @param {number} [options.height] - Target height for resizing (optional)
1170
+ * @param {string} [options.filepath] - File path to save screenshot (optional)
1171
+ * @returns {Promise<ReadableStream|void>} Returns PNG stream if no filepath, void if saved to file
1172
+ * @fires Remote#screencap-start - Emitted when screenshot capture begins
1173
+ * @fires Remote#screencap-captured - Emitted when raw screenshot is captured
1174
+ * @fires Remote#screencap-processing - Emitted when image processing begins
1175
+ * @fires Remote#screencap-ready - Emitted when final processed stream is ready
1176
+ * @fires Remote#screencap-saved - Emitted when screenshot is saved to file
1177
+ * @fires Remote#screencap-complete - Emitted when entire operation is complete
1178
+ * @fires Remote#log - Emitted with screenshot operation status
1179
+ * @fires Remote#error - Emitted if screenshot operation fails
1180
+ * @example
1181
+ * // Basic screenshot - returns stream
1182
+ * const pngStream = await remote.screencap();
1183
+ *
1184
+ * // Screenshot with resizing
1185
+ * const resizedStream = await remote.screencap({ width: 1280, height: 720 });
1186
+ *
1187
+ * // Screenshot saved to file
1188
+ * await remote.screencap({ filepath: './screenshot.png' });
1189
+ *
1190
+ * // Screenshot with resizing and file save
1191
+ * await remote.screencap({ width: 640, height: 360, filepath: './thumb.png' });
1192
+ *
1193
+ * // Event-driven usage (non-blocking)
1194
+ * remote.screencap({ width: 1280, filepath: './shot.png' });
1195
+ * remote.on('screencap-complete', (data) => {
1196
+ * console.log('Screenshot ready:', data.filepath);
1197
+ * });
1198
+ */
1199
+ async screencap(options = {}) {
1200
+ const startTime = performance.now();
1201
+ const { width, height, filepath } = options;
1202
+
1203
+ try {
1204
+ emitLog("info", "=== Taking device screenshot ===", "screencap");
1205
+
1206
+ // Emit start event
1207
+ emitter.emit("screencap-start", {
1208
+ timestamp: new Date().toISOString(),
1209
+ options: { width, height, filepath }
1210
+ });
1211
+
1212
+ // Ensure we're connected before taking screenshot
1213
+ await ensureConnected();
1214
+
1215
+ emitLog("info", "Capturing screenshot using native screencap utility", "screencap");
1216
+
1217
+ // Use the native device.screencap() method which should return PNG
1218
+ const screencapStream = await device.screencap();
1219
+ const captureTime = performance.now();
1220
+
1221
+ emitLog("info", `✅ Screenshot captured successfully (${(captureTime - startTime).toFixed(2)}ms)`, "screencap");
1222
+
1223
+ // Emit captured event
1224
+ emitter.emit("screencap-captured", {
1225
+ timestamp: new Date().toISOString(),
1226
+ captureTime: captureTime - startTime
1227
+ });
1228
+
1229
+ // Determine if we need Sharp processing (only for resizing)
1230
+ const needsSharpProcessing = width || height;
1231
+
1232
+ // Handle file save without processing (direct PNG stream to file)
1233
+ if (filepath && !needsSharpProcessing) {
1234
+ const backgroundOperation = (async () => {
1235
+ try {
1236
+ const fileOpStartTime = performance.now();
1237
+
1238
+ emitLog("info", `💾 [BACKGROUND] Starting direct save to: ${filepath}`, "screencap");
1239
+
1240
+ // Direct pipe: ADB PNG stream -> File (no Sharp processing)
1241
+ const directPipeStartTime = performance.now();
1242
+ const writeStream = createWriteStream(filepath);
1243
+
1244
+ // Store the raw PNG stream for user access
1245
+ lastScreencapData = screencapStream;
1246
+
1247
+ emitLog("info", `🔄 [BACKGROUND] Piping stream to file...`, "screencap");
1248
+ screencapStream.pipe(writeStream);
1249
+
1250
+ emitLog("info", `⏳ [BACKGROUND] Waiting for write stream to finish...`, "screencap");
1251
+ await new Promise((resolve, reject) => {
1252
+ writeStream.on("finish", () => {
1253
+ emitLog("info", `✅ [BACKGROUND] Write stream finished for ${filepath}`, "screencap");
1254
+ resolve();
1255
+ });
1256
+ writeStream.on("error", (err) => {
1257
+ emitLog("error", `❌ [BACKGROUND] Write stream error for ${filepath}: ${err.message}`, "screencap");
1258
+ reject(err);
1259
+ });
1260
+ });
1261
+
1262
+ const directPipeTime = performance.now() - directPipeStartTime;
1263
+ const totalFileOpTime = performance.now() - fileOpStartTime;
1264
+ const totalTime = performance.now() - startTime;
1265
+
1266
+ emitLog("info", `✅ Screenshot saved directly to ${filepath}`, "screencap");
1267
+ emitLog("info", `⚡ Direct pipe timing: ${directPipeTime.toFixed(2)}ms (no Sharp processing!)`, "screencap");
1268
+
1269
+ // Emit saved event with timing
1270
+ emitter.emit("screencap-saved", {
1271
+ timestamp: new Date().toISOString(),
1272
+ filepath,
1273
+ timing: {
1274
+ adbStream: captureTime - startTime,
1275
+ directPipe: directPipeTime,
1276
+ fileOperation: totalFileOpTime,
1277
+ total: totalTime
1278
+ }
1279
+ });
1280
+
1281
+ // Emit complete event
1282
+ emitter.emit("screencap-complete", {
1283
+ timestamp: new Date().toISOString(),
1284
+ filepath,
1285
+ processed: false,
1286
+ timing: {
1287
+ adbStream: captureTime - startTime,
1288
+ directPipe: directPipeTime,
1289
+ fileOperation: totalFileOpTime,
1290
+ total: totalTime
1291
+ }
1292
+ });
1293
+ } catch (saveError) {
1294
+ emitLog("error", `💥 [BACKGROUND] Direct pipe error: ${saveError.message}`, "screencap");
1295
+ localEmitError(saveError, "screencap", `Failed to save screenshot directly to ${filepath}: ${saveError.message}`);
1296
+ } finally {
1297
+ emitLog("info", `🧹 [BACKGROUND] Cleaning up background operation for ${filepath}`, "screencap");
1298
+ backgroundOperations.delete(backgroundOperation);
1299
+ }
1300
+ })();
1301
+
1302
+ backgroundOperations.add(backgroundOperation);
1303
+ emitLog("info", "Direct PNG pipe started in background", "screencap");
1304
+ return; // Don't return a stream when saving to file
1305
+ }
1306
+
1307
+ if (!needsSharpProcessing && !filepath) {
1308
+ // Store the raw PNG stream for user access
1309
+ lastScreencapData = screencapStream;
1310
+
1311
+ // Return raw stream if no processing or file save needed
1312
+ emitLog("info", "Raw PNG stream ready (no processing needed)", "screencap");
1313
+ emitter.emit("screencap-ready", {
1314
+ timestamp: new Date().toISOString(),
1315
+ processed: false,
1316
+ totalTime: captureTime - startTime
1317
+ });
1318
+ emitter.emit("screencap-complete", {
1319
+ timestamp: new Date().toISOString(),
1320
+ totalTime: captureTime - startTime,
1321
+ processed: false
1322
+ });
1323
+ return screencapStream;
1324
+ }
1325
+
1326
+ // Process the image
1327
+ emitLog("info", "Processing screenshot image...", "screencap");
1328
+ emitter.emit("screencap-processing", {
1329
+ timestamp: new Date().toISOString(),
1330
+ width,
1331
+ height,
1332
+ filepath
1333
+ });
1334
+
1335
+ const processStartTime = performance.now();
1336
+
1337
+ // Create Sharp transform pipeline
1338
+ let sharpTransform = sharp();
1339
+
1340
+ // Apply resizing if width or height specified
1341
+ if (width || height) {
1342
+ const resizeOptions = {
1343
+ fit: "inside", // Maintain aspect ratio
1344
+ withoutEnlargement: true // Don't upscale
1345
+ };
1346
+ if (width) resizeOptions.width = width;
1347
+ if (height) resizeOptions.height = height;
1348
+
1349
+ sharpTransform = sharpTransform.resize(resizeOptions);
1350
+ emitLog("info", `Resizing to ${width || "auto"}x${height || "auto"}`, "screencap");
1351
+ }
1352
+
1353
+ // Ensure PNG format with fastest compression settings
1354
+ sharpTransform = sharpTransform.png({
1355
+ compressionLevel: 1, // Fastest compression (0-9, lower = faster)
1356
+ progressive: false // Disable progressive encoding
1357
+ });
1358
+
1359
+ if (filepath) {
1360
+ // Background process handles saving and updates lastScreencapData when done
1361
+ const backgroundOperation = (async () => {
1362
+ try {
1363
+ const fileOpStartTime = performance.now();
1364
+ const writeStream = createWriteStream(filepath);
1365
+
1366
+ // Process and save data, collecting it for lastScreencapData
1367
+ const chunks = [];
1368
+ const processedStream = screencapStream.pipe(sharpTransform);
1369
+
1370
+ await new Promise((resolve, reject) => {
1371
+ processedStream.on("data", (chunk) => {
1372
+ chunks.push(chunk);
1373
+ writeStream.write(chunk);
1374
+ });
1375
+
1376
+ processedStream.on("end", () => {
1377
+ writeStream.end();
1378
+ // Save processed data to lastScreencapData when done
1379
+ lastScreencapData = Buffer.concat(chunks);
1380
+
1381
+ const totalFileOpTime = performance.now() - fileOpStartTime;
1382
+ const totalTime = performance.now() - startTime;
1383
+
1384
+ emitLog("info", `✅ Screenshot saved to ${filepath}`, "screencap");
1385
+ emitLog("info", `⏱️ File save timing: ${totalFileOpTime.toFixed(2)}ms, Total: ${totalTime.toFixed(2)}ms`, "screencap");
1386
+
1387
+ emitter.emit("screencap-saved", {
1388
+ timestamp: new Date().toISOString(),
1389
+ filepath,
1390
+ timing: { fileOperation: totalFileOpTime, total: totalTime }
1391
+ });
1392
+
1393
+ emitter.emit("screencap-complete", {
1394
+ timestamp: new Date().toISOString(),
1395
+ filepath,
1396
+ processed: true,
1397
+ width,
1398
+ height,
1399
+ timing: { fileOperation: totalFileOpTime, total: totalTime }
1400
+ });
1401
+
1402
+ resolve();
1403
+ });
1404
+
1405
+ processedStream.on("error", (error) => {
1406
+ reject(error);
1407
+ });
1408
+ });
1409
+ } catch (saveError) {
1410
+ // Show full error details for debugging
1411
+ emitLog("error", `💥 [BACKGROUND SHARP] File save error: ${saveError.message}`, "screencap");
1412
+ emitLog("error", `💥 [BACKGROUND SHARP] Error stack: ${saveError.stack}`, "screencap");
1413
+
1414
+ // Only suppress specific libspng/PNG processing errors that occur after disconnection
1415
+ if (
1416
+ !connected &&
1417
+ saveError.message &&
1418
+ (saveError.message.includes("libspng") ||
1419
+ saveError.message.includes("pngload_buffer") ||
1420
+ saveError.message.includes("read error"))
1421
+ ) {
1422
+ emitLog("debug", `PNG processing error after disconnection (suppressed): ${filepath}`, "screencap");
1423
+ } else {
1424
+ // Emit all other errors with full details
1425
+ localEmitError(saveError, "screencap", `Failed to save screenshot to ${filepath}: ${saveError.message}`);
1426
+ }
1427
+ } finally {
1428
+ // Remove from background operations when complete
1429
+ emitLog("info", `🧹 [BACKGROUND SHARP] Cleaning up background operation for ${filepath}`, "screencap");
1430
+ backgroundOperations.delete(backgroundOperation);
1431
+ }
1432
+ })();
1433
+
1434
+ // Track the background operation
1435
+ backgroundOperations.add(backgroundOperation);
1436
+ emitLog("info", "Screenshot processing started in background", "screencap");
1437
+ return; // Don't return a stream when saving to file
1438
+ } else {
1439
+ // Return processed stream
1440
+ const processedStream = screencapStream.pipe(sharpTransform);
1441
+ const processEndTime = performance.now();
1442
+
1443
+ const streamCaptureTime = captureTime - startTime;
1444
+ const sharpProcessTime = processEndTime - processStartTime;
1445
+ const totalTime = processEndTime - startTime;
1446
+
1447
+ // Debug timing variables
1448
+ emitLog(
1449
+ "debug",
1450
+ `🔍 Timing variables: captureTime=${captureTime}, startTime=${startTime}, processEndTime=${processEndTime}, processStartTime=${processStartTime}`,
1451
+ "screencap"
1452
+ );
1453
+
1454
+ emitLog("info", `PNG stream processed and ready`, "screencap");
1455
+ try {
1456
+ emitLog(
1457
+ "info",
1458
+ `⏱️ Timing breakdown: Capture=${streamCaptureTime.toFixed(2)}ms, Sharp=${sharpProcessTime.toFixed(2)}ms, Total=${totalTime.toFixed(2)}ms`,
1459
+ "screencap"
1460
+ );
1461
+ } catch (timingError) {
1462
+ emitLog(
1463
+ "error",
1464
+ `⚠️ Timing log error in stream processing: ${timingError.message}. Variables: streamCaptureTime=${streamCaptureTime}, sharpProcessTime=${sharpProcessTime}, totalTime=${totalTime}`,
1465
+ "screencap"
1466
+ );
1467
+ }
1468
+
1469
+ // Emit ready event
1470
+ emitter.emit("screencap-ready", {
1471
+ timestamp: new Date().toISOString(),
1472
+ processed: true,
1473
+ width,
1474
+ height,
1475
+ timing: {
1476
+ capture: streamCaptureTime,
1477
+ sharpProcess: sharpProcessTime,
1478
+ total: totalTime
1479
+ }
1480
+ });
1481
+
1482
+ // Emit complete event
1483
+ emitter.emit("screencap-complete", {
1484
+ timestamp: new Date().toISOString(),
1485
+ processed: true,
1486
+ width,
1487
+ height,
1488
+ timing: {
1489
+ capture: streamCaptureTime,
1490
+ sharpProcess: sharpProcessTime,
1491
+ total: totalTime
1492
+ }
1493
+ });
1494
+
1495
+ // Store the processed stream for user access
1496
+ lastScreencapData = processedStream;
1497
+
1498
+ return processedStream;
1499
+ }
1500
+ } catch (error) {
1501
+ localEmitError(error, "screencap", "Failed to capture screenshot");
1502
+
1503
+ // Provide helpful error messages for common issues
1504
+ if (error.message && error.message.includes("unauthorized")) {
1505
+ emitLog("error", "Device unauthorized - ensure ADB debugging is enabled and device is authorized", "screencap");
1506
+ } else if (error.message && error.message.includes("device not found")) {
1507
+ emitLog("error", "Device not found - check IP address and ADB connection", "screencap");
1508
+ } else if (error.message && error.message.includes("screencap")) {
1509
+ emitLog("warn", "Screencap utility may not be available - automatic fallback to framebuffer attempted", "screencap");
1510
+ } else if (error.message && error.message.includes("ENOENT")) {
1511
+ emitLog("error", `File path error: ${error.message}`, "screencap");
1512
+ }
1513
+
1514
+ throw error;
1515
+ }
1516
+ },
1517
+
1518
+ /**
1519
+ * Takes a thumbnail screenshot with default width of 240px.
1520
+ * @public
1521
+ * @param {Object} [options={}] - Thumbnail options
1522
+ * @param {number} [options.width=240] - Target width for thumbnail (default: 240)
1523
+ * @param {number} [options.height] - Target height for thumbnail (optional)
1524
+ * @param {string} [options.filepath] - File path to save thumbnail (optional)
1525
+ * @returns {Promise<ReadableStream|void>} Returns PNG stream if no filepath, void if saved to file
1526
+ * @fires Remote#screencap-start - Emitted when thumbnail capture begins
1527
+ * @fires Remote#screencap-captured - Emitted when raw screenshot is captured
1528
+ * @fires Remote#screencap-processing - Emitted when image processing begins
1529
+ * @fires Remote#screencap-ready - Emitted when final processed stream is ready
1530
+ * @fires Remote#screencap-saved - Emitted when thumbnail is saved to file
1531
+ * @fires Remote#screencap-complete - Emitted when entire thumbnail operation is complete
1532
+ * @fires Remote#log - Emitted with thumbnail operation status
1533
+ * @fires Remote#error - Emitted if thumbnail operation fails
1534
+ * @example
1535
+ * // Basic thumbnail with default 240px width
1536
+ * const thumbnailStream = await remote.thumbnail();
1537
+ *
1538
+ * // Thumbnail with custom dimensions
1539
+ * const customThumb = await remote.thumbnail({ width: 320, height: 180 });
1540
+ *
1541
+ * // Thumbnail saved to file
1542
+ * await remote.thumbnail({ filepath: './thumb.png' });
1543
+ *
1544
+ * // Thumbnail with custom size and file save
1545
+ * await remote.thumbnail({ width: 160, height: 90, filepath: './small-thumb.png' });
1546
+ */
1547
+ async thumbnail(options = {}) {
1548
+ // Set default width to 240 if not specified
1549
+ const thumbnailOptions = {
1550
+ width: 240,
1551
+ ...options
1552
+ };
1553
+
1554
+ emitLog("info", `📸 Taking thumbnail screenshot (${thumbnailOptions.width}x${thumbnailOptions.height || "auto"})`, "thumbnail");
1555
+
1556
+ // Call screencap with thumbnail options
1557
+ return await this.screencap(thumbnailOptions);
1558
+ },
1559
+
1560
+ /**
1561
+ * Waits until the Android TV device has finished booting.
1562
+ * @public
1563
+ * @param {number} [timeout=60000] - Maximum time to wait in milliseconds (default: 60 seconds)
1564
+ * @returns {Promise<boolean>} Returns true when device has completed booting
1565
+ * @fires Remote#log - Emitted with boot monitoring status
1566
+ * @fires Remote#error - Emitted if boot monitoring fails
1567
+ * @example
1568
+ * await remote.waitBootComplete(); // Wait with default 60 second timeout
1569
+ * await remote.waitBootComplete(120000); // Wait up to 2 minutes
1570
+ */
1571
+ async waitBootComplete(timeout = 60000) {
1572
+ try {
1573
+ emitLog("info", "=== Waiting for device boot completion ===", "waitBootComplete");
1574
+
1575
+ // Ensure we're connected before monitoring boot status
1576
+ await ensureConnected();
1577
+
1578
+ emitLog("info", `Monitoring boot status (timeout: ${timeout}ms)`, "waitBootComplete");
1579
+
1580
+ // Use the native device.waitBootComplete() method
1581
+ const result = await device.waitBootComplete();
1582
+
1583
+ emitLog("info", "✅ Device boot completed successfully", "waitBootComplete");
1584
+ emitLog("info", "Device is now ready for operations", "waitBootComplete");
1585
+
1586
+ return result;
1587
+ } catch (error) {
1588
+ emitError(error, "waitBootComplete", "Failed while waiting for boot completion");
1589
+
1590
+ // Provide helpful error messages for common issues
1591
+ if (error.message && error.message.includes("unauthorized")) {
1592
+ emitLog("error", "Device unauthorized - ensure ADB debugging is enabled and device is authorized", "waitBootComplete");
1593
+ } else if (error.message && error.message.includes("device not found")) {
1594
+ emitLog("error", "Device not found - check IP address and ADB connection", "waitBootComplete");
1595
+ } else if (error.message && error.message.includes("timeout")) {
1596
+ emitLog("error", `Boot completion timeout after ${timeout}ms - device may still be starting`, "waitBootComplete");
1597
+ } else if (error.message && error.message.includes("connection")) {
1598
+ emitLog("error", "Connection lost while waiting for boot completion", "waitBootComplete");
1599
+ }
1600
+
1601
+ throw error;
1602
+ }
1603
+ },
819
1604
 
820
1605
  /**
821
1606
  * All remote key functions support both promise and callback styles.
@@ -952,37 +1737,45 @@ export default function createRemote(config) {
952
1737
  key: Object.assign(
953
1738
  wrapAsync(function (keyName, options) {
954
1739
  options = options || {};
955
- if (!keycodes[keyName]) {
956
- const error = new Error("Unknown key: " + keyName);
957
- emitError(error, "keyboard.key", `Unknown key: ${keyName}`);
1740
+ if (!keyboardKeys[keyName]) {
1741
+ const error = new Error("Unknown keyboard key: " + keyName);
1742
+ emitError(error, "keyboard.key", `Unknown keyboard key: ${keyName}`);
958
1743
  return Promise.reject(error);
959
1744
  }
960
1745
  if (!options.forceKeycode) {
961
- // Try inputText for single character keys
962
- if (keyName.length === 1) {
963
- return inputText(keyName);
964
- }
1746
+ // Send as text character
1747
+ return inputText(keyboardKeys[keyName]);
1748
+ }
1749
+ // Fallback to keycode if exists
1750
+ if (keycodes[keyName]) {
1751
+ return inputKeycode(keycodes[keyName]);
965
1752
  }
966
- // Fallback to keycode
967
- return inputKeycode(keycodes[keyName]);
1753
+ const error = new Error("No keycode available for key: " + keyName);
1754
+ emitError(error, "keyboard.key", `No keycode available for key: ${keyName}`);
1755
+ return Promise.reject(error);
968
1756
  }),
969
1757
  {
970
- // Dynamically add all key functions and .keycode subobject
1758
+ // Dynamically add all keyboard key functions and .keycode subobject
971
1759
  ...(() => {
972
1760
  const keyFns = {};
973
- Object.keys(keycodes).forEach((keyName) => {
1761
+ Object.keys(keyboardKeys).forEach((keyName) => {
974
1762
  /**
975
- * Sends this key using inputText (if possible) or keycode fallback.
1763
+ * Sends this key using inputText or keycode fallback.
976
1764
  * @returns {Promise<any>}
977
1765
  * @example
978
1766
  * keyboard.key.a();
979
1767
  */
980
1768
  keyFns[keyName] = wrapAsync(function (options) {
981
1769
  options = options || {};
982
- if (!options.forceKeycode && keyName.length === 1) {
983
- return inputText(keyName);
1770
+ if (!options.forceKeycode) {
1771
+ return inputText(keyboardKeys[keyName]);
1772
+ }
1773
+ if (keycodes[keyName]) {
1774
+ return inputKeycode(keycodes[keyName]);
984
1775
  }
985
- return inputKeycode(keycodes[keyName]);
1776
+ const error = new Error("No keycode available for key: " + keyName);
1777
+ emitError(error, "keyboard.key", `No keycode available for key: ${keyName}`);
1778
+ return Promise.reject(error);
986
1779
  });
987
1780
  /**
988
1781
  * Sends this key using keycode only.
@@ -990,9 +1783,11 @@ export default function createRemote(config) {
990
1783
  * @example
991
1784
  * keyboard.key.a.keycode();
992
1785
  */
993
- keyFns[keyName].keycode = wrapAsync(function () {
994
- return inputKeycode(keycodes[keyName]);
995
- });
1786
+ if (keycodes[keyName]) {
1787
+ keyFns[keyName].keycode = wrapAsync(function () {
1788
+ return inputKeycode(keycodes[keyName]);
1789
+ });
1790
+ }
996
1791
  });
997
1792
  return keyFns;
998
1793
  })(),
@@ -1002,34 +1797,25 @@ export default function createRemote(config) {
1002
1797
  */
1003
1798
  shift: (() => {
1004
1799
  const shiftFns = {};
1005
- Object.keys(keycodes).forEach((keyName) => {
1006
- /**
1007
- * Sends this key with shift using inputText (if possible) or keycode fallback.
1008
- * @returns {Promise<any>}
1009
- * @example
1010
- * keyboard.key.shift.a();
1011
- */
1012
- shiftFns[keyName] = wrapAsync(function (options) {
1013
- options = options || {};
1014
- if (!options.forceKeycode && keyName.length === 1) {
1015
- return inputText(keyName.toUpperCase());
1016
- }
1017
- return inputKeycodeWrapped(keycodes.shiftLeft).then(() => {
1018
- return inputKeycodeLongPressWrapped(keycodes[keyName]);
1019
- });
1020
- });
1800
+ Object.keys(keyboardKeys).forEach((keyName) => {
1801
+ const char = keyboardKeys[keyName];
1802
+ const shiftedChar = getShiftedCharacter(keyName, char);
1021
1803
 
1022
- /**
1023
- * Sends this key with shift using keycode only.
1024
- * @returns {Promise<any>}
1025
- * @example
1026
- * keyboard.key.shift.a.keycode();
1027
- */
1028
- shiftFns[keyName].keycode = wrapAsync(function () {
1029
- return inputKeycodeWrapped(keycodes.shiftLeft).then(() => {
1030
- return inputKeycodeLongPressWrapped(keycodes[keyName]);
1804
+ // Only create shift function if the character actually changes when shifted
1805
+ if (shiftedChar !== char) {
1806
+ /**
1807
+ * Sends this key with shift using inputText (shifted character).
1808
+ * Note: No keycode method available for shift variants since Android
1809
+ * ADB doesn't support sending multiple keycodes simultaneously.
1810
+ * @returns {Promise<any>}
1811
+ * @example
1812
+ * keyboard.key.shift.a(); // Sends "A"
1813
+ */
1814
+ shiftFns[keyName] = wrapAsync(function () {
1815
+ // Send shifted character as text
1816
+ return inputText(shiftedChar);
1031
1817
  });
1032
- });
1818
+ }
1033
1819
  });
1034
1820
  return shiftFns;
1035
1821
  })()
@@ -1037,6 +1823,18 @@ export default function createRemote(config) {
1037
1823
  )
1038
1824
  }
1039
1825
  };
1826
+
1827
+ // Handle initialization if autoConnect is enabled
1828
+ if (autoConnect) {
1829
+ try {
1830
+ // Wait for initialization to complete
1831
+ await realInitPromise;
1832
+ } catch (error) {
1833
+ // If initialization fails, still return the remote but emit error
1834
+ emitError(error, "createRemote", "Auto-connect failed during initialization");
1835
+ }
1836
+ }
1837
+
1040
1838
  return remoteApi;
1041
1839
  }
1042
1840
 
@@ -1045,10 +1843,10 @@ export default function createRemote(config) {
1045
1843
  * @public
1046
1844
  * @param {RemoteConfig} config - Configuration for the remote.
1047
1845
  * @returns {Promise<Remote>} Resolves with a ready remote instance.
1048
- *
1846
+ *
1049
1847
  * @description
1050
- * Creates a remote instance and waits for initialization to complete if autoConnect is enabled.
1051
- *
1848
+ * Alias for createRemote() - both functions now return ready-to-use remote instances.
1849
+ *
1052
1850
  * @example
1053
1851
  * // ESM with event handling
1054
1852
  * const remote = await createAndroidTVRemote({ ip: "192.168.1.100" });
@@ -1056,14 +1854,8 @@ export default function createRemote(config) {
1056
1854
  * remote.on('error', (data) => console.error(data));
1057
1855
  */
1058
1856
  export async function createAndroidTVRemote(config) {
1059
- const remote = createRemote(config);
1060
-
1061
- // Only wait for initialization if autoConnect is enabled
1062
- if (config.autoConnect !== false) {
1063
- await remote.initPromise;
1064
- }
1065
-
1066
- return remote;
1857
+ // Now createRemote is async and handles initialization internally
1858
+ return await createRemote(config);
1067
1859
  }
1068
1860
 
1069
1861
  // Add static create method to the default export