Sunday 7 August 2016

lg4j – Java library for controlling LG TVs

Inspired by lgcommander, lg4j is a Java API for controlling LG TVs via the webservice interface.

Example usage

First you need find the TV’s IP address and get an authentication key by executing:

Lg4j lg4j = new Lg4j();
String ip = lg4j.discoverIpAddress();
lg4j.displayAuthenticationKey(ip);

This will display a key on the TV in the bottom right corner:

Next, use the authentication key to authenticate with the TV:

lg4j.authenticate(ip, 674689);

After authentication you can send commands to the TV, for example to turn down the TV one level:

lg4j.sendKey(ip, KeyCodes.VOLUME_DOWN);

Putting it all together:

Lg4j lg4j = new Lg4j();
String ip = lg4j.discoverIpAddress();
lg4j.displayAuthenticationKey(ip);
int session = lg4j.authenticate(ip, 674689);
lg4j.sendKey(ip, KeyCodes.VOLUME_DOWN);

Source Code

  • Code available in GitHub - lg4j

Build and Test

The project is a standard Maven project which can be built with:

mvn clean install

For the JUnit tests to pass an LG TV must be available on the network and the correct authentication key set in the unit test code. Testing was performed against a LG 42LF580V, your mileage may vary with a different model.