@cldmv/node-android-tv-remote 1.5.4 → 2.0.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.
@@ -1,9 +1,56 @@
1
- // @ts-check
2
1
  /**
3
- * Android TV Remote module.
2
+ * @Project: @cldmv/node-android-tv-remote
3
+ * @Filename: /src/lib/android-tv-remote.mjs
4
+ * @Date: 2025-10-15 10:19:05 -07:00 (1760548745)
5
+ * @Author: Nate Hyson <CLDMV>
6
+ * @Email: <Shinrai@users.noreply.github.com>
7
+ * -----
8
+ * @Last modified by: Nate Hyson <CLDMV> (Shinrai@users.noreply.github.com)
9
+ * @Last modified time: 2025-10-15 11:13:38 -07:00 (1760552018)
10
+ * -----
11
+ * @Copyright: Copyright (c) 2013-2025 Catalyzed Motivation Inc. All rights reserved.
12
+ */
13
+
14
+ /**
15
+ * Android TV Remote module - Event-driven ADB remote control for Android TV devices.
16
+ *
4
17
  * @module android-tv-remote
18
+ *
19
+ * @description
20
+ * This module provides an event-driven interface for controlling Android TV devices via ADB.
21
+ * All operations emit events instead of console logging, allowing for better integration
22
+ * and programmatic handling of device communication.
23
+ *
24
+ * @example
25
+ * // ESM usage with event handling
26
+ * import createRemote from "@cldmv/node-android-tv-remote";
27
+ *
28
+ * const remote = createRemote({ ip: "192.168.1.100" });
29
+ *
30
+ * // Listen for log events
31
+ * remote.on('log', (data) => {
32
+ * console.log(`[${data.level}] ${data.message}`, data.source);
33
+ * });
34
+ *
35
+ * // Listen for errors
36
+ * remote.on('error', (data) => {
37
+ * console.error(`Error from ${data.source}:`, data.error.message);
38
+ * });
39
+ *
40
+ * // Use the remote
41
+ * await remote.press.home();
42
+ *
43
+ * @example
44
+ * // Static create method
45
+ * import { createAndroidTVRemote } from "@cldmv/node-android-tv-remote";
46
+ *
47
+ * const remote = await createAndroidTVRemote({ ip: "192.168.1.100" });
48
+ * remote.on('log', console.log);
49
+ * await remote.press.play();
5
50
  */
51
+
6
52
  /**
53
+ * Configuration object for Android TV Remote.
7
54
  * @typedef {Object} RemoteConfig
8
55
  * @property {string} ip - The IP address of the device.
9
56
  * @property {number} [port=5555] - The port for ADB connection.
@@ -14,53 +61,77 @@
14
61
  * @property {boolean} [maintainConnection=true] - Whether to maintain the ADB connection with a heartbeat.
15
62
  * @property {number} [heartbeatInterval=30000] - Heartbeat interval in ms (default 30s).
16
63
  * @property {number} [connectionCheckInterval=30000] - Interval in ms for periodic connection checks (default 30s).
17
- * @property {boolean} [quiet=true] - Suppress connection log output if true.
64
+ * @property {number} [connectTimeout=10000] - Timeout in ms for ADB connection attempts (default 10s).
65
+ * @property {boolean} [quiet=true] - Suppress log events if true (errors are always emitted).
18
66
  */
