From 923218e4cab6ebc3b3a04d65f9c0a11f0ca847e9 Mon Sep 17 00:00:00 2001 From: domo-site <93765654+mgrafr@users.noreply.github.com> Date: Tue, 22 Feb 2022 16:50:49 +0100 Subject: [PATCH 01/14] modif pour Domoticz MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit le script initial tente en permanence de se reconnecter (toutes les 5 secondes) ; je préfère gérer les reconnexions à partir de domoticz. --- index.js | 990 +++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 954 insertions(+), 36 deletions(-) diff --git a/index.js b/index.js index 83d9a70..04ac4fc 100644 --- a/index.js +++ b/index.js @@ -1,36 +1,954 @@ -var express = require('express') -var app = express() -var bodyParser = require('body-parser'); -var fs = require('fs'); - -try { - var CONFIG = require('./config') -} catch (e) { - fs.writeFile("config.json", '{"lgtvip" : "0.0.0.0", "lgtvmac" : "00:00:00:00:00:00"}', function(err) { - if(err) { - return console.log(err); - } - console.log("Config file created"); - }); -} finally { - console.log(CONFIG); -} - -app.use(bodyParser.json()); // for parsing application/json -app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded - -app.use(express.static('public')) - -app.get('/', function(req, res, next) { - res.type('html').sendFile(__dirname + '/index.html'); -}); - -app.use('/input', require('./apis/change-input')); -app.use('/volume', require('./apis/change-volume')); -app.use('/alert', require('./apis/alert')); -app.use('/off', require('./apis/turn-off')); -app.use('/on', require('./apis/turn-on')); - -app.listen(5555, function () { - console.log('LGTV http server is up in http://localhost:5555') -}) +// +// LG webos smart TV control app +// references: +// https://github.com/ConnectSDK/Connect-SDK-Android-Core +// https://github.com/CODeRUS/harbour-lgremote-webos +// +// 1: send handshake per below -> receive client key if not already +// 2: the protocol is using JSON strings with requests from the client, responses +// from the TV. Subscriptions probably means the TV will push notifications +// without prior individual requests. +// 3: client request has these fields: +// type : register/request/subscribe +// id : command + _ + message count (the response will mirror this number) +// uri : command endpoint URI +// payload : optional, eg input source string when changing input +// +// All callbacks follow the common pattern of function(error, ....) {} +// ie first argument is false if the call went ok, or true if an error occurred. +// Then, the second argument is most often the result if applicable, or not +// existant respectively. +// ----------------------------------------------------------------------------- +var fs = require('fs'); // for storing client key +// var http = require('http'); // for communication with Kodi + +// var WebSocket = require('ws'); +var WebSocketClient = require('websocket').client; // for communication with TV +var client = new WebSocketClient(); +var handshaken = false; + +// for SSDP discover of TV on the LAN +var dgram = require('dgram'); + +var eventemitter = new (require('events').EventEmitter); // for match ws request -- response +eventemitter.setMaxListeners(0); // enable infinite number of listeners + +// connection to TV +var wsurl = 'ws://lgsmarttv.lan:3000'; + +// once connected, store client key (retrieved from TV) in this file +var client_key_filename = "./client-key.txt"; + +// bool for callbacks +var RESULT_ERROR = true; +var RESULT_OK = false; +// ----------------------------------------------------------------------------- +// send this ask for permission to control the TV +// alternatives: pairingType = PROMPT or PIN +// PROMPT is arguably more convenient as it opens a yes/no dialog on the TV while +// PIN show a three-digit random number that has to be communicated to this app. + +// this works and gives full auth +// handshake without client key, for first connection +var hello = "{\"type\":\"register\",\"id\":\"register_0\",\"payload\":{\"forcePairing\":false,\"pairingType\":\"PROMPT\",\"manifest\":{\"manifestVersion\":1,\"appVersion\":\"1.1\",\"signed\":{\"created\":\"20140509\",\"appId\":\"com.lge.test\",\"vendorId\":\"com.lge\",\"localizedAppNames\":{\"\":\"LG Remote App\",\"ko-KR\":\"리모컨 앱\",\"zxx-XX\":\"ЛГ Rэмotэ AПП\"},\"localizedVendorNames\":{\"\":\"LG Electronics\"},\"permissions\":[\"TEST_SECURE\",\"CONTROL_INPUT_TEXT\",\"CONTROL_MOUSE_AND_KEYBOARD\",\"READ_INSTALLED_APPS\",\"READ_LGE_SDX\",\"READ_NOTIFICATIONS\",\"SEARCH\",\"WRITE_SETTINGS\",\"WRITE_NOTIFICATION_ALERT\",\"CONTROL_POWER\",\"READ_CURRENT_CHANNEL\",\"READ_RUNNING_APPS\",\"READ_UPDATE_INFO\",\"UPDATE_FROM_REMOTE_APP\",\"READ_LGE_TV_INPUT_EVENTS\",\"READ_TV_CURRENT_TIME\"],\"serial\":\"2f930e2d2cfe083771f68e4fe7bb07\"},\"permissions\":[\"LAUNCH\",\"LAUNCH_WEBAPP\",\"APP_TO_APP\",\"CLOSE\",\"TEST_OPEN\",\"TEST_PROTECTED\",\"CONTROL_AUDIO\",\"CONTROL_DISPLAY\",\"CONTROL_INPUT_JOYSTICK\",\"CONTROL_INPUT_MEDIA_RECORDING\",\"CONTROL_INPUT_MEDIA_PLAYBACK\",\"CONTROL_INPUT_TV\",\"CONTROL_POWER\",\"READ_APP_STATUS\",\"READ_CURRENT_CHANNEL\",\"READ_INPUT_DEVICE_LIST\",\"READ_NETWORK_STATE\",\"READ_RUNNING_APPS\",\"READ_TV_CHANNEL_LIST\",\"WRITE_NOTIFICATION_TOAST\",\"READ_POWER_STATE\",\"READ_COUNTRY_INFO\"],\"signatures\":[{\"signatureVersion\":1,\"signature\":\"eyJhbGdvcml0aG0iOiJSU0EtU0hBMjU2Iiwia2V5SWQiOiJ0ZXN0LXNpZ25pbmctY2VydCIsInNpZ25hdHVyZVZlcnNpb24iOjF9.hrVRgjCwXVvE2OOSpDZ58hR+59aFNwYDyjQgKk3auukd7pcegmE2CzPCa0bJ0ZsRAcKkCTJrWo5iDzNhMBWRyaMOv5zWSrthlf7G128qvIlpMT0YNY+n/FaOHE73uLrS/g7swl3/qH/BGFG2Hu4RlL48eb3lLKqTt2xKHdCs6Cd4RMfJPYnzgvI4BNrFUKsjkcu+WD4OO2A27Pq1n50cMchmcaXadJhGrOqH5YmHdOCj5NSHzJYrsW0HPlpuAx/ECMeIZYDh6RMqaFM2DXzdKX9NmmyqzJ3o/0lkk/N97gfVRLW5hA29yeAwaCViZNCP8iC9aO0q9fQojoa7NQnAtw==\"}]}}}"; + +// handshake with client key, for subsequent connections +var hello_w_key = "{\"type\":\"register\",\"id\":\"register_0\",\"payload\":{\"forcePairing\":false,\"pairingType\":\"PROMPT\",\"client-key\":\"CLIENTKEYGOESHERE\",\"manifest\":{\"manifestVersion\":1,\"appVersion\":\"1.1\",\"signed\":{\"created\":\"20140509\",\"appId\":\"com.lge.test\",\"vendorId\":\"com.lge\",\"localizedAppNames\":{\"\":\"LG Remote App\",\"ko-KR\":\"리모컨 앱\",\"zxx-XX\":\"ЛГ Rэмotэ AПП\"},\"localizedVendorNames\":{\"\":\"LG Electronics\"},\"permissions\":[\"TEST_SECURE\",\"CONTROL_INPUT_TEXT\",\"CONTROL_MOUSE_AND_KEYBOARD\",\"READ_INSTALLED_APPS\",\"READ_LGE_SDX\",\"READ_NOTIFICATIONS\",\"SEARCH\",\"WRITE_SETTINGS\",\"WRITE_NOTIFICATION_ALERT\",\"CONTROL_POWER\",\"READ_CURRENT_CHANNEL\",\"READ_RUNNING_APPS\",\"READ_UPDATE_INFO\",\"UPDATE_FROM_REMOTE_APP\",\"READ_LGE_TV_INPUT_EVENTS\",\"READ_TV_CURRENT_TIME\"],\"serial\":\"2f930e2d2cfe083771f68e4fe7bb07\"},\"permissions\":[\"LAUNCH\",\"LAUNCH_WEBAPP\",\"APP_TO_APP\",\"CLOSE\",\"TEST_OPEN\",\"TEST_PROTECTED\",\"CONTROL_AUDIO\",\"CONTROL_DISPLAY\",\"CONTROL_INPUT_JOYSTICK\",\"CONTROL_INPUT_MEDIA_RECORDING\",\"CONTROL_INPUT_MEDIA_PLAYBACK\",\"CONTROL_INPUT_TV\",\"CONTROL_POWER\",\"READ_APP_STATUS\",\"READ_CURRENT_CHANNEL\",\"READ_INPUT_DEVICE_LIST\",\"READ_NETWORK_STATE\",\"READ_RUNNING_APPS\",\"READ_TV_CHANNEL_LIST\",\"WRITE_NOTIFICATION_TOAST\",\"READ_POWER_STATE\",\"READ_COUNTRY_INFO\"],\"signatures\":[{\"signatureVersion\":1,\"signature\":\"eyJhbGdvcml0aG0iOiJSU0EtU0hBMjU2Iiwia2V5SWQiOiJ0ZXN0LXNpZ25pbmctY2VydCIsInNpZ25hdHVyZVZlcnNpb24iOjF9.hrVRgjCwXVvE2OOSpDZ58hR+59aFNwYDyjQgKk3auukd7pcegmE2CzPCa0bJ0ZsRAcKkCTJrWo5iDzNhMBWRyaMOv5zWSrthlf7G128qvIlpMT0YNY+n/FaOHE73uLrS/g7swl3/qH/BGFG2Hu4RlL48eb3lLKqTt2xKHdCs6Cd4RMfJPYnzgvI4BNrFUKsjkcu+WD4OO2A27Pq1n50cMchmcaXadJhGrOqH5YmHdOCj5NSHzJYrsW0HPlpuAx/ECMeIZYDh6RMqaFM2DXzdKX9NmmyqzJ3o/0lkk/N97gfVRLW5hA29yeAwaCViZNCP8iC9aO0q9fQojoa7NQnAtw==\"}]}}}"; +// --------------------------------------------------------- +// get the handshake string used for setting up the ws connection +function get_handshake() { + if (fs.existsSync(client_key_filename)) { + var ck = fs.readFileSync(client_key_filename); + console.log("Client key:" + ck); + return hello_w_key.replace("CLIENTKEYGOESHERE", ck); + + } else { + console.log("First usage, let's pair with TV."); + return hello; + } +} +// --------------------------------------------------------- +// store the client key on disk so that we don't have to pair next time +function store_client_key(ck) { + console.log("Storing client key:" + ck); + fs.writeFileSync(client_key_filename, ck); +} +/*---------------------------------------------------------------------------*/ +client.on('connectFailed', function(error) { + // failed to connect, set timer to retry in a few seconds + console.log('Connect Error: ' + error.toString()); + //setTimeout(function(){connect();}, 5000); +}); +/*---------------------------------------------------------------------------*/ +// store the connection in a variable with larger scope so that we may later +// refer to it and close connection. +var clientconnection = {}; +client.on('connect', function(connection) { + console.log('WebSocket Client Connected on IP:' + connection.remoteAddress); + clientconnection = connection; + //-------------------------------------------------------------------------- + connection.on('error', function(error) { + console.log("Connection Error: " + error.toString()); + throw new Error("Websocket connection error:" + error.toString()); + }); + //-------------------------------------------------------------------------- + connection.on('close', function() { + console.log('LG TV disconnected'); + clientconnection = {}; + eventemitter.emit("lgtv_ws_closed"); + }); + //-------------------------------------------------------------------------- + connection.on('message', function(message) { + if (message.type === 'utf8') { + var json = JSON.parse(message.utf8Data); + console.log('<--- received: %s', message.utf8Data); + // console.log('<--- emitting: %s', json.id); + eventemitter.emit(json.id, json); + } else { + console.log('<--- received: %s', message.toString()); + } + }); + //-------------------------------------------------------------------------- + + handshaken = false; + var hs = get_handshake(); + console.log("Sending handshake: %s", hs); + connection.send(hs); + // connection.sendUTF(hs); // works as well +}); +/*---------------------------------------------------------------------------*/ +var isConnected = function(){ + if (typeof clientconnection.connected === 'undefined') { + // console.log("disconnected"); + return false; + } + return clientconnection.connected; +}; +//------------------------------------------ +var close_connection = function(){ + // console.log("disconnecting"); + clientconnection.close(); +}; +//------------------------------------------ +var remote_ip = function(){ + if (typeof clientconnection.remoteAddress === 'undefined') { + return "0.0.0.0"; + } + return clientconnection.remoteAddress; +}; +//------------------------------------------ +var ws_send = function(str){ + if (typeof clientconnection.connected === 'undefined') { + return false; + } + if (typeof str !== 'string') { + return false; + } + if (clientconnection.connected) { + clientconnection.send(str); + } + return clientconnection.connected; +}; +/*---------------------------------------------------------------------------*/ +// this is the old version, using the ws lib; above is the new, using websocket lib + // try { + // var ws = new WebSocket(wsurl); + // } catch(err) { + // console.log(err); + // console.log("Error, could not open websocket (are you connected to the Internet?)"); + // process.exit(0); // TODO better error handling, what is appropriate here - raise some error. + // } + // // --------------------------------------------------------- + // // callback for when connection is opened, ie the websocket handshake is done and + // // we should perform TV handshake. + // ws.on('open', function() { + // console.log('opened connection to TV'); + // // send handshake - will either show prompt on TV (if first connect), or auth us + // var hs = get_handshake(); + // ws.send(hs); + // }); + // // --------------------------------------------------------- + // ws.on('close', function() { + // console.log('LG TV disconnected'); + // eventemitter.emit("lgtv_ws_closed"); + // }); + // // --------------------------------------------------------- + // // callback for when we receive something on the websocket connection: can be + // // either responses or events + // ws.on('message', function(message) { + // var json = JSON.parse(message); + // console.log('<--- received: %s', message); + // eventemitter.emit(json.id, json); + // }); +/*---------------------------------------------------------------------------*/ +// send the SSDP discover message that the TV will respond to. +var _send_ssdp_discover = function(socket) +{ + var ssdp_rhost = "239.255.255.250"; + var ssdp_rport = 1900; + + // these fields are all required + var ssdp_msg = 'M-SEARCH * HTTP/1.1\r\n'; + ssdp_msg += 'HOST: 239.255.255.250:1900\r\n'; + ssdp_msg += 'MAN: "ssdp:discover"\r\n'; + ssdp_msg += 'MX: 5\r\n'; + ssdp_msg += "ST: urn:dial-multiscreen-org:service:dial:1\r\n"; + ssdp_msg += "USER-AGENT: iOS/5.0 UDAP/2.0 iPhone/4\r\n\r\n"; + var message = new Buffer(ssdp_msg); + + socket.send(message, 0, message.length, ssdp_rport, ssdp_rhost, function(err, bytes) { + if (err) throw err; + // console.log('SSDP message sent to ' + ssdp_rhost +':'+ ssdp_rport); + // console.log(message.toString()); + }); +}; +/*---------------------------------------------------------------------------*/ +var discover_ip = function(retry_timeout_seconds, tv_ip_found_callback) +{ + var server = dgram.createSocket('udp4'); + var timeout = 0; + var cb = tv_ip_found_callback || undefined; + + // sanitize parameters and set default otherwise + if (retry_timeout_seconds && typeof(retry_timeout_seconds) === 'number') { + timeout = retry_timeout_seconds; + } else if (!tv_ip_found_callback && typeof(retry_timeout_seconds) === 'function') { + // overloading, the first parameter was not a timeout, but the callback + // and we thus assume no timeout is given + cb = retry_timeout_seconds; + } + + // when server has opened, send a SSDP discover message + server.on('listening', function() { + _send_ssdp_discover(server); + + // retry automatically if set + if (timeout > 0) { + // set timeout before next probe + // XXXXX + // after timeout seconds, invoke callback indicating failure + // cb(true, ""); + } + }); + + // scan incoming messages for the magic string + server.on('message', function(message, remote) { + if (message.indexOf("LG Smart TV")) { + server.close(); + if (cb) { + cb(false, remote.address); + } + } + }); + + server.bind(); // listen to 0.0.0.0:random + return server; +}; +/*---------------------------------------------------------------------------*/ +// send a command to the TV after having established a paired connection +var command_count = 0; + +var send_command = function(prefix, msgtype, uri, payload, fn) { + command_count++; + var msg = '{"id":"' + prefix + command_count + '","type":"' + msgtype + '","uri":"' + uri + '"'; + if (typeof payload === 'string' && payload.length > 0) { + msg += ',"payload":' + payload + "}"; + } else { + msg += "}"; + } + console.log("---> Sending command:" + msg); + + // if we were provided a callback, we register an event emitter listener for this. + // note: there is a clear risk of memory leaks should we have a lot of outstanding + // requests that never gets responses as the listeners are only cleared on response + // or websocket close. + try { + if (typeof fn === 'function') { + eventemitter.once(prefix + command_count, function (message) { + // console.log("*** emitter listener for " + prefix + command_count + " with message:" + message); + fn(RESULT_OK, message); + }); + } + ws_send(msg); + + } catch(err) { + console.log("Error, not connected to TV:" + err.toString()); + if (typeof fn === 'function') { + fn(RESULT_ERROR, "not connected"); + } + } +}; +//------------------------------------------ +var open_connection = function(host, fn){ + // console.log("connecting"); + clientconnection = {}; + try { + client.connect(host); + fn(RESULT_OK, {}); + } catch(error) { + fn(RESULT_ERROR, error.toString()); + } +}; +/*---------------------------------------------------------------------------*/ +// verify that the provided host string contains ws protocol and port 3000, +// valid input examples: +// lgsmarttv.lan +// 192.168.1.86 +// 192.168.1.86:3000 +// ws://192.168.1.86:3000 +// ws://192.168.1.86 +// if protocol or port is lacking, they are added +// returns either the corrected host string, or false if totally invalid hoststring + +var _check_host_string = function(hoststr) +{ + if (hoststr.indexOf("ws://") !== 0) { + hoststr = "ws://" + hoststr; + } + if (hoststr.indexOf(":3000") !== (hoststr.length - 5)) { + hoststr += ":3000"; + } + + return hoststr; +}; +/*---------------------------------------------------------------------------*/ +// Connect to TV using either a host string (eg "192.168.1.213", "lgsmarttv.lan") +// or undefined for using the default "lgsmarttv.lan" + +var connect = function(host, fn) { + // if already connected, no need to connect again + // (unless hostname is new, but this package is basically written for the usecase + // of having a single TV on the LAN) + if (isConnected() && handshaken) { + if (typeof fn === 'function') { + fn(RESULT_OK, {}); + } + return; + } + + // sanitize and set hostname + if (host === undefined) { + // no hostname specified, use default + host = wsurl; + } else if (typeof(host) !== 'string') { + // XXXXX error, argument error + // throw something or at least give ample warning + host = wsurl; + } + host = _check_host_string(host); + if (host === false) { + // provided host string is wrong, throw something + // XXXX + } + + // open websocket connection and perform handshake + open_connection(host, function(err, msg){ + if (!err) { + // The connection was opened and the ws connection callback will automatically + // send the handshake, but we here register the listener for the response to + // that handshake; should be moved for code clarity + eventemitter.on("register_0", function (message) { + var ck = message.payload["client-key"]; + if (typeof ck === 'undefined') { + + } else { + store_client_key(ck); + handshaken = true; + if (typeof fn === 'function') { + fn(RESULT_OK, {}); + } + } + // {"type":"registered","id":"register_0","payload":{"client-key":"a32c6abeab6a601d626ccdeb4749f0fa"}} + }); + } else { + if (typeof fn === 'function') { + fn(RESULT_ERROR, msg); + } + } + }); +}; +/*---------------------------------------------------------------------------*/ +var ip = function() { + return remote_ip(); +}; +/*---------------------------------------------------------------------------*/ +var connected = function() { + return isConnected(); +}; +/*---------------------------------------------------------------------------*/ +var disconnect = function(fn) { + close_connection(); + eventemitter.once("lgtv_ws_closed", function () { + if(typeof fn === 'function') { + fn(RESULT_OK); + } + }); +}; +// --------------------------------------------------------- +// show a float on the TV +var unsubscribe = function(id, fn) { + var msg = '{"id":"' + id + '","type":"unsubscribe"}'; + console.log("---> Sending command:" + msg); + try { + if (typeof fn === 'function') { + eventemitter.once(prefix + command_count, function (message) { + // console.log("*** emitter listener for " + prefix + command_count + " with message:" + message); + fn(RESULT_OK, message); + }); + } + ws_send(msg); + // ws.send(msg); + + } catch(err) { + console.log("Error, not connected to TV."); + if (typeof fn === 'function') { + fn(RESULT_ERROR, "not connected"); + } + } +}; +// --------------------------------------------------------- +// show a float on the TV +function show_float(text, fn) { + send_command("", "request", "ssap://system.notifications/createToast", '{"message": "MSG"}'.replace('MSG', text), fn); +} +// --------------------------------------------------------- +// launch browser at URL; will open a new tab if already open +function open_browser_at(url, fn) { + // response: {"type":"response","id":"0","payload":{"returnValue":true,"id":"com.webos.app.browser","sessionId":"Y29tLndlYm9zLmFwcC5icm93c2VyOnVuZGVmaW5lZA=="}} + + // must start with http:// or https:// + console.log('opening browser at:%s', url); + var protocol = url.substring(0, 7).toLowerCase(); + if (protocol !== 'http://' && protocol !== 'https:/') { + url = "http://" + url; + } + + send_command("", "request", "ssap://system.launcher/open", JSON.stringify({target: url}), function(err, resp){ + var ret = ""; + if (!err) { + ret = {sessionId: resp.payload.sessionId}; + } else { + ret = JSON.stringify(response); + } + fn(err, ret); + }); +} +/*---------------------------------------------------------------------------*/ +var turn_off = function(fn) { + send_command("", "request", "ssap://system/turnOff", null, fn); +}; +/*---------------------------------------------------------------------------*/ +var channellist = function(fn) { + send_command("channels_", "request", "ssap://tv/getChannelList", null, function(err, resp) { + // send_command("channels_", "subscribe", "ssap://tv/getChannelList", null, function(err, resp) { + if (!err) { + try { + // extract channel list + var channellistarray = resp.payload.channelList; + var retlist = {channels : []}; + for (var i = channellistarray.length - 1; i >= 0; i--) { + var ch = {id: channellistarray[i].channelId, + name: channellistarray[i].channelName, + number: channellistarray[i].channelNumber}; + // console.log(channellistarray[i]); + console.log(ch); + retlist.channels.push(ch); + } + fn(RESULT_OK, JSON.stringify(retlist)); + + } catch(e) { + console.log("Error:" + e); + fn(RESULT_ERROR, resp); + } + + } else { + console.log("Error:" + err); + fn(RESULT_ERROR, err); + } + }); +}; +/*---------------------------------------------------------------------------*/ +var channel = function(fn) { + // send_command("channels_", "subscribe", "ssap://tv/getCurrentChannel", null, function(err, resp) { + send_command("channels_", "request", "ssap://tv/getCurrentChannel", null, function(err, resp) { +// {"type":"response","id":"channels_1","payload": {"channelId":"0_13_7_0_0_1307_0","signalChannelId":"0_1307_0","channelModeId":0,"channelModeName":"Terrestrial","channelTypeId":0,"channelTypeName":"Terrestrial Analog TV","channelNumber":"7","channelName":"SVT ","physicalNumber":13,"isSkipped":false,"isLocked":false,"isDescrambled":false,"isScrambled":false,"isFineTuned":false,"isInvisible":false,"favoriteGroup":null,"hybridtvType":null,"dualChannel":{"dualChannelId":null,"dualChannelTypeId":null,"dualChannelTypeName":null,"dualChannelNumber":null},"returnValue":true}} + + if (typeof fn === 'function') { + if (!err) { + if (resp.error) { + fn(RESULT_ERROR, "Error, probably not TV input right now"); + } else { + // return a subset of all information + fn(RESULT_OK, {id: resp.payload.channelId, // internal id, used for setting channel + name: resp.payload.channelName, // name as on TV, eg SVT + number: resp.payload.channelNumber}); // number on TV + } + } else { + console.log("Error:" + err); + fn(RESULT_ERROR, "Error, could not get answer"); + } + } + }); +}; +/*---------------------------------------------------------------------------*/ +/* set the active channel; use channelId as from the channellist, such as eg 0_13_7_0_0_1307_0 */ +var set_channel = function(channel, fn) { + send_command("", "request", "ssap://tv/openChannel", JSON.stringify({channelId: channel}), function(err, resp){ + if (err) { + fn(err, {}); + } else { + if (resp.type == "response") { + // {"type":"response","id":"1","payload":{"returnValue":true}} + fn(RESULT_OK, channel); + } else if (resp.type == "error") { + // {"type":"error","id":"1","error":"500 Application error","payload":{"returnValue":false,"errorCode":-1000,"errorText":"invalid channel id"}} + fn(RESULT_ERROR, resp.payload.errorText); + } else { + fn(RESULT_ERROR, "unknown error"); + } + } + }); +}; +/*---------------------------------------------------------------------------*/ +// note: the TV does not consider 'live TV' as part of the external input list. +// This will just return eg HDMI_1, HDMI_2, SCART_1, etc. +var inputlist = function(fn) { + // send_command("input_", "subscribe", "ssap://tv/getExternalInputList", null, function(err, resp) { + send_command("input_", "request", "ssap://tv/getExternalInputList", null, function(err, resp) { + if (typeof fn === 'function') { +// <--- received: {"type":"response","id":"input_1","payload": {"devices":[{"id":"SCART_1","label":"AV1","port":1,"appId":"com.webos.app.externalinput.scart","icon":"http://lgsmarttv.lan:3000/resources/f84946f3119c23cda549bdcf6ad02a89c73f7682/scart.png","modified":false,"autoav":false,"currentTVStatus":"","subList":[],"subCount":0,"connected":false,"favorite":false},{...}, {...}],"returnValue":true}} + if (!err) { + try { + // extract a nice and simple inputlist + var devs = resp.payload.devices; + var ret = {}; + for (var i = devs.length - 1; i >= 0; i--) { + ret[devs[i].id] = devs[i].icon; + } + console.log(ret); + + fn(RESULT_OK, ret); + } catch(error) { + console.log("Error:" + error); + fn(RESULT_ERROR, error); + } + } else { + console.log("Error:" + err); + fn(RESULT_ERROR, err); + } + } + }); +}; +/*---------------------------------------------------------------------------*/ +// get current input source +var input = function(fn) { + if (typeof fn === 'function') { + fn(RESULT_ERROR, {reason: "not implemented"}); + } +}; +/*---------------------------------------------------------------------------*/ +// set input source +var set_input = function(input, fn) { + send_command("", "request", "ssap://tv/switchInput", JSON.stringify({inputId: input}), function(err, resp){ + if (err) { + fn(RESULT_ERROR, resp); + } else { + if (resp.payload.errorCode) { + fn(RESULT_ERROR, resp.payload.errorText); + // {"type":"response","id":"1","payload":{"returnValue":true,"errorCode":-1000,"errorText":"no such input"}} + } else { + fn(RESULT_OK, input); + // {"type":"response","id":"1","payload":{"returnValue":true}} + } + } + }); +}; +/*---------------------------------------------------------------------------*/ +// set mute +var set_mute = function(setmute, fn) { + if(typeof setmute !== 'boolean') { + fn(RESULT_ERROR, {reason: "mute must be boolean"}); + } else { + send_command("", "request", "ssap://audio/setMute", JSON.stringify({mute: setmute}), fn); + } +}; +/*---------------------------------------------------------------------------*/ +var toggle_mute = function(fn) { + muted(function(err, resp){ + if (!err) { + var tomute = !resp; + send_command("", "request", "ssap://audio/setMute", JSON.stringify({mute: tomute}), fn); + } else { + fn(err, {}); + } + }); +}; +/*---------------------------------------------------------------------------*/ +var muted = function(fn) { + send_command("status_", "request", "ssap://audio/getStatus", null, function(err, response){ + if (!err) { + fn(RESULT_OK, response.payload.mute); + } else { + fn(RESULT_ERROR, response); + } + }); +}; +/*---------------------------------------------------------------------------*/ +// get volume as 0..100 if not muted, if muted then volume is -1 +var volume = function(fn) { + // send_command("status_", "subscribe", "ssap://audio/getVolume", null, function(err, response){ + send_command("status_", "request", "ssap://audio/getVolume", null, function(err, response){ + // {"type":"response","id":"status_1","payload":{"muted":false,"scenario":"mastervolume_tv_speaker","active":false,"action":"requested","volume":7,"returnValue":true,"subscribed":true}} + if (!err) { + var muted = response.payload.muted; + var ret = -1; + if (!muted) { + ret = response.payload.volume; + } + fn(RESULT_OK, ret); + } else { + fn(RESULT_ERROR, response); + } + }); +}; +/*---------------------------------------------------------------------------*/ +var set_volume = function(volumelevel, fn) { + if (typeof volumelevel !== 'number') { + fn(RESULT_ERROR, "volume must be a number"); + + } else if(volumelevel < 0 || volumelevel > 100) { + fn(RESULT_ERROR, "volume must be 0..100"); + + } else { + send_command("", "request", "ssap://audio/setVolume", JSON.stringify({volume: volumelevel}), fn); + } +}; +/*---------------------------------------------------------------------------*/ +var input_media_play = function(fn) { + send_command("", "request", "ssap://media.controls/play", null, fn); +}; +/*---------------------------------------------------------------------------*/ +var input_media_stop = function(fn) { + send_command("", "request", "ssap://media.controls/stop", null, fn); +}; +/*---------------------------------------------------------------------------*/ +var input_media_pause = function(fn) { + send_command("", "request", "ssap://media.controls/pause", null, fn); +}; +/*---------------------------------------------------------------------------*/ +var input_media_rewind = function(fn) { + send_command("", "request", "ssap://media.controls/rewind", null, fn); +}; +/*---------------------------------------------------------------------------*/ +var input_media_forward = function(fn) { + send_command("", "request", "ssap://media.controls/fastForward", null, fn); +}; +/*---------------------------------------------------------------------------*/ +var input_channel_up = function(fn) { + send_command("", "request", "ssap://tv/channelUp", null, fn); +}; +/*---------------------------------------------------------------------------*/ +var input_channel_down = function(fn) { + send_command("", "request", "ssap://tv/channelDown", null, fn); +}; +/*---------------------------------------------------------------------------*/ +var input_three_d_on = function(fn) { + send_command("", "request", "ssap://com.webos.service.tv.display/set3DOn", null, fn); +}; +/*---------------------------------------------------------------------------*/ +var input_three_d_off = function(fn) { + send_command("", "request", "ssap://com.webos.service.tv.display/set3DOff", null, fn); +}; +/*---------------------------------------------------------------------------*/ +var get_status = function(fn) { + send_command("status_", "request", "ssap://audio/getStatus", null, fn); + // send_command("status_", "subscribe", "ssap://audio/getStatus", null, fn); +}; +/*---------------------------------------------------------------------------*/ +var sw_info = function(fn) { + send_command("sw_info_", "request", "ssap://com.webos.service.update/getCurrentSWInformation", null, fn); +// received: {"type":"response","id":"sw_info_0","payload":{"returnValue":true,"product_name":"webOS","model_name":"HE_DTV_WT1M_AFAAABAA","sw_type":"FIRMWARE","major_ver":"04","minor_ver":"41.32","country":"SE","device_id":"cc:2d:8c:cf:94:8c","auth_flag":"N","ignore_disable":"N","eco_info":"01","config_key":"00","language_code":"sv-SE"}} +}; +/*---------------------------------------------------------------------------*/ +var services = function(fn) { + send_command("services_", "request", "ssap://api/getServiceList", null, function(err, resp) { + if (typeof fn === 'function') { + if (!err) { + try { +// received: {"type":"response","id":"services_1","payload":{"services":[{"name":"api","version":1},{"name":"audio","version":1},{"name":"media.controls","version":1},{"name":"media.viewer","version":1},{"name":"pairing","version":1},{"name":"system","version":1},{"name":"system.launcher","version":1},{"name":"system.notifications","version":1},{"name":"tv","version":1},{"name":"webapp","version":2}],"returnValue":true}} + var services = resp.payload.services; + fn(RESULT_OK, resp.payload.services); + } catch(e) { + console.log("Error:" + e); + fn(RESULT_ERROR, e); + } + } else { + console.log("Error:" + err); + fn(RESULT_ERROR, err); + } + } + }); +}; +/*---------------------------------------------------------------------------*/ +var apps = function(fn) { + send_command("launcher_", "request", "ssap://com.webos.applicationManager/listLaunchPoints", null, function(err, response) { + // send_command("launcher_", "subscribe", "ssap://com.webos.applicationManager/listLaunchPoints", null, function(err, response) { + if (typeof fn === 'function') { + if (!err) { + try { + // extract a nice and simple list of apps + var applist = {}; + var launchpoints = response.payload.launchPoints; + for (var i = launchpoints.length - 1; i >= 0; i--) { + // var oneapp = {}; + // oneapp["title"] = launchpoints[i]["title"]; + // oneapp["id"] = launchpoints[i]["launchPointId"]; +// {"removable":false,"largeIcon":"/mnt/otncabi/usr/palm/applications/com.webos.app.discovery/lgstore_130x130.png","vendor":"LGE","id":"com.webos.app.discovery","title":"LG Store","bgColor":"","vendorUrl":"","iconColor":"#cf0652","appDescription":"","params":{},"version":"1.0.18","bgImage":"/mnt/otncabi/usr/palm/applications/com.webos.app.discovery/lgstore_preview.png","icon":"http://lgsmarttv.lan:3000/resources/60ad544bd03663793dda37dbb21f10575408c73a/lgstore_80x80.png","launchPointId":"com.webos.app.discovery_default","imageForRecents":""}, + applist[launchpoints[i]["title"]] = launchpoints[i]["launchPointId"]; + } + console.log("Returning applist:"); + console.log(applist); + fn(RESULT_OK, applist); + } catch(e) { + console.log("Error:" + e); + fn(RESULT_ERROR, e); + } + } else { + console.log("Error:" + err); + fn(RESULT_ERROR, err); + } + } + }); +}; +/*---------------------------------------------------------------------------*/ +function open_app_with_payload(payload, fn) { + send_command("", "request", "ssap://com.webos.applicationManager/launch", payload, null, fn); +} +/*---------------------------------------------------------------------------*/ +var start_app = function(appid, fn) { + send_command("", "request", "ssap://system.launcher/launch", JSON.stringify({id: appid}), function(err, resp){ + if (!err) { + if (resp.payload.errorCode) { + fn(RESULT_ERROR, resp.payload.errorText); + // {"type":"error","id":"1","error":"500 Application error","payload":{"returnValue":false,"errorCode":-101,"errorText":"\"bogusapp\" was not found OR Unsupported Application Type"}} + } else { + fn(RESULT_OK, {sessionId : resp.payload.sessionId}); + } + } else { + fn(err, resp); + } + }); +}; +/*---------------------------------------------------------------------------*/ +var close_app = function(appid, fn) { + send_command("", "request", "ssap://system.launcher/close", JSON.stringify({id: appid}), function(err, resp){ + if (!err) { + if (resp.payload.errorCode) { + // Note: This error response may come as a result of trying to close an app + // that is not already open + // {"type":"error","id":"1","error":"500 Application error","payload":{"returnValue":false,"errorCode":-1000,"errorText":"Permission denied"}} + fn(RESULT_ERROR, resp.payload.errorText); + } else { + fn(RESULT_OK, {sessionId : resp.payload.sessionId}); + } + } else { + fn(err, resp); + } + }); +}; +/*---------------------------------------------------------------------------*/ +var input_pointer_connect = function(fn) { + if (typeof fn === 'function') { + fn(RESULT_ERROR, {reason: "not implemented"}); + } +}; +/*---------------------------------------------------------------------------*/ +var input_pointer_move = function(dx, dy, fn) { + // function sendMove(dx, dy) { + // pointerSocket.sendLogMessage('type:move\ndx:' + dx + '\ndy:' + dy + '\ndown:0\n\n') + if (typeof fn === 'function') { + fn(RESULT_ERROR, {reason: "not implemented"}); + } +}; +/*---------------------------------------------------------------------------*/ +var input_pointer_click = function(fn) { + // function sendClick() { + // pointerSocket.sendLogMessage('type:click\n\n') + if (typeof fn === 'function') { + fn(RESULT_ERROR, {reason: "not implemented"}); + } +}; +/*---------------------------------------------------------------------------*/ +var input_pointer_disconnect = function(fn) { + if (typeof fn === 'function') { + fn(RESULT_ERROR, {reason: "not implemented"}); + } +}; +/*---------------------------------------------------------------------------*/ +var input_text = function(text, fn) { + // is this the right call for the right API here? + // function sendInput(btype, bname) { + // pointerSocket.sendLogMessage('type:' + btype + '\nname:' + bname + '\n\n') + if (typeof fn === 'function') { + fn(RESULT_ERROR, {reason: "not implemented"}); + } +}; +/*---------------------------------------------------------------------------*/ +var input_pointer_scroll = function(dx, dy, fn) { + // pointerSocket.sendLogMessage('type:scroll\ndx:0\ndy:' + dy + '\ndown:0\n\n') + if (typeof fn === 'function') { + fn(RESULT_ERROR, {reason: "not implemented"}); + } +}; +/*---------------------------------------------------------------------------*/ +var input_enter = function(fn) { + send_command("", "request", "ssap://com.webos.service.ime/sendEnterKey", null, fn); +}; +/*---------------------------------------------------------------------------*/ +var input_pause = function(fn) { + send_command("pause_", "request", "ssap://media.controls/pause", null, fn); +}; +/*---------------------------------------------------------------------------*/ +var input_play = function(fn) { + send_command("play_", "request", "ssap://media.controls/play", null, fn); +}; +/*---------------------------------------------------------------------------*/ +var input_stop = function(fn) { + send_command("stop_", "request", "ssap://media.controls/stop", null, fn); +}; +/*---------------------------------------------------------------------------*/ +var input_volumeup = function(fn) { + send_command("volumeup_", "request", "ssap://audio/volumeUp", null, fn); +}; +/*---------------------------------------------------------------------------*/ +var input_volumedown = function(fn) { + send_command("volumedown_", "request", "ssap://audio/volumeDown", null, fn); +}; +/*---------------------------------------------------------------------------*/ +var input_backspace = function(count, fn) { + var c = count === undefined ? 1 : count; + send_command("", "request", "ssap://com.webos.service.ime/deleteCharacters", {"count": c}, fn); +}; +/*---------------------------------------------------------------------------*/ +var open_youtube_at_id = function(video_id, fn) { + var vurl = "http://www.youtube.com/tv?v=" + video_id; + open_youtube_at_url(vurl, fn); +}; +/*---------------------------------------------------------------------------*/ +var open_youtube_at_url = function(url, fn) { + var youtube_appid = "youtube.leanback.v4"; + var payload = {id: youtube_appid, params : {contentTarget: url}}; + send_command("", "request", "ssap://system.launcher/launch", JSON.stringify(payload), function(err, resp){ + if (!err) { + if (resp.payload.errorCode) { + fn(RESULT_ERROR, resp.payload.errorText); + // {"type":"error","id":"1","error":"500 Application error","payload":{"returnValue":false,"errorCode":-101,"errorText":"\"bogusapp\" was not found OR Unsupported Application Type"}} + } else { + fn(RESULT_OK, {sessionId : resp.payload.sessionId}); + } + } else { + fn(err, resp); + } + }); + + + // public void launchAppWithInfo(final AppInfo appInfo, Object params, final Launcher.AppLaunchListener listener) { + // String uri = "ssap://system.launcher/launch"; + // contentId = (String) ((JSONObject) params).get("contentId"); + // payload.put("id", appId); + // payload.put("contentId", contentId); + // payload.put("params", params); + +// {id : youtube.leanback.v4} +// {contentTarget: url} + + // open_app_with_payload({"id": "youtube.leanback.v4", "params": { "contentTarget": video_url }}); +}; +/*---------------------------------------------------------------------------*/ +var temporarydbg = function(count, fn) { + // send_command("http_header_", "request", "ssap://com.webos.service.sdx/getHttpHeaderForServiceRequest", null, fn); + // {"type":"response","id":"http_header_1","payload": + // {"returnValue":true,"header":"X-Device-Product:webOS\r\nX-Device-Platform:WT1M\r\nX-Device-Model:HE_DTV_WT1M_AFAAABAA\r\nX-Device-Netcast-Platform-Version:1.3.2\r\nX-Device-Eco-Info:01\r\nX-Device-Country-Group:EU\r\nX-Device-Publish-Flag:Y\r\nX-Device-ContentsQA-Flag:N\r\nX-Device-FW-Version:04.41.32\r\nX-Device-SDK-VERSION:1.3.2\r\nX-Device-ID:hEPv0JRPP5oIzP9mv9lAdGC1SC2CKe/SFzOGJKQv1hoygpWsNib7+mbwPklqA2FPj1KXM8l79B43RorjNIifB9g776LqceGmvucarN2tHbRrqzflDsU9MF50NCMH7ili\r\nX-Device-Sales-Model:60LB870V-ZA\r\nX-Device-Type:T01\r\nAccept:application/json\r\nX-Device-Language:sv-SE\r\nX-Device-Locale:sv-SE\r\nX-Device-Country:SE\r\nHOST:SE.lgtvsdp.com\r\nX-Device-Remote-Flag:N\r\nX-Device-FCK:81\r\nX-Device-Eula:additionalDataAllowed,generalTermsAllowed,networkAllowed,voiceAllowed\r\nX-Authentication:+dNxJb6+Al+Y6NmHAGXchGJm55U=\r\ncookie:JSESSIONID=KqU+lnNuRtbCrV0u6iFR4VIE.node_sdp20; Path=/rest; Secure\r\n","X-Device-Product":"webOS","X-Device-Platform":"WT1M","X-Device-Model":"HE_DTV_WT1M_AFAAABAA","X-Device-Netcast-Platform-Version":"1.3.2","X-Device-Eco-Info":"01","X-Device-Country-Group":"EU","X-Device-Publish-Flag":"Y","X-Device-ContentsQA-Flag":"N","X-Device-FW-Version":"04.41.32","X-Device-SDK-VERSION":"1.3.2","X-Device-ID":"hEPv0JRPP5oIzP9mv9lAdGC1SC2CKe/SFzOGJKQv1hoygpWsNib7+mbwPklqA2FPj1KXM8l79B43RorjNIifB9g776LqceGmvucarN2tHbRrqzflDsU9MF50NCMH7ili","X-Device-Sales-Model":"60LB870V-ZA","X-Device-Type":"T01","Accept":"application/json","X-Device-Language":"sv-SE","X-Device-Locale":"sv-SE","X-Device-Country":"SE","HOST":"SE.lgtvsdp.com","X-Device-Remote-Flag":"N","X-Device-FCK":"81","X-Device-Eula":"additionalDataAllowed,generalTermsAllowed,networkAllowed,voiceAllowed","X-Authentication":"+dNxJb6+Al+Y6NmHAGXchGJm55U=","cookie":"JSESSIONID=KqU+lnNuRtbCrV0u6iFR4VIE.node_sdp20; Path=/rest; Secure"}} + + + // send_command("launcher_", "subscribe", "ssap://com.webos.applicationManager/listLaunchPoints", null, fn); + // response is same or at least very similar to list apps + fn(false, {}); + +// other ssap endpoints: + // ssap://tv/getCurrentChannel + // ssap://tv/getChannelProgramInfo + // ssap://com.webos.applicationManager/getForegroundAppInfo + // ssap://com.webos.service.appstatus/getAppStatus + // ssap://system.launcher/getAppState + // ssap://tv/getChannelProgramInfo + // ssap://media.viewer/close + // ssap://webapp/closeWebApp +}; +/*---------------------------------------------------------------------------*/ +// commands related to input such as remote control and text input +exports.input_enter = input_enter; /* remote control 'enter' */ +exports.input_pause = input_pause; /* remote control 'pause' */ +exports.input_play = input_play; /* remote control 'play' */ +exports.input_stop = input_stop; /* remote control 'stop' */ +exports.input_volumeup = input_volumeup; /* remote control 'volume up' */ +exports.input_volumedown = input_volumedown; /* remote control 'volume down' */ +exports.input_channel_up = input_channel_up; /* remote control volume up */ +exports.input_channel_down = input_channel_down; /* remote control volume down */ +exports.input_media_play = input_media_play; /* remote control play */ +exports.input_media_stop = input_media_stop; /* remote control stop */ +exports.input_media_pause = input_media_pause; /* remote control pause */ +exports.input_media_rewind = input_media_rewind; /* remote control rewind */ +exports.input_media_forward = input_media_forward; /* remote control forward */ +exports.input_three_d_on = input_three_d_on; /* remote control 3d on */ +exports.input_three_d_off = input_three_d_off; /* remote control 3d off */ +exports.input_backspace = input_backspace; /* send 'backspace' */ +exports.input_text = input_text; /* insert text */ +exports.input_pointer_connect = input_pointer_connect; /* get pointer (like mouse pointer) */ +exports.input_pointer_scroll = input_pointer_scroll; /* scroll */ +exports.input_pointer_move = input_pointer_move; /* move the pointer */ +exports.input_pointer_click = input_pointer_click; /* click pointer */ +exports.input_pointer_disconnect = input_pointer_disconnect; /* disconnect the pointer */ + +// apps such as youtube, browser, and anything that may be installed +exports.open_youtube_at_id = open_youtube_at_id; /* open youtube at videoid */ +exports.open_youtube_at_url = open_youtube_at_url; /* open youtube at url */ +exports.open_browser_at = open_browser_at; /* open webbrowser at url */ +exports.apps = apps; /* get list of apps */ +exports.start_app = start_app; /* start app */ +exports.close_app = close_app; /* close app */ + +// TV source input-related +exports.inputlist = inputlist; /* get list of inputs */ +exports.input = input; /* get active input source */ +exports.set_input = set_input; /* set input source */ + +// sound volume related +exports.set_mute = set_mute; +exports.toggle_mute = toggle_mute; +exports.muted = muted; /* is the TV muted? */ +exports.volume = volume; /* get volume */ +exports.set_volume = set_volume; /* set volume */ + +// connect and power related +exports.discover_ip = discover_ip; /* discover the TV IP address */ +exports.connect = connect; /* connect to TV */ +exports.disconnect = disconnect; /* disconnect from TV */ +exports.turn_off = turn_off; /* turn the TV off */ + +// various status/state information +exports.get_status = get_status; /* get status information from TV */ +exports.sw_info = sw_info; /* get software info such as webos version */ +exports.services = services; /* get available services on the TV */ +exports.ip = ip; /* get the TV IP-address */ +exports.connected = connected; /* are we connected to the TV? */ +exports.show_float = show_float; /* show a small information box with text on the TV */ + +// set, get channels +exports.channellist = channellist; /* get list of channels available */ +exports.channel = channel; /* get active channel */ +exports.set_channel = set_channel; /* set active channel */ + +// debug and temporary +exports.temporarydbg = temporarydbg; +/*---------------------------------------------------------------------------*/ From ce3e434a533fb928c6944c9cf1a3d3cff8972495 Mon Sep 17 00:00:00 2001 From: domo-site <93765654+mgrafr@users.noreply.github.com> Date: Tue, 22 Feb 2022 17:12:33 +0100 Subject: [PATCH 02/14] Update README.md --- README.md | 438 +----------------------------------------------------- 1 file changed, 4 insertions(+), 434 deletions(-) diff --git a/README.md b/README.md index 0e25033..5e27e96 100644 --- a/README.md +++ b/README.md @@ -1,443 +1,13 @@ # Description -Easy way to control your LG webOS 3 TV (INCLUDING TURNING ON). -After installing run `npm start` and check out `http://localhost:3000` for examples, or check the docs for HTTP requests. -Can easily serve as a service for any kind of home automation (host on a Rasberry Pi). - -Forked from msloth's project. +adaptation du script de Danovadia/lgtv-http-server +pour une utilisation avec Domoticz +voir le site domo-site.fr # LGTV ## Installation -`npm install lgtv` and set up the TV per below. - -## Prerequisites - -First, the device (eg your computer) must be on the same network as the TV. Second, you should enable the TV to broadcast itself as `lgsmarttv.lan` in the local network. This setting is under `Network/LG Connect Apps`. This is necessary in order for this module to find the TV on the network and allow apps to connect. You also need to be on the same network as the TV. - -## Quick start - -The first time you run it against the TV, you need to give the program access to the TV by answering `yes` to the prompt on the TV. From then on, the received client key is used so you don't have to perform this step again. - -Then, follow some of the examples to begin with, eg `examples/show-float.js` to show a float pop up on the screen: - -```js -lgtv = require("lgtv"); - -var tv_ip_address = "192.168.1.214"; -lgtv.connect(tv_ip_address, function(err, response){ - if (!err) { - lgtv.show_float("It works!", function(err, response){ - if (!err) { - lgtv.disconnect(); - } - }); // show float - } -}); // connect -``` - -Now that you can do this, we also can change input source to eg TV/HDMI/whatever, list and open apps, open browser, open Youtube app, change channel/volume, turn off the TV etc. Basically the only thing that doesn't work right now is a) turning on the TV, which doesn't seem possible this way, and b) opening Youtube at an URL (coming soon). - -### Using a hostname or IP-address of the TV - -The above uses a default hostname, `lgsmarttv.lan`. Your TV may not follow that, or you may have more than one TV. Then you can specify the hostname like below. The hostname can be eg `kitchen-tv.lan`, `192.168.1.214` or similar. - -```js -lgtv = require("lgtv"); - -lgtv.connect("192.168.1.214", function(err, response){ - if (!err) { - lgtv.show_float("It works!", function(err, response){ - if (!err) { - lgtv.disconnect(); - } - }); // show float - } -}); // connect -``` - -### Auto-detecting the TV on the network - -If you don't know the IP of the TV, or the hostname, you can scan for it using the `discover_ip()` function like below. Beware that this takes 3-4 seconds for the round-trip times (the TV is slow to respond to the SSDP discover probe). - -```js -lgtv = require("lgtv"); - -var retry_timeout = 10; // seconds -lgtv.discover_ip(retry_timeout, function(err, ipaddr) { - if (err) { - console.log("Failed to find TV IP address on the LAN. Verify that TV is on, and that you are on the same LAN/Wifi."); - } else { - console.log("TV ip addr is: " + ipaddr); - } -}); -``` - -If you want to autodiscover each time, this would work, - -```js -lgtv = require("lgtv"); - -var retry_timeout = 10; // seconds -lgtv.discover_ip(retry_timeout, function(err, ipaddr) { - if (err) { - console.log("Failed to find TV IP address on the LAN. Verify that TV is on, and that you are on the same LAN/Wifi."); - - } else { - lgtv.connect(ipaddr, function(err, response){ - if (!err) { - lgtv.show_float("Found you!", function(err, response){ - if (!err) { - lgtv.disconnect(); - } - }); // show float - } - }); // connect - } -}); -``` - -## Introduction - -This module is targeting the LG Smart TVs running WebOS, ie later 2014 or 2015 models. -Previous models used another OS and other protocols and won't work with this. - -* Controlling the TV means - * (finding the TV on your local network) - * establishing a connection, ie successful handshake - * controlling input source, volume, etc - -There is some useful information out there already: - -* LG TV: - * LG remote app on android store - - you could sniff traffic on network as it interacts with TV - - you could reverse engineer by downloading .apk, run dex2jar etc etc - * LG remote app by third-party developers - - https://github.com/CODeRUS/harbour-lgremote-webos - -seems like it is written with deep knowledge of WebOS internals - * look through the open source SDK's and API's published by LG - - https://github.com/ConnectSDK/Connect-SDK-Android-Core - -## Motivation - -There is an LG remote control app for Android, but it is horribly slow. Also, it is very generic and mirrors the physical remote control. With this module I can chain a set of commands such as change input to HDMI_1 and set volume 10 and make them happen programmatically instead of finding the right buttons in the app. I also combine this with a corresponding module for controlling a Kodi media player. - -# Communication overview - -I recently bought a new TV, a LG 60LB870V, which is a 2014 TV running WebOS 1.x. The same day I got the TV, I ran `nmap` on the TV and `Wireshark` on the network the TV was connected to, with the following results (full results at the bottom). - -``` -Port Scanning host results - Open TCP Port: 1061 - Open TCP Port: 1424 - Open TCP Port: 1900 ssdp - Open TCP Port: 1970 - Open TCP Port: 3000 ws - Open TCP Port: 3001 wss - Open TCP Port: 9955 - Open TCP Port: 9998 - Open TCP Port: 18181 - Open TCP Port: 36866 -``` - -Through Wireshark, I saw the TV sending UDP: - - * SSDP (simple service discovery protocol) to `239.255.255.250:1900`, presenting several SSDP endpoints - * `192.168.1.255:9956` and `224.0.0.113:9956`. Port `9956` and the contents show this - is `alljoyn`-traffic, something I haven't encountered before but is a service - discovery protocol of some kind according to Wikipedia. The addresses are multicast/broadcast. - -In the TV menus I had also enabled `zeroconf` meaning I can now address the TV by an -address valid in the local network, by default `lgsmarttv.lan` which is found by mDNS. This setting -is, IIRC, under `Network/LG Connect Apps`. - -The TV IP address can otherwise be found using SSDP; send this: - -``` -'M-SEARCH * HTTP/1.1\r\n' -'HOST: 239.255.255.250:1900\r\n' -'MX: 30\r\n' -'MAN: "ssdp:discover\r\n"' -'ST: urn:lge-com:service:webos-second-screen:1\r\n\r\n' -``` - -to `udp://239.255.255.250:1900`, then the TV will respond. -This may be an alternative schema: `urn:schemas-upnp-org:device:MediaRenderer:1`. - -## Pairing and communication - -Most of the communication is over websockets on port 3000, or 3001. - -The application must pair with the TV in order to be allowed to control it. -The pairing handshake used here is a hardcoded handshake retrieved from another LG remote control application, -which in turn seems to have retrieved it from the official LG remote control app. No fields -can be changed or the handshake will fail, and only basic commands are allowed. The handshake -contains a base-64 signature, which if "debased" starts `{"algorithm":"RSA-SHA256","keyId":"test-signing-cert","signatureVersion":1}`. -This may just be a hash of the signature, perhaps in JSON format, but I haven't persued this further. - -If the signing information is not included, or something is changed - thus invalidating the signing - the handshake will -still succeed, but some commands are not permitted (such as getting information about the TV software). - -After the handshake, the rest of the communication stays over the same websocket socket. Data and commands are sent -in cleartext JSON format, eg - -``` -{"type":"response","id":"status_0","payload":{"scenario":"mastervolume_tv_speaker","active":false,"action":"requested","volume":0,"returnValue":true,"subscribed":true,"mute":false}} -``` - -The `type` is either (at least, there may be more), - -* `request` - a single request, eg get volume -* `response` - response to a request, or subscription event -* `subscribe` - subscribe to a topic ie get notifications when something happens, eg channel is changed -* `unsubscribe` - unsubscribe a subscribed topic - -The `id` is a concatenation of the command and a message counter, like so: - -``` -Request: -{"type":"request","id":"status_3", ...} - -Response: -{"type":"response","id":"status_3", ...} -``` - -This is used so that a request can be matched with a response. - ----------------------------------------------------------- - -# Complete nmap report - -Command: `sudo nmap -sV -p 1-65535 192.168.1.86` - -Result: - -``` -Starting Nmap 6.40-2 ( http://nmap.org ) at 2014-12-30 14:13 CET -Nmap scan report for 192.168.1.86 -Host is up (0.028s latency). -Not shown: 65525 closed ports -PORT STATE SERVICE VERSION -1126/tcp open tcpwrapped -1261/tcp open tcpwrapped -1843/tcp open tcpwrapped -1900/tcp open upnp? -3000/tcp open ppp? -3001/tcp open ssl/nessus? -9955/tcp open unknown -9998/tcp open distinct32? -18181/tcp open opsec-cvp? -36866/tcp open unknown -6 services unrecognized despite returning data. If you know the service/version, please submit the following fingerprints at http://www.insecure.org/cgi-bin/servicefp-submit.cgi : -==============NEXT SERVICE FINGERPRINT (SUBMIT INDIVIDUALLY)============== -SF-Port1900-TCP:V=6.40-2%I=7%D=12/30%Time=54A2A53E%P=x86_64-apple-darwin10 -SF:.8.0%r(GetRequest,52,"HTTP/1\.1\x20404\x20Not\x20Found\r\nDate:\x20Tue, -SF:\x2030\x20Dec\x202014\x2013:13:48\x20GMT\r\nConnection:\x20close\r\n\r\ -SF:n")%r(HTTPOptions,52,"HTTP/1\.1\x20404\x20Not\x20Found\r\nDate:\x20Tue, -SF:\x2030\x20Dec\x202014\x2013:13:53\x20GMT\r\nConnection:\x20close\r\n\r\ -SF:n")%r(FourOhFourRequest,52,"HTTP/1\.1\x20404\x20Not\x20Found\r\nDate:\x -SF:20Tue,\x2030\x20Dec\x202014\x2013:13:53\x20GMT\r\nConnection:\x20close\ -SF:r\n\r\n"); -==============NEXT SERVICE FINGERPRINT (SUBMIT INDIVIDUALLY)============== -SF-Port3000-TCP:V=6.40-2%I=7%D=12/30%Time=54A2A543%P=x86_64-apple-darwin10 -SF:.8.0%r(GetRequest,58,"HTTP/1\.1\x20200\x20OK\r\nDate:\x20Tue,\x2030\x20 -SF:Dec\x202014\x2013:13:53\x20GMT\r\nConnection:\x20close\r\n\r\nHello\x20 -SF:world\r\n")%r(HTTPOptions,58,"HTTP/1\.1\x20200\x20OK\r\nDate:\x20Tue,\x -SF:2030\x20Dec\x202014\x2013:13:53\x20GMT\r\nConnection:\x20close\r\n\r\nH -SF:ello\x20world\r\n"); -==============NEXT SERVICE FINGERPRINT (SUBMIT INDIVIDUALLY)============== -SF-Port3001-TCP:V=6.40-2%T=SSL%I=7%D=12/30%Time=54A2A561%P=x86_64-apple-da -SF:rwin10.8.0%r(GetRequest,58,"HTTP/1\.1\x20200\x20OK\r\nDate:\x20Tue,\x20 -SF:30\x20Dec\x202014\x2013:14:23\x20GMT\r\nConnection:\x20close\r\n\r\nHel -SF:lo\x20world\r\n")%r(HTTPOptions,58,"HTTP/1\.1\x20200\x20OK\r\nDate:\x20 -SF:Tue,\x2030\x20Dec\x202014\x2013:14:23\x20GMT\r\nConnection:\x20close\r\ -SF:n\r\nHello\x20world\r\n"); -==============NEXT SERVICE FINGERPRINT (SUBMIT INDIVIDUALLY)============== -SF-Port9955-TCP:V=6.40-2%I=7%D=12/30%Time=54A2A573%P=x86_64-apple-darwin10 -SF:.8.0%r(Kerberos,F,"ERROR\x20Unknown\r\n"); -==============NEXT SERVICE FINGERPRINT (SUBMIT INDIVIDUALLY)============== -SF-Port9998-TCP:V=6.40-2%I=7%D=12/30%Time=54A2A543%P=x86_64-apple-darwin10 -SF:.8.0%r(GetRequest,5C8,"HTTP/1\.1\x20200\x20OK\r\nConnection:\x20close\r -SF:\nContent-Length:\x201395\r\nContent-Type:\x20text/html\r\n\r\n\n\n\nfunctio -SF:n\x20createPageList\(\)\x20{\n\x20\x20\x20\x20var\x20xhr\x20=\x20new\x2 -SF:0XMLHttpRequest;\n\x20\x20\x20\x20xhr\.open\(\"GET\",\x20\"/pagelist\.j -SF:son\"\);\n\x20\x20\x20\x20xhr\.onload\x20=\x20function\(e\)\x20{\n\x20\ -SF:x20\x20\x20\x20\x20\x20\x20if\x20\(xhr\.status\x20==\x20200\)\x20{\n\x2 -SF:0\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20var\x20pages\x20=\x20JSON\ -SF:.parse\(xhr\.responseText\);\n\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\ -SF:x20\x20if\x20\(pages\.length\)\n\x20\x20\x20\x20\x20\x20\x20\x20\x20\x2 -SF:0\x20\x20\x20\x20\x20\x20document\.getElementById\(\"noPageNotice\"\)\. -SF:style\.display\x20=\x20\"none\";\n\n\x20\x20\x20\x20\x20\x20\x20\x20\x2 -SF:0\x20\x20\x20var\x20pageList\x20=\x20document\.createElement\(\"ol\"\); -SF:\n\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20for\x20\(var\x20i\x20 -SF:in\x20pages\)\x20{\n\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x2 -SF:0\x20\x20\x20var\x20link\x20=\x20document\.createElement\(\"a\"\);\n\x2 -SF:0\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20var\x20tit -SF:le\x20=\x20pages\[i\]\.title\x20\?\x20pages\[i\]\.title\x20:\x20\(\"Pag -SF:e\x20\"\x20\+\x20\(Number\(pages\[i\]\.id\)\)\);\n\x20\x20\x20\x20\x20\ -SF:x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20var\x20url\x20=\x20pages\[i\ -SF:]\.url;\n\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x -SF:20link\.appendChild\(document\.createTextNode\(title\x20\+\x20\(url\x20 -SF:\?\x20\(\"\x20\[\"\x20\+\x20url\x20\+\x20\"\]\"\)\x20:\x20\"\"\x20\)\)\ -SF:);\n\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20lin -SF:k\.setAttribute\(\"hre")%r(HTTPOptions,5C8,"HTTP/1\.1\x20200\x20OK\r\nC -SF:onnection:\x20close\r\nContent-Length:\x201395\r\nContent-Type:\x20text -SF:/html\r\n\r\n\n\n\nfunction\x20createPageList\(\)\x20{\n\x20\x20\x20\x20var\ -SF:x20xhr\x20=\x20new\x20XMLHttpRequest;\n\x20\x20\x20\x20xhr\.open\(\"GET -SF:\",\x20\"/pagelist\.json\"\);\n\x20\x20\x20\x20xhr\.onload\x20=\x20func -SF:tion\(e\)\x20{\n\x20\x20\x20\x20\x20\x20\x20\x20if\x20\(xhr\.status\x20 -SF:==\x20200\)\x20{\n\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20var\x -SF:20pages\x20=\x20JSON\.parse\(xhr\.responseText\);\n\x20\x20\x20\x20\x20 -SF:\x20\x20\x20\x20\x20\x20\x20if\x20\(pages\.length\)\n\x20\x20\x20\x20\x -SF:20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20document\.getElementById\ -SF:(\"noPageNotice\"\)\.style\.display\x20=\x20\"none\";\n\n\x20\x20\x20\x -SF:20\x20\x20\x20\x20\x20\x20\x20\x20var\x20pageList\x20=\x20document\.cre -SF:ateElement\(\"ol\"\);\n\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20 -SF:for\x20\(var\x20i\x20in\x20pages\)\x20{\n\x20\x20\x20\x20\x20\x20\x20\x -SF:20\x20\x20\x20\x20\x20\x20\x20\x20var\x20link\x20=\x20document\.createE -SF:lement\(\"a\"\);\n\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\ -SF:x20\x20\x20var\x20title\x20=\x20pages\[i\]\.title\x20\?\x20pages\[i\]\. -SF:title\x20:\x20\(\"Page\x20\"\x20\+\x20\(Number\(pages\[i\]\.id\)\)\);\n -SF:\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20var\x20 -SF:url\x20=\x20pages\[i\]\.url;\n\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\ -SF:x20\x20\x20\x20\x20\x20link\.appendChild\(document\.createTextNode\(tit -SF:le\x20\+\x20\(url\x20\?\x20\(\"\x20\[\"\x20\+\x20url\x20\+\x20\"\]\"\)\ -SF:x20:\x20\"\"\x20\)\)\);\n\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x -SF:20\x20\x20\x20\x20link\.setAttribute\(\"hre"); -==============NEXT SERVICE FINGERPRINT (SUBMIT INDIVIDUALLY)============== -SF-Port36866-TCP:V=6.40-2%I=7%D=12/30%Time=54A2A543%P=x86_64-apple-darwin1 -SF:0.8.0%r(GetRequest,198,"HTTP/1\.1\x20200\x20OK\r\nContent-Type:\x20text -SF:/xml\r\nDate:\x20Tue,\x2030\x20Dec\x202014\x2013:13:53\x20GMT\r\nConnec -SF:tion:\x20close\r\n\r\n<\?xml\x20version=\"1\.0\"\x20encoding=\"UTF-8\"\ -SF:?>runninglf85fem4srqg84i7vis9ppj0ie")%r(FourOhFourRequest,52,"HTTP/1\.1\x20404\x20Not\x20F -SF:ound\r\nDate:\x20Tue,\x2030\x20Dec\x202014\x2013:13:59\x20GMT\r\nConnec -SF:tion:\x20close\r\n\r\n"); -MAC Address: (Unknown) - -Service detection performed. Please report any incorrect results at http://nmap.org/submit/ . -Nmap done: 1 IP address (1 host up) scanned in 209.82 seconds -``` - -Update, with the latest firmware as of today, the `1.4.0-2507(afro-ashley)`, the nmap looks like below. Also, I don't see it advertising itself over SSDP like before, nor answer to the ssdp query as it did before. - -``` --[691]> sudo nmap -sV -p 1-65535 192.168.1.86 -Password: +`npm install lgtv` -Starting Nmap 6.40-2 ( http://nmap.org ) at 2015-10-29 21:37 CET -Nmap scan report for 192.168.1.86 -Host is up (0.0076s latency). -Not shown: 65525 closed ports -PORT STATE SERVICE VERSION -1701/tcp open tcpwrapped -1742/tcp open tcpwrapped -1881/tcp open tcpwrapped -1900/tcp open upnp? -3000/tcp open ppp? -3001/tcp open ssl/nessus? -9955/tcp open unknown -9998/tcp open distinct32? -18181/tcp open opsec-cvp? -36866/tcp open unknown -6 services unrecognized despite returning data. If you know the service/version, please submit the following fingerprints at http://www.insecure.org/cgi-bin/servicefp-submit.cgi : -==============NEXT SERVICE FINGERPRINT (SUBMIT INDIVIDUALLY)============== -SF-Port1900-TCP:V=6.40-2%I=7%D=10/29%Time=563283C6%P=x86_64-apple-darwin10 -SF:.8.0%r(GetRequest,52,"HTTP/1\.1\x20404\x20Not\x20Found\r\nDate:\x20Thu, -SF:\x2029\x20Oct\x202015\x2020:38:26\x20GMT\r\nConnection:\x20close\r\n\r\ -SF:n")%r(HTTPOptions,52,"HTTP/1\.1\x20404\x20Not\x20Found\r\nDate:\x20Thu, -SF:\x2029\x20Oct\x202015\x2020:38:31\x20GMT\r\nConnection:\x20close\r\n\r\ -SF:n")%r(FourOhFourRequest,52,"HTTP/1\.1\x20404\x20Not\x20Found\r\nDate:\x -SF:20Thu,\x2029\x20Oct\x202015\x2020:38:31\x20GMT\r\nConnection:\x20close\ -SF:r\n\r\n"); -==============NEXT SERVICE FINGERPRINT (SUBMIT INDIVIDUALLY)============== -SF-Port3000-TCP:V=6.40-2%I=7%D=10/29%Time=563283CB%P=x86_64-apple-darwin10 -SF:.8.0%r(GetRequest,58,"HTTP/1\.1\x20200\x20OK\r\nDate:\x20Thu,\x2029\x20 -SF:Oct\x202015\x2020:38:31\x20GMT\r\nConnection:\x20close\r\n\r\nHello\x20 -SF:world\r\n")%r(HTTPOptions,58,"HTTP/1\.1\x20200\x20OK\r\nDate:\x20Thu,\x -SF:2029\x20Oct\x202015\x2020:38:31\x20GMT\r\nConnection:\x20close\r\n\r\nH -SF:ello\x20world\r\n"); -==============NEXT SERVICE FINGERPRINT (SUBMIT INDIVIDUALLY)============== -SF-Port3001-TCP:V=6.40-2%T=SSL%I=7%D=10/29%Time=563283E8%P=x86_64-apple-da -SF:rwin10.8.0%r(GetRequest,58,"HTTP/1\.1\x20200\x20OK\r\nDate:\x20Thu,\x20 -SF:29\x20Oct\x202015\x2020:39:00\x20GMT\r\nConnection:\x20close\r\n\r\nHel -SF:lo\x20world\r\n")%r(HTTPOptions,58,"HTTP/1\.1\x20200\x20OK\r\nDate:\x20 -SF:Thu,\x2029\x20Oct\x202015\x2020:39:00\x20GMT\r\nConnection:\x20close\r\ -SF:n\r\nHello\x20world\r\n"); -==============NEXT SERVICE FINGERPRINT (SUBMIT INDIVIDUALLY)============== -SF-Port9955-TCP:V=6.40-2%I=7%D=10/29%Time=563283D5%P=x86_64-apple-darwin10 -SF:.8.0%r(Kerberos,F,"ERROR\x20Unknown\r\n"); -==============NEXT SERVICE FINGERPRINT (SUBMIT INDIVIDUALLY)============== -SF-Port9998-TCP:V=6.40-2%I=7%D=10/29%Time=563283CB%P=x86_64-apple-darwin10 -SF:.8.0%r(GetRequest,5C8,"HTTP/1\.1\x20200\x20OK\r\nConnection:\x20close\r -SF:\nContent-Length:\x201395\r\nContent-Type:\x20text/html\r\n\r\n\n\n\nfunctio -SF:n\x20createPageList\(\)\x20{\n\x20\x20\x20\x20var\x20xhr\x20=\x20new\x2 -SF:0XMLHttpRequest;\n\x20\x20\x20\x20xhr\.open\(\"GET\",\x20\"/pagelist\.j -SF:son\"\);\n\x20\x20\x20\x20xhr\.onload\x20=\x20function\(e\)\x20{\n\x20\ -SF:x20\x20\x20\x20\x20\x20\x20if\x20\(xhr\.status\x20==\x20200\)\x20{\n\x2 -SF:0\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20var\x20pages\x20=\x20JSON\ -SF:.parse\(xhr\.responseText\);\n\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\ -SF:x20\x20if\x20\(pages\.length\)\n\x20\x20\x20\x20\x20\x20\x20\x20\x20\x2 -SF:0\x20\x20\x20\x20\x20\x20document\.getElementById\(\"noPageNotice\"\)\. -SF:style\.display\x20=\x20\"none\";\n\n\x20\x20\x20\x20\x20\x20\x20\x20\x2 -SF:0\x20\x20\x20var\x20pageList\x20=\x20document\.createElement\(\"ol\"\); -SF:\n\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20for\x20\(var\x20i\x20 -SF:in\x20pages\)\x20{\n\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x2 -SF:0\x20\x20\x20var\x20link\x20=\x20document\.createElement\(\"a\"\);\n\x2 -SF:0\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20var\x20tit -SF:le\x20=\x20pages\[i\]\.title\x20\?\x20pages\[i\]\.title\x20:\x20\(\"Pag -SF:e\x20\"\x20\+\x20\(Number\(pages\[i\]\.id\)\)\);\n\x20\x20\x20\x20\x20\ -SF:x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20var\x20url\x20=\x20pages\[i\ -SF:]\.url;\n\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x -SF:20link\.appendChild\(document\.createTextNode\(title\x20\+\x20\(url\x20 -SF:\?\x20\(\"\x20\[\"\x20\+\x20url\x20\+\x20\"\]\"\)\x20:\x20\"\"\x20\)\)\ -SF:);\n\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20lin -SF:k\.setAttribute\(\"hre")%r(HTTPOptions,5C8,"HTTP/1\.1\x20200\x20OK\r\nC -SF:onnection:\x20close\r\nContent-Length:\x201395\r\nContent-Type:\x20text -SF:/html\r\n\r\n\n\n\nfunction\x20createPageList\(\)\x20{\n\x20\x20\x20\x20var\ -SF:x20xhr\x20=\x20new\x20XMLHttpRequest;\n\x20\x20\x20\x20xhr\.open\(\"GET -SF:\",\x20\"/pagelist\.json\"\);\n\x20\x20\x20\x20xhr\.onload\x20=\x20func -SF:tion\(e\)\x20{\n\x20\x20\x20\x20\x20\x20\x20\x20if\x20\(xhr\.status\x20 -SF:==\x20200\)\x20{\n\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20var\x -SF:20pages\x20=\x20JSON\.parse\(xhr\.responseText\);\n\x20\x20\x20\x20\x20 -SF:\x20\x20\x20\x20\x20\x20\x20if\x20\(pages\.length\)\n\x20\x20\x20\x20\x -SF:20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20document\.getElementById\ -SF:(\"noPageNotice\"\)\.style\.display\x20=\x20\"none\";\n\n\x20\x20\x20\x -SF:20\x20\x20\x20\x20\x20\x20\x20\x20var\x20pageList\x20=\x20document\.cre -SF:ateElement\(\"ol\"\);\n\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20 -SF:for\x20\(var\x20i\x20in\x20pages\)\x20{\n\x20\x20\x20\x20\x20\x20\x20\x -SF:20\x20\x20\x20\x20\x20\x20\x20\x20var\x20link\x20=\x20document\.createE -SF:lement\(\"a\"\);\n\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\ -SF:x20\x20\x20var\x20title\x20=\x20pages\[i\]\.title\x20\?\x20pages\[i\]\. -SF:title\x20:\x20\(\"Page\x20\"\x20\+\x20\(Number\(pages\[i\]\.id\)\)\);\n -SF:\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20var\x20 -SF:url\x20=\x20pages\[i\]\.url;\n\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\ -SF:x20\x20\x20\x20\x20\x20link\.appendChild\(document\.createTextNode\(tit -SF:le\x20\+\x20\(url\x20\?\x20\(\"\x20\[\"\x20\+\x20url\x20\+\x20\"\]\"\)\ -SF:x20:\x20\"\"\x20\)\)\);\n\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x -SF:20\x20\x20\x20\x20link\.setAttribute\(\"hre"); -==============NEXT SERVICE FINGERPRINT (SUBMIT INDIVIDUALLY)============== -SF-Port36866-TCP:V=6.40-2%I=7%D=10/29%Time=563283CB%P=x86_64-apple-darwin1 -SF:0.8.0%r(GetRequest,145,"HTTP/1\.1\x20200\x20OK\r\nContent-Type:\x20text -SF:/xml\r\nDate:\x20Thu,\x2029\x20Oct\x202015\x2020:38:31\x20GMT\r\nConnec -SF:tion:\x20close\r\n\r\n<\?xml\x20version=\"1\.0\"\x20encoding=\"UTF-8\"\ -SF:?>running")% -SF:r(FourOhFourRequest,52,"HTTP/1\.1\x20404\x20Not\x20Found\r\nDate:\x20Th -SF:u,\x2029\x20Oct\x202015\x2020:38:36\x20GMT\r\nConnection:\x20close\r\n\ -SF:r\n"); -MAC Address: (Unknown) -Service detection performed. Please report any incorrect results at http://nmap.org/submit/ . -Nmap done: 1 IP address (1 host up) scanned in 180.22 seconds -``` From 56446a81d88e67ab0a0f0f64d140907af42306c4 Mon Sep 17 00:00:00 2001 From: domo-site <93765654+mgrafr@users.noreply.github.com> Date: Tue, 22 Feb 2022 17:15:23 +0100 Subject: [PATCH 03/14] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 5e27e96..a693795 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,8 @@ # Description -adaptation du script de Danovadia/lgtv-http-server -pour une utilisation avec Domoticz -voir le site domo-site.fr +a partir du script de Danovadia/lgtv-http-server
+pour une utilisation avec Domoticz:
+index.js à placer dans node_module/lgtv + # LGTV From 37eeb3c76e622328766e3d12f764fd3ea33adbd1 Mon Sep 17 00:00:00 2001 From: domo-site <93765654+mgrafr@users.noreply.github.com> Date: Tue, 22 Feb 2022 17:16:17 +0100 Subject: [PATCH 04/14] sup --- apis/alert.js | 25 ---------------------- apis/change-input.js | 25 ---------------------- apis/change-volume.js | 27 ------------------------ apis/client-key.txt | 1 - apis/input-cli.js | 49 ------------------------------------------- apis/input-tv.js | 24 --------------------- apis/open-browser.js | 17 --------------- apis/open-youtube.js | 24 --------------------- apis/turn-off.js | 24 --------------------- apis/turn-on.js | 24 --------------------- 10 files changed, 240 deletions(-) delete mode 100644 apis/alert.js delete mode 100644 apis/change-input.js delete mode 100644 apis/change-volume.js delete mode 100644 apis/client-key.txt delete mode 100644 apis/input-cli.js delete mode 100644 apis/input-tv.js delete mode 100644 apis/open-browser.js delete mode 100644 apis/open-youtube.js delete mode 100644 apis/turn-off.js delete mode 100644 apis/turn-on.js diff --git a/apis/alert.js b/apis/alert.js deleted file mode 100644 index 0c66837..0000000 --- a/apis/alert.js +++ /dev/null @@ -1,25 +0,0 @@ -var lgtv = require("lgtv"); -var express = require('express'); -var router = express.Router(); -var request = require('request'); -var CONFIG = require('../config') - -var popAlert = function(alert) { - lgtv.connect(CONFIG.lgtvip, function(err, response){ - if (!err) { - lgtv.show_float(alert, function(err, response){ - if (!err) { - console.log('Alert fired: ' + alert); - } - }); - } - }); -}; - -router.get('/:alert', function (req, res) { - var alert = req.params.alert; - popAlert(alert); - res.send('Alert fired: ' + alert) -}); - -module.exports = router; diff --git a/apis/change-input.js b/apis/change-input.js deleted file mode 100644 index f29867c..0000000 --- a/apis/change-input.js +++ /dev/null @@ -1,25 +0,0 @@ -var lgtv = require("lgtv"); -var express = require('express'); -var router = express.Router(); -var request = require('request'); -var CONFIG = require('../config') - -var changeInput = function(input) { - lgtv.connect(CONFIG.lgtvip, function(err, response){ - if (!err) { - lgtv.set_input(input, function(err, response){ - if (!err) { - console.log('Input was changed to ' + input); - } - }); - } - }); -}; - -router.get('/:input', function (req, res) { - var input = req.params.input; - changeInput(input); - res.send('Input was set to ' + input) -}); - -module.exports = router; diff --git a/apis/change-volume.js b/apis/change-volume.js deleted file mode 100644 index 49dada7..0000000 --- a/apis/change-volume.js +++ /dev/null @@ -1,27 +0,0 @@ -var lgtv = require("../lgtv"); -var express = require('express'); -var router = express.Router(); -var request = require('request'); -var CONFIG = require('../config') - -var changeVolume = function(volume) { - lgtv.connect(CONFIG.lgtvip, function(err, response){ - if (!err) { - lgtv.set_volume(volume, function(err, response){ - }); - } - }); -}; - -router.get('/:volume', function (req, res) { - var volume = Number(req.params.volume); - if (volume > 99) { - res.send('Invalid volume. Please set between 0-99.') - } else { - changeVolume(volume); - res.send('Volume was set to ' + volume) - } -}); - - -module.exports = router; diff --git a/apis/client-key.txt b/apis/client-key.txt deleted file mode 100644 index e1be5b2..0000000 --- a/apis/client-key.txt +++ /dev/null @@ -1 +0,0 @@ -3dfc9bb451d448b18405ce86b1046f48 \ No newline at end of file diff --git a/apis/input-cli.js b/apis/input-cli.js deleted file mode 100644 index e1df4ce..0000000 --- a/apis/input-cli.js +++ /dev/null @@ -1,49 +0,0 @@ -/*---------------------------------------------------------------------------*/ -/* -Use this example to set an input, eg - node input-cli.js HDMI_1 - node input-cli.js HDMI_2 - node input-cli.js TV -when using TV, we need to start the TV app (here the analog TV, perhaps digital -TV needs a different app). - */ -/*---------------------------------------------------------------------------*/ -lgtv = require("lg"); -/*---------------------------------------------------------------------------*/ -var args = process.argv.slice(2); -var input = "HDMI_1"; -if (args.length > 0) { - input = args[0]; -} - -var retry_timeout = 10; -var run_test = function() { - lgtv.discover_ip(retry_timeout, function(err, ipaddr) { - if (err) { - console.log("Failed to find TV IP address on the LAN. Verify that TV is on, and that you are on the same LAN/Wifi."); - - } else { - console.log("Found TV at address " + ipaddr + ", running example."); - lgtv.connect(ipaddr, function(err, response){ - if (!err) { - if (input === "TV") { - // special case, needs to start an app - lgtv.start_app("com.webos.app.livetv", function(err, response){ - if (!err) { - lgtv.disconnect(); - } - }); - } else { - lgtv.set_input(input, function(err, response){ - if (!err) { - lgtv.disconnect(); - } - }); - } - } - }); - } - }); -}; - -run_test(); diff --git a/apis/input-tv.js b/apis/input-tv.js deleted file mode 100644 index 9282f63..0000000 --- a/apis/input-tv.js +++ /dev/null @@ -1,24 +0,0 @@ -lgtv = require("lgtv"); -/*---------------------------------------------------------------------------*/ -var retry_timeout = 10; -var run_test = function() { - lgtv.discover_ip(retry_timeout, function(err, ipaddr) { - if (err) { - console.log("Failed to find TV IP address on the LAN. Verify that TV is on, and that you are on the same LAN/Wifi."); - - } else { - console.log("Found TV at address " + ipaddr + ", running example."); - lgtv.connect(ipaddr, function(err, response){ - if (!err) { - lgtv.start_app("com.webos.app.livetv", function(err, response){ - if (!err) { - lgtv.disconnect(); - } - }); - } - }); - } - }); -}; - -run_test(); diff --git a/apis/open-browser.js b/apis/open-browser.js deleted file mode 100644 index dbf57d4..0000000 --- a/apis/open-browser.js +++ /dev/null @@ -1,17 +0,0 @@ -lgtv = require("lgtv"); -/*---------------------------------------------------------------------------*/ -var retry_timeout = 10; -var run_test = function() { - console.log("Found TV at address running example."); - lgtv.connect('10.0.1.200', function(err, response){ - if (!err) { - lgtv.open_browser_at("http://github.com/msloth", function(err, response){ - if (!err) { - lgtv.disconnect(); - } - }); - } - }); -}; - -run_test(); diff --git a/apis/open-youtube.js b/apis/open-youtube.js deleted file mode 100644 index 89ab046..0000000 --- a/apis/open-youtube.js +++ /dev/null @@ -1,24 +0,0 @@ -lgtv = require("lgtv"); -/*---------------------------------------------------------------------------*/ -var retry_timeout = 10; -var run_test = function() { - lgtv.discover_ip(retry_timeout, function(err, ipaddr) { - if (err) { - console.log("Failed to find TV IP address on the LAN. Verify that TV is on, and that you are on the same LAN/Wifi."); - - } else { - console.log("Found TV at address " + ipaddr + ", running example."); - lgtv.connect(ipaddr, function(err, response){ - if (!err) { - lgtv.start_app("youtube.leanback.v4", function(err, response){ - if (!err) { - lgtv.disconnect(); - } - }); - } - }); - } - }); -}; - -run_test(); diff --git a/apis/turn-off.js b/apis/turn-off.js deleted file mode 100644 index fcb8fad..0000000 --- a/apis/turn-off.js +++ /dev/null @@ -1,24 +0,0 @@ -var lgtv = require("lgtv"); -var express = require('express'); -var router = express.Router(); -var request = require('request'); -var CONFIG = require('../config') - -var turnOff = function() { - lgtv.connect(CONFIG.lgtvip, function(err, response){ - lgtv.turn_off(function(err, response){ - if (!err) { - console.log("turn_off succeeded:" + JSON.stringify(response)); - } else { - console.log("turn_off failed:" + JSON.stringify(response)); - } - }); - }); -}; - -router.get('/', function (req, res) { - turnOff() - res.send('TV was turned off.') -}); - -module.exports = router; diff --git a/apis/turn-on.js b/apis/turn-on.js deleted file mode 100644 index 476094b..0000000 --- a/apis/turn-on.js +++ /dev/null @@ -1,24 +0,0 @@ -var lgtv = require("lgtv"); -var express = require('express'); -var router = express.Router(); -var request = require('request'); -var wol = require('node-wol'); -var CONFIG = require('../config') - -var turnOn = function() { - wol.wake(CONFIG.lgtvmac, { - address: CONFIG.lgtvip, - port: 3000 - }, function(error) { - if(error) { - return; - } - }); - var magicPacket = wol.createMagicPacket(CONFIG.lgtvmac); -}; - -router.get('/', function (req, res) { - turnOn() -}); - -module.exports = router; From 814de3e0c82e88af7efb32281ba209a494e48008 Mon Sep 17 00:00:00 2001 From: domo-site <93765654+mgrafr@users.noreply.github.com> Date: Tue, 22 Feb 2022 17:16:37 +0100 Subject: [PATCH 05/14] sup --- tests/tests.js | 686 ------------------------------------------------- 1 file changed, 686 deletions(-) delete mode 100644 tests/tests.js diff --git a/tests/tests.js b/tests/tests.js deleted file mode 100644 index 568d109..0000000 --- a/tests/tests.js +++ /dev/null @@ -1,686 +0,0 @@ - - -lgtv = require("./lg-webos-controller"); -/*---------------------------------------------------------------------------*/ -var input_enter_test = function() { - lgtv.input_enter(function(err, response){ - if (!err) { - console.log("input_enter succeeded:" + JSON.stringify(response)); - } else { - console.log("input_enter failed:" + JSON.stringify(response)); - } - }); -}; -/*---------------------------------------------------------------------------*/ -var input_pause_test = function() { - lgtv.input_pause(function(err, response){ - if (!err) { - console.log("input_pause succeeded:" + JSON.stringify(response)); - } else { - console.log("input_pause failed:" + JSON.stringify(response)); - } - }); -}; -/*---------------------------------------------------------------------------*/ -var input_play_test = function() { - lgtv.input_play(function(err, response){ - if (!err) { - console.log("input_play succeeded:" + JSON.stringify(response)); - } else { - console.log("input_play failed:" + JSON.stringify(response)); - } - }); -}; -/*---------------------------------------------------------------------------*/ -var input_stop_test = function() { - lgtv.input_stop(function(err, response){ - if (!err) { - console.log("input_stop succeeded:" + JSON.stringify(response)); - } else { - console.log("input_stop failed:" + JSON.stringify(response)); - } - }); -}; -/*---------------------------------------------------------------------------*/ -var input_volumeup_test = function() { - lgtv.input_volumeup(function(err, response){ - if (!err) { - console.log("input_volumeup succeeded:" + JSON.stringify(response)); - } else { - console.log("input_volumeup failed:" + JSON.stringify(response)); - } - }); -}; -/*---------------------------------------------------------------------------*/ -var input_volumedown_test = function() { - lgtv.input_volumedown(function(err, response){ - if (!err) { - console.log("input_volumedown succeeded:" + JSON.stringify(response)); - } else { - console.log("input_volumedown failed:" + JSON.stringify(response)); - } - }); -}; -/*---------------------------------------------------------------------------*/ -var input_channel_up_test = function() { - lgtv.input_channel_up(function(err, response){ - if (!err) { - console.log("input_channel_up_test succeeded"); - } else { - console.log("input_channel_up_test failed:"); - console.log(err.toString()); - console.log(response); - } - }); -}; -/*---------------------------------------------------------------------------*/ -var input_channel_down_test = function() { - lgtv.input_channel_down(function(err, response){ - if (!err) { - console.log("input_channel_down_test succeeded"); - } else { - console.log("input_channel_down_test failed:"); - console.log(err.toString()); - console.log(response); - } - }); -}; -/*---------------------------------------------------------------------------*/ -var input_media_play_test = function() { - lgtv.input_media_play(function(err, response){ - if (!err) { - console.log("input_media_play_test succeeded"); - } else { - console.log("input_media_play_test failed:"); - console.log(err.toString()); - console.log(response); - } - }); -}; -/*---------------------------------------------------------------------------*/ -var input_media_stop_test = function() { - lgtv.input_media_stop(function(err, response){ - if (!err) { - console.log("input_media_stop_test succeeded"); - } else { - console.log("input_media_stop_test failed:"); - console.log(err.toString()); - console.log(response); - } - }); -}; -/*---------------------------------------------------------------------------*/ -var input_media_pause_test = function() { - lgtv.input_media_pause(function(err, response ){ - if (!err) { - console.log("input_media_pause_test succeeded"); - } else { - console.log("input_media_pause_test failed:"); - console.log(err.toString()); - console.log(response); - } - }); -}; -/*---------------------------------------------------------------------------*/ -var input_media_rewind_test = function() { - lgtv.input_media_rewind(function(err, response){ - if (!err) { - console.log("input_media_rewind_test succeeded"); - } else { - console.log("input_media_rewind_test failed:"); - console.log(err.toString()); - console.log(response); - } - }); -}; -/*---------------------------------------------------------------------------*/ -var input_media_forward_test = function() { - lgtv.input_media_forward(function(err, response ){ - if (!err) { - console.log("input_media_forward_test succeeded"); - } else { - console.log("input_media_forward_test failed:"); - console.log(err.toString()); - console.log(response); - } - }); -}; -/*---------------------------------------------------------------------------*/ -var input_three_d_on_test = function() { - lgtv.input_three_d_on(function(err, response){ - if (!err) { - console.log("input_three_d_on_test succeeded"); - } else { - console.log("input_three_d_on_test failed:"); - console.log(err.toString()); - console.log(response); - } - }); -}; -/*---------------------------------------------------------------------------*/ -var input_three_d_off_test = function() { - lgtv.input_three_d_off(function(err, response ){ - if (!err) { - console.log("input_three_d_off_test succeeded"); - } else { - console.log("input_three_d_off_test failed:"); - console.log(err.toString()); - console.log(response); - } - }); -}; -/*---------------------------------------------------------------------------*/ -var input_backspace_test = function() { - lgtv.input_backspace(function(err, response){ - if (!err) { - console.log("input_backspace succeeded:" + JSON.stringify(response)); - } else { - console.log("input_backspace failed:" + JSON.stringify(response)); - } - }); -}; -/*---------------------------------------------------------------------------*/ -var input_text_test = function() { - lgtv.input_text(function(err, response){ - if (!err) { - console.log("input_text succeeded:" + JSON.stringify(response)); - } else { - console.log("input_text failed:" + JSON.stringify(response)); - } - }); -}; -/*---------------------------------------------------------------------------*/ -var input_pointer_connect_test = function(fn) { - lgtv.input_pointer_connect(function(err, response){ - if (!err) { - console.log("input_pointer_connect succeeded:" + JSON.stringify(response)); - } else { - console.log("input_pointer_connect failed:" + JSON.stringify(response)); - } - }); -}; -/*---------------------------------------------------------------------------*/ -var input_pointer_move_test = function() { - lgtv.input_pointer_move(function(err, response){ - if (!err) { - console.log("input_pointer_move succeeded:" + JSON.stringify(response)); - } else { - console.log("input_pointer_move failed:" + JSON.stringify(response)); - } - }); -}; -/*---------------------------------------------------------------------------*/ -var input_pointer_click_test = function() { - lgtv.input_pointer_click(function(err, response){ - if (!err) { - console.log("input_pointer_click succeeded:" + JSON.stringify(response)); - } else { - console.log("input_pointer_click failed:" + JSON.stringify(response)); - } - }); -}; -/*---------------------------------------------------------------------------*/ -var input_pointer_scroll_test = function(dx, dy) { - lgtv.input_pointer_scroll(dx, dy, function(err, response){ - if (!err) { - console.log("input_pointer_scroll succeeded:" + JSON.stringify(response)); - } else { - console.log("input_pointer_scroll failed:" + JSON.stringify(response)); - } - }); -}; -/*---------------------------------------------------------------------------*/ -var input_pointer_disconnect_test = function() { - lgtv.input_pointer_disconnect(function(err, response){ - if (!err) { - console.log("input_pointer_disconnect succeeded:" + JSON.stringify(response)); - } else { - console.log("input_pointer_disconnect failed:" + JSON.stringify(response)); - } - }); -}; -/*---------------------------------------------------------------------------*/ -var open_youtube_at_id_test = function(id) { - lgtv.open_youtube_at_id(id, function(err, response){ - if (!err) { - console.log("open_youtube_at_id succeeded:" + JSON.stringify(response)); - } else { - console.log("open_youtube_at_id failed:" + JSON.stringify(response)); - } - }); -}; -/*---------------------------------------------------------------------------*/ -var open_youtube_at_url_test = function(url) { - lgtv.open_youtube_at_url(url, function(err, response){ - if (!err) { - console.log("open_youtube_at_url succeeded:" + JSON.stringify(response)); - } else { - console.log("open_youtube_at_url failed:" + JSON.stringify(response)); - } - }); -}; -/*---------------------------------------------------------------------------*/ -var open_browser_at_test = function(url) { - lgtv.open_browser_at(url, function(err, response){ - if (!err) { - console.log("open_browser_at succeeded:" + JSON.stringify(response)); - } else { - console.log("open_browser_at failed:" + JSON.stringify(response)); - } - }); -}; -/*---------------------------------------------------------------------------*/ -var apps_test = function() { - lgtv.apps(function(err, response){ - if (!err) { - console.log("apps succeeded:" + JSON.stringify(response)); - } else { - console.log("apps failed:" + JSON.stringify(response)); - } - }); -}; -/*---------------------------------------------------------------------------*/ -var start_app_test = function(appid) { - lgtv.start_app(appid, function(err, response){ - if (!err) { - console.log("start_app succeeded:" + JSON.stringify(response)); - } else { - console.log("start_app failed:" + JSON.stringify(response)); - } - }); -}; -/*---------------------------------------------------------------------------*/ -var close_app_test = function(appid) { - lgtv.close_app(appid, function(err, response){ - if (!err) { - console.log("close_app succeeded:" + JSON.stringify(response)); - } else { - console.log("close_app failed:" + JSON.stringify(response)); - } - }); -}; -/*---------------------------------------------------------------------------*/ -var inputlist_test = function() { - lgtv.inputlist(function(err, response){ - if (!err) { - console.log("inputlist succeeded:" + JSON.stringify(response)); - } else { - console.log("inputlist failed:" + JSON.stringify(response)); - } - }); -}; -/*---------------------------------------------------------------------------*/ -var input_test = function() { - lgtv.input(function(err, response){ - if (!err) { - console.log("input succeeded:" + JSON.stringify(response)); - } else { - console.log("input failed:" + JSON.stringify(response)); - } - }); -}; -/*---------------------------------------------------------------------------*/ -var set_input_test = function(inputid) { - lgtv.set_input(inputid, function(err, response){ - if (!err) { - console.log("set_input succeeded:" + JSON.stringify(response)); - } else { - console.log("set_input failed:" + JSON.stringify(response)); - } - }); -}; -/*---------------------------------------------------------------------------*/ -var muted_test = function() { - lgtv.muted(function(err, response){ - if (!err) { - console.log("muted succeeded:" + JSON.stringify(response)); - } else { - console.log("muted failed:" + JSON.stringify(response)); - } - }); -}; -/*---------------------------------------------------------------------------*/ -var set_mute_test = function(mute) { - lgtv.set_mute(mute, function(err, response){ - if (!err) { - console.log("muted succeeded:" + JSON.stringify(response)); - } else { - console.log("muted failed:" + JSON.stringify(response)); - } - }); -}; -/*---------------------------------------------------------------------------*/ -var toggle_mute_test = function() { - lgtv.toggle_mute(function(err, response){ - if (!err) { - console.log("muted succeeded:" + JSON.stringify(response)); - } else { - console.log("muted failed:" + JSON.stringify(response)); - } - }); -}; -/*---------------------------------------------------------------------------*/ -var volume_test = function() { - lgtv.volume(function(err, response){ - if (!err) { - console.log("volume succeeded:" + JSON.stringify(response)); - } else { - console.log("volume failed:" + JSON.stringify(response)); - } - }); -}; -/*---------------------------------------------------------------------------*/ -var set_volume_test = function(vl) { - lgtv.set_volume(vl, function(err, response){ - if (!err) { - console.log("set_volume succeeded:" + JSON.stringify(response)); - } else { - console.log("set_volume failed:" + JSON.stringify(response)); - } - }); -}; -/*---------------------------------------------------------------------------*/ -var connect_test = function(hostname, fn) { - lgtv.connect(hostname, function(err, response){ - if (!err) { - console.log("connect succeeded:" + JSON.stringify(response)); - } else { - console.log("connect failed:" + JSON.stringify(response)); - } - fn(err); - }); -}; -/*---------------------------------------------------------------------------*/ -var disconnect_test = function() { - lgtv.disconnect(function(err, response){ - if (!err) { - console.log("disconnect succeeded:" + JSON.stringify(response)); - } else { - console.log("disconnect failed:" + JSON.stringify(response)); - } - }); -}; -/*---------------------------------------------------------------------------*/ -var turn_off_test = function() { - lgtv.turn_off(function(err, response){ - if (!err) { - console.log("turn_off succeeded:" + JSON.stringify(response)); - } else { - console.log("turn_off failed:" + JSON.stringify(response)); - } - }); -}; -/*---------------------------------------------------------------------------*/ -var get_status_test = function() { - lgtv.get_status(function(err, response){ - if (!err) { - console.log("get status succeeded:" + JSON.stringify(response)); - } else { - console.log("get status failed:" + JSON.stringify(response)); - } - }); -}; -/*---------------------------------------------------------------------------*/ -var sw_info_test = function() { - lgtv.sw_info(function(err, response){ - if (!err) { - console.log("sw_info succeeded:" + JSON.stringify(response)); - } else { - console.log("sw_info failed:" + JSON.stringify(response)); - } - }); -}; -/*---------------------------------------------------------------------------*/ -var services_test = function() { - lgtv.services(function(err, response){ - if (!err) { - console.log("services succeeded:" + JSON.stringify(response)); - } else { - console.log("services failed:" + JSON.stringify(response)); - } - }); -}; -/*---------------------------------------------------------------------------*/ -// test for getting the IP address after already having connected to the TV -var ip_test = function() { - lgtv.ip(function(err, response){ - if (!err) { - console.log("ip succeeded:" + JSON.stringify(response)); - } else { - console.log("ip failed:" + JSON.stringify(response)); - } - }); -}; -/*---------------------------------------------------------------------------*/ -// test for finding the IP address of the TV on the LAN -var discover_ip_test = function(retry_timeout_s, callback) { - lgtv.discover_ip(retry_timeout_s, callback); -}; -/*---------------------------------------------------------------------------*/ -var connected_test = function() { - lgtv.connected(function(err, response){ - if (!err) { - console.log("connected succeeded:" + JSON.stringify(response)); - } else { - console.log("connected failed:" + JSON.stringify(response)); - } - }); -}; -/*---------------------------------------------------------------------------*/ -var show_float_test = function() { - lgtv.show_float("Test float succeded!", function(err, response){ - if (!err) { - console.log("show_float succeeded:" + JSON.stringify(response)); - } else { - console.log("show_float failed:" + JSON.stringify(response)); - } - }); -}; -/*---------------------------------------------------------------------------*/ -var channellist_test = function() { - lgtv.channellist(function(err, response){ - if (!err) { - console.log("channellist succeeded:" + JSON.stringify(response)); - } else { - console.log("channellist failed:" + JSON.stringify(response)); - } - }); -}; -/*---------------------------------------------------------------------------*/ -var channel_test = function() { - lgtv.channel(function(err, response){ - if (!err) { - console.log("channel succeeded:" + JSON.stringify(response)); - } else { - console.log("channel failed:" + JSON.stringify(response)); - } - }); -}; -/*---------------------------------------------------------------------------*/ -var set_channel_test = function(chid) { - lgtv.set_channel(chid, function(err, response){ - if (!err) { - console.log("set_channel succeeded:" + JSON.stringify(response)); - } else { - console.log("set_channel failed:" + JSON.stringify(response)); - } - }); -}; -/*---------------------------------------------------------------------------*/ -var temporarydbg_test = function() { - lgtv.temporarydbg(function(err, response){ - if (!err) { - console.log("tempdbg succeeded:" + JSON.stringify(response)); - } else { - console.log("tempdbg failed:" + JSON.stringify(response)); - } - }); -}; -/*---------------------------------------------------------------------------*/ -// This is the list of functions that this file tests. - -// exports.input_enter = input_enter; /* remote control 'enter' */ -// exports.input_pause = input_pause; /* remote control 'pause' */ -// exports.input_play = input_play; /* remote control 'play' */ -// exports.input_stop = input_stop; /* remote control 'stop' */ -// exports.input_volumeup = input_volumeup; /* remote control 'volume up' */ -// exports.input_volumedown = input_volumedown; /* remote control 'volume down' */ -// exports.input_backspace = input_backspace; /* send 'backspace' */ -// exports.input_text = input_text; /* insert text */ -// exports.input_pointer_connect = input_pointer_connect; /* get pointer (like mouse pointer) */ -// exports.input_pointer_move = input_pointer_move; /* move the pointer */ -// exports.input_pointer_click = input_pointer_click; /* click pointer */ -// exports.input_pointer_disconnect = input_pointer_disconnect; /* disconnect the pointer */ -// exports.open_youtube_at_id = open_youtube_at_id; /* open youtube at videoid */ -// exports.open_youtube_at_url = open_youtube_at_url; /* open youtube at url */ -// exports.open_browser_at = open_browser_at; /* open webbrowser at url */ -// exports.apps = apps; /* get list of apps */ -// exports.start_app = start_app; /* start app */ -// exports.close_app = close_app; /* close app */ -// exports.inputlist = inputlist; /* get list of inputs */ -// exports.input = input; /* get active input source */ -// exports.set_input = set_input; /* set input source */ -// exports.set_mute = set_mute; -// exports.toggle_mute = toggle_mute; -// exports.muted = muted; /* is the TV muted? */ -// exports.volume = volume; /* get volume */ -// exports.set_volume = set_volume; /* set volume */ -// exports.connect = connect; /* connect to TV */ -// exports.disconnect = disconnect; /* disconnect from TV */ -// exports.turn_off = turn_off; /* turn the TV off */ -// exports.status = status; /* get status information from TV */ -// exports.sw_info = sw_info; /* get software info such as webos version */ -// exports.services = services; /* get available services on the TV */ -// exports.ip = ip; /* get the TV IP-address */ -// exports.connected = connected; /* are we connected to the TV? */ -// exports.show_float = show_float; /* show a small information box with text on the TV */ -// exports.channellist = channellist; /* get list of channels available */ -// exports.channel = channel; /* get active channel */ -// exports.set_channel = set_channel; /* set active channel */ - -/*---------------------------------------------------------------------------*/ -var retry_timeout = 10; -discover_ip_test(retry_timeout, function(err, ipaddr) { - if (err) { - console.log("Failed to find TV IP address on the LAN. Verify that TV is on, and that you are on the same LAN/Wifi."); - } else { - console.log("TV ip addr is: " + ipaddr); - } -}); - - -connect_test("192.168.1.86", function(err){ - if (!err) { - setTimeout(function() { - // disconnect_test(); // funkade inte - // events.js:72 - // throw er; // Unhandled 'error' event - // ^ - // Error: first argument must be a valid error code number - // at Sender.close (/Users/marcuslunden/Dropbox/Syncfolder/Syncfolder/node.js/rest-kodi-webostv-controller/node_modules/ws/lib/Sender.js:44:49) - // at WebSocket.close (/Users/marcuslunden/Dropbox/Syncfolder/Syncfolder/node.js/rest-kodi-webostv-controller/node_modules/ws/lib/WebSocket.js:117:18) - // at Object.disconnect (/Users/marcuslunden/Dropbox/Syncfolder/Syncfolder/node.js/rest-kodi-webostv-controller/lg-webos-controller.js:239:6) - // at disconnect_test (/Users/marcuslunden/Dropbox/Syncfolder/Syncfolder/node.js/rest-kodi-webostv-controller/test-lg-webos-controller.js:267:10) - // at null._onTimeout (/Users/marcuslunden/Dropbox/Syncfolder/Syncfolder/node.js/rest-kodi-webostv-controller/test-lg-webos-controller.js:421:7) - // at Timer.listOnTimeout [as ontimeout] (timers.js:110:15) - setTimeout(function() { - console.log("-----------exiting."); - process.exit(0); - }, 1000); - }, 5000); - - // input_test(); - // input_text_test(); - input_pointer_connect_test(function(err, resp){ - if (!err) { - // move the pointer a bit - input_pointer_move_test(10, 10, function(err, resp){ - // then scroll - if (!err) { - input_pointer_scroll_test(function(err, resp){ - if (!err) { - // click it - input_pointer_click_test(function(err, resp){ - if (!err) { - // finally disconnect - input_pointer_disconnect_test(function(err, resp){ - if (!err) { - console.log("input pointer all OK!"); - } - }); - } - }); // input_pointer_click_test - } - }); // input_pointer_scroll_test - } - }); //input_pointer_move_test - } - }); // input_pointer_connect_test - - // open_youtube_at_id_test("IEVE3KSKQ0o"); - // open_youtube_at_id_test("bogus"); - // open_youtube_at_url_test("https://www.youtube.com/watch?v=IEVE3KSKQ0o"); - // open_youtube_at_url_test("www.youtube.com/watch?v=IEVE3KSKQ0o"); - // open_youtube_at_url_test("bogus"); - - // ip_test(); - // connected_test(); - // channellist_test(); - // apps_test(); - - // tested and working as expected------------ - // input_stop_test(); - // input_enter_test(); - // input_backspace_test(); - // input_pause_test(); - - // input_channel_up_test(); - // input_channel_down_test(); - // input_three_d_on_test(); - // input_three_d_off_test(); - // input_media_play_test(); - // input_media_pause_test(); - // input_media_stop_test(); - // input_media_rewind_test(); - // input_media_forward_test(); - - // open_browser_at_test("www.google.com"); - // set_channel_test("0_3_10_0_0_65535_0"); - // set_channel_test("boguschannel"); // should fail - // channel_test(); - // sw_info_test(); - // services_test(); - // show_float_test(); - // turn_off_test(); - // apps_test(); - // muted_test(); - // input_play_test(); - // input_volumeup_test(); - // input_volumedown_test(); - - // set_volume_test(-2); // should fail - // set_volume_test(101); // should fail - // set_volume_test("osijdfosdn"); // should fail - // set_volume_test(); // should fail - // set_volume_test(0); - // set_volume_test(10); - // volume_test(); - // toggle_mute_test(); - // set_mute_test(true); - // set_mute_test(false); - // set_mute_test(243); // not boolean -> should fail - - // start_app_test("youtube.leanback.v4"); // open youtube - // start_app_test("com.webos.app.livetv"); // open TV channel - // start_app_test("bogusapp"); - // close_app_test("youtube.leanback.v4"); - - // get_status_test(); // gives audio status, should instead give other status right? - // inputlist_test(); - // set_input_test("HDMI_1"); - // set_input_test("bogus_input"); // should fail - - // temporarydbg_test(); - } -}); -/*---------------------------------------------------------------------------*/ From d2ba435735db10647855fe8fcbc2bb123041ee44 Mon Sep 17 00:00:00 2001 From: domo-site <93765654+mgrafr@users.noreply.github.com> Date: Tue, 22 Feb 2022 17:17:30 +0100 Subject: [PATCH 06/14] Delete .gitignore --- .gitignore | 38 -------------------------------------- 1 file changed, 38 deletions(-) delete mode 100644 .gitignore diff --git a/.gitignore b/.gitignore deleted file mode 100644 index def68b8..0000000 --- a/.gitignore +++ /dev/null @@ -1,38 +0,0 @@ -# Logs -logs -*.log - -# Runtime data -pids -*.pid -*.seed - -# Directory for instrumented libs generated by jscoverage/JSCover -lib-cov - -# Coverage directory used by tools like istanbul -coverage - -# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) -.grunt - -# Compiled binary addons (http://nodejs.org/api/addons.html) -build/Release - -# Dependency directory -# Commenting this out is preferred by some people, see -# https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git- -node_modules - -# Users Environment Variables -.lock-wscript - -#damn osx -.DS_Store - -# Client Key -./client-key.txt -./apis/client-key.txt - -# Config -./config.json From 77e10f1137df2e301a714b0ee1ac39238676f78d Mon Sep 17 00:00:00 2001 From: domo-site <93765654+mgrafr@users.noreply.github.com> Date: Tue, 22 Feb 2022 17:17:48 +0100 Subject: [PATCH 07/14] Delete client-key.txt --- client-key.txt | 1 - 1 file changed, 1 deletion(-) delete mode 100644 client-key.txt diff --git a/client-key.txt b/client-key.txt deleted file mode 100644 index 724513e..0000000 --- a/client-key.txt +++ /dev/null @@ -1 +0,0 @@ -4d66e79667f72e06ec215e6a837c9105 \ No newline at end of file From b172ad373a706f7b9d699480d2b1b82aea79ac8b Mon Sep 17 00:00:00 2001 From: domo-site <93765654+mgrafr@users.noreply.github.com> Date: Tue, 22 Feb 2022 17:22:31 +0100 Subject: [PATCH 08/14] Delete config.json --- config.json | 1 - 1 file changed, 1 deletion(-) delete mode 100644 config.json diff --git a/config.json b/config.json deleted file mode 100644 index 3101c73..0000000 --- a/config.json +++ /dev/null @@ -1 +0,0 @@ -{"lgtvip" : "10.0.1.200", "lgtvmac" : "30:A9:DE:E5:28:4C"} From c9911d9477c824069e22eb5f98ead3c646b54a74 Mon Sep 17 00:00:00 2001 From: domo-site <93765654+mgrafr@users.noreply.github.com> Date: Tue, 22 Feb 2022 17:22:43 +0100 Subject: [PATCH 09/14] Delete package.json --- package.json | 34 ---------------------------------- 1 file changed, 34 deletions(-) delete mode 100644 package.json diff --git a/package.json b/package.json deleted file mode 100644 index ac95201..0000000 --- a/package.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "LG-tv-http-server", - "version": "0.2.4", - "description": "Simple lib to interact with and control an LG WebOS smart TV.", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "repository": { - "type": "git", - "url": "git://github.com/msloth/lgtv.js.git" - }, - "keywords": [ - "tv", - "smarttv", - "webos", - "remote", - "control" - ], - "author": "Marcus Linderoth (https://github.com/msloth)", - "license": "MIT", - "bugs": { - "url": "https://github.com/msloth/lgtv.js/issues" - }, - "homepage": "https://github.com/msloth/lgtv.js", - "dependencies": { - "body-parser": "^1.16.0", - "express": "^4.14.1", - "lgtv": "^0.2.4", - "node-wol": "^0.1.1", - "request": "^2.79.0", - "websocket": "^1.0.17" - } -} From a4ccd4c69f41b3155f122d8b5afd2f15b8f26013 Mon Sep 17 00:00:00 2001 From: domo-site <93765654+mgrafr@users.noreply.github.com> Date: Tue, 22 Feb 2022 17:22:53 +0100 Subject: [PATCH 10/14] Delete lgtv.js --- lgtv.js | 953 -------------------------------------------------------- 1 file changed, 953 deletions(-) delete mode 100644 lgtv.js diff --git a/lgtv.js b/lgtv.js deleted file mode 100644 index d0ffa13..0000000 --- a/lgtv.js +++ /dev/null @@ -1,953 +0,0 @@ -// -// LG webos smart TV control app -// references: -// https://github.com/ConnectSDK/Connect-SDK-Android-Core -// https://github.com/CODeRUS/harbour-lgremote-webos -// -// 1: send handshake per below -> receive client key if not already -// 2: the protocol is using JSON strings with requests from the client, responses -// from the TV. Subscriptions probably means the TV will push notifications -// without prior individual requests. -// 3: client request has these fields: -// type : register/request/subscribe -// id : command + _ + message count (the response will mirror this number) -// uri : command endpoint URI -// payload : optional, eg input source string when changing input -// -// All callbacks follow the common pattern of function(error, ....) {} -// ie first argument is false if the call went ok, or true if an error occurred. -// Then, the second argument is most often the result if applicable, or not -// existant respectively. -// ----------------------------------------------------------------------------- -var fs = require('fs'); // for storing client key -// var http = require('http'); // for communication with Kodi - -// var WebSocket = require('ws'); -var WebSocketClient = require('websocket').client; // for communication with TV -var client = new WebSocketClient(); -var handshaken = false; - -// for SSDP discover of TV on the LAN -var dgram = require('dgram'); - -var eventemitter = new (require('events').EventEmitter); // for match ws request -- response -eventemitter.setMaxListeners(0); // enable infinite number of listeners - -// connection to TV -var wsurl = 'ws://lgsmarttv.lan:3000'; - -// once connected, store client key (retrieved from TV) in this file -var client_key_filename = "./client-key.txt"; - -// bool for callbacks -var RESULT_ERROR = true; -var RESULT_OK = false; -// ----------------------------------------------------------------------------- -// send this ask for permission to control the TV -// alternatives: pairingType = PROMPT or PIN -// PROMPT is arguably more convenient as it opens a yes/no dialog on the TV while -// PIN show a three-digit random number that has to be communicated to this app. - -// this works and gives full auth -// handshake without client key, for first connection -var hello = "{\"type\":\"register\",\"id\":\"register_0\",\"payload\":{\"forcePairing\":false,\"pairingType\":\"PROMPT\",\"manifest\":{\"manifestVersion\":1,\"appVersion\":\"1.1\",\"signed\":{\"created\":\"20140509\",\"appId\":\"com.lge.test\",\"vendorId\":\"com.lge\",\"localizedAppNames\":{\"\":\"LG Remote App\",\"ko-KR\":\"리모컨 앱\",\"zxx-XX\":\"ЛГ Rэмotэ AПП\"},\"localizedVendorNames\":{\"\":\"LG Electronics\"},\"permissions\":[\"TEST_SECURE\",\"CONTROL_INPUT_TEXT\",\"CONTROL_MOUSE_AND_KEYBOARD\",\"READ_INSTALLED_APPS\",\"READ_LGE_SDX\",\"READ_NOTIFICATIONS\",\"SEARCH\",\"WRITE_SETTINGS\",\"WRITE_NOTIFICATION_ALERT\",\"CONTROL_POWER\",\"READ_CURRENT_CHANNEL\",\"READ_RUNNING_APPS\",\"READ_UPDATE_INFO\",\"UPDATE_FROM_REMOTE_APP\",\"READ_LGE_TV_INPUT_EVENTS\",\"READ_TV_CURRENT_TIME\"],\"serial\":\"2f930e2d2cfe083771f68e4fe7bb07\"},\"permissions\":[\"LAUNCH\",\"LAUNCH_WEBAPP\",\"APP_TO_APP\",\"CLOSE\",\"TEST_OPEN\",\"TEST_PROTECTED\",\"CONTROL_AUDIO\",\"CONTROL_DISPLAY\",\"CONTROL_INPUT_JOYSTICK\",\"CONTROL_INPUT_MEDIA_RECORDING\",\"CONTROL_INPUT_MEDIA_PLAYBACK\",\"CONTROL_INPUT_TV\",\"CONTROL_POWER\",\"READ_APP_STATUS\",\"READ_CURRENT_CHANNEL\",\"READ_INPUT_DEVICE_LIST\",\"READ_NETWORK_STATE\",\"READ_RUNNING_APPS\",\"READ_TV_CHANNEL_LIST\",\"WRITE_NOTIFICATION_TOAST\",\"READ_POWER_STATE\",\"READ_COUNTRY_INFO\"],\"signatures\":[{\"signatureVersion\":1,\"signature\":\"eyJhbGdvcml0aG0iOiJSU0EtU0hBMjU2Iiwia2V5SWQiOiJ0ZXN0LXNpZ25pbmctY2VydCIsInNpZ25hdHVyZVZlcnNpb24iOjF9.hrVRgjCwXVvE2OOSpDZ58hR+59aFNwYDyjQgKk3auukd7pcegmE2CzPCa0bJ0ZsRAcKkCTJrWo5iDzNhMBWRyaMOv5zWSrthlf7G128qvIlpMT0YNY+n/FaOHE73uLrS/g7swl3/qH/BGFG2Hu4RlL48eb3lLKqTt2xKHdCs6Cd4RMfJPYnzgvI4BNrFUKsjkcu+WD4OO2A27Pq1n50cMchmcaXadJhGrOqH5YmHdOCj5NSHzJYrsW0HPlpuAx/ECMeIZYDh6RMqaFM2DXzdKX9NmmyqzJ3o/0lkk/N97gfVRLW5hA29yeAwaCViZNCP8iC9aO0q9fQojoa7NQnAtw==\"}]}}}"; - -// handshake with client key, for subsequent connections -var hello_w_key = "{\"type\":\"register\",\"id\":\"register_0\",\"payload\":{\"forcePairing\":false,\"pairingType\":\"PROMPT\",\"client-key\":\"CLIENTKEYGOESHERE\",\"manifest\":{\"manifestVersion\":1,\"appVersion\":\"1.1\",\"signed\":{\"created\":\"20140509\",\"appId\":\"com.lge.test\",\"vendorId\":\"com.lge\",\"localizedAppNames\":{\"\":\"LG Remote App\",\"ko-KR\":\"리모컨 앱\",\"zxx-XX\":\"ЛГ Rэмotэ AПП\"},\"localizedVendorNames\":{\"\":\"LG Electronics\"},\"permissions\":[\"TEST_SECURE\",\"CONTROL_INPUT_TEXT\",\"CONTROL_MOUSE_AND_KEYBOARD\",\"READ_INSTALLED_APPS\",\"READ_LGE_SDX\",\"READ_NOTIFICATIONS\",\"SEARCH\",\"WRITE_SETTINGS\",\"WRITE_NOTIFICATION_ALERT\",\"CONTROL_POWER\",\"READ_CURRENT_CHANNEL\",\"READ_RUNNING_APPS\",\"READ_UPDATE_INFO\",\"UPDATE_FROM_REMOTE_APP\",\"READ_LGE_TV_INPUT_EVENTS\",\"READ_TV_CURRENT_TIME\"],\"serial\":\"2f930e2d2cfe083771f68e4fe7bb07\"},\"permissions\":[\"LAUNCH\",\"LAUNCH_WEBAPP\",\"APP_TO_APP\",\"CLOSE\",\"TEST_OPEN\",\"TEST_PROTECTED\",\"CONTROL_AUDIO\",\"CONTROL_DISPLAY\",\"CONTROL_INPUT_JOYSTICK\",\"CONTROL_INPUT_MEDIA_RECORDING\",\"CONTROL_INPUT_MEDIA_PLAYBACK\",\"CONTROL_INPUT_TV\",\"CONTROL_POWER\",\"READ_APP_STATUS\",\"READ_CURRENT_CHANNEL\",\"READ_INPUT_DEVICE_LIST\",\"READ_NETWORK_STATE\",\"READ_RUNNING_APPS\",\"READ_TV_CHANNEL_LIST\",\"WRITE_NOTIFICATION_TOAST\",\"READ_POWER_STATE\",\"READ_COUNTRY_INFO\"],\"signatures\":[{\"signatureVersion\":1,\"signature\":\"eyJhbGdvcml0aG0iOiJSU0EtU0hBMjU2Iiwia2V5SWQiOiJ0ZXN0LXNpZ25pbmctY2VydCIsInNpZ25hdHVyZVZlcnNpb24iOjF9.hrVRgjCwXVvE2OOSpDZ58hR+59aFNwYDyjQgKk3auukd7pcegmE2CzPCa0bJ0ZsRAcKkCTJrWo5iDzNhMBWRyaMOv5zWSrthlf7G128qvIlpMT0YNY+n/FaOHE73uLrS/g7swl3/qH/BGFG2Hu4RlL48eb3lLKqTt2xKHdCs6Cd4RMfJPYnzgvI4BNrFUKsjkcu+WD4OO2A27Pq1n50cMchmcaXadJhGrOqH5YmHdOCj5NSHzJYrsW0HPlpuAx/ECMeIZYDh6RMqaFM2DXzdKX9NmmyqzJ3o/0lkk/N97gfVRLW5hA29yeAwaCViZNCP8iC9aO0q9fQojoa7NQnAtw==\"}]}}}"; -// --------------------------------------------------------- -// get the handshake string used for setting up the ws connection -function get_handshake() { - if (fs.existsSync(client_key_filename)) { - var ck = fs.readFileSync(client_key_filename); - console.log("Client key:" + ck); - return hello_w_key.replace("CLIENTKEYGOESHERE", ck); - - } else { - console.log("First usage, let's pair with TV."); - return hello; - } -} -// --------------------------------------------------------- -// store the client key on disk so that we don't have to pair next time -function store_client_key(ck) { - console.log("Storing client key:" + ck); - fs.writeFileSync(client_key_filename, ck); -} -/*---------------------------------------------------------------------------*/ -client.on('connectFailed', function(error) { - // failed to connect, set timer to retry in a few seconds - console.log('Connect Error: ' + error.toString()); - setTimeout(function(){connect();}, 5000); -}); -/*---------------------------------------------------------------------------*/ -// store the connection in a variable with larger scope so that we may later -// refer to it and close connection. -var clientconnection = {}; -client.on('connect', function(connection) { - console.log('WebSocket Client Connected on IP:' + connection.remoteAddress); - clientconnection = connection; - //-------------------------------------------------------------------------- - connection.on('error', function(error) { - console.log("Connection Error: " + error.toString()); - throw new Error("Websocket connection error:" + error.toString()); - }); - //-------------------------------------------------------------------------- - connection.on('close', function() { - console.log('LG TV disconnected'); - clientconnection = {}; - eventemitter.emit("lgtv_ws_closed"); - }); - //-------------------------------------------------------------------------- - connection.on('message', function(message) { - if (message.type === 'utf8') { - var json = JSON.parse(message.utf8Data); - console.log('<--- received: %s', message.utf8Data); - // console.log('<--- emitting: %s', json.id); - eventemitter.emit(json.id, json); - } else { - console.log('<--- received: %s', message.toString()); - } - }); - //-------------------------------------------------------------------------- - - handshaken = false; - var hs = get_handshake(); - console.log("Sending handshake: ", hs); - connection.send(hs); - // connection.sendUTF(hs); // works as well -}); -/*---------------------------------------------------------------------------*/ -var isConnected = function(){ - if (typeof clientconnection.connected === 'undefined') { - // console.log("disconnected"); - return false; - } - return clientconnection.connected; -}; -//------------------------------------------ -var close_connection = function(){ - // console.log("disconnecting"); - clientconnection.close(); -}; -//------------------------------------------ -var remote_ip = function(){ - if (typeof clientconnection.remoteAddress === 'undefined') { - return "0.0.0.0"; - } - return clientconnection.remoteAddress; -}; -//------------------------------------------ -var ws_send = function(str){ - if (typeof clientconnection.connected === 'undefined') { - return false; - } - if (typeof str !== 'string') { - return false; - } - if (clientconnection.connected) { - clientconnection.send(str); - } - return clientconnection.connected; -}; -/*---------------------------------------------------------------------------*/ -// this is the old version, using the ws lib; above is the new, using websocket lib - // try { - // var ws = new WebSocket(wsurl); - // } catch(err) { - // console.log(err); - // console.log("Error, could not open websocket (are you connected to the Internet?)"); - // process.exit(0); // TODO better error handling, what is appropriate here - raise some error. - // } - // // --------------------------------------------------------- - // // callback for when connection is opened, ie the websocket handshake is done and - // // we should perform TV handshake. - // ws.on('open', function() { - // console.log('opened connection to TV'); - // // send handshake - will either show prompt on TV (if first connect), or auth us - // var hs = get_handshake(); - // ws.send(hs); - // }); - // // --------------------------------------------------------- - // ws.on('close', function() { - // console.log('LG TV disconnected'); - // eventemitter.emit("lgtv_ws_closed"); - // }); - // // --------------------------------------------------------- - // // callback for when we receive something on the websocket connection: can be - // // either responses or events - // ws.on('message', function(message) { - // var json = JSON.parse(message); - // console.log('<--- received: %s', message); - // eventemitter.emit(json.id, json); - // }); -/*---------------------------------------------------------------------------*/ -// send the SSDP discover message that the TV will respond to. -var _send_ssdp_discover = function(socket) -{ - var ssdp_rhost = "239.255.255.250"; - var ssdp_rport = 1900; - - // these fields are all required - var ssdp_msg = 'M-SEARCH * HTTP/1.1\r\n'; - ssdp_msg += 'HOST: 239.255.255.250:1900\r\n'; - ssdp_msg += 'MAN: "ssdp:discover"\r\n'; - ssdp_msg += 'MX: 5\r\n'; - ssdp_msg += "ST: urn:dial-multiscreen-org:service:dial:1\r\n"; - ssdp_msg += "USER-AGENT: iOS/5.0 UDAP/2.0 iPhone/4\r\n\r\n"; - var message = new Buffer(ssdp_msg); - - socket.send(message, 0, message.length, ssdp_rport, ssdp_rhost, function(err, bytes) { - if (err) throw err; - // console.log('SSDP message sent to ' + ssdp_rhost +':'+ ssdp_rport); - // console.log(message.toString()); - }); -}; -/*---------------------------------------------------------------------------*/ -var discover_ip = function(retry_timeout_seconds, tv_ip_found_callback) -{ - var server = dgram.createSocket('udp4'); - var timeout = 0; - var cb = tv_ip_found_callback || undefined; - - // sanitize parameters and set default otherwise - if (retry_timeout_seconds && typeof(retry_timeout_seconds) === 'number') { - timeout = retry_timeout_seconds; - } else if (!tv_ip_found_callback && typeof(retry_timeout_seconds) === 'function') { - // overloading, the first parameter was not a timeout, but the callback - // and we thus assume no timeout is given - cb = retry_timeout_seconds; - } - - // when server has opened, send a SSDP discover message - server.on('listening', function() { - _send_ssdp_discover(server); - - // retry automatically if set - if (timeout > 0) { - // set timeout before next probe - // XXXXX - // after timeout seconds, invoke callback indicating failure - // cb(true, ""); - } - }); - - // scan incoming messages for the magic string - server.on('message', function(message, remote) { - if (message.indexOf("LG Smart TV")) { - server.close(); - if (cb) { - cb(false, remote.address); - } - } - }); - - server.bind(); // listen to 0.0.0.0:random - return server; -}; -/*---------------------------------------------------------------------------*/ -// send a command to the TV after having established a paired connection -var command_count = 0; - -var send_command = function(prefix, msgtype, uri, payload, fn) { - command_count++; - var msg = '{"id":"' + prefix + command_count + '","type":"' + msgtype + '","uri":"' + uri + '"'; - if (typeof payload === 'string' && payload.length > 0) { - msg += ',"payload":' + payload + "}"; - } else { - msg += "}"; - } - console.log("---> Sending command:" + msg); - - // if we were provided a callback, we register an event emitter listener for this. - // note: there is a clear risk of memory leaks should we have a lot of outstanding - // requests that never gets responses as the listeners are only cleared on response - // or websocket close. - try { - if (typeof fn === 'function') { - eventemitter.once(prefix + command_count, function (message) { - // console.log("*** emitter listener for " + prefix + command_count + " with message:" + message); - fn(RESULT_OK, message); - }); - } - ws_send(msg); - - } catch(err) { - console.log("Error, not connected to TV:" + err.toString()); - if (typeof fn === 'function') { - fn(RESULT_ERROR, "not connected"); - } - } -}; -//------------------------------------------ -var open_connection = function(host, fn){ - // console.log("connecting"); - clientconnection = {}; - try { - client.connect(host); - fn(RESULT_OK, {}); - } catch(error) { - fn(RESULT_ERROR, error.toString()); - } -}; -/*---------------------------------------------------------------------------*/ -// verify that the provided host string contains ws protocol and port 3000, -// valid input examples: -// lgsmarttv.lan -// 192.168.1.86 -// 192.168.1.86:3000 -// ws://192.168.1.86:3000 -// ws://192.168.1.86 -// if protocol or port is lacking, they are added -// returns either the corrected host string, or false if totally invalid hoststring - -var _check_host_string = function(hoststr) -{ - if (hoststr.indexOf("ws://") !== 0) { - hoststr = "ws://" + hoststr; - } - if (hoststr.indexOf(":3000") !== (hoststr.length - 5)) { - hoststr += ":3000"; - } - - return hoststr; -}; -/*---------------------------------------------------------------------------*/ -// Connect to TV using either a host string (eg "192.168.1.213", "lgsmarttv.lan") -// or undefined for using the default "lgsmarttv.lan" - -var connect = function(host, fn) { - // if already connected, no need to connect again - // (unless hostname is new, but this package is basically written for the usecase - // of having a single TV on the LAN) - if (isConnected() && handshaken) { - if (typeof fn === 'function') { - fn(RESULT_OK, {}); - } - return; - } - - // sanitize and set hostname - if (host === undefined) { - // no hostname specified, use default - host = wsurl; - } else if (typeof(host) !== 'string') { - // XXXXX error, argument error - // throw something or at least give ample warning - host = wsurl; - } - host = _check_host_string(host); - if (host === false) { - // provided host string is wrong, throw something - // XXXX - } - - // open websocket connection and perform handshake - open_connection(host, function(err, msg){ - if (!err) { - // The connection was opened and the ws connection callback will automatically - // send the handshake, but we here register the listener for the response to - // that handshake; should be moved for code clarity - eventemitter.on("register_0", function (message) { - var ck = message.payload["client-key"]; - if (typeof ck === 'undefined') { - - } else { - store_client_key(ck); - handshaken = true; - if (typeof fn === 'function') { - fn(RESULT_OK, {}); - } - } - // {"type":"registered","id":"register_0","payload":{"client-key":"a32c6abeab6a601d626ccdeb4749f0fa"}} - }); - } else { - if (typeof fn === 'function') { - fn(RESULT_ERROR, msg); - } - } - }); -}; -/*---------------------------------------------------------------------------*/ -var ip = function() { - return remote_ip(); -}; -/*---------------------------------------------------------------------------*/ -var connected = function() { - return isConnected(); -}; -/*---------------------------------------------------------------------------*/ -var disconnect = function(fn) { - close_connection(); - eventemitter.once("lgtv_ws_closed", function () { - if(typeof fn === 'function') { - fn(RESULT_OK); - } - }); -}; -// --------------------------------------------------------- -// show a float on the TV -var unsubscribe = function(id, fn) { - var msg = '{"id":"' + id + '","type":"unsubscribe"}'; - console.log("---> Sending command:" + msg); - try { - if (typeof fn === 'function') { - eventemitter.once(prefix + command_count, function (message) { - // console.log("*** emitter listener for " + prefix + command_count + " with message:" + message); - fn(RESULT_OK, message); - }); - } - ws_send(msg); - // ws.send(msg); - - } catch(err) { - console.log("Error, not connected to TV."); - if (typeof fn === 'function') { - fn(RESULT_ERROR, "not connected"); - } - } -}; -// --------------------------------------------------------- -// show a float on the TV -function show_float(text, fn) { - send_command("", "request", "ssap://system.notifications/createToast", '{"message": "MSG"}'.replace('MSG', text), fn); -} -// --------------------------------------------------------- -// launch browser at URL; will open a new tab if already open -function open_browser_at(url, fn) { - // response: {"type":"response","id":"0","payload":{"returnValue":true,"id":"com.webos.app.browser","sessionId":"Y29tLndlYm9zLmFwcC5icm93c2VyOnVuZGVmaW5lZA=="}} - - // must start with http:// or https:// - console.log('opening browser at:%s', url); - var protocol = url.substring(0, 7).toLowerCase(); - if (protocol !== 'http://' && protocol !== 'https:/') { - url = "http://" + url; - } - - send_command("", "request", "ssap://system.launcher/open", JSON.stringify({target: url}), function(err, resp){ - var ret = ""; - if (!err) { - ret = {sessionId: resp.payload.sessionId}; - } else { - ret = JSON.stringify(response); - } - fn(err, ret); - }); -} -/*---------------------------------------------------------------------------*/ -var turn_off = function(fn) { - send_command("", "request", "ssap://system/turnOff", null, fn); -}; -/*---------------------------------------------------------------------------*/ -var channellist = function(fn) { - send_command("channels_", "request", "ssap://tv/getChannelList", null, function(err, resp) { - // send_command("channels_", "subscribe", "ssap://tv/getChannelList", null, function(err, resp) { - if (!err) { - try { - // extract channel list - var channellistarray = resp.payload.channelList; - var retlist = {channels : []}; - for (var i = channellistarray.length - 1; i >= 0; i--) { - var ch = {id: channellistarray[i].channelId, - name: channellistarray[i].channelName, - number: channellistarray[i].channelNumber}; - // console.log(channellistarray[i]); - console.log(ch); - retlist.channels.push(ch); - } - fn(RESULT_OK, JSON.stringify(retlist)); - - } catch(e) { - console.log("Error:" + e); - fn(RESULT_ERROR, resp); - } - - } else { - console.log("Error:" + err); - fn(RESULT_ERROR, err); - } - }); -}; -/*---------------------------------------------------------------------------*/ -var channel = function(fn) { - // send_command("channels_", "subscribe", "ssap://tv/getCurrentChannel", null, function(err, resp) { - send_command("channels_", "request", "ssap://tv/getCurrentChannel", null, function(err, resp) { -// {"type":"response","id":"channels_1","payload": {"channelId":"0_13_7_0_0_1307_0","signalChannelId":"0_1307_0","channelModeId":0,"channelModeName":"Terrestrial","channelTypeId":0,"channelTypeName":"Terrestrial Analog TV","channelNumber":"7","channelName":"SVT ","physicalNumber":13,"isSkipped":false,"isLocked":false,"isDescrambled":false,"isScrambled":false,"isFineTuned":false,"isInvisible":false,"favoriteGroup":null,"hybridtvType":null,"dualChannel":{"dualChannelId":null,"dualChannelTypeId":null,"dualChannelTypeName":null,"dualChannelNumber":null},"returnValue":true}} - - if (typeof fn === 'function') { - if (!err) { - if (resp.error) { - fn(RESULT_ERROR, "Error, probably not TV input right now"); - } else { - // return a subset of all information - fn(RESULT_OK, {id: resp.payload.channelId, // internal id, used for setting channel - name: resp.payload.channelName, // name as on TV, eg SVT - number: resp.payload.channelNumber}); // number on TV - } - } else { - console.log("Error:" + err); - fn(RESULT_ERROR, "Error, could not get answer"); - } - } - }); -}; -/*---------------------------------------------------------------------------*/ -/* set the active channel; use channelId as from the channellist, such as eg 0_13_7_0_0_1307_0 */ -var set_channel = function(channel, fn) { - send_command("", "request", "ssap://tv/openChannel", JSON.stringify({channelId: channel}), function(err, resp){ - if (err) { - fn(err, {}); - } else { - if (resp.type == "response") { - // {"type":"response","id":"1","payload":{"returnValue":true}} - fn(RESULT_OK, channel); - } else if (resp.type == "error") { - // {"type":"error","id":"1","error":"500 Application error","payload":{"returnValue":false,"errorCode":-1000,"errorText":"invalid channel id"}} - fn(RESULT_ERROR, resp.payload.errorText); - } else { - fn(RESULT_ERROR, "unknown error"); - } - } - }); -}; -/*---------------------------------------------------------------------------*/ -// note: the TV does not consider 'live TV' as part of the external input list. -// This will just return eg HDMI_1, HDMI_2, SCART_1, etc. -var inputlist = function(fn) { - // send_command("input_", "subscribe", "ssap://tv/getExternalInputList", null, function(err, resp) { - send_command("input_", "request", "ssap://tv/getExternalInputList", null, function(err, resp) { - if (typeof fn === 'function') { -// <--- received: {"type":"response","id":"input_1","payload": {"devices":[{"id":"SCART_1","label":"AV1","port":1,"appId":"com.webos.app.externalinput.scart","icon":"http://lgsmarttv.lan:3000/resources/f84946f3119c23cda549bdcf6ad02a89c73f7682/scart.png","modified":false,"autoav":false,"currentTVStatus":"","subList":[],"subCount":0,"connected":false,"favorite":false},{...}, {...}],"returnValue":true}} - if (!err) { - try { - // extract a nice and simple inputlist - var devs = resp.payload.devices; - var ret = {}; - for (var i = devs.length - 1; i >= 0; i--) { - ret[devs[i].id] = devs[i].icon; - } - console.log(ret); - - fn(RESULT_OK, ret); - } catch(error) { - console.log("Error:" + error); - fn(RESULT_ERROR, error); - } - } else { - console.log("Error:" + err); - fn(RESULT_ERROR, err); - } - } - }); -}; -/*---------------------------------------------------------------------------*/ -// get current input source -var input = function(fn) { - if (typeof fn === 'function') { - fn(RESULT_ERROR, {reason: "not implemented"}); - } -}; -/*---------------------------------------------------------------------------*/ -// set input source -var set_input = function(input, fn) { - send_command("", "request", "ssap://tv/switchInput", JSON.stringify({inputId: input}), function(err, resp){ - if (err) { - fn(RESULT_ERROR, resp); - } else { - if (resp.payload.errorCode) { - fn(RESULT_ERROR, resp.payload.errorText); - // {"type":"response","id":"1","payload":{"returnValue":true,"errorCode":-1000,"errorText":"no such input"}} - } else { - fn(RESULT_OK, input); - // {"type":"response","id":"1","payload":{"returnValue":true}} - } - } - }); -}; -/*---------------------------------------------------------------------------*/ -// set mute -var set_mute = function(setmute, fn) { - if(typeof setmute !== 'boolean') { - fn(RESULT_ERROR, {reason: "mute must be boolean"}); - } else { - send_command("", "request", "ssap://audio/setMute", JSON.stringify({mute: setmute}), fn); - } -}; -/*---------------------------------------------------------------------------*/ -var toggle_mute = function(fn) { - muted(function(err, resp){ - if (!err) { - var tomute = !resp; - send_command("", "request", "ssap://audio/setMute", JSON.stringify({mute: tomute}), fn); - } else { - fn(err, {}); - } - }); -}; -/*---------------------------------------------------------------------------*/ -var muted = function(fn) { - send_command("status_", "request", "ssap://audio/getStatus", null, function(err, response){ - if (!err) { - fn(RESULT_OK, response.payload.mute); - } else { - fn(RESULT_ERROR, response); - } - }); -}; -/*---------------------------------------------------------------------------*/ -// get volume as 0..100 if not muted, if muted then volume is -1 -var volume = function(fn) { - // send_command("status_", "subscribe", "ssap://audio/getVolume", null, function(err, response){ - send_command("status_", "request", "ssap://audio/getVolume", null, function(err, response){ - // {"type":"response","id":"status_1","payload":{"muted":false,"scenario":"mastervolume_tv_speaker","active":false,"action":"requested","volume":7,"returnValue":true,"subscribed":true}} - if (!err) { - var muted = response.payload.muted; - var ret = -1; - if (!muted) { - ret = response.payload.volume; - } - fn(RESULT_OK, ret); - } else { - fn(RESULT_ERROR, response); - } - }); -}; -/*---------------------------------------------------------------------------*/ -var set_volume = function(volumelevel, fn) { - if (typeof volumelevel !== 'number') { - fn(RESULT_ERROR, "volume must be a number"); - - } else if(volumelevel < 0 || volumelevel > 100) { - fn(RESULT_ERROR, "volume must be 0..100"); - - } else { - send_command("", "request", "ssap://audio/setVolume", JSON.stringify({volume: volumelevel}), fn); - } -}; -/*---------------------------------------------------------------------------*/ -var input_media_play = function(fn) { - send_command("", "request", "ssap://media.controls/play", null, fn); -}; -/*---------------------------------------------------------------------------*/ -var input_media_stop = function(fn) { - send_command("", "request", "ssap://media.controls/stop", null, fn); -}; -/*---------------------------------------------------------------------------*/ -var input_media_pause = function(fn) { - send_command("", "request", "ssap://media.controls/pause", null, fn); -}; -/*---------------------------------------------------------------------------*/ -var input_media_rewind = function(fn) { - send_command("", "request", "ssap://media.controls/rewind", null, fn); -}; -/*---------------------------------------------------------------------------*/ -var input_media_forward = function(fn) { - send_command("", "request", "ssap://media.controls/fastForward", null, fn); -}; -/*---------------------------------------------------------------------------*/ -var input_channel_up = function(fn) { - send_command("", "request", "ssap://tv/channelUp", null, fn); -}; -/*---------------------------------------------------------------------------*/ -var input_channel_down = function(fn) { - send_command("", "request", "ssap://tv/channelDown", null, fn); -}; -/*---------------------------------------------------------------------------*/ -var input_three_d_on = function(fn) { - send_command("", "request", "ssap://com.webos.service.tv.display/set3DOn", null, fn); -}; -/*---------------------------------------------------------------------------*/ -var input_three_d_off = function(fn) { - send_command("", "request", "ssap://com.webos.service.tv.display/set3DOff", null, fn); -}; -/*---------------------------------------------------------------------------*/ -var get_status = function(fn) { - send_command("status_", "request", "ssap://audio/getStatus", null, fn); - // send_command("status_", "subscribe", "ssap://audio/getStatus", null, fn); -}; -/*---------------------------------------------------------------------------*/ -var sw_info = function(fn) { - send_command("sw_info_", "request", "ssap://com.webos.service.update/getCurrentSWInformation", null, fn); -// received: {"type":"response","id":"sw_info_0","payload":{"returnValue":true,"product_name":"webOS","model_name":"HE_DTV_WT1M_AFAAABAA","sw_type":"FIRMWARE","major_ver":"04","minor_ver":"41.32","country":"SE","device_id":"cc:2d:8c:cf:94:8c","auth_flag":"N","ignore_disable":"N","eco_info":"01","config_key":"00","language_code":"sv-SE"}} -}; -/*---------------------------------------------------------------------------*/ -var services = function(fn) { - send_command("services_", "request", "ssap://api/getServiceList", null, function(err, resp) { - if (typeof fn === 'function') { - if (!err) { - try { -// received: {"type":"response","id":"services_1","payload":{"services":[{"name":"api","version":1},{"name":"audio","version":1},{"name":"media.controls","version":1},{"name":"media.viewer","version":1},{"name":"pairing","version":1},{"name":"system","version":1},{"name":"system.launcher","version":1},{"name":"system.notifications","version":1},{"name":"tv","version":1},{"name":"webapp","version":2}],"returnValue":true}} - var services = resp.payload.services; - fn(RESULT_OK, resp.payload.services); - } catch(e) { - console.log("Error:" + e); - fn(RESULT_ERROR, e); - } - } else { - console.log("Error:" + err); - fn(RESULT_ERROR, err); - } - } - }); -}; -/*---------------------------------------------------------------------------*/ -var apps = function(fn) { - send_command("launcher_", "request", "ssap://com.webos.applicationManager/listLaunchPoints", null, function(err, response) { - // send_command("launcher_", "subscribe", "ssap://com.webos.applicationManager/listLaunchPoints", null, function(err, response) { - if (typeof fn === 'function') { - if (!err) { - try { - // extract a nice and simple list of apps - var applist = {}; - var launchpoints = response.payload.launchPoints; - for (var i = launchpoints.length - 1; i >= 0; i--) { - // var oneapp = {}; - // oneapp["title"] = launchpoints[i]["title"]; - // oneapp["id"] = launchpoints[i]["launchPointId"]; -// {"removable":false,"largeIcon":"/mnt/otncabi/usr/palm/applications/com.webos.app.discovery/lgstore_130x130.png","vendor":"LGE","id":"com.webos.app.discovery","title":"LG Store","bgColor":"","vendorUrl":"","iconColor":"#cf0652","appDescription":"","params":{},"version":"1.0.18","bgImage":"/mnt/otncabi/usr/palm/applications/com.webos.app.discovery/lgstore_preview.png","icon":"http://lgsmarttv.lan:3000/resources/60ad544bd03663793dda37dbb21f10575408c73a/lgstore_80x80.png","launchPointId":"com.webos.app.discovery_default","imageForRecents":""}, - applist[launchpoints[i]["title"]] = launchpoints[i]["launchPointId"]; - } - console.log("Returning applist:"); - console.log(applist); - fn(RESULT_OK, applist); - } catch(e) { - console.log("Error:" + e); - fn(RESULT_ERROR, e); - } - } else { - console.log("Error:" + err); - fn(RESULT_ERROR, err); - } - } - }); -}; -/*---------------------------------------------------------------------------*/ -function open_app_with_payload(payload, fn) { - send_command("", "request", "ssap://com.webos.applicationManager/launch", payload, null, fn); -} -/*---------------------------------------------------------------------------*/ -var start_app = function(appid, fn) { - send_command("", "request", "ssap://system.launcher/launch", JSON.stringify({id: appid}), function(err, resp){ - if (!err) { - if (resp.payload.errorCode) { - fn(RESULT_ERROR, resp.payload.errorText); - // {"type":"error","id":"1","error":"500 Application error","payload":{"returnValue":false,"errorCode":-101,"errorText":"\"bogusapp\" was not found OR Unsupported Application Type"}} - } else { - fn(RESULT_OK, {sessionId : resp.payload.sessionId}); - } - } else { - fn(err, resp); - } - }); -}; -/*---------------------------------------------------------------------------*/ -var close_app = function(appid, fn) { - send_command("", "request", "ssap://system.launcher/close", JSON.stringify({id: appid}), function(err, resp){ - if (!err) { - if (resp.payload.errorCode) { - // Note: This error response may come as a result of trying to close an app - // that is not already open - // {"type":"error","id":"1","error":"500 Application error","payload":{"returnValue":false,"errorCode":-1000,"errorText":"Permission denied"}} - fn(RESULT_ERROR, resp.payload.errorText); - } else { - fn(RESULT_OK, {sessionId : resp.payload.sessionId}); - } - } else { - fn(err, resp); - } - }); -}; -/*---------------------------------------------------------------------------*/ -var input_pointer_connect = function(fn) { - if (typeof fn === 'function') { - fn(RESULT_ERROR, {reason: "not implemented"}); - } -}; -/*---------------------------------------------------------------------------*/ -var input_pointer_move = function(dx, dy, fn) { - // function sendMove(dx, dy) { - // pointerSocket.sendLogMessage('type:move\ndx:' + dx + '\ndy:' + dy + '\ndown:0\n\n') - if (typeof fn === 'function') { - fn(RESULT_ERROR, {reason: "not implemented"}); - } -}; -/*---------------------------------------------------------------------------*/ -var input_pointer_click = function(fn) { - // function sendClick() { - // pointerSocket.sendLogMessage('type:click\n\n') - if (typeof fn === 'function') { - fn(RESULT_ERROR, {reason: "not implemented"}); - } -}; -/*---------------------------------------------------------------------------*/ -var input_pointer_disconnect = function(fn) { - if (typeof fn === 'function') { - fn(RESULT_ERROR, {reason: "not implemented"}); - } -}; -/*---------------------------------------------------------------------------*/ -var input_text = function(text, fn) { - // is this the right call for the right API here? - // function sendInput(btype, bname) { - // pointerSocket.sendLogMessage('type:' + btype + '\nname:' + bname + '\n\n') - if (typeof fn === 'function') { - fn(RESULT_ERROR, {reason: "not implemented"}); - } -}; -/*---------------------------------------------------------------------------*/ -var input_pointer_scroll = function(dx, dy, fn) { - // pointerSocket.sendLogMessage('type:scroll\ndx:0\ndy:' + dy + '\ndown:0\n\n') - if (typeof fn === 'function') { - fn(RESULT_ERROR, {reason: "not implemented"}); - } -}; -/*---------------------------------------------------------------------------*/ -var input_enter = function(fn) { - send_command("", "request", "ssap://com.webos.service.ime/sendEnterKey", null, fn); -}; -/*---------------------------------------------------------------------------*/ -var input_pause = function(fn) { - send_command("pause_", "request", "ssap://media.controls/pause", null, fn); -}; -/*---------------------------------------------------------------------------*/ -var input_play = function(fn) { - send_command("play_", "request", "ssap://media.controls/play", null, fn); -}; -/*---------------------------------------------------------------------------*/ -var input_stop = function(fn) { - send_command("stop_", "request", "ssap://media.controls/stop", null, fn); -}; -/*---------------------------------------------------------------------------*/ -var input_volumeup = function(fn) { - send_command("volumeup_", "request", "ssap://audio/volumeUp", null, fn); -}; -/*---------------------------------------------------------------------------*/ -var input_volumedown = function(fn) { - send_command("volumedown_", "request", "ssap://audio/volumeDown", null, fn); -}; -/*---------------------------------------------------------------------------*/ -var input_backspace = function(count, fn) { - var c = count === undefined ? 1 : count; - send_command("", "request", "ssap://com.webos.service.ime/deleteCharacters", {"count": c}, fn); -}; -/*---------------------------------------------------------------------------*/ -var open_youtube_at_id = function(video_id, fn) { - var vurl = "http://www.youtube.com/tv?v=" + video_id; - open_youtube_at_url(vurl, fn); -}; -/*---------------------------------------------------------------------------*/ -var open_youtube_at_url = function(url, fn) { - var youtube_appid = "youtube.leanback.v4"; - var payload = {id: youtube_appid, params : {contentTarget: url}}; - send_command("", "request", "ssap://system.launcher/launch", JSON.stringify(payload), function(err, resp){ - if (!err) { - if (resp.payload.errorCode) { - fn(RESULT_ERROR, resp.payload.errorText); - // {"type":"error","id":"1","error":"500 Application error","payload":{"returnValue":false,"errorCode":-101,"errorText":"\"bogusapp\" was not found OR Unsupported Application Type"}} - } else { - fn(RESULT_OK, {sessionId : resp.payload.sessionId}); - } - } else { - fn(err, resp); - } - }); - - - // public void launchAppWithInfo(final AppInfo appInfo, Object params, final Launcher.AppLaunchListener listener) { - // String uri = "ssap://system.launcher/launch"; - // contentId = (String) ((JSONObject) params).get("contentId"); - // payload.put("id", appId); - // payload.put("contentId", contentId); - // payload.put("params", params); - -// {id : youtube.leanback.v4} -// {contentTarget: url} - - // open_app_with_payload({"id": "youtube.leanback.v4", "params": { "contentTarget": video_url }}); -}; -/*---------------------------------------------------------------------------*/ -var temporarydbg = function(count, fn) { - // send_command("http_header_", "request", "ssap://com.webos.service.sdx/getHttpHeaderForServiceRequest", null, fn); - // {"type":"response","id":"http_header_1","payload": - // {"returnValue":true,"header":"X-Device-Product:webOS\r\nX-Device-Platform:WT1M\r\nX-Device-Model:HE_DTV_WT1M_AFAAABAA\r\nX-Device-Netcast-Platform-Version:1.3.2\r\nX-Device-Eco-Info:01\r\nX-Device-Country-Group:EU\r\nX-Device-Publish-Flag:Y\r\nX-Device-ContentsQA-Flag:N\r\nX-Device-FW-Version:04.41.32\r\nX-Device-SDK-VERSION:1.3.2\r\nX-Device-ID:hEPv0JRPP5oIzP9mv9lAdGC1SC2CKe/SFzOGJKQv1hoygpWsNib7+mbwPklqA2FPj1KXM8l79B43RorjNIifB9g776LqceGmvucarN2tHbRrqzflDsU9MF50NCMH7ili\r\nX-Device-Sales-Model:60LB870V-ZA\r\nX-Device-Type:T01\r\nAccept:application/json\r\nX-Device-Language:sv-SE\r\nX-Device-Locale:sv-SE\r\nX-Device-Country:SE\r\nHOST:SE.lgtvsdp.com\r\nX-Device-Remote-Flag:N\r\nX-Device-FCK:81\r\nX-Device-Eula:additionalDataAllowed,generalTermsAllowed,networkAllowed,voiceAllowed\r\nX-Authentication:+dNxJb6+Al+Y6NmHAGXchGJm55U=\r\ncookie:JSESSIONID=KqU+lnNuRtbCrV0u6iFR4VIE.node_sdp20; Path=/rest; Secure\r\n","X-Device-Product":"webOS","X-Device-Platform":"WT1M","X-Device-Model":"HE_DTV_WT1M_AFAAABAA","X-Device-Netcast-Platform-Version":"1.3.2","X-Device-Eco-Info":"01","X-Device-Country-Group":"EU","X-Device-Publish-Flag":"Y","X-Device-ContentsQA-Flag":"N","X-Device-FW-Version":"04.41.32","X-Device-SDK-VERSION":"1.3.2","X-Device-ID":"hEPv0JRPP5oIzP9mv9lAdGC1SC2CKe/SFzOGJKQv1hoygpWsNib7+mbwPklqA2FPj1KXM8l79B43RorjNIifB9g776LqceGmvucarN2tHbRrqzflDsU9MF50NCMH7ili","X-Device-Sales-Model":"60LB870V-ZA","X-Device-Type":"T01","Accept":"application/json","X-Device-Language":"sv-SE","X-Device-Locale":"sv-SE","X-Device-Country":"SE","HOST":"SE.lgtvsdp.com","X-Device-Remote-Flag":"N","X-Device-FCK":"81","X-Device-Eula":"additionalDataAllowed,generalTermsAllowed,networkAllowed,voiceAllowed","X-Authentication":"+dNxJb6+Al+Y6NmHAGXchGJm55U=","cookie":"JSESSIONID=KqU+lnNuRtbCrV0u6iFR4VIE.node_sdp20; Path=/rest; Secure"}} - - - // send_command("launcher_", "subscribe", "ssap://com.webos.applicationManager/listLaunchPoints", null, fn); - // response is same or at least very similar to list apps - fn(false, {}); - -// other ssap endpoints: - // ssap://tv/getCurrentChannel - // ssap://tv/getChannelProgramInfo - // ssap://com.webos.applicationManager/getForegroundAppInfo - // ssap://com.webos.service.appstatus/getAppStatus - // ssap://system.launcher/getAppState - // ssap://tv/getChannelProgramInfo - // ssap://media.viewer/close - // ssap://webapp/closeWebApp -}; -/*---------------------------------------------------------------------------*/ -// commands related to input such as remote control and text input -exports.input_enter = input_enter; /* remote control 'enter' */ -exports.input_pause = input_pause; /* remote control 'pause' */ -exports.input_play = input_play; /* remote control 'play' */ -exports.input_stop = input_stop; /* remote control 'stop' */ -exports.input_volumeup = input_volumeup; /* remote control 'volume up' */ -exports.input_volumedown = input_volumedown; /* remote control 'volume down' */ -exports.input_channel_up = input_channel_up; /* remote control volume up */ -exports.input_channel_down = input_channel_down; /* remote control volume down */ -exports.input_media_play = input_media_play; /* remote control play */ -exports.input_media_stop = input_media_stop; /* remote control stop */ -exports.input_media_pause = input_media_pause; /* remote control pause */ -exports.input_media_rewind = input_media_rewind; /* remote control rewind */ -exports.input_media_forward = input_media_forward; /* remote control forward */ -exports.input_three_d_on = input_three_d_on; /* remote control 3d on */ -exports.input_three_d_off = input_three_d_off; /* remote control 3d off */ -exports.input_backspace = input_backspace; /* send 'backspace' */ -exports.input_text = input_text; /* insert text */ -exports.input_pointer_connect = input_pointer_connect; /* get pointer (like mouse pointer) */ -exports.input_pointer_scroll = input_pointer_scroll; /* scroll */ -exports.input_pointer_move = input_pointer_move; /* move the pointer */ -exports.input_pointer_click = input_pointer_click; /* click pointer */ -exports.input_pointer_disconnect = input_pointer_disconnect; /* disconnect the pointer */ - -// apps such as youtube, browser, and anything that may be installed -exports.open_youtube_at_id = open_youtube_at_id; /* open youtube at videoid */ -exports.open_youtube_at_url = open_youtube_at_url; /* open youtube at url */ -exports.open_browser_at = open_browser_at; /* open webbrowser at url */ -exports.apps = apps; /* get list of apps */ -exports.start_app = start_app; /* start app */ -exports.close_app = close_app; /* close app */ - -// TV source input-related -exports.inputlist = inputlist; /* get list of inputs */ -exports.input = input; /* get active input source */ -exports.set_input = set_input; /* set input source */ - -// sound volume related -exports.set_mute = set_mute; -exports.toggle_mute = toggle_mute; -exports.muted = muted; /* is the TV muted? */ -exports.volume = volume; /* get volume */ -exports.set_volume = set_volume; /* set volume */ - -// connect and power related -exports.discover_ip = discover_ip; /* discover the TV IP address */ -exports.connect = connect; /* connect to TV */ -exports.disconnect = disconnect; /* disconnect from TV */ -exports.turn_off = turn_off; /* turn the TV off */ - -// various status/state information -exports.get_status = get_status; /* get status information from TV */ -exports.sw_info = sw_info; /* get software info such as webos version */ -exports.services = services; /* get available services on the TV */ -exports.ip = ip; /* get the TV IP-address */ -exports.connected = connected; /* are we connected to the TV? */ -exports.show_float = show_float; /* show a small information box with text on the TV */ - -// set, get channels -exports.channellist = channellist; /* get list of channels available */ -exports.channel = channel; /* get active channel */ -exports.set_channel = set_channel; /* set active channel */ - -// debug and temporary -exports.temporarydbg = temporarydbg; From 28fedb5355ca8c1b2db5aa9fee232dda48c70e2b Mon Sep 17 00:00:00 2001 From: domo-site <93765654+mgrafr@users.noreply.github.com> Date: Tue, 22 Feb 2022 17:24:14 +0100 Subject: [PATCH 11/14] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index a693795..8436617 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,7 @@ index.js à placer dans node_module/lgtv ## Installation `npm install lgtv` +placer index.js dans node_modules/lgtv From c15e5337c5700a55e6d9b43c787b69bddca78d7f Mon Sep 17 00:00:00 2001 From: domo-site <93765654+mgrafr@users.noreply.github.com> Date: Sat, 26 Feb 2022 18:17:52 +0100 Subject: [PATCH 12/14] Add files via upload --- new1.js | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 new1.js diff --git a/new1.js b/new1.js new file mode 100644 index 0000000..f07d88c --- /dev/null +++ b/new1.js @@ -0,0 +1,11 @@ +lgtv = require("lgtv"); +var tv_ip_address = "192.168.1.24"; +lgtv.connect(tv_ip_address, function(err, response){ + if (!err) { + lgtv.show_float("It works!", function(err, response){ + if (!err) { + lgtv.disconnect(); + } + }); // show float + } +}); // connect \ No newline at end of file From be1a6a10f43fd5bffc41cbfd9d20dbbb3da40162 Mon Sep 17 00:00:00 2001 From: domo-site <93765654+mgrafr@users.noreply.github.com> Date: Sat, 26 Feb 2022 18:23:18 +0100 Subject: [PATCH 13/14] Update README.md --- README.md | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 8436617..da6d569 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,16 @@ # Description -a partir du script de Danovadia/lgtv-http-server
-pour une utilisation avec Domoticz:
-index.js à placer dans node_module/lgtv - +Notification sur téléviseur WebOS (LG par exemple) +à partir du script de Danovadia/lgtv-http-server
+pour une utilisation avec Domoticz:
+index.js à placer dans node_module/lgtv

+new1.js est un fichier de test pour verifier l'affichage d'une notification sur le téléviseur

+Plus d'infos sur http://domo-site.fr/accueil/dossiers/32 # LGTV ## Installation -`npm install lgtv` +`npm install lgtv`
placer index.js dans node_modules/lgtv From 5e907ae5d088db285ed2852b1796b4fc9c0d5fb8 Mon Sep 17 00:00:00 2001 From: domo-site <93765654+mgrafr@users.noreply.github.com> Date: Sat, 26 Feb 2022 18:24:23 +0100 Subject: [PATCH 14/14] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index da6d569..eac02be 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # Description Notification sur téléviseur WebOS (LG par exemple) -à partir du script de Danovadia/lgtv-http-server
+à partir du script de Danovadia/lgtv-http-server

pour une utilisation avec Domoticz:
index.js à placer dans node_module/lgtv

new1.js est un fichier de test pour verifier l'affichage d'une notification sur le téléviseur