@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.
package/README.md CHANGED
@@ -18,7 +18,16 @@
18
18
 
19
19
  ## Overview
20
20
 
21
- A Node.js module for controlling Android TV devices via ADB. Supports sending keycodes, keyboard input, and remote control commands. Designed for compatibility with a wide range of Android TV devices, including Fire TV, Chromecast with Google TV, and more.
21
+ A modern, **event-driven** Node.js module for controlling Android TV devices via ADB. Supports sending keycodes, keyboard input, and remote control commands. Designed for compatibility with a wide range of Android TV devices, including Fire TV, Chromecast with Google TV, and more.
22
+
23
+ ### Key Features
24
+
25
+ - 🎯 **Event-driven architecture** - No console pollution, structured event data
26
+ - 🔄 **ESM & CommonJS support** - Works with both `import` and `require`
27
+ - 🛡️ **Error resilience** - Errors emit events instead of crashing your app
28
+ - 🔗 **Method chaining** - Fluent API for event listener management
29
+ - 📊 **Structured logging** - Timestamped, categorized log events with source tracking
30
+ - 🚀 **Promise-based** - Modern async/await support with callback compatibility
22
31
 
23
32
  ## Installation
24
33
 
@@ -61,8 +70,15 @@ npm install android-tv-remote
61
70
 
62
71
  ## Usage
63
72
 
73
+ ### Basic Usage
74
+
64
75
  ```js
76
+ // ESM
77
+ import createRemote from "android-tv-remote";
78
+
79
+ // CJS
65
80
  const createRemote = require("android-tv-remote");
81
+
66
82
  const remote = createRemote({ ip: "192.168.1.100" });
67
83
 
68
84
  // Connect
@@ -78,17 +94,101 @@ await remote.keyboard.text("hello world");
78
94
  await remote.disconnect();
79
95
  ```
80
96
 
97
+ ### Event-Driven Usage (Recommended)
98
+
99
+ This module uses an **event-driven architecture** instead of console logging. All operations emit structured events that you can listen to:
100
+
101
+ ```js
102
+ import createRemote from "android-tv-remote";
103
+
104
+ const remote = createRemote({ ip: "192.168.1.100" });
105
+
106
+ // Listen for log events (info, warn, error, debug)
107
+ remote.on("log", (data) => {
108
+ console.log(`[${data.level}] ${data.source}: ${data.message}`);
109
+ });
110
+
111
+ // Listen for error events
112
+ remote.on("error", (data) => {
113
+ console.error(`ERROR from ${data.source}:`, data.error.message);
114
+
115
+ // Handle specific error types
116
+ if (data.error.message.includes("device unauthorized")) {
117
+ console.log("Please authorize ADB on your Android TV device");
118
+ }
119
+ });
120
+
121
+ // Use the remote
122
+ await remote.press.home();
123
+ ```
124
+
125
+ ### Static Create Method
126
+
127
+ For cleaner async initialization:
128
+
129
+ ```js
130
+ import { createAndroidTVRemote } from "android-tv-remote";
131
+
132
+ const remote = await createAndroidTVRemote({ ip: "192.168.1.100" });
133
+ remote.on("log", console.log);
134
+ await remote.press.play();
135
+ ```
136
+
137
+ ### Event Data Structure
138
+
139
+ **Log Events:**
140
+
141
+ ```js
142
+ {
143
+ level: 'info' | 'warn' | 'error' | 'debug',
144
+ message: 'Human readable message',
145
+ source: 'connect' | 'disconnect' | 'handleSettings' | etc,
146
+ timestamp: '2025-10-15T18:37:44.854Z',
147
+ data?: any // Optional additional data
148
+ }
149
+ ```
150
+
151
+ **Error Events:**
152
+
153
+ ```js
154
+ {
155
+ error: Error, // The actual error object
156
+ source: 'connect' | 'adb' | 'keyboard.key' | etc,
157
+ message: 'Human readable error message',
158
+ timestamp: '2025-10-15T18:37:44.854Z'
159
+ }
160
+ ```
161
+
81
162
  ## API
