@cldmv/node-android-tv-remote 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,11 +1,12 @@
1
1
  {
2
2
  "name": "@cldmv/node-android-tv-remote",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "A Node.js library for controlling Android TV devices via ADB keycodes and text input.",
5
5
  "main": "src/lib/android-tv-remote.js",
6
6
  "scripts": {
7
7
  "test": "jest",
8
- "postinstall": "node scripts/postinstall.js"
8
+ "postinstall": "node scripts/postinstall.js",
9
+ "setup-device": "node scripts/setup-device.js"
9
10
  },
10
11
  "keywords": [
11
12
  "android",
@@ -0,0 +1,41 @@
1
+ #!/usr/bin/env node
2
+
3
+ const readline = require("readline");
4
+ const AndroidTVSetup = require("../src/lib/adb/setup");
5
+
6
+ /**
7
+ * Interactive CLI for setting up a new Android TV device.
8
+ * Prompts for IP and port, then runs setup.
9
+ */
10
+ async function prompt(question, defaultValue) {
11
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
12
+ return new Promise((resolve) => {
13
+ rl.question(`${question}${defaultValue ? ` [${defaultValue}]` : ""}: `, (answer) => {
14
+ rl.close();
15
+ resolve(answer || defaultValue);
16
+ });
17
+ });
18
+ }
19
+
20
+ async function main() {
21
+ const ip = await prompt("Enter device IP address");
22
+ if (!ip) {
23
+ console.error("IP address is required.");
24
+ process.exit(1);
25
+ }
26
+ const port = parseInt(await prompt("Enter device port", "5555"), 10) || 5555;
27
+ const quiet = false;
28
+ const setup = new AndroidTVSetup({ ip, port, quiet });
29
+ try {
30
+ await setup.connect();
31
+ await setup.setSettings();
32
+ await setup.ensureAwake();
33
+ await setup.disconnect();
34
+ console.log("\nSetup complete!");
35
+ } catch (err) {
36
+ setup.errorWithTime("Error:", err.message || err);
37
+ process.exit(1);
38
+ }
39
+ }
40
+
41
+ main();
@@ -0,0 +1,144 @@
1
+ /**
2
+ * AndroidTVSetup class for configuring and managing Android TV devices via ADB.
3
+ *
4
+ * Usage:
5
+ * const setup = new AndroidTVSetup({ ip, port, quiet });
6
+ * await setup.connect();
7
+ * await setup.setSettings();
8
+ * await setup.ensureAwake();
9
+ * await setup.disconnect();
10
+ */
11
+ const createRemote = require("../android-tv-remote");
12
+
13
+ class AndroidTVSetup {
14
+ /**
15
+ * @param {Object} options
16
+ * @param {string} options.ip - The IP address of the ADB device.
17
+ * @param {number} [options.port=5555] - The port number for the ADB connection.
18
+ * @param {boolean} [options.quiet=true] - Suppress log output except for results.
19
+ */
20
+ constructor({ ip, port = 5555, quiet = true }) {
21
+ this.ip = ip;
22
+ this.port = port;
23
+ this.quiet = quiet;
24
+ this.remote = createRemote({ ip, port, quiet });
25
+ this.host = `${ip}:${port}`;
26
+ }
27
+
28
+ logWithTime(...args) {
29
+ if (!this.quiet) {
30
+ const now = new Date().toISOString();
31
+ console.log(`[${now}]`, ...args);
32
+ }
33
+ }
34
+ warnWithTime(...args) {
35
+ if (!this.quiet) {
36
+ const now = new Date().toISOString();
37
+ console.warn(`[${now}]`, ...args);
38
+ }
39
+ }
40
+ errorWithTime(...args) {
41
+ const now = new Date().toISOString();
42
+ console.error(`[${now}]`, ...args);
43
+ }
44
+
45
+ async connect() {
46
+ await this.remote.connect();
47
+ this.logWithTime(`Connected to ${this.host}`);
48
+ }
49
+
50
+ async disconnect() {
51
+ try {
52
+ await this.remote.disconnect();
53
+ this.logWithTime("Disconnected cleanly");
54
+ } catch (err) {
55
+ if (err.message && err.message.includes("disconnected")) {
56
+ this.warnWithTime("Warning: Device already disconnected before explicit disconnect call.");
57
+ } else {
58
+ this.errorWithTime("Error:", err.message || err);
59
+ if (err.message && err.message.includes("device unauthorized")) {
60
+ this.errorWithTime(
61
+ "Your device is unauthorized. Please check your TV and accept the authorization dialog to allow this computer to connect via ADB."
62
+ );
63
+ }
64
+ process.exit(1);
65
+ }
66
+ }
67
+ }
68
+
69
+ /**
70
+ * Set all recommended settings for always-on display and max brightness.
71
+ */
72
+ async setSettings() {
73
+ // Use the remote's handleSettings for all settings
74
+ await this.remote.handleSettings("set", this.quiet);
75
+ // svc power stayon true and brightness are not in handleSettings, so do them here
76
+ await this.remote.connect();
77
+ const cmds = ["settings put system screen_brightness_mode 0", "settings put system screen_brightness 255", "svc power stayon true"];
78
+ for (const cmd of cmds) {
79
+ (await this.remote.inputKeycode) ? Promise.resolve() : Promise.resolve(); // placeholder for future
80
+ await this.remotePressShell(cmd);
81
+ this.logWithTime(`Ran: ${cmd}`);
82
+ }
83
+ await this.remote.disconnect();
84
+ }
85
+
86
+ /**
87
+ * Helper to run a shell command using the remote's ADB client.
88
+ * @param {string} cmd
89
+ * @returns {Promise<void>}
90
+ */
91
+ async remotePressShell(cmd) {
92
+ // Use the internal client for shell commands
93
+ if (this.remote && this.remote.inputKeycode) {
94
+ // fallback: use adbkit directly if needed
95
+ const adb = require("adbkit");
96
+ const client = adb.createClient();
97
+ await client.shell(this.host, cmd).then(adb.util.readAll);
98
+ } else if (this.remote && this.remote.client) {
99
+ await this.remote.client.shell(this.host, cmd).then(require("adbkit").util.readAll);
100
+ }
101
+ }
102
+
103
+ /**
104
+ * Ensures the device is awake and on the home screen.
105
+ */
106
+ async ensureAwake() {
107
+ // Use the remote's ADB client for dumpsys power
108
+ const adb = require("adbkit");
109
+ const client = adb.createClient();
110
+ const output = await client
111
+ .shell(this.host, "dumpsys power")
112
+ .then(adb.util.readAll)
113
+ .then((b) => b.toString());
114
+ const parsed = this.parsePowerState(output);
115
+ this.logWithTime("\n--- Power State ---");
116
+ this.logWithTime(`mIsPowered: ${parsed.mIsPowered}`);
117
+ this.logWithTime(`mWakefulness: ${parsed.mWakefulness}`);
118
+ this.logWithTime(`mDisplayReady: ${parsed.mDisplayReady}`);
119
+ this.logWithTime("-------------------\n");
120
+ // Use remote.inputKeycode for keyevents
121
+ if (parsed.mIsPowered !== "true") await this.remote.inputKeycode(26);
122
+ if (parsed.mWakefulness !== "Awake") await this.remote.inputKeycode(224);
123
+ if (parsed.mDisplayReady !== "true") await this.remote.inputKeycode(26);
124
+ await this.remote.inputKeycode(3); // HOME
125
+ }
126
+
127
+ /**
128
+ * Parses the output of 'dumpsys power' to extract power, wake, and display state.
129
+ * @param {string} output - The full output string from 'dumpsys power'.
130
+ * @returns {{ mIsPowered: string, mWakefulness: string, mDisplayReady: string }}
131
+ */
132
+ parsePowerState(output) {
133
+ const mIsPoweredMatch = output.match(/^\s*mIsPowered=([a-zA-Z0-9]+)/m);
134
+ const mWakefulnessMatch = output.match(/^\s*mWakefulness=([a-zA-Z0-9]+)/m);
135
+ const mDisplayReadyMatch = output.match(/^\s*mDisplayReady=([a-zA-Z0-9]+)/m);
136
+ return {
137
+ mIsPowered: mIsPoweredMatch ? mIsPoweredMatch[1] : "unknown",
138
+ mWakefulness: mWakefulnessMatch ? mWakefulnessMatch[1] : "unknown",
139
+ mDisplayReady: mDisplayReadyMatch ? mDisplayReadyMatch[1] : "unknown"
140
+ };
141
+ }
142
+ }
143
+
144
+ module.exports = AndroidTVSetup;
@@ -75,15 +75,38 @@ function wrapAsync(fn) {
75
75
 
76
76
  /**
77
77
  * Handles disconnect and connection errors, outputs helpful messages, and exits the process.
78
+ * Also provides onboarding steps for common authentication and connection issues.
78
79
  * @private
79
80
  * @param {Error} err - The error object.
81
+ * @example
82
+ * try {
83
+ * // ...code that may throw
84
+ * } catch (err) {
85
+ * handleDisconnectError(err);
86
+ * }
80
87
  */
81
88
  function handleDisconnectError(err) {
82
89
  errorWithTime("Error:", err.message || err);
83
- if (err.message && err.message.includes("device unauthorized")) {
90
+ if (err.message && (err.message.includes("device unauthorized") || err.message.includes("failed to authenticate"))) {
84
91
  errorWithTime(
85
- "Your device is unauthorized. Please check your TV and accept the authorization dialog to allow this system to connect via ADB."
92
+ "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."
86
93
  );
94
+ errorWithTime("If you do not see a prompt, try disconnecting and reconnecting the device, or reboot your TV.");
95
+ errorWithTime("If the problem persists, remove the device from the list of authorized ADB devices in Developer Options and try again.");
96
+ errorWithTime(
97
+ "Tip: In Developer Options on your TV, try toggling 'ADB Debugging' off and then back on. This often resolves authentication issues."
98
+ );
99
+ }
100
+ if (err.message && (err.message.includes("actively refused") || err.message.includes("No connection could be made"))) {
101
+ errorWithTime("\nThe device refused the connection. To enable ADB, follow these steps on your Android TV or Fire TV:");
102
+ errorWithTime("1. Open Settings > Device Preferences > About (or My Fire TV > About)");
103
+ errorWithTime("2. Scroll to 'Build' and press OK 7 times to enable Developer Options");
104
+ errorWithTime("3. Go back to Settings > Device Preferences > Developer Options");
105
+ errorWithTime("4. Enable 'Developer Options' if needed, then enable 'ADB Debugging' and 'Apps from Unknown Sources'");
106
+ errorWithTime("5. Ensure your TV and computer are on the same network");
107
+ errorWithTime("6. On your computer, run: adb connect <device-ip>:5555");
108
+ errorWithTime("7. Accept the authorization prompt on your TV");
109
+ errorWithTime("\nIf you do not see 'Developer Options', repeat step 2 until it appears.");
87
110
  }
88
111
  process.exit(1);
89
112
  }
@@ -388,6 +411,19 @@ module.exports = function (config) {
388
411
  if (key === "ok" || key === "select") {
389
412
  return inputKeycode(keycodes.dpadCenter || keycodes.ok);
390
413
  }
414
+ // Map up/down/left/right to dpad keycodes
415
+ if (key === "up") {
416
+ return inputKeycode(keycodes.dpadUp);
417
+ }
418
+ if (key === "down") {
419
+ return inputKeycode(keycodes.dpadDown);
420
+ }
421
+ if (key === "left") {
422
+ return inputKeycode(keycodes.dpadLeft);
423
+ }
424
+ if (key === "right") {
425
+ return inputKeycode(keycodes.dpadRight);
426
+ }
391
427
  // Special handling for play/pause
392
428
  if (key === "play") {
393
429
  return inputKeycode(keycodes.mediaPlay || keycodes.playPause);
@@ -419,6 +455,18 @@ module.exports = function (config) {
419
455
  if (key === "ok" || key === "select") {
420
456
  return inputKeycodeLongPressWrapped(keycodes.dpadCenter || keycodes.ok);
421
457
  }
458
+ if (key === "up") {
459
+ return inputKeycodeLongPressWrapped(keycodes.dpadUp);
460
+ }
461
+ if (key === "down") {
462
+ return inputKeycodeLongPressWrapped(keycodes.dpadDown);
463
+ }
464
+ if (key === "left") {
465
+ return inputKeycodeLongPressWrapped(keycodes.dpadLeft);
466
+ }
467
+ if (key === "right") {
468
+ return inputKeycodeLongPressWrapped(keycodes.dpadRight);
469
+ }
422
470
  if (key === "play") {
423
471
  return inputKeycodeLongPressWrapped(keycodes.mediaPlay || keycodes.playPause);
424
472
  }
@@ -438,6 +486,17 @@ module.exports = function (config) {
438
486
  return inputKeycodeLongPressWrapped(keycodes[key]);
439
487
  });
440
488
  });
489
+ // Robust aliasing: always add if dpad keys exist in keycodes
490
+ // if (typeof obj.dpadUp === "function" || keycodes.dpadUp) obj.up = obj.dpadUp;
491
+ // if (typeof obj.dpadDown === "function" || keycodes.dpadDown) obj.down = obj.dpadDown;
492
+ // if (typeof obj.dpadLeft === "function" || keycodes.dpadLeft) obj.left = obj.dpadLeft;
493
+ // if (typeof obj.dpadRight === "function" || keycodes.dpadRight) obj.right = obj.dpadRight;
494
+ // if (typeof obj.dpadCenter === "function" || keycodes.dpadCenter) obj.ok = obj.dpadCenter;
495
+ // if (typeof longObj.dpadUp === "function") longObj.up = longObj.dpadUp;
496
+ // if (typeof longObj.dpadDown === "function") longObj.down = longObj.dpadDown;
497
+ // if (typeof longObj.dpadLeft === "function") longObj.left = longObj.dpadLeft;
498
+ // if (typeof longObj.dpadRight === "function") longObj.right = longObj.dpadRight;
499
+ // if (typeof longObj.dpadCenter === "function") longObj.ok = longObj.dpadCenter;
441
500
  obj.long = longObj;
442
501
  return obj;
443
502
  })(),
@@ -1,102 +1,35 @@
1
- const adb = require("adbkit");
2
-
3
- /**
4
- * Test script to connect to an ADB device and read settings.
5
- * Usage: node test/connect-readall.js <ip> [port]
6
- */
7
-
8
- /**
9
- * Get or set Android settings via ADB.
10
- * @param {string} ip
11
- * @param {number} port
12
- * @param {string} mode - 'get' or 'set'
13
- * @returns {Promise<void>}
14
- */
15
-
16
- function logWithTime(...args) {
17
- const now = new Date().toISOString();
18
- console.log(`[${now}]`, ...args);
19
- }
20
- function warnWithTime(...args) {
21
- const now = new Date().toISOString();
22
- console.warn(`[${now}]`, ...args);
23
- }
24
- function errorWithTime(...args) {
25
- const now = new Date().toISOString();
26
- console.error(`[${now}]`, ...args);
27
- }
28
-
29
- function handleSettings(ip, port, mode, quiet = true) {
30
- const client = adb.createClient();
31
- const host = `${ip}:${port}`;
32
- const keys = [
33
- { ns: "system", key: "screen_off_timeout", value: 2147483647 },
34
- { ns: "secure", key: "sleep_timeout", value: 0 },
35
- { ns: "global", key: "stay_on_while_plugged_in", value: 3 }
36
- ];
37
-
38
- return client
39
- .connect(ip, port)
40
- .then(() => {
41
- if (!quiet) logWithTime(`Connected to ${host}`);
42
- let chain = Promise.resolve();
43
- keys.forEach((item) => {
44
- chain = chain.then(() => {
45
- let cmd;
46
- if (mode === "set") {
47
- cmd = `settings put ${item.ns} ${item.key} ${item.value}`;
48
- } else {
49
- cmd = `settings get ${item.ns} ${item.key}`;
50
- }
51
- return client
52
- .shell(host, cmd)
53
- .then(adb.util.readAll)
54
- .then((result) => {
55
- if (!quiet) {
56
- if (mode === "set") {
57
- logWithTime(`Set ${item.ns} ${item.key} to ${item.value}`);
58
- } else {
59
- logWithTime(`${item.ns} ${item.key}: ${result.toString().trim()}`);
60
- }
61
- }
62
- });
63
- });
64
- });
65
- return chain;
66
- })
67
- .then(() => client.disconnect(ip, port))
68
- .then(() => {
69
- if (!quiet) logWithTime("Disconnected cleanly");
70
- })
71
- .catch((err) => {
72
- if (err.message && err.message.includes("disconnected")) {
73
- if (!quiet) warnWithTime("Warning: Device already disconnected before explicit disconnect call.");
74
- } else {
75
- errorWithTime("Error:", err.message || err);
76
- if (err.message && err.message.includes("device unauthorized")) {
77
- errorWithTime(
78
- "Your device is unauthorized. Please check your TV and accept the authorization dialog to allow this computer to connect via ADB."
79
- );
80
- }
81
- process.exit(1);
82
- }
83
- });
1
+ // Test script to connect to an ADB device and read settings.
2
+ // Usage: node test/connect-readall.js <ip> [port] [get|set] [--quiet]
3
+ const AndroidTVSetup = require("../src/lib/adb/setup");
4
+ const readline = require("readline");
5
+
6
+ async function main() {
7
+ const ip = process.argv[2];
8
+ const port = process.argv[3] ? parseInt(process.argv[3], 10) : 5555;
9
+ const mode = process.argv[4] === "set" ? "set" : "get";
10
+ const quiet = process.argv.includes("--quiet");
11
+
12
+ if (!ip) {
13
+ console.error("Usage: node test/connect-readall.js <ip> [port] [get|set] [--quiet]");
14
+ process.exit(1);
15
+ }
16
+
17
+ if (!quiet) console.log(`Running in ${mode} mode on ${ip}:${port}`);
18
+
19
+ const setup = new AndroidTVSetup({ ip, port, quiet });
20
+ try {
21
+ await setup.connect();
22
+ if (mode === "set") {
23
+ await setup.setSettings();
24
+ }
25
+ await setup.ensureAwake();
26
+ await setup.disconnect();
27
+ } catch (err) {
28
+ setup.errorWithTime("Error:", err.message || err);
29
+ process.exit(1);
30
+ }
31
+
32
+ if (!quiet) console.log(`Ran in ${mode} mode on ${ip}:${port}`);
84
33
  }
85
34
 
86
- // CLI usage
87
-
88
- const ip = process.argv[2];
89
- const port = process.argv[3] ? parseInt(process.argv[3], 10) : 5555;
90
- const mode = process.argv[4] === "set" ? "set" : "get";
91
- const quiet = process.argv.includes("--quiet");
92
-
93
- if (!ip) {
94
- errorWithTime("Usage: node test/connect-readall.js <ip> [port] [get|set] [--quiet]");
95
- process.exit(1);
96
- }
97
-
98
- if (!quiet) logWithTime(`Running in ${mode} mode on ${ip}:${port}`);
99
-
100
- handleSettings(ip, port, mode, quiet);
101
-
102
- if (!quiet) logWithTime(`Ran in ${mode} mode on ${ip}:${port}`);
35
+ main();
@@ -0,0 +1,68 @@
1
+ // Interactive test script for Android TV Remote
2
+ // Prompts for IP and port, connects, and sends button presses at intervals.
3
+ // Usage: node test/interactive-remote.js
4
+
5
+ const readline = require("readline");
6
+ const AndroidTVSetup = require("../src/lib/adb/setup");
7
+
8
+ /**
9
+ * Prompts the user for input in the terminal.
10
+ * @param {string} query - The prompt message.
11
+ * @returns {Promise<string>} The user's input.
12
+ * @example
13
+ * const ip = await prompt("Enter IP: ");
14
+ */
15
+ function prompt(query) {
16
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
17
+ return new Promise((resolve) =>
18
+ rl.question(query, (ans) => {
19
+ rl.close();
20
+ resolve(ans);
21
+ })
22
+ );
23
+ }
24
+
25
+ /**
26
+ * Runs the interactive remote test.
27
+ * Prompts for IP/port, connects, and sends button presses.
28
+ */
29
+ async function main() {
30
+ const ip = (await prompt("Enter device IP: ")).trim();
31
+ let portInput = await prompt("Enter port [5555]: ");
32
+ const port = portInput.trim() ? parseInt(portInput.trim(), 10) : 5555;
33
+ if (!ip) {
34
+ console.error("IP address is required.");
35
+ process.exit(1);
36
+ }
37
+ const setup = new AndroidTVSetup({ ip, port, quiet: false });
38
+ try {
39
+ await setup.connect();
40
+ console.log(`Connected to ${ip}:${port}`);
41
+ // List of buttons to press (as method names on setup.remote.press)
42
+ const buttons = ["home", "up", "down", "left", "right", "ok", "back"];
43
+ for (let i = 0; i < buttons.length; i++) {
44
+ const btn = buttons[i];
45
+ if (setup.remote && setup.remote.press && typeof setup.remote.press[btn] === "function") {
46
+ console.log(`Pressing: ${btn}`);
47
+ await setup.remote.press[btn]();
48
+ } else {
49
+ console.log(`Button '${btn}' not available.`);
50
+ }
51
+ if (btn === "home") {
52
+ await new Promise((res) => setTimeout(res, 750)); // 750ms after home
53
+ } else if (btn === "back") {
54
+ await new Promise((res) => setTimeout(res, 2500)); // 2.5s for back
55
+ } else {
56
+ await new Promise((res) => setTimeout(res, 500));
57
+ }
58
+ }
59
+ await setup.disconnect();
60
+ console.log("Test complete. Disconnected.");
61
+ } catch (err) {
62
+ if (setup.errorWithTime) setup.errorWithTime("Error:", err.message || err);
63
+ else console.error("Error:", err.message || err);
64
+ process.exit(1);
65
+ }
66
+ }
67
+
68
+ main();