@cldmv/node-android-tv-remote 2.0.0 → 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.
@@ -6,7 +6,7 @@
6
6
  * @Email: <Shinrai@users.noreply.github.com>
7
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 time: 2025-10-15 21:09:09 -07:00 (1760587749)
10
10
  * -----
11
11
  * @Copyright: Copyright (c) 2013-2025 Catalyzed Motivation Inc. All rights reserved.
12
12
  */
@@ -70,7 +70,7 @@
70
70
  * @typedef {Object} LogEventData
71
71
  * @property {string} level - Log level: 'info', 'warn', 'error', 'debug'.
72
72
  * @property {string} message - Log message.
73
- * @property {string} source - Source of the log message (e.g., 'connect', 'disconnect', 'handleSettings').
73
+ * @property {string} source - Source of the log message (e.g., 'connect', 'disconnect', 'setSettings').
74
74
  * @property {string} timestamp - ISO timestamp of when the log was created.
75
75
  * @property {any} [data] - Optional additional data related to the log.
76
76
  */
@@ -87,10 +87,13 @@
87
87
  /**
88
88
  * Android TV Remote instance with event emission capabilities.
89
89
  * @typedef {Object} Remote
90
- * @property {function(string, boolean=): Promise<void>} handleSettings - Get or set Android settings via ADB.
90
+ * @property {function(string=): Promise<void>} setSettings - Configure or retrieve Android TV settings for optimal remote operation.
91
91
  * @property {function(function(Error=, any=)=): Promise<void>|undefined} connect - Connect to the device. Supports both promise and callback styles.
92
92
  * @property {function(function(Error=, any=)=): Promise<void>|undefined} disconnect - Disconnect from the device. Supports both promise and callback styles.
93
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).
94
97
  * @property {function(boolean=): Promise<"connected"|"disconnected"|"unknown">} getConnectionStatus - Returns the current connection status; optionally performs a live check.
95
98
  * @property {boolean} isConnected - True if the module believes it is connected (internal state, not a live check).
96
99
  * @property {Object} press - Remote control key functions for Android TV remotes.
@@ -105,6 +108,12 @@
105
108
  *
106
109
  * @fires Remote#log - Emitted for informational messages, warnings, and debug info.
107
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.
108
117
  *
109
118
  * @example
110
119
  * // Event handling examples
@@ -131,6 +140,9 @@
131
140
 
132
141
  import adbkit from "@devicefarmer/adbkit";
133
142
  import { EventEmitter } from "events";
143
+ import { createWriteStream } from "fs";
144
+ import { pipeline } from "stream/promises";
145
+ import sharp from "sharp";
134
146
  const Adb = adbkit.Adb;
135
147
 
136
148
  /**
@@ -180,6 +192,17 @@ function emitLog(level, message, source = "android-tv-remote", data = null) {
180
192
  * @param {string} [message] - Additional error message.
181
193
  */
