@cldmv/node-android-tv-remote 1.5.5 → 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).
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.
18
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,17 +259,21 @@ 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
  /**
@@ -169,42 +281,63 @@ module.exports = function (config) {
169
281
  * This ensures the internal state is correct if the device is already connected.
170
282
  * Expose a promise (initPromise) that resolves or rejects based on the result.
171
283
  */
284
+ const INIT_TIMEOUT_MS = 7000;
285
+
172
286
  /**
173
287
  * Internal resolve/reject for initPromise, always defined as functions.
174
288
  */
175
- let initPromiseResolve = (_v) => {};
176
- let initPromiseReject = (_e) => {};
289
+ let initPromiseResolve;
290
+ let initPromiseReject;
291
+
177
292
  /**
178
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.
179
295
  * @type {Promise<void>}
180
296
  * @example
181
297
  * remote.initPromise.then(() => { ... }).catch((err) => { ... });
182
298
  */
183
- const initPromise = new Promise((resolve, reject) => {
299
+ const realInitPromise = new Promise((resolve, reject) => {
184
300
  initPromiseResolve = resolve;
185
301
  initPromiseReject = reject;
186
- });
187
- (async () => {
188
- try {
189
- const status = await getConnectionStatus(true);
190
- if (status === "connected") {
191
- connected = true;
192
- if (!quiet) logWithTime("Already connected to " + host + " (on init)");
193
- startHeartbeat();
194
- initPromiseResolve();
195
- } else {
196
- // Try to connect if not already connected
197
- await connect();
198
- if (connected) {
199
- initPromiseResolve();
302
+ if (!autoConnect) {
303
+ // Skip initialization if autoConnect is disabled
304
+ initPromiseResolve(undefined);
305
+ return;
306
+ }
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);
200
315
  } else {
201
- initPromiseReject(new Error("Failed to connect to device on initialization."));
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
+ }
202
325
  }
326
+ } catch (e) {
327
+ emitError(e instanceof Error ? e : new Error(String(e)), "initPromise", "Exception during initialization");
328
+ initPromiseReject(e);
203
329
  }
204
- } catch (e) {
205
- initPromiseReject(e);
206
- }
207
- })();
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
+ ]);
208
341
 
209
342
  /**
210
343
  * Resets the disconnect timer if autoDisconnect is enabled.
@@ -214,7 +347,7 @@ module.exports = function (config) {
214
347
  function resetDisconnectTimer() {
215
348
  if (!autoDisconnect) return;
216
349
  if (disconnectTimer) clearTimeout(disconnectTimer);
217
- disconnectTimer = setTimeout(function () {
350
+ disconnectTimer = setTimeout(() => {
218
351
  if (connected) disconnect();
219
352
  }, disconnectTimeout * 1000);
220
353
  }
@@ -231,7 +364,7 @@ module.exports = function (config) {
231
364
  heartbeatTimer = setInterval(() => {
232
365
  if (!connected) return;
233
366
  // Send a no-op shell command to keep the connection alive
234
- client.shell(host, "echo heartbeat").catch(() => {});
367
+ device.shell("echo heartbeat").catch(() => {});
235
368
  }, heartbeatInterval);
236
369
  startConnectionCheck();
237
370
  }
@@ -250,12 +383,13 @@ module.exports = function (config) {
250
383
  const deviceId = host;
251
384
  const found = devices.some((d) => d.id === deviceId);
252
385
  if (!found) {
253
- 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");
254
387
  connected = false;
255
388
  await connect();
256
389
  }
257
390
  } catch (err) {
258
- 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");
259
393
  }
260
394
  }, connectionCheckInterval);
261
395
  }
@@ -296,19 +430,19 @@ module.exports = function (config) {
296
430
  */
