@cldmv/node-android-tv-remote 2.0.0 → 2.1.7

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,236 +0,0 @@
1
- /**
2
- * Comprehensive test script for dual device ensureAwake operations.
3
- * Tests both 10.6.0.133 and 10.6.0.18 devices simultaneously.
4
- *
5
- * Usage: node test/dual-device-ensureawake.mjs
6
- */
7
-
8
- import AndroidTVSetup from "../src/lib/adb/setup.mjs";
9
-
10
- /**
11
- * Enhanced logger that prefixes output with device identifier and timestamp
12
- * @param {string} deviceId - Device identifier (e.g., "10.6.0.133")
13
- * @param {string} level - Log level
14
- * @param {string} message - Log message
15
- * @param {any} data - Additional data
16
- */
17
- const log = (deviceId, level, message, data = null) => {
18
- const timestamp = new Date().toISOString();
19
- const prefix = `[${timestamp}] [${deviceId}] [${level.toUpperCase()}]`;
20
- console.log(`${prefix} ${message}`);
21
- if (data) {
22
- console.log(`${prefix} Data:`, JSON.stringify(data, null, 2));
23
- }
24
- };
25
-
26
- /**
27
- * Creates and configures a device setup with comprehensive event handling
28
- * @param {string} ip - Device IP address
29
- * @param {number} port - Device port
30
- * @returns {AndroidTVSetup} Configured setup instance
31
- */
32
- const createDeviceSetup = (ip, port = 5555) => {
33
- const setup = new AndroidTVSetup({
34
- ip,
35
- port,
36
- quiet: false, // We want to see all logs
37
- autoConnect: false // We'll control connection manually
38
- });
39
-
40
- // Set up comprehensive event listeners
41
- setup.on("log", (logData) => {
42
- log(ip, logData.level, logData.message, logData.data);
43
- });
44
-
45
- setup.on("error", (errorData) => {
46
- log(ip, "ERROR", `${errorData.source}: ${errorData.message}`, {
47
- error: errorData.error.message,
48
- stack: errorData.error.stack
49
- });
50
- });
51
-
52
- // Add remote event listeners if available
53
- if (setup.remote) {
54
- setup.remote.on("log", (logData) => {
55
- log(ip, logData.level, `[REMOTE] ${logData.message}`, logData.data);
56
- });
57
-
58
- setup.remote.on("error", (errorData) => {
59
- log(ip, "ERROR", `[REMOTE] ${errorData.source}: ${errorData.message}`, {
60
- error: errorData.error.message,
61
- stack: errorData.error.stack
62
- });
63
- });
64
-
65
- setup.remote.on("connect", () => {
66
- log(ip, "INFO", "[REMOTE] Connected successfully");
67
- });
68
-
69
- setup.remote.on("disconnect", () => {
70
- log(ip, "INFO", "[REMOTE] Disconnected successfully");
71
- });
72
- }
73
-
74
- return setup;
75
- };
76
-
77
- /**
78
- * Performs the complete test sequence for a single device
79
- * @param {string} ip - Device IP address
80
- * @returns {Promise<{success: boolean, error?: Error, timing: Object}>}
81
- */
82
- const testDevice = async (ip) => {
83
- const startTime = Date.now();
84
- const timing = {};
85
- let setup = null;
86
-
87
- try {
88
- log(ip, "INFO", "=== Starting device test sequence ===");
89
-
90
- // Create setup
91
- timing.setupCreated = Date.now() - startTime;
92
- setup = createDeviceSetup(ip);
93
- log(ip, "INFO", `Setup created (${timing.setupCreated}ms)`);
94
-
95
- // Connect
96
- const connectStart = Date.now();
97
- await setup.connect();
98
- timing.connected = Date.now() - connectStart;
99
- log(ip, "INFO", `Connected successfully (${timing.connected}ms)`);
100
-
101
- // Ensure awake
102
- const awakeStart = Date.now();
103
- await setup.ensureAwake();
104
- timing.ensureAwake = Date.now() - awakeStart;
105
- log(ip, "INFO", `ensureAwake completed (${timing.ensureAwake}ms)`);
106
-
107
- // Disconnect
108
- const disconnectStart = Date.now();
109
- await setup.disconnect();
110
- timing.disconnected = Date.now() - disconnectStart;
111
- log(ip, "INFO", `Disconnected successfully (${timing.disconnected}ms)`);
112
-
113
- timing.total = Date.now() - startTime;
114
- log(ip, "SUCCESS", `=== Test completed successfully (${timing.total}ms total) ===`);
115
-
116
- return { success: true, timing };
117
- } catch (error) {
118
- timing.total = Date.now() - startTime;
119
- log(ip, "ERROR", `=== Test failed (${timing.total}ms total) ===`, {
120
- error: error.message,
121
- stack: error.stack
122
- });
123
-
124
- // Attempt cleanup
125
- if (setup) {
126
- try {
127
- log(ip, "INFO", "Attempting cleanup disconnect...");
128
- await setup.disconnect();
129
- log(ip, "INFO", "Cleanup disconnect successful");
130
- } catch (cleanupError) {
131
- log(ip, "WARN", "Cleanup disconnect failed", {
132
- error: cleanupError.message
133
- });
134
- }
135
- }
136
-
137
- return { success: false, error, timing };
138
- }
139
- };
140
-
141
- /**
142
- * Main test execution function
143
- */
144
- const runDualDeviceTest = async () => {
145
- const devices = ["10.6.0.133", "10.6.0.18"];
146
- const overallStart = Date.now();
147
-
148
- console.log("========================================");
149
- console.log("DUAL DEVICE ENSURE AWAKE TEST");
150
- console.log("========================================");
151
- console.log(`Testing devices: ${devices.join(", ")}`);
152
- console.log(`Start time: ${new Date().toISOString()}`);
153
- console.log("========================================\n");
154
-
155
- // Test devices in parallel
156
- log("MAIN", "INFO", "Starting parallel device tests...");
157
-
158
- const results = await Promise.allSettled(devices.map((ip) => testDevice(ip)));
159
-
160
- const overallTime = Date.now() - overallStart;
161
-
162
- // Process results
163
- console.log("\n========================================");
164
- console.log("TEST RESULTS SUMMARY");
165
- console.log("========================================");
166
-
167
- const summary = {
168
- successful: 0,
169
- failed: 0,
170
- devices: {}
171
- };
172
-
173
- results.forEach((result, index) => {
174
- const ip = devices[index];
175
-
176
- if (result.status === "fulfilled") {
177
- const deviceResult = result.value;
178
- summary.devices[ip] = deviceResult;
179
-
180
- if (deviceResult.success) {
181
- summary.successful++;
182
- console.log(`✅ ${ip}: SUCCESS (${deviceResult.timing.total}ms)`);
183
- console.log(` - Connect: ${deviceResult.timing.connected}ms`);
184
- console.log(` - EnsureAwake: ${deviceResult.timing.ensureAwake}ms`);
185
- console.log(` - Disconnect: ${deviceResult.timing.disconnected}ms`);
186
- } else {
187
- summary.failed++;
188
- console.log(`❌ ${ip}: FAILED (${deviceResult.timing.total}ms)`);
189
- console.log(` - Error: ${deviceResult.error.message}`);
190
- }
191
- } else {
192
- summary.failed++;
193
- summary.devices[ip] = {
194
- success: false,
195
- error: result.reason,
196
- timing: { total: 0 }
197
- };
198
- console.log(`❌ ${ip}: PROMISE REJECTED`);
199
- console.log(` - Reason: ${result.reason.message}`);
200
- }
201
- });
202
-
203
- console.log("----------------------------------------");
204
- console.log(`Total time: ${overallTime}ms`);
205
- console.log(`Successful: ${summary.successful}/${devices.length}`);
206
- console.log(`Failed: ${summary.failed}/${devices.length}`);
207
- console.log("========================================\n");
208
-
209
- // Exit with appropriate code
210
- const exitCode = summary.failed > 0 ? 1 : 0;
211
- log("MAIN", "INFO", `Test completed with exit code ${exitCode}`);
212
-
213
- return summary;
214
- };
215
-
216
- // Handle unhandled rejections and exceptions
217
- process.on("unhandledRejection", (reason, promise) => {
218
- console.error("Unhandled Rejection at:", promise, "reason:", reason);
219
- process.exit(1);
220
- });
221
-
222
- process.on("uncaughtException", (error) => {
223
- console.error("Uncaught Exception:", error);
224
- process.exit(1);
225
- });
226
-
227
- // Run the test
228
- runDualDeviceTest()
229
- .then((summary) => {
230
- const exitCode = summary.failed > 0 ? 1 : 0;
231
- process.exit(exitCode);
232
- })
233
- .catch((error) => {
234
- console.error("Fatal error in test execution:", error);
235
- process.exit(1);
236
- });
@@ -1,106 +0,0 @@
1
- /**
2
- * Event System Demonstration
3
- *
4
- * This example shows how to use the event-driven Android TV Remote.
5
- * All operations emit events instead of console logging.
6
- *
7
- * Usage: node test/event-system-demo.mjs
8
- */
9
-
10
- import createRemote, { createAndroidTVRemote } from "../src/lib/android-tv-remote.mjs";
11
-
12
- console.log("=== Android TV Remote Event System Demo ===\n");
13
-
14
- // Example 1: Basic event handling
15
- console.log("1. Creating remote with basic event handling...");
16
- const remote = createRemote({
17
- ip: "127.0.0.1",
18
- autoConnect: false,
19
- quiet: false // Enable all log events
20
- });
21
-
22
- // Set up event listeners
23
- remote.on("log", (data) => {
24
- const timestamp = new Date(data.timestamp).toLocaleTimeString();
25
- console.log(`[${timestamp}] ${data.level.toUpperCase()} [${data.source}]: ${data.message}`);
26
- if (data.data) {
27
- console.log(` Data:`, data.data);
28
- }
29
- });
30
-
31
- remote.on("error", (data) => {
32
- const timestamp = new Date(data.timestamp).toLocaleTimeString();
33
- console.error(`[${timestamp}] ERROR [${data.source}]: ${data.message}`);
34
- console.error(` Error:`, data.error.message);
35
- });
36
-
37
- console.log("✓ Event listeners set up");
38
- console.log("✓ Remote created successfully");
39
-
40
- // Example 2: Test API surface methods (these don't require device connection)
41
- console.log("\n2. Testing API surface methods...");
42
- try {
43
- const keyboardKeys = remote.getKeyboardKeys();
44
- console.log(`✓ Found ${keyboardKeys.length} keyboard keys`);
45
-
46
- const pressCommands = remote.getPressCommands();
47
- console.log(`✓ Found ${pressCommands.length} press commands`);
48
- } catch (error) {
49
- console.error("✗ API surface test failed:", error.message);
50
- }
51
-
52
- // Example 3: Test unknown key error (should emit error event)
53
- console.log("\n3. Testing error event emission...");
54
- try {
55
- // This should emit an error event for unknown key
56
- await remote.keyboard.key("nonexistentkey");
57
- } catch (error) {
58
- console.log("✓ Caught expected error for unknown key");
59
- }
60
-
61
- // Example 4: Demonstrate static create method
62
- console.log("\n4. Demonstrating static create method...");
63
- try {
64
- // This would normally wait for connection, but we disabled autoConnect
65
- const remote2 = await createAndroidTVRemote({
66
- ip: "192.168.1.100",
67
- autoConnect: false
68
- });
69
-
70
- remote2.on("log", (data) => {
71
- console.log(`[REMOTE2] ${data.level}: ${data.message}`);
72
- });
73
-
74
- console.log("✓ Static create method works");
75
- } catch (error) {
76
- console.error("✗ Static create failed:", error.message);
77
- }
78
-
79
- // Example 5: Chaining event listeners
80
- console.log("\n5. Demonstrating method chaining...");
81
- const remote3 = createRemote({ ip: "10.0.0.1", autoConnect: false })
82
- .on("log", (data) => console.log(`[CHAIN] LOG: ${data.message}`))
83
- .on("error", (data) => console.log(`[CHAIN] ERROR: ${data.message}`))
84
- .once("log", (data) => console.log(`[CHAIN] FIRST LOG ONLY: ${data.message}`));
85
-
86
- console.log("✓ Method chaining works");
87
-
88
- // Example 6: Event listener management
89
- console.log("\n6. Demonstrating event listener management...");
90
- const testHandler = (data) => console.log(`Test handler: ${data.message}`);
91
-
92
- remote3.on("log", testHandler);
93
- console.log("✓ Added test handler");
94
-
95
- remote3.off("log", testHandler);
96
- console.log("✓ Removed test handler");
97
-
98
- console.log("\n=== Demo Complete ===");
99
- console.log("\nKey Features Demonstrated:");
100
- console.log("• Event-driven architecture (no console.log/console.error)");
101
- console.log("• Structured event data with timestamps and sources");
102
- console.log("• Error events instead of thrown exceptions");
103
- console.log("• Method chaining for event listeners");
104
- console.log("• Static create method for async initialization");
105
- console.log("• Separation of log levels (info, warn, error, debug)");
106
- console.log("\nFor a real device, set autoConnect: true and provide a valid IP address.");
@@ -1,82 +0,0 @@
1
- /**
2
- * @Project: @cldmv/node-android-tv-remote
3
- * @Filename: /test/interactive-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 10:57:02 -07:00 (1760551022)
10
- * -----
11
- * @Copyright: Copyright (c) 2013-2025 Catalyzed Motivation Inc. All rights reserved.
12
- */
13
-
14
- // Interactive test script for Android TV Remote
15
- // Prompts for IP and port, connects, and sends button presses at intervals.
16
- // Usage: node test/interactive-remote.mjs
17
-
18
- import readline from "readline";
19
- import createRemote from "../src/lib/android-tv-remote.mjs";
20
-
21
- /**
22
- * Prompts the user for input in the terminal.
23
- * @param {string} query - The prompt message.
24
- * @returns {Promise<string>} The user's input.
25
- * @example
26
- * const ip = await prompt("Enter IP: ");
27
- */
28
- function prompt(query) {
29
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
30
- return new Promise((resolve) =>
31
- rl.question(query, (ans) => {
32
- rl.close();
33
- resolve(ans);
34
- })
35
- );
36
- }
37
-
38
- /**
39
- * Runs the interactive remote test using the main remote module.
40
- * Prompts for IP/port, connects, and sends button presses.
41
- * @returns {Promise<void>}
42
- */
43
- async function main() {
44
- const ip = (await prompt("Enter device IP: ")).trim();
45
- let portInput = await prompt("Enter port [5555]: ");
46
- const port = portInput.trim() ? parseInt(portInput.trim(), 10) : 5555;
47
- if (!ip) {
48
- console.error("IP address is required.");
49
- process.exit(1);
50
- }
51
- try {
52
- const remote = createRemote({ ip, port });
53
- await remote.connect();
54
- console.log(`Connected to ${ip}:${port}`);
55
- // List of buttons to press (as method names on remote.press)
56
- const buttons = ["home", "up", "down", "left", "right", "ok", "back"];
57
- for (let i = 0; i < buttons.length; i++) {
58
- const btn = buttons[i];
59
- if (remote.press && typeof remote.press[btn] === "function") {
60
- console.log(`Pressing: ${btn}`);
61
- await remote.press[btn]();
62
- } else {
63
- console.log(`Button '${btn}' not available.`);
64
- }
65
- if (btn === "home") {
66
- await new Promise((res) => setTimeout(res, 750)); // 750ms after home
67
- } else if (btn === "back") {
68
- await new Promise((res) => setTimeout(res, 2500)); // 2.5s for back
69
- } else {
70
- await new Promise((res) => setTimeout(res, 500));
71
- }
72
- }
73
- await remote.disconnect();
74
- console.log("Test complete. Disconnected.");
75
- } catch (err) {
76
- if (remote.errorWithTime) remote.errorWithTime("Error:", err.message || err);
77
- else console.error("Error:", err.message || err);
78
- process.exit(1);
79
- }
80
- }
81
-
82
- main();
@@ -1,78 +0,0 @@
1
- /**
2
- * @Project: @cldmv/node-android-tv-remote
3
- * @Filename: /test/retry-init-adb.test.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 10:57:13 -07:00 (1760551033)
10
- * -----
11
- * @Copyright: Copyright (c) 2013-2025 Catalyzed Motivation Inc. All rights reserved.
12
- */
13
-
14
- /**
15
- * Test for ADB initialization retry logic using the real android-tv-remote module.
16
- *
17
- * To run: node test/retry-init-adb.test.mjs
18
- */
19
-
20
- import assert from "assert";
21
- import createRemote from "../src/lib/android-tv-remote.mjs";
22
-
23
- /**
24
- * Attempts to initialize ADB repeatedly until successful or max attempts.
25
- * Calls remote.initPromise every 500ms until it resolves or rejects.
26
- * Logs each attempt and result for debugging.
27
- * @param {Object} remote - The remote instance from android-tv-remote.
28
- * @param {number} maxAttempts - Maximum attempts before giving up.
29
- * @returns {Promise<{success: boolean, attempts: number, error?: Error}>}
30
- */
31
- async function tryInitADB(remote, maxAttempts = 10) {
32
- let attempt = 0;
33
- while (attempt < maxAttempts) {
34
- attempt++;
35
- console.log(`[init] tryInitADB attempt #${attempt}`);
36
- try {
37
- await Promise.race([
38
- remote.initPromise,
39
- new Promise((_, reject) => setTimeout(() => reject(new Error("initPromise timeout")), 4000))
40
- ]);
41
- console.log(`[init] initADB result: true`);
42
- return { success: true, attempts: attempt };
43
- } catch (err) {
44
- console.warn(`[init] initADB failed: ${err && err.message}`);
45
- if (attempt >= maxAttempts) {
46
- return { success: false, attempts: attempt, error: err };
47
- }
48
- // Wait before retrying
49
- await new Promise((resolve) => setTimeout(resolve, 500));
50
- }
51
- }
52
- return { success: false, attempts: attempt };
53
- }
54
-
55
- // --- TESTS ---
56
- (async function runTests() {
57
- // Test: Should fail to connect to an unreachable device and retry
58
- // const remote = createRemote({ ip: "10.42.0.210", port: 5555, autoConnect: true, quiet: false }); // unreachable IP
59
- // const result = await tryInitADB(remote, 3);
60
- // assert.strictEqual(result.success, false, "Should fail to connect to unreachable device");
61
- // assert.ok(result.attempts >= 3, "Should attempt at least 3 times");
62
- // console.log("Test passed: Retries and fails as expected for unreachable device.");
63
-
64
- (async () => {
65
- const remote = createRemote({ ip: "10.42.0.210", port: 5555, autoConnect: true, quiet: false });
66
- try {
67
- await remote.initPromise;
68
- console.log("initPromise resolved");
69
- } catch (err) {
70
- console.error("initPromise rejected:", err);
71
- }
72
- })();
73
- // Optionally, test a reachable device if you have one:
74
- // const remote2 = createRemote({ ip: "YOUR_DEVICE_IP", port: 5555, autoConnect: true, quiet: false });
75
- // const result2 = await tryInitADB(remote2, 2);
76
- // assert.strictEqual(result2.success, true, "Should connect to reachable device");
77
- // console.log("Test passed: Connects to reachable device.");
78
- })();