182
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
+
183
206
  emitter.emit("error", {
184
207
  error,
185
208
  source,
@@ -235,6 +258,32 @@ function handleDisconnectError(err) {
235
258
  * @see https://developer.android.com/reference/android/view/KeyEvent
236
259
  */
237
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
+ }
238
287
 
239
288
  /**
240
289
  * Remote keys mapping loaded from JSON file.
@@ -244,13 +293,13 @@ import keycodes from "../data/keycodes.json" with { type: "json" };
244
293
  import remoteKeys from "../data/remote-keys.json" with { type: "json" };
245
294
 
246
295
  /**
247
- * Factory function to create a Remote instance.
296
+ * Factory function to create a ready-to-use Remote instance.
248
297
  * @function
249
298
  * @public
250
299
  * @param {RemoteConfig} config - Configuration for the remote.
251
- * @returns {Remote}
300
+ * @returns {Promise<Remote>} A promise that resolves to a ready-to-use remote instance
252
301
  */
253
- export default function createRemote(config) {
302
+ export default async function createRemote(config) {
254
303
  // Ensure config is an object and has the required 'ip' property
255
304
  if (!config || typeof config !== "object" || !config.ip) {
256
305
  throw new Error("Missing required 'ip' property in RemoteConfig.");
@@ -265,6 +314,30 @@ export default function createRemote(config) {
265
314
  });
266
315
  const device = client.getDevice(host);
267
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
+
268
341
  const autoConnect = config.autoConnect !== false; // default true
269
342
  const autoDisconnect = config.autoDisconnect === true; // default false
270
343
  const disconnectTimeout = typeof config.disconnectTimeout === "number" ? config.disconnectTimeout : 10;
@@ -458,27 +531,42 @@ export default function createRemote(config) {
458
531
  * @internal
459
532
  * @returns {Promise<void>}
460
533
  */
461
- function disconnect() {
534
+ async function disconnect() {
462
535
  if (disconnectTimer) {
463
536
  clearTimeout(disconnectTimer);
464
537
  disconnectTimer = null;
465
538
  }
466
539
  stopHeartbeat();
467
- return client
468
- .disconnect(ip, port)
469
- .then(() => {
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");
470
565
  connected = false;
471
- if (!quiet) emitLog("info", `Disconnected from ${host}`, "disconnect");
472
566
  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
- });
567
+ }
568
+ return handleDisconnectError(err);
569
+ }
482
570
  }
483
571
  const disconnectWrapped = wrapAsync(disconnect);
484
572
 
@@ -526,26 +614,6 @@ export default function createRemote(config) {
526
614
  }
527
615
  const inputTextWrapped = wrapAsync(inputText);
528
616
 
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
617
  /**
550
618
  * Returns the current connection status as tracked by the module.
551
619
  * Optionally performs a live check against adb devices if requested.
@@ -611,6 +679,13 @@ export default function createRemote(config) {
611
679
  return Object.keys(this.press).filter((k) => k !== "long" && typeof this.press[k] === "function");
612
680
  }
613
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
+
614
689
  const remoteApi = {
615
690
  /**
616
691
  * Promise that resolves if initial auto-connect succeeds, or rejects if it fails.
@@ -713,64 +788,218 @@ export default function createRemote(config) {
713
788
  get isConnected() {
714
789
  return isConnected();
715
790
  },
791
+
716
792
  /**
717
- * Get or set Android settings via ADB.
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.
718
812
  * @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
813
+ * @param {string} [mode='set'] - 'get' to retrieve settings, 'set' to configure settings
814
+ * @fires Remote#log - Emitted with settings operation results
723
815
  * @fires Remote#error - Emitted if settings operations fail
724
816
  * @example
725
- * remote.handleSettings('get', false);
817
+ * await remote.setSettings(); // Set all optimal settings
818
+ * await remote.setSettings('get'); // Get current settings values
726
819
  */
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);
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
+ }
772
847
  }
773
- });
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
+ }
774
1003
  },
775
1004
 
776
1005
  /**
@@ -817,6 +1046,504 @@ export default function createRemote(config) {
817
1046
  * @type {(code: number, cb?: (err?: Error, result?: any) => any) => Promise<any> | undefined}
818
1047
  */ (inputKeycodeWrapped),