297
431
  function connect() {
298
432
  if (connected) {
299
- if (!quiet) logWithTime("Already connected to " + host);
433
+ if (!quiet) emitLog("info", `Already connected to ${host}`, "connect");
300
434
  return Promise.resolve();
301
435
  }
302
436
  return client
303
437
  .connect(ip, port)
304
- .then(function () {
438
+ .then(() => {
305
439
  connected = true;
306
- if (!quiet) logWithTime("Connected to " + host);
440
+ if (!quiet) emitLog("info", `Connected to ${host}`, "connect");
307
441
  startHeartbeat();
308
442
  })
309
- .catch(function (err) {
443
+ .catch((err) => {
310
444
  if (err.message && err.message.includes("already connected")) {
311
- if (!quiet) warnWithTime("Warning: Device already connected.");
445
+ if (!quiet) emitLog("warn", "Device already connected", "connect");
312
446
  connected = true;
313
447
  startHeartbeat();
314
448
  return true;
@@ -332,14 +466,14 @@ module.exports = function (config) {
332
466
  stopHeartbeat();
333
467
  return client
334
468
  .disconnect(ip, port)
335
- .then(function () {
469
+ .then(() => {
336
470
  connected = false;
337
- if (!quiet) logWithTime("Disconnected from " + host);
471
+ if (!quiet) emitLog("info", `Disconnected from ${host}`, "disconnect");
338
472
  return true;
339
473
  })
340
- .catch(function (err) {
474
+ .catch((err) => {
341
475
  if (err.message && err.message.includes("disconnected")) {
342
- if (!quiet) warnWithTime("Warning: Device already disconnected before explicit disconnect call.");
476
+ if (!quiet) emitLog("warn", "Device already disconnected before explicit disconnect call", "disconnect");
343
477
  connected = false;
344
478
  return true;
345
479
  }
@@ -352,12 +486,12 @@ module.exports = function (config) {
352
486
  * Sends a keycode to the device, auto-connects/disconnects as needed.
353
487
  * @internal
354
488
  * @param {number} code - The Android keycode to send.
355
- * @returns {Promise}
489
+ * @returns {Promise<any>}
356
490
  */
357
491
  function inputKeycode(code) {
358
- return ensureConnected().then(function () {
492
+ return ensureConnected().then(() => {
359
493
  resetDisconnectTimer();
360
- return client.shell(host, "input keyevent " + code);
494
+ return device.shell("input keyevent " + code);
361
495
  });
362
496
  }
363
497
  const inputKeycodeWrapped = wrapAsync(inputKeycode);
@@ -366,13 +500,13 @@ module.exports = function (config) {
366
500
  * Sends a long press keycode to the device, auto-connects/disconnects as needed.
367
501
  * @internal
368
502
  * @param {number} code - The Android keycode to send as a long press.
369
- * @returns {Promise}
503
+ * @returns {Promise<any>}
370
504
  */
371
505
  function inputKeycodeLongPress(code) {
372
506
  const cmd = "sendevent " + inputDevice + " 1 " + code + " 1 && " + "sleep 1 && " + "sendevent " + inputDevice + " 1 " + code + " 0";
373
- return ensureConnected().then(function () {
507
+ return ensureConnected().then(() => {
374
508
  resetDisconnectTimer();
375
- return client.shell(host, cmd);
509
+ return device.shell(cmd);
376
510
  });
377
511
  }
378
512
  const inputKeycodeLongPressWrapped = wrapAsync(inputKeycodeLongPress);
@@ -381,13 +515,13 @@ module.exports = function (config) {
381
515
  * Sends text input to the device, auto-connects/disconnects as needed.
382
516
  * @internal
383
517
  * @param {string} text - The text to input.
384
- * @returns {Promise}
518
+ * @returns {Promise<any>}
385
519
  */
386
520
  function inputText(text) {
387
521
  const escaped = text.replace(/ /g, "%s");
388
- return ensureConnected().then(function () {
522
+ return ensureConnected().then(() => {
389
523
  resetDisconnectTimer();
390
- return client.shell(host, 'input text "' + escaped + '"');
524
+ return device.shell('input text "' + escaped + '"');
391
525
  });
392
526
  }
393
527
  const inputTextWrapped = wrapAsync(inputText);
@@ -398,34 +532,18 @@ module.exports = function (config) {
398
532
  for (let i = 0; i < 26; i++) {
399
533
  const letter = String.fromCharCode(97 + i);
400
534
  const code = 29 + i;
401
- keyboardKeys[letter] = (function (code) {
402
- return function () {
403
- return inputKeycode(code);
404
- };
405
- })(code);
406
- keyboardShiftKeys[letter] = (function (code) {
407
- return function () {
408
- return inputKeycode(keycodes.shiftLeft).then(function () {
409
- return inputKeycode(code);
410
- });
411
- };
535
+ keyboardKeys[letter] = ((code) => () => inputKeycode(code))(code);
536
+ keyboardShiftKeys[letter] = ((code) => () => {
537
+ return inputKeycode(keycodes.shiftLeft).then(() => inputKeycode(code));
412
538
  })(code);
413
539
  }
414
540
 
415
- keyboardKeys.enter = function () {
416
- return inputKeycode(keycodes.enter);
417
- };
418
- keyboardKeys.space = function () {
419
- return inputKeycode(keycodes.space);
420
- };
421
- keyboardKeys.del = function () {
422
- return inputKeycode(keycodes.del);
423
- };
541
+ keyboardKeys.enter = () => inputKeycode(keycodes.enter);
542
+ keyboardKeys.space = () => inputKeycode(keycodes.space);
543
+ keyboardKeys.del = () => inputKeycode(keycodes.del);
424
544
 
425
- keyboardShiftKeys.enter = function () {
426
- return inputKeycode(keycodes.shiftLeft).then(function () {
427
- return inputKeycode(keycodes.enter);
428
- });
545
+ keyboardShiftKeys.enter = () => {
546
+ return inputKeycode(keycodes.shiftLeft).then(() => inputKeycode(keycodes.enter));
429
547
  };
430
548
 
431
549
  /**
@@ -501,6 +619,62 @@ module.exports = function (config) {
501
619
  * remote.initPromise.then(() => { ... }).catch((err) => { ... });
502
620
  */
503
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
+ },
504
678
  /**
505
679
  * Returns the current connection status as tracked by the module, or does a live check if requested.
506
680
  * @function
@@ -517,7 +691,7 @@ module.exports = function (config) {
517
691
  * @example
518
692
  * remote.getKeyboardKeys();
519
693
  */
520
- getKeyboardKeys: function () {
694
+ getKeyboardKeys() {
521
695
  return getKeyboardKeys.call(remoteApi);
522
696
  },
523
697
  /**
@@ -526,7 +700,7 @@ module.exports = function (config) {
526
700
  * @example
527
701
  * remote.getPressCommands();
528
702
  */
529
- getPressCommands: function () {
703
+ getPressCommands() {
530
704
  return getPressCommands.call(remoteApi);
531
705
  },
532
706
  /**
@@ -545,10 +719,12 @@ module.exports = function (config) {
545
719
  * @param {string} mode - 'get' or 'set'.
546
720
  * @param {boolean} [overrideQuiet] - Optionally override the quiet flag for this call.
547
721
  * @returns {Promise<void>}
722
+ * @fires Remote#log - Emitted with settings operation status and results
723
+ * @fires Remote#error - Emitted if settings operations fail
548
724
  * @example
549
725
  * remote.handleSettings('get', false);
550
726
  */
551
- handleSettings: function (mode, overrideQuiet) {
727
+ handleSettings(mode, overrideQuiet) {
552
728
  const keys = [
553
729
  { ns: "system", key: "screen_off_timeout", value: 2147483647 },
554
730
  { ns: "secure", key: "sleep_timeout", value: 0 },
@@ -558,7 +734,7 @@ module.exports = function (config) {
558
734
  return client
559
735
  .connect(ip, port)
560
736
  .then(() => {
561
- if (!useQuiet) logWithTime(`Connected to ${host}`);
737
+ if (!useQuiet) emitLog("info", `Connected to ${host}`, "handleSettings");
562
738
  let chain = Promise.resolve();
563
739
  keys.forEach((item) => {
564
740
  chain = chain.then(() => {
@@ -568,15 +744,15 @@ module.exports = function (config) {
568
744
  } else {
569
745
  cmd = `settings get ${item.ns} ${item.key}`;
570
746
  }
571
- return client
572
- .shell(host, cmd)
573
- .then(adb.util.readAll)
747
+ return device
748
+ .shell(cmd)
749
+ .then(Adb.util.readAll)
574
750
  .then((result) => {
575
751
  if (!useQuiet) {
576
752
  if (mode === "set") {
577
- logWithTime(`Set ${item.ns} ${item.key} to ${item.value}`);
753
+ emitLog("info", `Set ${item.ns} ${item.key} to ${item.value}`, "handleSettings");
578
754
  } else {
579
- logWithTime(`${item.ns} ${item.key}: ${result.toString().trim()}`);
755
+ emitLog("info", `${item.ns} ${item.key}: ${result.toString().trim()}`, "handleSettings");
580
756
  }
581
757
  }
582
758
  });
@@ -586,11 +762,11 @@ module.exports = function (config) {
586
762
  })
587
763
  .then(() => client.disconnect(ip, port))
588
764
  .then(() => {
589
- if (!useQuiet) logWithTime("Disconnected cleanly");
765
+ if (!useQuiet) emitLog("info", "Disconnected cleanly", "handleSettings");
590
766
  })
591
767
  .catch((err) => {
592
768
  if (err.message && err.message.includes("disconnected")) {
593
- if (!useQuiet) warnWithTime("Warning: Device already disconnected before explicit disconnect call.");
769
+ if (!useQuiet) emitLog("warn", "Device already disconnected before explicit disconnect call", "handleSettings");
594
770
  } else {
595
771
  return handleDisconnectError(err);
596
772
  }
@@ -602,6 +778,8 @@ module.exports = function (config) {
602
778
  * @public
603
779
  * @param {function(Error=, any=)=} [cb]
604
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
605
783
  * @example
606
784
  * await remote.connect();
607
785
  * remote.connect((err) => { ... });
@@ -615,6 +793,8 @@ module.exports = function (config) {
615
793
  * @public
616
794
  * @param {function(Error=, any=)=} [cb]
617
795
  * @returns {Promise|undefined}
796
+ * @fires Remote#log - Emitted with disconnection status information
797
+ * @fires Remote#error - Emitted if disconnection fails
618
798
  * @example
619
799
  * await remote.disconnect();
620
800
  * remote.disconnect((err) => { ... });
@@ -649,10 +829,10 @@ module.exports = function (config) {
649
829
  */
650
830
  const obj = {};
651
831
  const longObj = {};
652
- remoteKeys.forEach(function (key) {
832
+ remoteKeys.forEach((key) => {
653
833
  /**
654
834
  * Sends the corresponding keycode for this remote key.
655
- * @returns {Promise}
835
+ * @returns {Promise<any>}
656
836
  * @example
657
837
  * press.home();
658
838
  */
@@ -697,7 +877,7 @@ module.exports = function (config) {
697
877
 
698
878
  /**
699
879
  * Sends the corresponding keycode for this remote key as a long press.
700
- * @returns {Promise}
880
+ * @returns {Promise<any>}
701
881
  * @example
702
882
  * press.long.home();
703
883
  */
@@ -760,7 +940,7 @@ module.exports = function (config) {
760
940
  * Sends text input to the device.
761
941
  * @public
762
942
  * @param {string} text - The text to input.
763
- * @returns {Promise}
943
+ * @returns {Promise<any>}
764
944
  * @example
765
945
  * keyboard.text('hello');
766
946
  */
@@ -773,7 +953,9 @@ module.exports = function (config) {
773
953
  wrapAsync(function (keyName, options) {
774
954
  options = options || {};
775
955
  if (!keycodes[keyName]) {
776
- 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);
777
959
  }
778
960
  if (!options.forceKeycode) {
779
961
  // Try inputText for single character keys
@@ -788,10 +970,10 @@ module.exports = function (config) {
788
970
  // Dynamically add all key functions and .keycode subobject
789
971
  ...(() => {
790
972
  const keyFns = {};
791
- Object.keys(keycodes).forEach(function (keyName) {
973
+ Object.keys(keycodes).forEach((keyName) => {
792
974
  /**
793
975
  * Sends this key using inputText (if possible) or keycode fallback.
794
- * @returns {Promise}
976
+ * @returns {Promise<any>}
795
977
  * @example
796
978
  * keyboard.key.a();
797
979
  */
@@ -804,7 +986,7 @@ module.exports = function (config) {
804
986
  });
805
987
  /**
806
988
  * Sends this key using keycode only.
807
- * @returns {Promise}
989
+ * @returns {Promise<any>}
808
990
  * @example
809
991
  * keyboard.key.a.keycode();
810
992
  */
@@ -820,10 +1002,10 @@ module.exports = function (config) {
820
1002
  */
821
1003
  shift: (() => {
822
1004
  const shiftFns = {};
823
- Object.keys(keycodes).forEach(function (keyName) {
1005
+ Object.keys(keycodes).forEach((keyName) => {
824
1006
  /**
825
1007
  * Sends this key with shift using inputText (if possible) or keycode fallback.
826
- * @returns {Promise}
1008
+ * @returns {Promise<any>}
827
1009
  * @example
828
1010
  * keyboard.key.shift.a();
829
1011
  */
@@ -832,19 +1014,19 @@ module.exports = function (config) {
832
1014
  if (!options.forceKeycode && keyName.length === 1) {
833
1015
  return inputText(keyName.toUpperCase());
834
1016
  }
835
- return inputKeycodeWrapped(keycodes.shiftLeft).then(function () {
1017
+ return inputKeycodeWrapped(keycodes.shiftLeft).then(() => {
836
1018
  return inputKeycodeLongPressWrapped(keycodes[keyName]);
837
1019
  });
838
1020
  });
839
1021
 
840
1022
  /**
841
1023
  * Sends this key with shift using keycode only.
842
- * @returns {Promise}
1024
+ * @returns {Promise<any>}
843
1025
  * @example
844
1026
  * keyboard.key.shift.a.keycode();
845
1027
  */
846
1028
  shiftFns[keyName].keycode = wrapAsync(function () {
847
- return inputKeycodeWrapped(keycodes.shiftLeft).then(function () {
1029
+ return inputKeycodeWrapped(keycodes.shiftLeft).then(() => {
848
1030
  return inputKeycodeLongPressWrapped(keycodes[keyName]);
849
1031
  });
850
1032
  });
@@ -856,4 +1038,33 @@ module.exports = function (config) {
856
1038
  }
857
1039
  };
858
1040
  return remoteApi;
859
- };
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;