lgtv2

repository·master·Indexed 43 days ago

https://github.com/hobbyquaker/lgtv2

A Node.js module for remote controlling LG WebOS smart TVs via WebSocket. It supports secure (wss) and insecure (ws) connections, automatic pairing, Wake-on-LAN, and pointer input control. Version 2.0.2 is an ES module requiring Node.js 20.19+, 22.12+, or 24+.

Tokens
9K
Snippets
21
Records
39
Agent score
53%

What's inside lgtv2

  1. Understand the lgtv2 development roadmap and release strategy

    master

    The lgtv2 library is a standalone WebOS SSAP client used by various integrations like lgtv2mqtt, node-red-contrib-lgtv, and homebridge-webos-tv.

    The development follows a specific order of priority:

    1. 1.7.0 fix release: Focuses on wss/TLS support, error surfacing, keyfile fixes, and the secure/rejectUnauthorized options.
    2. 1.8.0 hygiene/helpers: General code cleanup and helper improvements.
    3. 2.0 modernization: Transition to ESM, Promises, ws, and full TypeScript typings.

    Note that lgtv2mqtt 1.3.0 requires lgtv2 1.7.0 or higher to function correctly with SSL/IPv6 fixes.

  2. Manage audio status and volume changes

    master

    When subscribing to audio changes, be aware that different firmware versions return different data shapes.

    • Older firmware: May use a changed array (e.g., res.changed.indexOf(...)) to indicate what changed.
    • Newer firmware: Often returns a volumeStatus object containing volume, muteStatus, and soundOutput without a changed array.

    To ensure compatibility across different TV models, it is recommended to use the audio/getStatus service to retrieve the current state rather than relying on the changed array hack.

  3. Handle TV pairing and connection events

    master

    LG WebOS TVs require manual acceptance of a connection request on the TV screen during the first connection. You can listen for these events to manage the user experience:

    • prompt: Emitted when the TV shows the pairing prompt. You should notify the user to accept it on the TV.
    • connect: Emitted when the connection is successfully established and paired.
    • error: Emitted on websocket, pairing, or TV errors. Subsequent identical connection errors (like EHOSTUNREACH when the TV is off) are throttled to avoid flooding logs.
    • mac: Emitted after pairing, providing the learned { wired, wifi } MAC addresses.
  4. Automatic MAC address learning for Wake-on-LAN

    master

    The library can automatically learn the TV's wired and Wi-Fi MAC addresses to make tv.wake() more reliable.

    After the initial pairing, the library reads com.webos.service.connectionmanager/getinfo and caches the MAC addresses in a file named <keyFile>.mac. When tv.wake() is called without arguments, it sends the WoL payload to both cached addresses.

    Options:

    • learnMac: false: Disables automatic MAC learning.
    • mac: '...': Manually provides a specific MAC address to override the learned ones.
  5. Monitor volume status changes

    master

    The library normalizes volumeStatus payloads to provide a consistent interface. When subscribing to volume changes, the payload includes volume, muted, and a changed flag. The changed property is computed by comparing the current state to the previous state in the subscription stream.

    // Conceptual payload shape for volume subscriptions
    // { volume: number, muted: boolean, changed: boolean }
  6. Wake the TV using MAC addresses

    master

    The wake() method can be used to wake the TV from standby.

    • Automatic MAC Discovery: After the initial pairing, the library learns the wired and Wi-Fi MAC addresses via the connectionmanager/getinfo command and caches them in a local file. When wake() is called without arguments, it uses these cached MACs.
    • Manual MAC Override: You can pass a specific MAC address or an array of MAC addresses to wake(mac) to target a specific network interface.
    • MAC Events: The library provides mac events and macs/mac properties to track discovered addresses.

    Note: You can opt-out of automatic MAC learning using the learnMac: false option.

    // Wake using cached MACs
    await lgtv.wake();
    
    // Wake using a specific MAC
    await lgtv.wake('00:11:22:33:44:55');
    
    // Wake using an array of MACs
    await lgtv.wake(['00:11:22:33:44:55', 'AA:BB:CC:DD:EE:FF']);
  7. Connect to newer LG TVs using WSS (port 3001)

    master

    Recent LG TV firmware (2023 onwards) often requires a secure WebSocket connection on port 3001 instead of the default port 3000. Because these TVs use self-signed certificates, you must explicitly disable certificate validation in the wsconfig object to prevent connection errors.

    Note: When providing wsconfig, ensure you are aware that in version 1.6.3, passing this object replaces the entire default configuration object. You may need to manually include keepalive settings if you require them.

    // Example configuration for newer TVs requiring WSS
    const config = {
      url: 'wss://<YOUR_TV_IP>:3001',
      wsconfig: {
        tlsOptions: {
          rejectUnauthorized: false
        }
      }
    };
  8. Upgrade to LGTV2 v2.0

    master

    Version 2.0 is a modernization release. While the core API remains largely unchanged, there are significant changes to the module format and the underlying transport layer.

    Module Format

    • ES Modules: The native way to import is import LGTV from 'lgtv2'.
    • CommonJS: const LGTV = require('lgtv2') continues to work on Node 20.19+, 22.12+, and 24 without needing .default. Calling it without new is also supported.
    • Node.js Support: Node versions earlier than 20.19 are no longer supported.

    Transport Layer Changes

    LGTV2 now uses the ws library instead of websocket. This removes the need for native add-ons like bufferutil or utf-8-validate.

    Consequences of the switch to ws:

    • The message event now delivers the raw frame as a string (previously it was a websocket message object containing utf8Data).
    • The close event payload is now an object: {code, reason}.
    • wsconfig is replaced by keepalive, keepaliveInterval, keepaliveGracePeriod, and wsOptions (which are passed directly to ws).
    • Note: wsconfig.dropConnectionOnKeepaliveTimeout has no equivalent in 2.0; this behavior is now always enabled.

    Connection Behavior (Unchanged)

    • Connection attempts start with wss://host:3001 and fall back to ws://host:3000.
    • verifyCert remains opt-in.
    • audio/getVolume payloads remain normalized to {volume, muted, changed}.
  9. Manage the client key file

    master

    The module stores the pairing client key in a file to allow subsequent connections without re-pairing.

    • keyFile: Path to the key file.
    • LGTV2_KEY_DIR: Environment variable to override the default directory where keys are stored.
    • Default Directories:
      • Linux: ~/.lgtv2/keyfile-<host>
      • macOS: ~/Library/Preferences/lgtv2/keyfile-<host>
      • Windows: %APPDATA%\lgtv2\keyfile-<host>
    • saveKey(key, callback): Use this option to provide a custom implementation for saving the key.
  10. Configure SSL certificate verification

    master

    Because LG TVs use a private PKI with self-signed certificates, you can choose how to handle verification using the verifyCert option in the constructor:

    • 'lg': Pins the LG intermediate/leaf certificate fingerprint. This is the strongest security option and is recommended for production if you want to avoid rejectUnauthorized: false.
    • 'tofu': Trust-on-first-use. Stores the fingerprint of the certificate used during the first connection.
    • fingerprint(s): Pass specific SHA-256 fingerprints to verify against.
    • Default: If not specified, the library defaults to rejectUnauthorized: false (status quo).
  11. Manage client keys and pairing

    master

    The client uses a client-key to maintain a paired connection with the TV.

    • Automatic Storage: By default, the client looks for keys in a directory determined by the OS (e.g., ~/.lgtv2 on Linux, %APPDATA%/lgtv2 on Windows). You can override this with LGTV_KEY_DIR env var or the keyFile config option.
    • Pairing: If no valid key is found, the client will emit a 'prompt' event. You must handle the pairing process (usually by interacting with the TV screen) and then use saveKey(key, cb) to persist the new key.
    • MAC Learning: If learnMac: true is set, the client will automatically query the TV for its wired and wifi MAC addresses and save them to a .mac file associated with the key file.