67
+
68
+ /**
69
+ * Log event data structure.
70
+ * @typedef {Object} LogEventData
71
+ * @property {string} level - Log level: 'info', 'warn', 'error', 'debug'.
72
+ * @property {string} message - Log message.
73
+ * @property {string} source - Source of the log message (e.g., 'connect', 'disconnect', 'handleSettings').
74
+ * @property {string} timestamp - ISO timestamp of when the log was created.
75
+ * @property {any} [data] - Optional additional data related to the log.
76
+ */
77
+
78
+ /**
79
+ * Error event data structure.
80
+ * @typedef {Object} ErrorEventData
81
+ * @property {Error} error - The error object that was thrown.
82
+ * @property {string} source - Source of the error (e.g., 'connect', 'disconnect', 'adb').
83
+ * @property {string} message - Human-readable error message.
84
+ * @property {string} timestamp - ISO timestamp of when the error occurred.
85
+ */
86
+
19
87
  /**
88
+ * Android TV Remote instance with event emission capabilities.
20
89
  * @typedef {Object} Remote
21
90
  * @property {function(string, boolean=): Promise<void>} handleSettings - Get or set Android settings via ADB.
22
- * @property {function(function(Error=, any=)=): Promise|undefined} connect - Connect to the device. Supports both promise and callback styles.
23
- * @property {function(function(Error=, any=)=): Promise|undefined} disconnect - Disconnect from the device. Supports both promise and callback styles.
24
- * @property {function(number, function(Error=, any=)=): Promise|undefined} inputKeycode - Send a keycode to the device. Supports both promise and callback styles.
91
+ * @property {function(function(Error=, any=)=): Promise<void>|undefined} connect - Connect to the device. Supports both promise and callback styles.
92
+ * @property {function(function(Error=, any=)=): Promise<void>|undefined} disconnect - Disconnect from the device. Supports both promise and callback styles.
93
+ * @property {function(number, function(Error=, any=)=): Promise<void>|undefined} inputKeycode - Send a keycode to the device. Supports both promise and callback styles.
25
94
  * @property {function(boolean=): Promise<"connected"|"disconnected"|"unknown">} getConnectionStatus - Returns the current connection status; optionally performs a live check.
26
95
  * @property {boolean} isConnected - True if the module believes it is connected (internal state, not a live check).
27
96
  * @property {Object} press - Remote control key functions for Android TV remotes.
28
97
  * @property {Object} keyboard - Keyboard interface for all keys, with text and keycode fallback.
29
98
  * @property {Object} keyboard.key - Contains all key functions.
30
99
  * @property {Object} keyboard.key.shift - Contains all shifted key functions.
100
+ *
101
+ * @property {function(string, Function): Remote} on - Add event listener. Returns remote instance for chaining.
102
+ * @property {function(string, Function): Remote} off - Remove event listener. Returns remote instance for chaining.
103
+ * @property {function(string, Function): Remote} once - Add one-time event listener. Returns remote instance for chaining.
104
+ * @property {function(string, ...any): boolean} emit - Emit an event. Returns true if event had listeners.
105
+ *
106
+ * @fires Remote#log - Emitted for informational messages, warnings, and debug info.
107
+ * @fires Remote#error - Emitted when errors occur during ADB operations.
108
+ *
109
+ * @example
110
+ * // Event handling examples
111
+ * remote.on('log', (data) => {
112
+ * if (data.level === 'error') {
113
+ * console.error(`ERROR [${data.source}]: ${data.message}`);
114
+ * } else if (data.level === 'warn') {
115
+ * console.warn(`WARN [${data.source}]: ${data.message}`);
116
+ * } else {
117
+ * console.log(`INFO [${data.source}]: ${data.message}`);
118
+ * }
119
+ * });
120
+ *
121
+ * remote.on('error', (data) => {
122
+ * console.error(`FATAL ERROR from ${data.source}:`);
123
+ * console.error(data.error.stack || data.error.message);
124
+ *
125
+ * // Handle specific error types
126
+ * if (data.error.message.includes('device unauthorized')) {
127
+ * console.log('Please authorize ADB on your Android TV device');
128
+ * }
129
+ * });
31
130
  */
32
131
 
33
- const adb = require("adbkit");
34
-
35
- /**
36
- * Logs a message with a datetime prefix.
37
- * @private
38
- * @param {...any} args - Arguments to log.
39
- */
40
- function logWithTime(...args) {
41
- const now = new Date().toISOString();
42
- console.log(`[${now}]`, ...args);
43
- }
44
-
45
- /**
46
- * Logs a warning with a datetime prefix.
47
- * @private
48
- * @param {...any} args - Arguments to warn.
49
- */
50
- function warnWithTime(...args) {
51
- const now = new Date().toISOString();
52
- console.warn(`[${now}]`, ...args);
53
- }
54
-
55
- /**
56
- * Logs an error with a datetime prefix.
57
- * @private
58
- * @param {...any} args - Arguments to error.
59
- */
60
- function errorWithTime(...args) {
61
- const now = new Date().toISOString();
62
- console.error(`[${now}]`, ...args);
63
- }
132
+ import adbkit from "@devicefarmer/adbkit";
133
+ import { EventEmitter } from "events";
134
+ const Adb = adbkit.Adb;
64
135
 
65
136
  /**
66
137
  * Wraps an async function to support both promise and callback styles.
@@ -80,8 +151,45 @@ function wrapAsync(fn) {
80
151
  };
81
152
  }
82
153
 
154
+ // Create event emitter for this instance
155
+ const emitter = new EventEmitter();
156
+
157
+ /**
158
+ * Emit a log event with structured data.
159
+ * @private
160
+ * @param {string} level - Log level (info, warn, error, debug).
161
+ * @param {string} message - Log message.
162
+ * @param {string} [source] - Source of the log message.
163
+ * @param {any} [data] - Additional data to include.
164
+ */
165
+ function emitLog(level, message, source = "android-tv-remote", data = null) {
166
+ emitter.emit("log", {
167
+ level,
168
+ message,
169
+ source,
170
+ timestamp: new Date().toISOString(),
171
+ ...(data && { data })
172
+ });
173
+ }
174
+
175
+ /**
176
+ * Emit an error event with structured data.
177
+ * @private
178
+ * @param {Error} error - The error object.
179
+ * @param {string} [source] - Source of the error.
180
+ * @param {string} [message] - Additional error message.
181
+ */
182
+ function emitError(error, source = "android-tv-remote", message = null) {
183
+ emitter.emit("error", {
184
+ error,
185
+ source,
186
+ message: message || error.message,
187
+ timestamp: new Date().toISOString()
188
+ });
189
+ }
190
+
83
191
  /**
84
- * Handles disconnect and connection errors, outputs helpful messages, and exits the process.
192
+ * Handles disconnect and connection errors, emits helpful messages.
85
193
  * Also provides onboarding steps for common authentication and connection issues.
86
194
  * @private
87
195
  * @param {Error} err - The error object.
@@ -92,31 +200,31 @@ function wrapAsync(fn) {
92
200
  * handleDisconnectError(err);
93
201
  * }
94
202
  */
