@cldmv/node-android-tv-remote 1.1.0 → 1.2.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,6 +1,6 @@
1
1
  {
2
2
  "name": "@cldmv/node-android-tv-remote",
3
- "version": "1.1.0",
3
+ "version": "1.2.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": {
@@ -8,8 +8,12 @@
8
8
  * @property {number} [port=5555] - The port for ADB connection.
9
9
  * @property {string} [inputDevice="/dev/input/event0"] - The input device path.
10
10
  * @property {boolean} [autoConnect=true] - Whether to auto-connect on command.
11
- * @property {boolean} [autoDisconnect=true] - Whether to auto-disconnect after inactivity.
11
+ * @property {boolean} [autoDisconnect=false] - Whether to auto-disconnect after inactivity.
12
12
  * @property {number} [disconnectTimeout=10] - Inactivity timeout in seconds before disconnecting.
13
+ * @property {boolean} [maintainConnection=true] - Whether to maintain the ADB connection with a heartbeat.
14
+ * @property {number} [heartbeatInterval=30000] - Heartbeat interval in ms (default 30s).
15
+ * @property {number} [connectionCheckInterval=30000] - Interval in ms for periodic connection checks (default 30s).
16
+ * @property {boolean} [quiet=true] - Suppress connection log output if true.
13
17
  */
14
18
  /**
15
19
  * @typedef {Object} Remote
@@ -17,6 +21,8 @@
17
21
  * @property {function(function(Error=, any=)=): Promise|undefined} connect - Connect to the device. Supports both promise and callback styles.
18
22
  * @property {function(function(Error=, any=)=): Promise|undefined} disconnect - Disconnect from the device. Supports both promise and callback styles.
19
23
  * @property {function(number, function(Error=, any=)=): Promise|undefined} inputKeycode - Send a keycode to the device. Supports both promise and callback styles.
24
+ * @property {function(boolean=): Promise<"connected"|"disconnected"|"unknown">} getConnectionStatus - Returns the current connection status; optionally performs a live check.
25
+ * @property {boolean} isConnected - True if the module believes it is connected (internal state, not a live check).
20
26
  * @property {Object} press - Remote control key functions for Android TV remotes.
21
27
  * @property {Object} keyboard - Keyboard interface for all keys, with text and keycode fallback.
22
28
  * @property {Object} keyboard.key - Contains all key functions.
@@ -131,12 +137,19 @@ const remoteKeys = require("../data/remote-keys.json");
131
137
  * @function
132
138
  * @public
133
139
  * @param {RemoteConfig} config - Configuration for the remote.
140
+ * @param {boolean} [config.maintainConnection=true] - Whether to maintain the ADB connection with a heartbeat.
141
+ * @param {number} [config.heartbeatInterval=30000] - Heartbeat interval in ms (default 30s).
134
142
  * @returns {Remote}
135
143
  */
136
144
  module.exports = function (config) {
137
145
  /**
138
146
  * @type {RemoteConfig}
139
147
  */
148
+ /**
149
+ * Initializes and configures the Android TV Remote instance.
150
+ * Handles connection, persistent heartbeat, and auto-reconnect logic.
151
+ * @returns {Remote}
152
+ */
140
153
  config = config || {};
141
154
  const ip = config.ip;
142
155
  const port = config.port || 5555;
@@ -145,13 +158,19 @@ module.exports = function (config) {
145
158
  const client = adb.createClient();
146
159
  let connected = false;
147
160
  const autoConnect = config.autoConnect !== false; // default true
148
- const autoDisconnect = config.autoDisconnect !== false; // default true
161
+ const autoDisconnect = config.autoDisconnect === true; // default false
149
162
  const disconnectTimeout = typeof config.disconnectTimeout === "number" ? config.disconnectTimeout : 10;
163
+ const connectionCheckInterval = typeof config.connectionCheckInterval === "number" ? config.connectionCheckInterval : 30000;
164
+ let connectionCheckTimer = null;
150
165
  let disconnectTimer = null;
151
166
  const quiet = config.quiet !== false; // default true
167
+ const maintainConnection = config.maintainConnection !== false; // default true
168
+ const heartbeatInterval = typeof config.heartbeatInterval === "number" ? config.heartbeatInterval : 30000;
169
+ let heartbeatTimer = null;
152
170
 
153
171
  /**
154
172
  * Resets the disconnect timer if autoDisconnect is enabled.
173
+ * Disconnects after inactivity if enabled.
155
174
  * @private
156
175
  */
157
176
  function resetDisconnectTimer() {
@@ -162,8 +181,65 @@ module.exports = function (config) {
162
181
  }, disconnectTimeout * 1000);
163
182
  }
164
183
 
184
+ /**
185
+ * Starts the heartbeat timer to maintain the ADB connection.
186
+ * Periodically sends a shell command to keep the connection alive.
187
+ * Also starts the periodic connection check for auto-reconnect.
188
+ * @private
189
+ */
190
+ function startHeartbeat() {
191
+ if (!maintainConnection) return;
192
+ if (heartbeatTimer) clearInterval(heartbeatTimer);
193
+ heartbeatTimer = setInterval(() => {
194
+ if (!connected) return;
195
+ // Send a no-op shell command to keep the connection alive
196
+ client.shell(host, "echo heartbeat").catch(() => {});
197
+ }, heartbeatInterval);
198
+ startConnectionCheck();
199
+ }
200
+
201
+ /**
202
+ * Starts the periodic connection check. If disconnected, attempts to reconnect.
203
+ * Ensures persistent, self-healing ADB connection.
204
+ * @private
205
+ */
206
+ function startConnectionCheck() {
207
+ if (connectionCheckTimer) clearInterval(connectionCheckTimer);
208
+ connectionCheckTimer = setInterval(async () => {
209
+ if (!connected) return;
210
+ try {
211
+ const devices = await client.listDevices();
212
+ const deviceId = host;
213
+ const found = devices.some((d) => d.id === deviceId);
214
+ if (!found) {
215
+ warnWithTime(`Device ${deviceId} not found in adb devices list. Attempting reconnect...`);
216
+ connected = false;
217
+ await connect();
218
+ }
219
+ } catch (err) {
220
+ warnWithTime("Error checking device connection:", err.message || err);
221
+ }
222
+ }, connectionCheckInterval);
223
+ }
224
+
225
+ /**
226
+ * Stops the heartbeat and connection check timers.
227
+ * @private
228
+ */
229
+ function stopHeartbeat() {
230
+ if (heartbeatTimer) {
231
+ clearInterval(heartbeatTimer);
232
+ heartbeatTimer = null;
233
+ }
234
+ if (connectionCheckTimer) {
235
+ clearInterval(connectionCheckTimer);
236
+ connectionCheckTimer = null;
237
+ }
238
+ }
239
+
165
240
  /**
166
241
  * Ensures connection if autoConnect is enabled.
242
+ * Used internally before sending commands.
167
243
  * @internal
168
244
  * @returns {Promise<void>}
169
245
  */
@@ -174,7 +250,8 @@ module.exports = function (config) {
174
250
  }
175
251
 
176
252
  /**
177
- * Connects to the ADB device.
253
+ * Connects to the ADB device and starts heartbeat/connection check.
254
+ * Handles already-connected state gracefully.
178
255
  * @internal
179
256
  * @returns {Promise<void>}
180
257
  */
@@ -184,11 +261,13 @@ module.exports = function (config) {
184
261
  .then(function () {
185
262
  connected = true;
186
263
  if (!quiet) logWithTime("Connected to " + host);
264
+ startHeartbeat();
187
265
  })
188
266
  .catch(function (err) {
189
267
  if (err.message && err.message.includes("already connected")) {
190
268
  if (!quiet) warnWithTime("Warning: Device already connected.");
191
269
  connected = true;
270
+ startHeartbeat();
192
271
  return;
193
272
  }
194
273
  handleDisconnectError(err);
@@ -197,7 +276,8 @@ module.exports = function (config) {
197
276
  const connectWrapped = wrapAsync(connect);
198
277
 
199
278
  /**
200
- * Disconnects from the ADB device.
279
+ * Disconnects from the ADB device and stops heartbeat/connection check.
280
+ * Handles already-disconnected state gracefully.
201
281
  * @internal
202
282
  * @returns {Promise<void>}
203
283
  */
@@ -206,6 +286,7 @@ module.exports = function (config) {
206
286
  clearTimeout(disconnectTimer);
207
287
  disconnectTimer = null;
208
288
  }
289
+ stopHeartbeat();
209
290
  return client
210
291
  .disconnect(ip, port)
211
292
  .then(function () {
@@ -303,7 +384,61 @@ module.exports = function (config) {
303
384
  });
304
385
  };
305
386
 
387
+ /**
388
+ * Returns the current connection status as tracked by the module.
389
+ * Optionally performs a live check against adb devices if requested.
390
+ * @public
391
+ * @param {boolean} [liveCheck=false] - If true, checks adb devices for actual connection.
392
+ * @returns {Promise<"connected"|"disconnected"|"unknown">}
393
+ * @example
394
+ * await remote.getConnectionStatus();
395
+ * await remote.getConnectionStatus(true); // live check
396
+ */
397
+ async function getConnectionStatus(liveCheck = false) {
398
+ if (!liveCheck) {
399
+ return connected ? "connected" : "disconnected";
400
+ }
401
+ try {
402
+ const devices = await client.listDevices();
403
+ const deviceId = host;
404
+ const found = devices.some((d) => d.id === deviceId);
405
+ return found ? "connected" : "disconnected";
406
+ } catch {
407
+ return "unknown";
408
+ }
409
+ }
410
+
411
+ /**
412
+ * Returns true if the module believes it is connected to the device.
413
+ * This is a fast check of internal state, not a live ADB query.
414
+ * @public
415
+ * @returns {boolean}
416
+ * @example
417
+ * if (remote.isConnected) { ... }
418
+ */
419
+ function isConnected() {
420
+ return !!connected;
421
+ }
422
+
306
423
  return {
424
+ /**
425
+ * Returns the current connection status as tracked by the module, or does a live check if requested.
426
+ * @function
427
+ * @param {boolean} [liveCheck=false] - If true, checks adb devices for actual connection.
428
+ * @returns {Promise<"connected"|"disconnected"|"unknown">}
429
+ * @example
430
+ * await remote.getConnectionStatus();
431
+ * await remote.getConnectionStatus(true); // live check
432
+ */
433
+ getConnectionStatus,
434
+ /**
435
+ * Returns true if the module believes it is connected to the device.
436
+ * @readonly
437
+ * @type {boolean}
438
+ * @example
439
+ * if (remote.isConnected) { ... }
440
+ */
441
+ isConnected,
307
442
  /**
308
443
  * Get or set Android settings via ADB.
309
444
  * @public
@@ -3,7 +3,7 @@
3
3
  // Usage: node test/interactive-remote.js
4
4
 
5
5
  const readline = require("readline");
6
- const AndroidTVSetup = require("../src/lib/adb/setup");
6
+ const remote = require("../src/lib/android-tv-remote");
7
7
 
8
8
  /**
9
9
  * Prompts the user for input in the terminal.
@@ -23,8 +23,9 @@ function prompt(query) {
23
23
  }
24
24
 
25
25
  /**
26
- * Runs the interactive remote test.
26
+ * Runs the interactive remote test using the main remote module.
27
27
  * Prompts for IP/port, connects, and sends button presses.
28
+ * @returns {Promise<void>}
28
29
  */
29
30
  async function main() {
30
31
  const ip = (await prompt("Enter device IP: ")).trim();
@@ -34,17 +35,16 @@ async function main() {
34
35
  console.error("IP address is required.");
35
36
  process.exit(1);
36
37
  }
37
- const setup = new AndroidTVSetup({ ip, port, quiet: false });
38
38
  try {
39
- await setup.connect();
39
+ await remote.connect({ ip, port });
40
40
  console.log(`Connected to ${ip}:${port}`);
41
- // List of buttons to press (as method names on setup.remote.press)
41
+ // List of buttons to press (as method names on remote.press)
42
42
  const buttons = ["home", "up", "down", "left", "right", "ok", "back"];
43
43
  for (let i = 0; i < buttons.length; i++) {
44
44
  const btn = buttons[i];
45
- if (setup.remote && setup.remote.press && typeof setup.remote.press[btn] === "function") {
45
+ if (remote.press && typeof remote.press[btn] === "function") {
46
46
  console.log(`Pressing: ${btn}`);
47
- await setup.remote.press[btn]();
47
+ await remote.press[btn]();
48
48
  } else {
49
49
  console.log(`Button '${btn}' not available.`);
50
50
  }
@@ -56,10 +56,10 @@ async function main() {
56
56
  await new Promise((res) => setTimeout(res, 500));
57
57
  }
58
58
  }
59
- await setup.disconnect();
59
+ await remote.disconnect();
60
60
  console.log("Test complete. Disconnected.");
61
61
  } catch (err) {
62
- if (setup.errorWithTime) setup.errorWithTime("Error:", err.message || err);
62
+ if (remote.errorWithTime) remote.errorWithTime("Error:", err.message || err);
63
63
  else console.error("Error:", err.message || err);
64
64
  process.exit(1);
65
65
  }