lgtv2mqtt2 1.0.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/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Marcin
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,43 @@
1
+ # `lgtv2mqtt2`
2
+
3
+ `lgtv2mqtt2` connects WebOS-based TVs with MQTT, exposing a couple of read-write properties to control the TV.
4
+
5
+ There's [`lgtv2mqtt`](https://github.com/hobbyquaker/lgtv2mqtt) but it didn't work for me, and none of the WebOS libraries on GitHub did either, other than the one bundled with [`homebridge-webos-tv`](https://github.com/merdok/homebridge-webos-tv/) which this project re-uses.
6
+
7
+ I only exposed the endpoints that I care about, and this repository is provided as-is - feel free to fork and change things and send PRs.
8
+
9
+ ## Installation
10
+
11
+ 1. `npm install lgtv2mqtt2` (optionally with `-g` if you want it to be available globally)
12
+ 2. create `~/.mqtt-config.json` containing:
13
+ ```
14
+ {
15
+ host: "MQTT_BROKER_ADDRESS",
16
+ username: "MQTT_BROKER_USERNAME",
17
+ password: "MQTT_BROKER_PASSWORD"
18
+ }
19
+ ```
20
+ 3. create `~/.lgtv-config.json` containing:
21
+ ```
22
+ {
23
+ ip: "LGTV_IP",
24
+ mac: "LGTV_MAC",
25
+ mqttBase: "MQTT_BASE_PATH",
26
+ }
27
+ ```
28
+ - it's best to assign static IP to your TV, and note the MAC address from the router
29
+ - the `mqttBase` is the path under which the properties will be stored
30
+
31
+ ## Usage
32
+
33
+ First, run `lgtv2mqtt2`.
34
+
35
+ The tool creates a couple of paths under the `mqttBase` (below). Their values are writable (which updates the TV state), and they react to TV state changes (say from a TV remote) and update the values in MQTT:
36
+
37
+ - `/power` `["on" | "off"]`
38
+ - `/screen` `["on" | "off"]`
39
+ - `/volume` `0 - 100`
40
+ - `/backlight` `0 - 100`
41
+ - `/input` `com.webos.app.hdmi[N]`
42
+
43
+
package/cli.js ADDED
@@ -0,0 +1,182 @@
1
+ #!/usr/bin/env node
2
+
3
+ import mqtt from "mqtt";
4
+
5
+ import LgTvController from "./vendor/LgTvController.js";
6
+ import Events from "./vendor/Events.js";
7
+
8
+ import getConfig from "./get-config.js";
9
+
10
+ const MQTT_CONFIG = getConfig(".mqtt-config.json", {
11
+ host: "MQTT_BROKER_ADDRESS",
12
+ username: "MQTT_BROKER_USERNAME",
13
+ password: "MQTT_BROKER_PASSWORD",
14
+ });
15
+
16
+ const LGTV_CONFIG = getConfig(".lgtv-config.json", {
17
+ ip: "LGTV_IP",
18
+ mac: "LGTV_MAC",
19
+ mqttBase: "MQTT_BASE_PATH",
20
+ });
21
+
22
+ const client = mqtt.connect(MQTT_CONFIG);
23
+
24
+ const lg = new LgTvController(LGTV_CONFIG.ip, LGTV_CONFIG.mac, "keyfile");
25
+ lg.connect();
26
+
27
+ const state = {};
28
+ const config = {
29
+ power: {
30
+ onLgEvents: {
31
+ [Events.TV_TURNED_ON]: () => {
32
+ publishMqttMessageIfDiffers("power", "on");
33
+ },
34
+ [Events.TV_TURNED_OFF]: () => {
35
+ publishMqttMessageIfDiffers("power", "off");
36
+ },
37
+ },
38
+
39
+ onMqttMessage: (value) => {
40
+ if (value === "on") {
41
+ lg.turnOn();
42
+ }
43
+
44
+ if (value === "off") {
45
+ lg.turnOff();
46
+ }
47
+ },
48
+ },
49
+
50
+ volume: {
51
+ onLgEvents: {
52
+ [Events.AUDIO_STATUS_CHANGED]: (value) => {
53
+ publishMqttMessageIfDiffers("volume", `${value.volume}`);
54
+ },
55
+ },
56
+
57
+ onMqttMessage: (value) => {
58
+ if (!lg.isTvOn()) {
59
+ return;
60
+ }
61
+
62
+ lg.setVolumeLevel(parseInt(value));
63
+ },
64
+ },
65
+
66
+ backlight: {
67
+ onLgEvents: {
68
+ [Events.PICTURE_SETTINGS_CHANGED]: (value) => {
69
+ publishMqttMessageIfDiffers("backlight", `${value.backlight}`);
70
+ },
71
+ },
72
+
73
+ onMqttMessage: (value) => {
74
+ if (!lg.isTvOn()) {
75
+ return;
76
+ }
77
+
78
+ lg.setBacklight(parseInt(value));
79
+ },
80
+ },
81
+
82
+ screen: {
83
+ onLgEvents: {
84
+ [Events.SCREEN_STATE_CHANGED]: (value) => {
85
+ if (value.state === "Screen On" || value.processing === "Screen On") {
86
+ publishMqttMessageIfDiffers("screen", "on");
87
+ } else if (value.state === "Screen Off") {
88
+ publishMqttMessageIfDiffers("screen", "off");
89
+ }
90
+ },
91
+ },
92
+
93
+ onMqttMessage: (value) => {
94
+ if (!lg.isTvOn()) {
95
+ return;
96
+ }
97
+
98
+ if (value === "on") {
99
+ lg.turnOnTvScreen();
100
+ }
101
+
102
+ if (value === "off") {
103
+ lg.turnOffTvScreen();
104
+ }
105
+ },
106
+ },
107
+
108
+ input: {
109
+ onLgEvents: {
110
+ [Events.FOREGROUND_APP_CHANGED]: (value) => {
111
+ // not sure what else can come up here
112
+ if (value.appId.includes("hdmi")) {
113
+ publishMqttMessageIfDiffers("input", value.appId);
114
+ }
115
+ },
116
+ },
117
+
118
+ onMqttMessage: (value) => {
119
+ if (!lg.isTvOn()) {
120
+ return;
121
+ }
122
+
123
+ lg.launchApp(value);
124
+ },
125
+ },
126
+ };
127
+
128
+ function publishMqttMessageIfDiffers(topic, value) {
129
+ if (state[topic] !== value) {
130
+ client.publishAsync(LGTV_CONFIG.mqttBase + "/" + topic, value, {
131
+ retain: true,
132
+ });
133
+ state[topic] = value;
134
+ }
135
+ }
136
+
137
+ client.on("message", (topic, message) => {
138
+ topic = topic.replace(LGTV_CONFIG.mqttBase + "/", "");
139
+ const mqttValue = message.toString();
140
+
141
+ if (!config[topic]) {
142
+ console.log("no config for topic:", topic);
143
+ return;
144
+ }
145
+
146
+ console.log(
147
+ "got mqtt message for topic:",
148
+ topic,
149
+ "with value:",
150
+ mqttValue,
151
+ "current state value is:",
152
+ state[topic]
153
+ );
154
+
155
+ if (state[topic] !== mqttValue) {
156
+ config[topic].onMqttMessage(mqttValue);
157
+ state[topic] = mqttValue;
158
+ }
159
+ });
160
+
161
+ Object.values(config).forEach(({ onLgEvents = {} }) => {
162
+ Object.entries(onLgEvents).forEach(([event, handler]) => {
163
+ lg.on(event, (value) => {
164
+ console.log("got lg event:", event, "with value:", value);
165
+ handler(value);
166
+ });
167
+ });
168
+ });
169
+
170
+ client.on("connect", () => {
171
+ Object.keys(config).forEach((topic) => {
172
+ console.log("subscribing to topic:", topic);
173
+ client.subscribe(LGTV_CONFIG.mqttBase + "/" + topic);
174
+ });
175
+ });
176
+
177
+ lg.on(Events.SETUP_FINISHED, () => {
178
+ console.log(
179
+ "setup finished!\nlist of external inputs:",
180
+ lg.getExternalInputList()
181
+ );
182
+ });
package/get-config.js ADDED
@@ -0,0 +1,43 @@
1
+ import { homedir } from "os";
2
+ import path from "path";
3
+ import fs from "fs";
4
+
5
+ export default function getConfig(filePath, exampleConfig) {
6
+ const configPath = path.join(homedir(), filePath);
7
+
8
+ if (!fs.existsSync(configPath)) {
9
+ console.log(`No "${configPath}" found, create one with this content:
10
+
11
+ ${JSON.stringify(exampleConfig, null, 2)}`);
12
+
13
+ process.exit(1);
14
+ }
15
+
16
+ let config;
17
+
18
+ try {
19
+ config = JSON.parse(fs.readFileSync(configPath, "utf-8"));
20
+ } catch (e) {
21
+ console.log(`Couldn't parse "${configPath}"
22
+
23
+ ${e}`);
24
+
25
+ process.exit(1);
26
+ }
27
+
28
+ let anyKeyMissing = false;
29
+ Object.keys(exampleConfig).forEach((requiredKey) => {
30
+ if (!config.hasOwnProperty(requiredKey)) {
31
+ console.log(
32
+ `Missing key "${requiredKey}" in config file "${configPath}"`
33
+ );
34
+ anyKeyMissing = true;
35
+ }
36
+ });
37
+
38
+ if (anyKeyMissing) {
39
+ process.exit(1);
40
+ }
41
+
42
+ return config;
43
+ }
package/package.json ADDED
@@ -0,0 +1,26 @@
1
+ {
2
+ "name": "lgtv2mqtt2",
3
+ "version": "1.0.0",
4
+ "main": "index.js",
5
+ "keywords": [],
6
+ "author": "",
7
+ "description": "",
8
+ "license": "ISC",
9
+ "scripts": {
10
+ "start": "./cli.js",
11
+ "vendor-libraries": "./vendor-libraries.sh"
12
+ },
13
+ "bin": {
14
+ "lgtv2mqtt2": "./cli.js"
15
+ },
16
+ "type": "module",
17
+ "dependencies": {
18
+ "mkdirp": "^1.0.4",
19
+ "mqtt": "^5.3.0",
20
+ "persist-path": "^1.0.2",
21
+ "tcp-ping": "^0.1.1",
22
+ "wake_on_lan": "^1.0.0",
23
+ "websocket": "^1.0.34"
24
+ },
25
+ "devDependencies": {}
26
+ }
@@ -0,0 +1,19 @@
1
+ export default {
2
+ SETUP_FINISHED: 'tvSetupFinished',
3
+ PIXEL_REFRESHER_STARTED: 'tvPixelRefresherStarted',
4
+ TV_TURNED_OFF: 'tvTurnedOff',
5
+ TV_TURNED_ON: 'tvTurnedOn',
6
+ SCREEN_SAVER_TURNED_ON: 'screenSaverTurnedOn',
7
+ SCREEN_STATE_CHANGED: 'screenStateChanged',
8
+ POWER_STATE_CHANGED: 'powerStateChanged',
9
+ AUDIO_STATUS_CHANGED: 'audioStatusChanged',
10
+ FOREGROUND_APP_CHANGED: 'foregroundAppChanged',
11
+ LIVE_TV_CHANNEL_CHANGED: 'liveTvChannelChanged',
12
+ SOUND_OUTPUT_CHANGED: 'soundOutputChanged',
13
+ NEW_APP_ADDED: 'appAdded',
14
+ APP_REMOVED: 'appRemoved',
15
+ VOLUME_UP: 'volumeUp', // not directly used but the event is present
16
+ VOLUME_DOWN: 'volumeDown', // not directly used but the event is present
17
+ PICTURE_SETTINGS_CHANGED: 'pictureSettingsChanged',
18
+ SOUND_SETTINGS_CHANGED: 'soundSettingsChanged',
19
+ };