203
+
95
204
  function handleDisconnectError(err) {
96
- errorWithTime("Error:", err.message || err);
205
+ emitError(err, "handleDisconnectError");
206
+
97
207
  if (err.message && (err.message.includes("device unauthorized") || err.message.includes("failed to authenticate"))) {
98
- errorWithTime(
99
- "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."
100
- );
101
- errorWithTime("If you do not see a prompt, try disconnecting and reconnecting the device, or reboot your TV.");
102
- errorWithTime("If the problem persists, remove the device from the list of authorized ADB devices in Developer Options and try again.");
103
- errorWithTime(
104
- "Tip: In Developer Options on your TV, try toggling 'ADB Debugging' off and then back on. This often resolves authentication issues."
105
- );
106
- process.exit(1);
208
+ 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");
107
213
  }
214
+
108
215
  if (err.message && (err.message.includes("actively refused") || err.message.includes("No connection could be made"))) {
109
- errorWithTime("\nThe device refused the connection. To enable ADB, follow these steps on your Android TV or Fire TV:");
110
- errorWithTime("1. Open Settings > Device Preferences > About (or My Fire TV > About)");
111
- errorWithTime("2. Scroll to 'Build' and press OK 7 times to enable Developer Options");
112
- errorWithTime("3. Go back to Settings > Device Preferences > Developer Options");
113
- errorWithTime("4. Enable 'Developer Options' if needed, then enable 'ADB Debugging' and 'Apps from Unknown Sources'");
114
- errorWithTime("5. Ensure your TV and computer are on the same network");
115
- errorWithTime("6. On your computer, run: adb connect <device-ip>:5555");
116
- errorWithTime("7. Accept the authorization prompt on your TV");
117
- errorWithTime("\nIf you do not see 'Developer Options', repeat step 2 until it appears.");
118
- process.exit(1);
216
+ 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");
218
+ emitLog("info", "1. Open Settings > Device Preferences > About (or My Fire TV > About)", "handleDisconnectError");
219
+ emitLog("info", "2. Scroll to 'Build' and press OK 7 times to enable Developer Options", "handleDisconnectError");
220
+ 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");
222
+ emitLog("info", "5. Ensure your TV and computer are on the same network", "handleDisconnectError");
223
+ emitLog("info", "6. On your computer, run: adb connect <device-ip>:5555", "handleDisconnectError");
224
+ emitLog("info", "7. Accept the authorization prompt on your TV", "handleDisconnectError");
225
+ emitLog("info", "If you do not see 'Developer Options', repeat step 2 until it appears.", "handleDisconnectError");
119
226
  }
227
+
120
228
  return err;
121
229
  }
122
230
 