819
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
+
820
1547
  /**
821
1548
  * All remote key functions support both promise and callback styles.
822
1549
  * @public
@@ -952,37 +1679,45 @@ export default function createRemote(config) {
952
1679
  key: Object.assign(
953
1680
  wrapAsync(function (keyName, options) {
954
1681
  options = options || {};
955
- if (!keycodes[keyName]) {
956
- const error = new Error("Unknown key: " + keyName);
957
- emitError(error, "keyboard.key", `Unknown key: ${keyName}`);
1682
+ if (!keyboardKeys[keyName]) {
1683
+ const error = new Error("Unknown keyboard key: " + keyName);
1684
+ emitError(error, "keyboard.key", `Unknown keyboard key: ${keyName}`);
958
1685
  return Promise.reject(error);
959
1686
  }
960
1687
  if (!options.forceKeycode) {
961
- // Try inputText for single character keys
962
- if (keyName.length === 1) {
963
- return inputText(keyName);
964
- }
1688
+ // Send as text character
1689
+ return inputText(keyboardKeys[keyName]);
965
1690
  }
966
- // Fallback to keycode
967
- return inputKeycode(keycodes[keyName]);
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);
968
1698
  }),
969
1699
  {
970
- // Dynamically add all key functions and .keycode subobject
1700
+ // Dynamically add all keyboard key functions and .keycode subobject
971
1701
  ...(() => {
972
1702
  const keyFns = {};
973
- Object.keys(keycodes).forEach((keyName) => {
1703
+ Object.keys(keyboardKeys).forEach((keyName) => {
974
1704
  /**
975
- * Sends this key using inputText (if possible) or keycode fallback.
1705
+ * Sends this key using inputText or keycode fallback.
976
1706
  * @returns {Promise<any>}
977
1707
  * @example
978
1708
  * keyboard.key.a();
979
1709
  */
980
1710
  keyFns[keyName] = wrapAsync(function (options) {
981
1711
  options = options || {};
982
- if (!options.forceKeycode && keyName.length === 1) {
983
- return inputText(keyName);
1712
+ if (!options.forceKeycode) {
1713
+ return inputText(keyboardKeys[keyName]);
1714
+ }
1715
+ if (keycodes[keyName]) {
1716
+ return inputKeycode(keycodes[keyName]);
984
1717
  }
985
- return inputKeycode(keycodes[keyName]);
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);
986
1721
  });
987
1722
  /**
988
1723
  * Sends this key using keycode only.
@@ -990,9 +1725,11 @@ export default function createRemote(config) {
990
1725
  * @example
991
1726
  * keyboard.key.a.keycode();
992
1727
  */
993
- keyFns[keyName].keycode = wrapAsync(function () {
994
- return inputKeycode(keycodes[keyName]);
995
- });
1728
+ if (keycodes[keyName]) {
1729
+ keyFns[keyName].keycode = wrapAsync(function () {
1730
+ return inputKeycode(keycodes[keyName]);
1731
+ });
1732
+ }
996
1733
  });
997
1734
  return keyFns;
998
1735
  })(),
@@ -1002,34 +1739,25 @@ export default function createRemote(config) {
1002
1739
  */
1003
1740
  shift: (() => {
1004
1741
  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]);
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);
1019
1759
  });
1020
- });
1021
-
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]);
1031
- });
1032
- });
1760
+ }
1033
1761
  });
1034
1762
  return shiftFns;
1035
1763
  })()
@@ -1037,6 +1765,18 @@ export default function createRemote(config) {
1037
1765
  )
1038
1766
  }
1039
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
+
1040
1780
  return remoteApi;
1041
1781
  }
1042
1782
 
@@ -1047,7 +1787,7 @@ export default function createRemote(config) {
1047
1787
  * @returns {Promise<Remote>} Resolves with a ready remote instance.
1048
1788
  *
1049
1789
  * @description
1050
- * Creates a remote instance and waits for initialization to complete if autoConnect is enabled.
1790
+ * Alias for createRemote() - both functions now return ready-to-use remote instances.
1051
1791
  *
1052
1792
  * @example
1053
1793
  * // ESM with event handling
@@ -1056,14 +1796,8 @@ export default function createRemote(config) {
1056
1796
  * remote.on('error', (data) => console.error(data));
1057
1797
  */
1058
1798
  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;
1799
+ // Now createRemote is async and handles initialization internally
1800
+ return await createRemote(config);
1067
1801
  }
1068
1802
 
1069
1803
  // Add static create method to the default export