82
163
 
83
- See [API documentation](#) for full details. Main methods:
164
+ ### Main Methods
165
+
166
+ - `connect()` / `disconnect()` - Device connection management
167
+ - `press.<key>()` / `press.long.<key>()` - Remote control buttons
168
+ - `keyboard.text(text)` - Text input
169
+ - `keyboard.key.<key>()` / `keyboard.key.<key>.keycode()` - Individual keys
170
+ - `keyboard.key.shift.<key>()` / `keyboard.key.shift.<key>.keycode()` - Shifted keys
171
+ - `inputKeycode(code)` - Raw Android keycodes
172
+ - `handleSettings(mode, [overrideQuiet])` - Android settings management
173
+
174
+ ### Event Methods
175
+
176
+ - `on(event, listener)` - Add event listener (returns remote for chaining)
177
+ - `off(event, listener)` - Remove event listener (returns remote for chaining)
178
+ - `once(event, listener)` - Add one-time event listener (returns remote for chaining)
179
+ - `emit(event, ...args)` - Emit custom events
180
+
181
+ ### Events
182
+
183
+ - `log` - Emitted for all operations (info, warn, error, debug levels)
184
+ - `error` - Emitted when errors occur (structured error data)
185
+
186
+ ### Properties
187
+
188
+ - `isConnected` - Boolean indicating connection status
189
+ - `initPromise` - Promise that resolves when initialization completes
84
190
 
85
- - `connect()` / `disconnect()`
86
- - `press.<key>()` / `press.long.<key>()`
87
- - `keyboard.text(text)`
88
- - `keyboard.key.<key>()` / `keyboard.key.<key>.keycode()`
89
- - `keyboard.key.shift.<key>()` / `keyboard.key.shift.<key>.keycode()`
90
- - `inputKeycode(code)`
91
- - `handleSettings(mode, [overrideQuiet])`
191
+ See JSDoc comments in source code for full API documentation.
92
192
 
93
193
  ## Supported Devices
94
194
 
package/index.cjs ADDED
@@ -0,0 +1,31 @@
1
+ /**
2
+ * @Project: @cldmv/node-android-tv-remote
3
+ * @Filename: /index.cjs
4
+ * @Date: 2025-10-15 10:29:19 -07:00 (1760549359)
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 10:39:45 -07:00 (1760549985)
10
+ * -----
11
+ * @Copyright: Copyright (c) 2013-2025 Catalyzed Motivation Inc. All rights reserved.
12
+ */
13
+
14
+ /**
15
+ * CommonJS entry point for @cldmv/node-android-tv-remote
16
+ *
17
+ * This file provides CommonJS (require) support for the Android TV Remote Library.
18
+ * It imports and re-exports the main createRemote function from the ESM module.
19
+ *
20
+ * @module @cldmv/node-android-tv-remote/cjs
21
+ */
22
+
23
+ const { createRequire } = require("module");
24
+ const requireESM = createRequire(__filename);
25
+
26
+ const { default: createRemote, AndroidTVSetup } = requireESM("./index.mjs");
27
+
28
+ module.exports = createRemote;
29
+ module.exports.createRemote = createRemote;
30
+ module.exports.AndroidTVSetup = AndroidTVSetup;
31
+ module.exports.default = createRemote;
package/index.mjs ADDED
@@ -0,0 +1,25 @@
1
+ /**
2
+ * @Project: @cldmv/node-android-tv-remote
3
+ * @Filename: /index.mjs
4
+ * @Date: 2025-10-15 10:29:19 -07:00 (1760549359)
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 10:40:23 -07:00 (1760550023)
10
+ * -----
11
+ * @Copyright: Copyright (c) 2013-2025 Catalyzed Motivation Inc. All rights reserved.
12
+ */
13
+
14
+ /**
15
+ * ES Module entry point for @cldmv/node-android-tv-remote
16
+ *
17
+ * This file provides ES Module (import) support for the Android TV Remote Library.
18
+ * It imports and re-exports the main createRemote function and helper classes.
19
+ *
20
+ * @module @cldmv/node-android-tv-remote/esm
21
+ */
22
+
23
+ export { default } from "./src/lib/android-tv-remote.mjs";
24
+ export { default as createRemote, createAndroidTVRemote } from "./src/lib/android-tv-remote.mjs";
25
+ export { default as AndroidTVSetup } from "./src/lib/adb/setup.mjs";
package/package.json CHANGED
@@ -1,12 +1,18 @@
1
1
  {
2
2
  "name": "@cldmv/node-android-tv-remote",
3
- "version": "1.5.4",
3
+ "version": "2.0.0",
4
4
  "description": "A Node.js library for controlling Android TV devices via ADB keycodes and text input.",
5
- "main": "src/lib/android-tv-remote.js",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "import": "./index.mjs",
9
+ "require": "./index.cjs"
10
+ }
11
+ },
6
12
  "scripts": {
7
13
  "test": "jest",
8
- "postinstall": "node scripts/postinstall.js",
9
- "setup-device": "node scripts/setup-device.js"
14
+ "postinstall": "node scripts/postinstall.mjs",
15
+ "setup-device": "node scripts/setup-device.mjs"
10
16
  },