@@ -126,14 +234,14 @@ function handleDisconnectError(err) {
126
234
  * @type {Object.<string, number>}
127
235
  * @see https://developer.android.com/reference/android/view/KeyEvent
128
236
  */
129
- const keycodes = require("../data/keycodes.json");
237
+ import keycodes from "../data/keycodes.json" with { type: "json" };
130
238
 
131
239
  /**
132
240
  * Remote keys mapping loaded from JSON file.
133
241
  * @internal
134
242
  * @type {string[]}
135
243
  */
136
- const remoteKeys = require("../data/remote-keys.json");
244
+ import remoteKeys from "../data/remote-keys.json" with { type: "json" };
137
245
 
138
246
  /**
139
247
  * Factory function to create a Remote instance.
@@ -142,7 +250,7 @@ const remoteKeys = require("../data/remote-keys.json");
142
250
  * @param {RemoteConfig} config - Configuration for the remote.
143
251
  * @returns {Remote}
144
252
  */
145
- module.exports = function (config) {
253
+ export default function createRemote(config) {
146
254
  // Ensure config is an object and has the required 'ip' property
147
255
  if (!config || typeof config !== "object" || !config.ip) {
148
256
  throw new Error("Missing required 'ip' property in RemoteConfig.");
@@ -151,35 +259,85 @@ module.exports = function (config) {
151
259
  const port = config.port || 5555;
152
260
  const inputDevice = config.inputDevice || "/dev/input/event0";
153
261
  const host = ip + ":" + port;
154
- const client = adb.createClient();
262
+ const connectTimeout = typeof config.connectTimeout === "number" ? config.connectTimeout : 10000;
263
+ const client = Adb.createClient({
264
+ timeout: connectTimeout
265
+ });
266
+ const device = client.getDevice(host);
155
267
  let connected = false;
156
268
  const autoConnect = config.autoConnect !== false; // default true
157
269
  const autoDisconnect = config.autoDisconnect === true; // default false
158
270
  const disconnectTimeout = typeof config.disconnectTimeout === "number" ? config.disconnectTimeout : 10;
159
- const connectionCheckInterval = typeof config.connectionCheckInterval === "number" ? config.connectionCheckInterval : 30000;
271
+ const connectionCheckInterval = typeof config.connectionCheckInterval === "number" ? config.connectionCheckInterval : 10000;
160
272
  let connectionCheckTimer = null;
161
273
  let disconnectTimer = null;
162
274
  const quiet = config.quiet !== false; // default true
163
275
  const maintainConnection = config.maintainConnection !== false; // default true
164
- const heartbeatInterval = typeof config.heartbeatInterval === "number" ? config.heartbeatInterval : 30000;
276
+ const heartbeatInterval = typeof config.heartbeatInterval === "number" ? config.heartbeatInterval : 20000;
165
277
  let heartbeatTimer = null;
166
278
 
167
279
  /**
168
280
  * On initialization, check if already connected to the device and set internal state.
169
281
  * This ensures the internal state is correct if the device is already connected.
282
+ * Expose a promise (initPromise) that resolves or rejects based on the result.
170
283
  */
171
- (async () => {
172
- try {
173
- const status = await getConnectionStatus(true);
174
- if (status === "connected") {
175
- connected = true;
176
- if (!quiet) logWithTime("Already connected to " + host + " (on init)");
177
- startHeartbeat();
178
- }
179
- } catch (e) {
180
- // Ignore errors on init
284
+ const INIT_TIMEOUT_MS = 7000;
285
+
286
+ /**
287
+ * Internal resolve/reject for initPromise, always defined as functions.
288
+ */
289
+ let initPromiseResolve;
290
+ let initPromiseReject;
291
+
292
+ /**
293
+ * Promise that resolves if initial auto-connect succeeds, or rejects if it fails.
294
+ * Now includes a timeout to prevent hanging forever if ADB never responds.
295
+ * @type {Promise<void>}
296
+ * @example
297
+ * remote.initPromise.then(() => { ... }).catch((err) => { ... });
298
+ */
299
+ const realInitPromise = new Promise((resolve, reject) => {
300
+ initPromiseResolve = resolve;
301
+ initPromiseReject = reject;
302
+ if (!autoConnect) {
303
+ // Skip initialization if autoConnect is disabled
304
+ initPromiseResolve(undefined);
305
+ return;
181
306
  }
182
- })();
307
+ (async () => {
308
+ try {
309
+ const status = await getConnectionStatus(true);
310
+ if (status === "connected") {
311
+ connected = true;
312
+ if (!quiet) emitLog("info", `Already connected to ${host} (on init)`, "initPromise");
313
+ startHeartbeat();
314
+ initPromiseResolve(undefined);
315
+ } else {
316
+ // Try to connect if not already connected
317
+ await connect();
318
+ if (connected) {
319
+ initPromiseResolve(undefined);
320
+ } else {
321
+ const error = new Error("Failed to connect to device on initialization.");
322
+ emitError(error, "initPromise", "Auto-connect failed during initialization");
323
+ initPromiseReject(error);
324
+ }
325
+ }
326
+ } catch (e) {
327
+ emitError(e instanceof Error ? e : new Error(String(e)), "initPromise", "Exception during initialization");
328
+ initPromiseReject(e);
329
+ }
330
+ })();
331
+ });
332
+
333
+ const initPromise = Promise.race([
334
+ realInitPromise,
335
+ new Promise((_, reject) => {
336
+ setTimeout(() => {
337
+ reject(new Error("ADB initPromise timed out"));
338
+ }, INIT_TIMEOUT_MS);
339
+ })
340
+ ]);
183
341
 
184
342
  /**
185
343
  * Resets the disconnect timer if autoDisconnect is enabled.
@@ -189,7 +347,7 @@ module.exports = function (config) {
189
347
  function resetDisconnectTimer() {
190
348
  if (!autoDisconnect) return;
191
349
  if (disconnectTimer) clearTimeout(disconnectTimer);
192
- disconnectTimer = setTimeout(function () {
350
+ disconnectTimer = setTimeout(() => {
193
351
  if (connected) disconnect();
194
352
  }, disconnectTimeout * 1000);
195
353
  }
@@ -206,7 +364,7 @@ module.exports = function (config) {
206
364
  heartbeatTimer = setInterval(() => {
207
365
  if (!connected) return;
208
366
  // Send a no-op shell command to keep the connection alive
209
- client.shell(host, "echo heartbeat").catch(() => {});
367
+ device.shell("echo heartbeat").catch(() => {});
210
368
  }, heartbeatInterval);
211
369
  startConnectionCheck();
212
370
  }
@@ -225,12 +383,13 @@ module.exports = function (config) {
225
383
  const deviceId = host;
226
384
  const found = devices.some((d) => d.id === deviceId);
227
385
  if (!found) {
228
- warnWithTime(`Device ${deviceId} not found in adb devices list. Attempting reconnect...`);
386
+ emitLog("warn", `Device ${deviceId} not found in adb devices list. Attempting reconnect...`, "connectionCheck");
229
387
  connected = false;
230
388
  await connect();
231
389
  }
232
390
  } catch (err) {
233
- warnWithTime("Error checking device connection:", err.message || err);
391
+ const error = err instanceof Error ? err : new Error(String(err));
392
+ emitLog("warn", `Error checking device connection: ${error.message}`, "connectionCheck");
234
393
  }
235
394
  }, connectionCheckInterval);
236
395
  }
@@ -271,19 +430,19 @@ module.exports = function (config) {
271
430
  */
272
431
  function connect() {
273
432
  if (connected) {
274
- if (!quiet) logWithTime("Already connected to " + host);
433
+ if (!quiet) emitLog("info", `Already connected to ${host}`, "connect");
275
434
  return Promise.resolve();
276
435
  }
277
436
  return client
278
437
  .connect(ip, port)
279
- .then(function () {
438
+ .then(() => {
280
439
  connected = true;
281
- if (!quiet) logWithTime("Connected to " + host);
440
+ if (!quiet) emitLog("info", `Connected to ${host}`, "connect");
282
441
  startHeartbeat();
283
442
  })
284
- .catch(function (err) {
443
+ .catch((err) => {
285
444
  if (err.message && err.message.includes("already connected")) {
286
- if (!quiet) warnWithTime("Warning: Device already connected.");
445
+ if (!quiet) emitLog("warn", "Device already connected", "connect");
287
446
  connected = true;
288
447
  startHeartbeat();
289
448
  return true;
@@ -307,14 +466,14 @@ module.exports = function (config) {
307
466
  stopHeartbeat();
308
467
  return client
309
468
  .disconnect(ip, port)
310
- .then(function () {
469
+ .then(() => {
311
470
  connected = false;
312
- if (!quiet) logWithTime("Disconnected from " + host);
471
+ if (!quiet) emitLog("info", `Disconnected from ${host}`, "disconnect");
313
472
  return true;
314
473
  })
315
- .catch(function (err) {
474
+ .catch((err) => {
316
475
  if (err.message && err.message.includes("disconnected")) {
317
- if (!quiet) warnWithTime("Warning: Device already disconnected before explicit disconnect call.");
476
+ if (!quiet) emitLog("warn", "Device already disconnected before explicit disconnect call", "disconnect");
318
477
  connected = false;
319
478
  return true;
320
479
  }
@@ -327,12 +486,12 @@ module.exports = function (config) {
327
486
  * Sends a keycode to the device, auto-connects/disconnects as needed.
328
487
  * @internal
329
488
  * @param {number} code - The Android keycode to send.
330
- * @returns {Promise}
489
+ * @returns {Promise<any>}
331
490
  */
332
491
  function inputKeycode(code) {
333
- return ensureConnected().then(function () {
492
+ return ensureConnected().then(() => {
334
493
  resetDisconnectTimer();
335
- return client.shell(host, "input keyevent " + code);
494
+ return device.shell("input keyevent " + code);
336
495
  });
337
496
  }
338
497
  const inputKeycodeWrapped = wrapAsync(inputKeycode);
@@ -341,13 +500,13 @@ module.exports = function (config) {
341
500
  * Sends a long press keycode to the device, auto-connects/disconnects as needed.
342
501
  * @internal
343
502
  * @param {number} code - The Android keycode to send as a long press.
344
- * @returns {Promise}
503
+ * @returns {Promise<any>}
345
504
  */
346
505
  function inputKeycodeLongPress(code) {
347
506
  const cmd = "sendevent " + inputDevice + " 1 " + code + " 1 && " + "sleep 1 && " + "sendevent " + inputDevice + " 1 " + code + " 0";
348
- return ensureConnected().then(function () {
507
+ return ensureConnected().then(() => {
349
508
  resetDisconnectTimer();
350
- return client.shell(host, cmd);
509
+ return device.shell(cmd);
351
510
  });
352
511
  }
353
512
  const inputKeycodeLongPressWrapped = wrapAsync(inputKeycodeLongPress);
@@ -356,13 +515,13 @@ module.exports = function (config) {
356
515
  * Sends text input to the device, auto-connects/disconnects as needed.
357
516
  * @internal
358
517
  * @param {string} text - The text to input.
359
- * @returns {Promise}
518
+ * @returns {Promise<any>}
360
519
  */
361
520
  function inputText(text) {
362
521
  const escaped = text.replace(/ /g, "%s");
363
- return ensureConnected().then(function () {
522
+ return ensureConnected().then(() => {
364
523
  resetDisconnectTimer();
365
- return client.shell(host, 'input text "' + escaped + '"');
524
+ return device.shell('input text "' + escaped + '"');
366
525
  });
367
526
  }
368
527
  const inputTextWrapped = wrapAsync(inputText);
@@ -373,34 +532,18 @@ module.exports = function (config) {
373
532
  for (let i = 0; i < 26; i++) {
374
533
  const letter = String.fromCharCode(97 + i);
375
534
  const code = 29 + i;
376
- keyboardKeys[letter] = (function (code) {
377
- return function () {
378
- return inputKeycode(code);
379
- };
380
- })(code);
381
- keyboardShiftKeys[letter] = (function (code) {
382
- return function () {
383
- return inputKeycode(keycodes.shiftLeft).then(function () {
384
- return inputKeycode(code);
385
- });
386
- };
535
+ keyboardKeys[letter] = ((code) => () => inputKeycode(code))(code);
536
+ keyboardShiftKeys[letter] = ((code) => () => {
537
+ return inputKeycode(keycodes.shiftLeft).then(() => inputKeycode(code));
387
538
  })(code);
388
539
  }
389
540
 
390
- keyboardKeys.enter = function () {
391
- return inputKeycode(keycodes.enter);
392
- };
393
- keyboardKeys.space = function () {
394
- return inputKeycode(keycodes.space);
395
- };
396
- keyboardKeys.del = function () {
397
- return inputKeycode(keycodes.del);
398
- };
541
+ keyboardKeys.enter = () => inputKeycode(keycodes.enter);
542
+ keyboardKeys.space = () => inputKeycode(keycodes.space);
543
+ keyboardKeys.del = () => inputKeycode(keycodes.del);
399
544
 
400
- keyboardShiftKeys.enter = function () {
401
- return inputKeycode(keycodes.shiftLeft).then(function () {
402
- return inputKeycode(keycodes.enter);
403
- });
545
+ keyboardShiftKeys.enter = () => {
546
+ return inputKeycode(keycodes.shiftLeft).then(() => inputKeycode(keycodes.enter));
404
547
  };
405
548
 
406
549
  /**
@@ -469,6 +612,69 @@ module.exports = function (config) {
469
612
  }
470
613
 
471
614
  const remoteApi = {
615
+ /**
616
+ * Promise that resolves if initial auto-connect succeeds, or rejects if it fails.
617
+ * @type {Promise<void>}
618
+ * @example
619
+ * remote.initPromise.then(() => { ... }).catch((err) => { ... });
620
+ */
621
+ initPromise,
622
+
623
+ /**
624
+ * Add event listener.
625
+ * @public
626
+ * @param {string} event - Event name.
627
+ * @param {Function} listener - Event listener function.
628
+ * @returns {Object} This remote instance for chaining.
629
+ * @example
630
+ * remote.on('log', (data) => console.log(data));
631
+ * remote.on('error', (data) => console.error(data));
632
+ */
633
+ on(event, listener) {
634
+ emitter.on(event, listener);
635
+ return remoteApi;
636
+ },
637
+
638
+ /**
639
+ * Remove event listener.
640
+ * @public
641
+ * @param {string} event - Event name.
642
+ * @param {Function} listener - Event listener function.
643
+ * @returns {Object} This remote instance for chaining.
644
+ * @example
645
+ * remote.off('log', logHandler);
646
+ */
647
+ off(event, listener) {
648
+ emitter.off(event, listener);
649
+ return remoteApi;
650
+ },
651
+
652
+ /**
653
+ * Add one-time event listener.
654
+ * @public
655
+ * @param {string} event - Event name.
656
+ * @param {Function} listener - Event listener function.
657
+ * @returns {Object} This remote instance for chaining.
658
+ * @example
659
+ * remote.once('log', (data) => console.log('First log:', data));
660
+ */
661
+ once(event, listener) {
662
+ emitter.once(event, listener);
663
+ return remoteApi;
664
+ },
665
+
666
+ /**
667
+ * Emit an event.
668
+ * @public
669
+ * @param {string} event - Event name.
670
+ * @param {...any} args - Event arguments.
671
+ * @returns {boolean} True if event had listeners.
672
+ * @example
673
+ * remote.emit('custom-event', { data: 'example' });
674
+ */
675
+ emit(event, ...args) {
676
+ return emitter.emit(event, ...args);
677
+ },
472
678
  /**
473
679
  * Returns the current connection status as tracked by the module, or does a live check if requested.
474
680
  * @function
@@ -485,7 +691,7 @@ module.exports = function (config) {
485
691
  * @example
486
692
  * remote.getKeyboardKeys();
487
693
  */
488
- getKeyboardKeys: function () {
694
+ getKeyboardKeys() {
489
695
  return getKeyboardKeys.call(remoteApi);
490
696
  },
491
697
  /**
@@ -494,7 +700,7 @@ module.exports = function (config) {
494
700
  * @example
495
701
  * remote.getPressCommands();
496
702
  */
497
- getPressCommands: function () {
703
+ getPressCommands() {
498
704
  return getPressCommands.call(remoteApi);
499
705
  },
500
706
  /**
@@ -513,10 +719,12 @@ module.exports = function (config) {
513
719
  * @param {string} mode - 'get' or 'set'.
514
720
  * @param {boolean} [overrideQuiet] - Optionally override the quiet flag for this call.
515
721
  * @returns {Promise<void>}
722
+ * @fires Remote#log - Emitted with settings operation status and results
723
+ * @fires Remote#error - Emitted if settings operations fail
516
724
  * @example
517
725
  * remote.handleSettings('get', false);
518
726
  */
519
- handleSettings: function (mode, overrideQuiet) {
727
+ handleSettings(mode, overrideQuiet) {
520
728
  const keys = [
521
729
  { ns: "system", key: "screen_off_timeout", value: 2147483647 },
522
730
  { ns: "secure", key: "sleep_timeout", value: 0 },
@@ -526,7 +734,7 @@ module.exports = function (config) {
526
734
  return client
527
735
  .connect(ip, port)
528
736
  .then(() => {
529
- if (!useQuiet) logWithTime(`Connected to ${host}`);
737
+ if (!useQuiet) emitLog("info", `Connected to ${host}`, "handleSettings");
530
738
  let chain = Promise.resolve();
531
739
  keys.forEach((item) => {
532
740
  chain = chain.then(() => {
@@ -536,15 +744,15 @@ module.exports = function (config) {
536
744
  } else {
537
745
  cmd = `settings get ${item.ns} ${item.key}`;
538
746
  }
539
- return client
540
- .shell(host, cmd)
541
- .then(adb.util.readAll)
747
+ return device
748
+ .shell(cmd)
749
+ .then(Adb.util.readAll)
542
750
  .then((result) => {
543
751
  if (!useQuiet) {
544
752
  if (mode === "set") {
545
- logWithTime(`Set ${item.ns} ${item.key} to ${item.value}`);
753
+ emitLog("info", `Set ${item.ns} ${item.key} to ${item.value}`, "handleSettings");
546
754
  } else {
547
- logWithTime(`${item.ns} ${item.key}: ${result.toString().trim()}`);
755
+ emitLog("info", `${item.ns} ${item.key}: ${result.toString().trim()}`, "handleSettings");
548
756
  }
549
757
  }
550
758
  });
@@ -554,11 +762,11 @@ module.exports = function (config) {
554
762
  })
555
763
  .then(() => client.disconnect(ip, port))
556
764
  .then(() => {
557
- if (!useQuiet) logWithTime("Disconnected cleanly");
765
+ if (!useQuiet) emitLog("info", "Disconnected cleanly", "handleSettings");
558
766
  })
559
767
  .catch((err) => {
560
768
  if (err.message && err.message.includes("disconnected")) {
561
- if (!useQuiet) warnWithTime("Warning: Device already disconnected before explicit disconnect call.");
769
+ if (!useQuiet) emitLog("warn", "Device already disconnected before explicit disconnect call", "handleSettings");
562
770
  } else {
563
771
  return handleDisconnectError(err);
564
772
  }
@@ -570,6 +778,8 @@ module.exports = function (config) {
570
778
  * @public
571
779
  * @param {function(Error=, any=)=} [cb]
572
780
  * @returns {Promise|undefined}
781
+ * @fires Remote#log - Emitted with connection status information
782
+ * @fires Remote#error - Emitted if connection fails or ADB errors occur
573
783
  * @example
574
784
  * await remote.connect();
575
785
  * remote.connect((err) => { ... });
@@ -583,6 +793,8 @@ module.exports = function (config) {
583
793
  * @public
584
794
  * @param {function(Error=, any=)=} [cb]
585
795
  * @returns {Promise|undefined}
796
+ * @fires Remote#log - Emitted with disconnection status information
797
+ * @fires Remote#error - Emitted if disconnection fails
586
798
  * @example
587
799
  * await remote.disconnect();
588
800
  * remote.disconnect((err) => { ... });
@@ -617,10 +829,10 @@ module.exports = function (config) {
617
829
  */
618
830
  const obj = {};
619
831
  const longObj = {};
620
- remoteKeys.forEach(function (key) {
832
+ remoteKeys.forEach((key) => {
621
833
  /**
622
834
  * Sends the corresponding keycode for this remote key.
623
- * @returns {Promise}
835
+ * @returns {Promise<any>}
624
836
  * @example
625
837
  * press.home();
626
838
  */
@@ -665,7 +877,7 @@ module.exports = function (config) {
665
877
 
666
878
  /**
667
879
  * Sends the corresponding keycode for this remote key as a long press.
668
- * @returns {Promise}
880
+ * @returns {Promise<any>}
669
881
  * @example
670
882
  * press.long.home();
671
883
  */
@@ -728,7 +940,7 @@ module.exports = function (config) {
728
940
  * Sends text input to the device.
729
941
  * @public
730
942
  * @param {string} text - The text to input.
731
- * @returns {Promise}
943
+ * @returns {Promise<any>}
732
944
  * @example
733
945
  * keyboard.text('hello');
734
946
  */
@@ -741,7 +953,9 @@ module.exports = function (config) {
741
953
  wrapAsync(function (keyName, options) {
742
954
  options = options || {};
743
955
  if (!keycodes[keyName]) {
744
- return Promise.reject(new Error("Unknown key: " + keyName));
956
+ const error = new Error("Unknown key: " + keyName);
957
+ emitError(error, "keyboard.key", `Unknown key: ${keyName}`);
958
+ return Promise.reject(error);
745
959
  }
746
960
  if (!options.forceKeycode) {
747
961
  // Try inputText for single character keys
@@ -756,10 +970,10 @@ module.exports = function (config) {
756
970
  // Dynamically add all key functions and .keycode subobject
757
971
  ...(() => {
758
972
  const keyFns = {};
759
- Object.keys(keycodes).forEach(function (keyName) {
973
+ Object.keys(keycodes).forEach((keyName) => {
760
974
  /**
761
975
  * Sends this key using inputText (if possible) or keycode fallback.
762
- * @returns {Promise}
976
+ * @returns {Promise<any>}
763
977
  * @example
764
978
  * keyboard.key.a();
765
979
  */
@@ -772,7 +986,7 @@ module.exports = function (config) {
772
986
  });
773
987
  /**
774
988
  * Sends this key using keycode only.
775
- * @returns {Promise}
989
+ * @returns {Promise<any>}
776
990
  * @example
777
991
  * keyboard.key.a.keycode();
778
992
  */
@@ -788,10 +1002,10 @@ module.exports = function (config) {
788
1002
  */
789
1003
  shift: (() => {
790
1004
  const shiftFns = {};
791
- Object.keys(keycodes).forEach(function (keyName) {
1005
+ Object.keys(keycodes).forEach((keyName) => {
792
1006
  /**
793
1007
  * Sends this key with shift using inputText (if possible) or keycode fallback.
794
- * @returns {Promise}
1008
+ * @returns {Promise<any>}
795
1009
  * @example
796
1010
  * keyboard.key.shift.a();
797
1011
  */
@@ -800,19 +1014,19 @@ module.exports = function (config) {
800
1014
  if (!options.forceKeycode && keyName.length === 1) {
801
1015
  return inputText(keyName.toUpperCase());
802
1016
  }
803
- return inputKeycodeWrapped(keycodes.shiftLeft).then(function () {
1017
+ return inputKeycodeWrapped(keycodes.shiftLeft).then(() => {
804
1018
  return inputKeycodeLongPressWrapped(keycodes[keyName]);
805
1019
  });
806
1020
  });
807
1021
 
808
1022
  /**
809
1023
  * Sends this key with shift using keycode only.
810
- * @returns {Promise}
1024
+ * @returns {Promise<any>}
811
1025
  * @example
812
1026
  * keyboard.key.shift.a.keycode();
813
1027
  */
814
1028
  shiftFns[keyName].keycode = wrapAsync(function () {
815
- return inputKeycodeWrapped(keycodes.shiftLeft).then(function () {
1029
+ return inputKeycodeWrapped(keycodes.shiftLeft).then(() => {
816
1030
  return inputKeycodeLongPressWrapped(keycodes[keyName]);
817
1031
  });
818
1032
  });
@@ -824,4 +1038,33 @@ module.exports = function (config) {
824
1038
  }
825
1039
  };
826
1040
  return remoteApi;
827
- };
1041
+ }
1042
+
1043
+ /**
1044
+ * Create and return a ready-to-use Android TV Remote instance.
1045
+ * @public
1046
+ * @param {RemoteConfig} config - Configuration for the remote.
1047
+ * @returns {Promise<Remote>} Resolves with a ready remote instance.
1048
+ *
1049
+ * @description
1050
+ * Creates a remote instance and waits for initialization to complete if autoConnect is enabled.
1051
+ *
1052
+ * @example
1053
+ * // ESM with event handling
1054
+ * const remote = await createAndroidTVRemote({ ip: "192.168.1.100" });
1055
+ * remote.on('log', (data) => console.log(data));
1056
+ * remote.on('error', (data) => console.error(data));
1057
+ */
1058
+ 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;
1067
+ }
1068
+
1069
+ // Add static create method to the default export
1070
+ createRemote.create = createAndroidTVRemote;