11
17
  "keywords": [
12
18
  "android",
@@ -37,9 +43,12 @@
37
43
  "homepage": "https://github.com/CLDMV/node-android-tv-remote#readme",
38
44
  "license": "MIT",
39
45
  "dependencies": {
40
- "adbkit": "2.11.1"
46
+ "@devicefarmer/adbkit": "^3.3.8"
41
47
  },
42
48
  "devDependencies": {
43
49
  "jest": "^30.0.5"
50
+ },
51
+ "publishConfig": {
52
+ "access": "public"
44
53
  }
45
54
  }
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * Postinstall script to check for adb and print install instructions if missing.
3
3
  */
4
- const { execSync } = require("child_process");
5
- const os = require("os");
4
+ import { execSync } from "child_process";
5
+ import os from "os";
6
6
 
7
7
  function hasAdb() {
8
8
  try {
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- const readline = require("readline");
4
- const AndroidTVSetup = require("../src/lib/adb/setup");
3
+ import readline from "readline";
4
+ import AndroidTVSetup from "../src/lib/adb/setup.mjs";
5
5
 
6
6
  /**
7
7
  * Interactive CLI for setting up a new Android TV device.
@@ -33,7 +33,7 @@ async function main() {
33
33
  await setup.disconnect();
34
34
  console.log("\nSetup complete!");
35
35
  } catch (err) {
36
- setup.errorWithTime("Error:", err.message || err);
36
+ console.error("Error:", err.message || err);
37
37
  process.exit(1);
38
38
  }
39
39
  }
@@ -0,0 +1,291 @@
1
+ /**
2
+ * @Project: @cldmv/node-android-tv-remote
3
+ * @Filename: /src/lib/adb/setup.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 12:04:44 -07:00 (1760555084)
10
+ * -----
11
+ * @Copyright: Copyright (c) 2013-2025 Catalyzed Motivation Inc. All rights reserved.
12
+ */
13
+
14
+ /**
15
+ * AndroidTVSetup class for configuring and managing Android TV devices via ADB.
16
+ *
17
+ * Usage:
18
+ * const setup = new AndroidTVSetup({ ip, port, quiet });
19
+ * await setup.connect();
20
+ * await setup.setSettings();
21
+ * await setup.ensureAwake();
22
+ * await setup.disconnect();
23
+ */
24
+ import createRemote from "../android-tv-remote.mjs";
25
+ import adbkit from "@devicefarmer/adbkit";
26
+ import { EventEmitter } from "events";
27
+
28
+ /**
29
+ * Android keycodes mapping loaded from JSON file.
30
+ * @internal
31
+ * @type {Object.<string, number>}
32
+ * @see https://developer.android.com/reference/android/view/KeyEvent
33
+ */
34
+ import keycodes from "../../data/keycodes.json" with { type: "json" };
35
+
36
+ const Adb = adbkit.Adb;
37
+
38
+ class AndroidTVSetup extends EventEmitter {
39
+ /**
40
+ * Create an AndroidTVSetup instance.
41
+ * @param {Object} options - Configuration options.
42
+ * @param {string} options.ip - Device IP address.
43
+ * @param {number} [options.port=5555] - Device port.
44
+ * @param {boolean} [options.quiet=false] - Suppress log output.
45
+ */
46
+ constructor(options = {}) {
47
+ super();
48
+ const { ip, port = 5555, quiet = false, autoConnect = true } = options;
49
+ this.ip = ip;
50
+ this.port = port;
51
+ this.quiet = quiet;
52
+ this.remote = createRemote({ ip, port, quiet, autoConnect });
53
+ this.host = `${ip}:${port}`;
54
+ }
55
+
56
+ /**
57
+ * Emit a log event with structured data.
58
+ * @private
59
+ * @param {string} level - Log level (info, warn, error, debug).
60
+ * @param {string} message - Log message.
61
+ * @param {string} [source] - Source of the log message.
62
+ * @param {any} [data] - Additional data to include.
63
+ */
64
+ emitLog(level, message, source = "android-tv-setup", data = null) {
65
+ if (!this.quiet || level === "error") {
66
+ this.emit("log", {
67
+ level,
68
+ message,
69
+ source,
70
+ timestamp: new Date().toISOString(),
71
+ ...(data && { data })
72
+ });
73
+ }
74
+ }
75
+
76
+ /**
77
+ * Emit an error event with structured data.
78
+ * @private
79
+ * @param {Error} error - The error object.
80
+ * @param {string} [source] - Source of the error.
81
+ * @param {string} [message] - Additional error message.
82
+ */
83
+ emitError(error, source = "android-tv-setup", message = null) {
84
+ this.emit("error", {
85
+ error,
86
+ source,
87
+ message: message || error.message,
88
+ timestamp: new Date().toISOString()
89
+ });
90
+ }
91
+
92
+ async connect() {
93
+ await this.remote.connect();
94
+ this.emitLog("info", `Connected to ${this.host}`, "connect");
95
+ }
96
+
97
+ async disconnect() {
98
+ try {
99
+ await this.remote.disconnect();
100
+ this.emitLog("info", "Disconnected cleanly", "disconnect");
101
+ } catch (err) {
102
+ if (err.message && err.message.includes("disconnected")) {
103
+ this.emitLog("warn", "Device already disconnected before explicit disconnect call", "disconnect");
104
+ } else {
105
+ this.emitError(err, "disconnect");
106
+ if (err.message && err.message.includes("device unauthorized")) {
107
+ this.emitLog(
108
+ "error",
109
+ "Your device is unauthorized. Please check your TV and accept the authorization dialog to allow this computer to connect via ADB.",
110
+ "disconnect"
111
+ );
112
+ }
113
+ // Don't exit the process, just emit the error
114
+ throw err;
115
+ }
116
+ }
117
+ }
118
+
119
+ /**
120
+ * Set all recommended settings for always-on display and max brightness.
121
+ */
122
+ async setSettings() {
123
+ // Use the remote's handleSettings for all settings
124
+ await this.remote.handleSettings("set", this.quiet);
125
+ // svc power stayon true and brightness are not in handleSettings, so do them here
126
+ await this.remote.connect();
127
+ const cmds = ["settings put system screen_brightness_mode 0", "settings put system screen_brightness 255", "svc power stayon true"];
128
+ for (const cmd of cmds) {
129
+ (await this.remote.inputKeycode) ? Promise.resolve() : Promise.resolve(); // placeholder for future
130
+ await this.remotePressShell(cmd);
131
+ this.emitLog("info", `Ran: ${cmd}`, "setSettings");
132
+ }
133
+ await this.remote.disconnect();
134
+ }
135
+
136
+ /**
137
+ * Helper to run a shell command using the remote's ADB client.
138
+ * @param {string} cmd
139
+ * @returns {Promise<void>}
140
+ */
141
+ async remotePressShell(cmd) {
142
+ // Use the internal client for shell commands
143
+ if (this.remote && this.remote.inputKeycode) {
144
+ // fallback: use @devicefarmer/adbkit directly if needed
145
+ const client = Adb.createClient();
146
+ const device = client.getDevice(this.host);
147
+ await device.shell(cmd).then(Adb.util.readAll);
148
+ } else if (this.remote && this.remote.client) {
149
+ const device = this.remote.client.getDevice(this.host);
150
+ await device.shell(cmd).then(Adb.util.readAll);
151
+ }
152
+ }
153
+
154
+ /**
155
+ * Ensures the device is awake and on the home screen.
156
+ * Checks initial state, sends all necessary commands, then verifies final state.
157
+ * Only reports errors for states that remain incorrect after all commands are sent.
158
+ */
159
+ async ensureAwake() {
160
+ this.emitLog("info", "=== Starting ensureAwake sequence ===", "ensureAwake");
161
+
162
+ // Helper function to get current power state
163
+ const getCurrentPowerState = async () => {
164
+ const client = Adb.createClient();
165
+ const device = client.getDevice(this.host);
166
+ const output = await device
167
+ .shell("dumpsys power")
168
+ .then(Adb.util.readAll)
169
+ .then((b) => b.toString());
170
+ return this.parsePowerState(output);
171
+ };
172
+
173
+ // Helper function to emit power state
174
+ const emitPowerState = (parsed, context = "") => {
175
+ const prefix = context ? `${context} - ` : "";
176
+ this.emitLog("info", `${prefix}Power State:`, "ensureAwake");
177
+ this.emitLog("info", ` mIsPowered: ${parsed.mIsPowered}`, "ensureAwake");
178
+ this.emitLog("info", ` mWakefulness: ${parsed.mWakefulness}`, "ensureAwake");
179
+ this.emitLog("info", ` mDisplayReady: ${parsed.mDisplayReady}`, "ensureAwake");
180
+ };
181
+
182
+ // Get initial state
183
+ let powerState = await getCurrentPowerState();
184
+ emitPowerState(powerState, "Initial");
185
+
186
+ // Track what commands we need to send
187
+ const commandsToSend = [];
188
+
189
+ // Check what needs to be fixed
190
+ if (powerState.mIsPowered !== "true") {
191
+ this.emitLog("info", `Device not powered (${powerState.mIsPowered}), will send POWER keycode`, "ensureAwake");
192
+ commandsToSend.push({ keycode: keycodes.power, reason: "power on device" });
193
+ } else {
194
+ this.emitLog("info", "✅ Device already powered", "ensureAwake");
195
+ }
196
+
197
+ if (powerState.mWakefulness !== "Awake") {
198
+ this.emitLog("info", `Device not awake (${powerState.mWakefulness}), will send WAKEUP keycode`, "ensureAwake");
199
+ commandsToSend.push({ keycode: keycodes.wakeup, reason: "wake device" });
200
+ } else {
201
+ this.emitLog("info", "✅ Device already awake", "ensureAwake");
202
+ }
203
+
204
+ if (powerState.mDisplayReady !== "true") {
205
+ this.emitLog("info", `Display not ready (${powerState.mDisplayReady}), will send POWER keycode`, "ensureAwake");
206
+ commandsToSend.push({ keycode: keycodes.power, reason: "ready display" });
207
+ } else {
208
+ this.emitLog("info", "✅ Display already ready", "ensureAwake");
209
+ }
210
+
211
+ // Always send HOME to ensure we're on home screen
212
+ commandsToSend.push({ keycode: keycodes.home, reason: "ensure home screen" });
213
+
214
+ // Execute all commands with delays between them
215
+ if (commandsToSend.length > 0) {
216
+ this.emitLog("info", `Sending ${commandsToSend.length} keycode(s)...`, "ensureAwake");
217
+
218
+ for (let i = 0; i < commandsToSend.length; i++) {
219
+ const cmd = commandsToSend[i];
220
+ this.emitLog("info", `Sending keycode ${cmd.keycode} to ${cmd.reason}`, "ensureAwake");
221
+ await this.remote.inputKeycode(cmd.keycode);
222
+
223
+ // Add delay between commands (except after the last one)
224
+ if (i < commandsToSend.length - 1) {
225
+ await new Promise(resolve => setTimeout(resolve, 300));
226
+ }
227
+ }
228
+
229
+ // Wait for commands to take effect
230
+ this.emitLog("info", "Waiting for commands to take effect...", "ensureAwake");
231
+ await new Promise(resolve => setTimeout(resolve, 800));
232
+ }
233
+
234
+ // Get final state and check results
235
+ powerState = await getCurrentPowerState();
236
+ emitPowerState(powerState, "Final");
237
+
238
+ // Check final state and only report persistent issues
239
+ const issues = [];
240
+
241
+ if (powerState.mIsPowered !== "true") {
242
+ issues.push(`Device still not powered: ${powerState.mIsPowered}`);
243
+ }
244
+
245
+ if (powerState.mWakefulness !== "Awake") {
246
+ issues.push(`Device still not awake: ${powerState.mWakefulness}`);
247
+ }
248
+
249
+ if (powerState.mDisplayReady !== "true") {
250
+ issues.push(`Display still not ready: ${powerState.mDisplayReady}`);
251
+ }
252
+
253
+ // Report results
254
+ if (issues.length === 0) {
255
+ this.emitLog("info", "🎉 ensureAwake completed successfully - device is fully ready", "ensureAwake");
256
+ } else {
257
+ // Log individual issues as warnings first
258
+ issues.forEach(issue => {
259
+ this.emitLog("warn", issue, "ensureAwake");
260
+ });
261
+
262
+ // Then emit a single error for the overall failure
263
+ this.emitError(
264
+ new Error(`ensureAwake failed with ${issues.length} persistent issue(s): ${issues.join(', ')}`),
265
+ "ensureAwake",
266
+ "Device not in expected final state after commands"
267
+ );
268
+ }
269
+
270
+ this.emitLog("info", "=== ensureAwake sequence complete ===", "ensureAwake");
271
+ return powerState;
272
+ }
273
+
274
+ /**
275
+ * Parses the output of 'dumpsys power' to extract power, wake, and display state.
276
+ * @param {string} output - The full output string from 'dumpsys power'.
277
+ * @returns {{ mIsPowered: string, mWakefulness: string, mDisplayReady: string }}
278
+ */
279
+ parsePowerState(output) {
280
+ const mIsPoweredMatch = output.match(/^\s*mIsPowered=([a-zA-Z0-9]+)/m);
281
+ const mWakefulnessMatch = output.match(/^\s*mWakefulness=([a-zA-Z0-9]+)/m);
282
+ const mDisplayReadyMatch = output.match(/^\s*mDisplayReady=([a-zA-Z0-9]+)/m);
283
+ return {
284
+ mIsPowered: mIsPoweredMatch ? mIsPoweredMatch[1] : "unknown",
285
+ mWakefulness: mWakefulnessMatch ? mWakefulnessMatch[1] : "unknown",
286
+ mDisplayReady: mDisplayReadyMatch ? mDisplayReadyMatch[1] : "unknown"
287
+ };
288
+ }
289
+ }
290
+
291
+ export default AndroidTVSetup;