LG TV steuern/abfragen ?

Nabend :slight_smile:

Nachdem wir uns ein verfrühtes Weihnachtsgeschenk gemacht haben, bin ich auf der Suche nach Möglichkeiten einen aktuellen LG TV zu steuern und/oder die Daten abzufragen.
Hat da jemand schon etwas fertiges laufen bzw. gibt es da ne Möglichkeit den Status abzufragen? Power/Kanal/Input/Lautstärke/Firmware usw. ?

Gruß
Jens

85 Klicks, aber keiner scheint etwas mitzuteilen zu haben … :confused::rolleyes: schade.

Hier gibt es Infos zu dem Protokoll, aber ich werde leider nicht schlau daraus:
Help - LG Smart TV Document

Hier gibt es eine Java Lösung für den Raspi
http://book2s.com/java/src/package/com/connectsdk/service/webostvservice.html

weitere Infos/Commandos
lgtv2

FHEM Lösung
FHEM Referenz

Hier habe ich dann noch eine PHP Class gefunden:

<?php

class webOSTV
{
	private $host, $port, $ws_key, $path, $lg_key, $sock, $connected=false, $handshaked=false;

	function webOSTV($host, $port=3000, $lgKey="NOKEY", $path="/")
	{
		$this->host = $host;
		$this->port = $port;
		$this->lg_key = $lgKey;
		$this->path = $path;
		$this->ws_key = $key = base64_encode(generateRandomString(16, false, true));
		if ($this->lg_key=="NOKEY") unset($this->lg_key);	
	}
		
	function connect()
	{
		$ws_handshake_cmd = "GET " . $this->path . " HTTP/1.1
";
		$ws_handshake_cmd.= "Upgrade: websocket
";
		$ws_handshake_cmd.= "Connection: Upgrade
";
		$ws_handshake_cmd.= "Sec-WebSocket-Version: 13
";			
		$ws_handshake_cmd.= "Sec-WebSocket-Key: " . $this->ws_key . "
";
		$ws_handshake_cmd.= "Host: ".$this->host.":".$this->port."

";
		$this->sock = fsockopen($this->host, $this->port, $errno, $errstr, 2);
		socket_set_timeout($this->sock, 0, 10000);
		echo     "Sending WS handshake
$ws_handshake_cmd
";
		$response = $this->send($ws_handshake_cmd);
		if ($response)
		{
			echo "WS Handshake Response:
$response
";
		} else 
			echo "ERROR during WS handshake!
";
		preg_match('#Sec-WebSocket-Accept:\s(.*)$#mU', $response, $matches);
		if ($matches) {
			$keyAccept = trim($matches[1]);
			$expectedResonse = base64_encode(pack('H*', sha1($this->ws_key . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
			$this->connected = ($keyAccept === $expectedResonse) ? true : false;
		} else $this->connected=false;
		if ($this->connected) echo "Sucessfull WS connection to $this->host:$this->port

";
		return $this->connected;  
	}
	
	function lg_handshake()
	{
		if (!$this->connected) $this->connect();
		if ($this->connected)
		{
			$handshake =    "{\"type\":\"register\",\"id\":\"register_0\",\"payload\":{\"forcePairing\":false,\"pairingType\":\"PROMPT\",\"client-key\":\"HANDSHAKEKEYGOESHERE\",\"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==\"}]}}}";
			if (isset($this->lg_key)) 
				$handshake = str_replace('HANDSHAKEKEYGOESHERE',$this->lg_key,$handshake);
			else  $handshake =    "{\"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==\"}]}}}";
			echo "Sending LG handshake
$handshake
";
			$response = $this->send(hybi10Encode($handshake));
			if ($response)
			{
				echo "
LG Handshake Response
".json_string($response)."
";
				$result = json_array($response);
				if ($result && array_key_exists('id',$result) &&  $result['id']=='result_0' && array_key_exists('client-key',$result['payload']))
				{
					// LG client-key received: COMPARE!!!
					if ($this->lg_key == $result['payload']['client-key'])
						echo "LG Client-Key successfully approved
"; 
				} else if ($result && array_key_exists('id',$result) &&  $result['id']=='register_0' && array_key_exists('pairingType',$result['payload']) && array_key_exists('returnValue',$result['payload']))
				{	// LG TV is prompting for access rights
					if ($result['payload']['pairingType'] == "PROMPT" && $result['payload']['returnValue'] == "true") 
					{
						$starttime = microtime(1);
						$lg_key_received = false;
						$error_received = false;
						do {
							$response = @fread($this->sock, 8192);
							$result = json_array($response);
							if ($result && array_key_exists('id',$result) &&  $result['id']=='register_0' && is_array($result['payload']) && array_key_exists('client-key',$result['payload']))
							{
								$lg_key_received = true;
								$this->lg_key = $result['payload']['client-key'];
								echo "LG Client-Key successfully received: $this->lg_key
"; 
							} else if ($result && array_key_exists('id',$result) &&  $result['id']=='register_0' && array_key_exists('error',$result))
							{
								$error_received = true;
								echo "ERROR: ".$result['error']."
";
							}
							usleep(200000);
							$time = microtime(1);
						} while ($time-$starttime<60 && !$lg_key_received && !$error_received);
					}
				}
			} else echo "ERROR during LG handshake:
";
		} else return FALSE; 
	}

	function disconnect()
	{ 
		$this->connected=false;
		@fclose($this->sock);
		echo "Connection closed to $this->host
";
	}

	function send($msg)
	{
		@fwrite($this->sock, $msg);
		usleep(250000);
		$response = @fread($this->sock, 8192);
		return $response;
	}
	
	function send_command($cmd)
	{
		if (!$this->connected) $this->connect();
		if ($this->connected)
		{
			echo "Sending command      : $cmd
";
			$response = $this->send(hybi10Encode($cmd));
			if ($response)
				echo "Command response     : ".json_string($response)."
";
			else 
				echo "Error sending command: $cmd
";
			return $response;			
		} 
	}
	
	function message($msg)
	{
		$command = "{\"id\":\"message\",\"type\":\"request\",\"uri\":\"ssap://system.notifications/createToast\",\"payload\":{\"message\": \"$msg\"}}";
		$this->send_command($command);
	}
	
	function power_off()
	{
		$command = "{\"id\":\"power_off\",\"type\":\"request\",\"uri\":\"ssap://system/turnOff\"}";
		$this->send_command($command);
	}

	function set_volume($vol)
	{
		$command = "{\"id\":\"set_volume\",\"type\":\"request\",\"uri\":\"ssap://audio/setVolume\",\"payload\":{\"volume\":$vol}}";
		$this->send_command($command);
	}
}	
		
function hybi10Encode($payload, $type = 'text', $masked = true) {
        $frameHead = array();
        $frame = '';
        $payloadLength = strlen($payload);

        switch ($type) {
            case 'text':
                // first byte indicates FIN, Text-Frame (10000001):
                $frameHead[0] = 129;
                break;

            case 'close':
                // first byte indicates FIN, Close Frame(10001000):
                $frameHead[0] = 136;
                break;

            case 'ping':
                // first byte indicates FIN, Ping frame (10001001):
                $frameHead[0] = 137;
                break;

            case 'pong':
                // first byte indicates FIN, Pong frame (10001010):
                $frameHead[0] = 138;
                break;
        }

        // set mask and payload length (using 1, 3 or 9 bytes)
        if ($payloadLength > 65535) {
            $payloadLengthBin = str_split(sprintf('%064b', $payloadLength), 8);
            $frameHead[1] = ($masked === true) ? 255 : 127;
            for ($i = 0; $i < 8; $i++) {
                $frameHead[$i + 2] = bindec($payloadLengthBin[$i]);
            }

            // most significant bit MUST be 0 (close connection if frame too big)
            if ($frameHead[2] > 127) {
                $this->close(1004);
                return false;
            }
        } elseif ($payloadLength > 125) {
            $payloadLengthBin = str_split(sprintf('%016b', $payloadLength), 8);
            $frameHead[1] = ($masked === true) ? 254 : 126;
            $frameHead[2] = bindec($payloadLengthBin[0]);
            $frameHead[3] = bindec($payloadLengthBin[1]);
        } else {
            $frameHead[1] = ($masked === true) ? $payloadLength + 128 : $payloadLength;
        }

        // convert frame-head to string:
        foreach (array_keys($frameHead) as $i) {
            $frameHead[$i] = chr($frameHead[$i]);
        }

        if ($masked === true) {
            // generate a random mask:
            $mask = array();
            for ($i = 0; $i < 4; $i++) {
                $mask[$i] = chr(rand(0, 255));
            }

            $frameHead = array_merge($frameHead, $mask);
        }
        $frame = implode('', $frameHead);
        // append payload to frame:
        for ($i = 0; $i < $payloadLength; $i++) {
            $frame .= ($masked === true) ? $payload[$i] ^ $mask[$i % 4] : $payload[$i];
        }

        return $frame;
    }

    function generateRandomString($length = 10, $addSpaces = true, $addNumbers = true)
	{  
		$characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"§$%&/()=[]{}';
		$useChars = array();
		// select some random chars:    
		for($i = 0; $i < $length; $i++)
		{
			$useChars[] = $characters[mt_rand(0, strlen($characters)-1)];
		}
		// add spaces and numbers:
		if($addSpaces === true)
		{
			array_push($useChars, ' ', ' ', ' ', ' ', ' ', ' ');
		}
		if($addNumbers === true)
		{
			array_push($useChars, rand(0,9), rand(0,9), rand(0,9));
		}
		shuffle($useChars);
		$randomString = trim(implode('', $useChars));
		$randomString = substr($randomString, 0, $length);
		return $randomString;
	}

	function json_array($str)
	{
		$result = json_decode(json_string($str),true);
		return $result;
	}
	
	function json_string($str)
	{
		$from = strpos($str,"{");
		$to = strripos($str,"}");
		$len = $to-$from+1;
		$result = substr($str,$from,$len);
		return $result;
	}
	
?>

und hier das passende Script dafür:

<?php

include_once 'webos.inc.php';
$tv = new webOSTV("192.168.0.200"); // Note the Client Key and put it into next line 
//$tv = new webOSTV("192.168.0.200",3000,"3a91c2ac6c052461bb313724c31b8f37");	// Change to the IP of your LG device
$tv->connect();						// 
$tv->lg_handshake();
$tv->message("YEAH, it works!!!");
sleep (5);
$tv->set_volume(100); 
sleep(10);
$tv->disconnect();

?>

Damit kann man zumindest schon mal die Lautstärke setzen, den Fernseher ausschalten und auch Textnachrichten senden, aber mehr ist damit leider nicht umgesetzt. Evtl. kann das ja jemand erweitern der mehr Plan davon hat als ich :rolleyes: und Dinge verfügbar machen wie Powerstatus (on/off) , Einschalten (geht scheinbar nicht ?), Welcher Eingang ist akiv usw.

Gruß
Jens

Hi,

ich hab einen etwas älteren LG smart TV.
Bisher hab ich keinen Sinn gesehen, diesen per IPS zu steuern, jetzt mit Echo Dot wird es jedoch mmn. interessant.
Werde morgen mal etwas „basteln“ gibt ja eine LG smart TV app, vielleicht bekomme ich was hin.

edit: habe hier was gefunden. https://github.com/SteveWinfield/PHP-LG-SmartTV

Gruß Christoph

hallo,
wenn Du da etwas hinbekommst bin ich sehr interressiert. Ich habe so einen Fernseher, mir fehlt nur das Programmierwissen, um selbst etwas zu stricken.
Gruß
Jürgen

Wie bereits geschrieben funktioniert das Script aus meinem Beitrag und wenn ich mir die Lösung von SteveWinfield ansehe, dann ist das auch nix großartig anderes :frowning:

Scheinbar wird einschalten bzw. die Abfrage vom Powerstatus nicht unterstützt.

Gruß
Jens

Ja, einschalten funktioniert leider nicht.
Ausschalten, umschalten, lautstärke, mute, und alle weiteren Knöpfe der Fernbedienung funktionieren. Habe ich vorhin getestet…

Hi, habe mal etwas geschrieben, funktioniert auch soweit aber habe selbst nicht die großen PHP Kenntnisse.
Daher bitte über die Strukturen etc. hinwegsehen :smiley:

Im LG_Command Skript die IP des TV eintragen. TV einschalten und das Skript einmal ausführen.
Am TV wird der Pairing Key angezeigt, dieser muss dann im Skript eingetragen werden.
Zudem werden Variablen mit Profilen und Ereignisse erstellt.

Gruß Christoph

Skript SmartTV.PHP

<?php
/**
 * ----------------------------------------
 * @title PHP-LG-SmartTV
 * @desc LG SmartTV API
 * @author Steve Winfield
 * @copyright 2014 $AUTHOR$
 * @license see /LICENCE
 * ----------------------------------------
 * https://github.com/SteveWinfield/PHP-LG-SmartTV
**/
if (!extension_loaded('curl')) {
	die ('You have to install/enable curl in order to use this application.');
}
/**
 * Some constants
**/
define ('TV_CMD_POWER', 1);
define ('TV_CMD_NUMBER_0', 2);
define ('TV_CMD_NUMBER_1', 3);
define ('TV_CMD_NUMBER_2', 4);
define ('TV_CMD_NUMBER_3', 5);
define ('TV_CMD_NUMBER_4', 6);
define ('TV_CMD_NUMBER_5', 7);
define ('TV_CMD_NUMBER_6', 8);
define ('TV_CMD_NUMBER_7', 9);
define ('TV_CMD_NUMBER_8', 10);
define ('TV_CMD_NUMBER_9', 11);
define ('TV_CMD_UP', 12);
define ('TV_CMD_DOWN', 13);
define ('TV_CMD_LEFT', 14);
define ('TV_CMD_RIGHT', 15);
define ('TV_CMD_OK', 20);
define ('TV_CMD_HOME_MENU', 21);
define ('TV_CMD_BACK', 23);
define ('TV_CMD_VOLUME_UP', 24);
define ('TV_CMD_VOLUME_DOWN', 25);
define ('TV_CMD_MUTE_TOGGLE', 26);
define ('TV_CMD_CHANNEL_UP', 27);
define ('TV_CMD_CHANNEL_DOWN', 28);
define ('TV_CMD_BLUE', 29);
define ('TV_CMD_GREEN', 30);
define ('TV_CMD_RED', 31);
define ('TV_CMD_YELLOW', 32);
define ('TV_CMD_PLAY', 33);
define ('TV_CMD_PAUSE', 34);
define ('TV_CMD_STOP', 35);
define ('TV_CMD_FAST_FORWARD', 36);
define ('TV_CMD_REWIND', 37);
define ('TV_CMD_SKIP_FORWARD', 38);
define ('TV_CMD_SKIP_BACKWARD', 39);
define ('TV_CMD_RECORD', 40);
define ('TV_CMD_RECORDING_LIST', 41);
define ('TV_CMD_REPEAT', 42);
define ('TV_CMD_LIVE_TV', 43);
define ('TV_CMD_EPG', 44);
define ('TV_CMD_PROGRAM_INFORMATION', 45);
define ('TV_CMD_ASPECT_RATIO', 46);
define ('TV_CMD_EXTERNAL_INPUT', 47);
define ('TV_CMD_PIP_SECONDARY_VIDEO', 48);
define ('TV_CMD_SHOW_SUBTITLE', 49);
define ('TV_CMD_PROGRAM_LIST', 50);
define ('TV_CMD_TELE_TEXT', 51);
define ('TV_CMD_MARK', 52);
define ('TV_CMD_3D_VIDEO', 400);
define ('TV_CMD_3D_LR', 401);
define ('TV_CMD_DASH', 402);
define ('TV_CMD_PREVIOUS_CHANNEL', 403);
define ('TV_CMD_FAVORITE_CHANNEL', 404);
define ('TV_CMD_QUICK_MENU', 405);
define ('TV_CMD_TEXT_OPTION', 406);
define ('TV_CMD_AUDIO_DESCRIPTION', 407);
define ('TV_CMD_ENERGY_SAVING', 409);
define ('TV_CMD_AV_MODE', 410);
define ('TV_CMD_SIMPLINK', 411);
define ('TV_CMD_EXIT', 412);
define ('TV_CMD_RESERVATION_PROGRAM_LIST', 413);
define ('TV_CMD_PIP_CHANNEL_UP', 414);
define ('TV_CMD_PIP_CHANNEL_DOWN', 415);
define ('TV_CMD_SWITCH_VIDEO', 416);
define ('TV_CMD_APPS', 417);
define ('TV_CMD_MOUSE_MOVE', 'HandleTouchMove');
define ('TV_CMD_MOUSE_CLICK', 'HandleTouchClick');
define ('TV_CMD_TOUCH_WHEEL', 'HandleTouchWheel');
define ('TV_CMD_CHANGE_CHANNEL', 'HandleChannelChange');
define ('TV_CMD_SCROLL_UP', 'up');
define ('TV_CMD_SCROLL_DOWN', 'down');
define ('TV_INFO_CURRENT_CHANNEL', 'cur_channel');
define ('TV_INFO_CHANNEL_LIST', 'channel_list');
define ('TV_INFO_CONTEXT_UI', 'context_ui');
define ('TV_INFO_VOLUME', 'volume_info');
define ('TV_INFO_SCREEN', 'screen_image');
define ('TV_INFO_3D', 'is_3d');
define ('TV_LAUNCH_APP', 'AppExecute');
class SmartTV {
	public function __construct($ipAddress, $port = 8080) {
		$this->connectionDetails = array($ipAddress, $port);
	}
	
	public function setPairingKey($pk) {
		$this->pairingKey = $pk;
	}
	
	public function displayPairingKey() {
		$this->sendXMLRequest('/roap/api/auth', self::encodeData(
			array('type' => 'AuthKeyReq'), 'auth'
		));
	}
	
	public function setSession($sess) {
		$this->session = $sess;
	}
	
	public function authenticate() {
		if ($this->pairingKey === null) {
			throw new Exception('No pairing key given.');
		}
		return ($this->session = $this->sendXMLRequest('/roap/api/auth', self::encodeData(
			array(
				'type' => 'AuthReq',
				'value' => $this->pairingKey
			),
			'auth'
		))['session']);
	}
	public function processCommand($commandName, $parameters = []) {
		if ($this->session === null) {
			throw new Exception('No session id given.');
		}
		if (is_numeric($commandName) && count($parameters) < 1) {
			$parameters['value'] = $commandName;
			$commandName = 'HandleKeyInput';
		}
		if (is_string($parameters) || is_numeric($parameters)) {
			$parameters = array('value' => $parameters);
		} elseif (is_object($parameters)) {
			$parameters = (array)$parameters;
		}
		$parameters['name'] = $commandName;
		return ($this->sendXMLRequest('/roap/api/command', 
			self::encodeData($parameters, 'command')
		));
	}
	
	public function queryData($targetId) {
		if ($this->session === null) {
			throw new Exception('No session id given.');
		}
		$var = $this->sendXMLRequest('/roap/api/data?target='.$targetId);
		return isset($var['data']) ? $var['data'] : $var;
	}
	
	private function sendXMLRequest($actionFile, $data = '') {
		curl_setopt(($ch = curl_init()), CURLOPT_URL, $this->connectionDetails[0] . ':' . $this->connectionDetails[1] . $actionFile);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
			'Content-Type: application/atom+xml',
			'Connection: Keep-Alive'
		));
		if (strlen($data) > 0) {
			curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		}
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$envar   = curl_exec($ch);
		$execute = (array)@simplexml_load_string($envar);
		if (isset($execute['ROAPError']) && $execute['ROAPError'] != '200') {
			throw new Exception('Error (' . $execute['ROAPError'] . '): ' . $execute['ROAPErrorDetail']);
		}
		return count($execute) < 2 ? $envar : $execute;
	}
	
	private static function encodeData($data, $actionType, $xml=null) {
		if ($xml == null) {
			$xml = simplexml_load_string("<!--?xml version=\"1.0\" encoding=\"utf-8\"?--><".$actionType." />");
		}
		foreach($data as $key => $value) {
			if (is_array($value))  {
				$node = $xml->addChild($key);
				self::encodeData($value, $actionType, $node);
			} else  {
				$xml->addChild($key, htmlentities($value));
			}
		}
		return $xml->asXML();
	}
	

	private $connectionDetails;
	private $pairingKey;
	private $session;
}

?>

Skript LG_command:

<?
/**
 * ----------------------------------------
 * Example - PHP LG SmartTV API
 * ----------------------------------------
 * https://github.com/SteveWinfield/PHP-LG-SmartTV
**/
include 'smartTV.php';
/**
 * Create instance of TV
 * @param IP Address of TV
 * (optional) @param Port of TV (default is 8080)
**/
$tv = new SmartTV('192.168.0.11'); 												// new SmartTV('192.168.2.103', 8080)
/**
 * Set pairing key (if you don't know the pairing key
 *				    execute the method ..->displayPairingKey() and it will
 * 				    be shown on your tv)
 * @param Key
**/
$tv->setPairingKey(696850);														// $tv->displayPairingKey();
/**
 * Authenticate to the tv
 * @except Login fails (wrong pairing key?)
**/
$setValueID = (40353 /*[Hausautomation\Entertainment\Archiv\LG-TV\SetValue]*/);	//ID von "SetValue" Script"


try {
	$tv->authenticate();
} catch (Exception $e) {
	die('Authentication failed, I am sorry.');
}


//Variablen erstellen
	function CreateVariableByName($id, $name, $type, $profile = "")
	{
	    # type: 0=boolean, 1 = integer, 2 = float, 3 = string;
	    global $IPS_SELF;
	    $vid = @IPS_GetVariableIDByName($name, $id);
	    if($vid === false)
	    {
	        $vid = IPS_CreateVariable($type);
	        IPS_SetParent($vid, $id);
	        IPS_SetName($vid, $name);
	        IPS_SetInfo($vid, "this variable was created by script #$IPS_SELF");
	        if($profile !== "") { IPS_SetVariableCustomProfile($vid, $profile); }
	    }
	    return $vid;
	}

if ($_IPS['SENDER'] == "Execute"){ 

//VariablenProfile erstellen
	IPS_CreateVariableProfile("LG_ChannelList", 1);
	IPS_CreateVariableProfile("LG_ColorButtons", 1);

//Profilparameter
	//LG_ChannelList
	$channels = $tv->queryData(TV_INFO_CHANNEL_LIST);
	$liste=array(); 
	$i=1;
				
	foreach ($channels as $channel) {
	$ChName = $channel->chname;
	settype($ChName,"String");
	IPS_SetVariableProfileAssociation("LG_ChannelList", $i, $ChName,  "", -1);
	$i++;
		If ($i == 33){ 											//max Anzahl an Integer Werte
		break;
		}

	
	}
	//LG_ColorButtons
	IPS_SetVariableProfileAssociation("LG_ColorButtons", 1, ".",  "", 0xFF0000);
	IPS_SetVariableProfileAssociation("LG_ColorButtons", 2, "..",  "", 0x00FF00);
	IPS_SetVariableProfileAssociation("LG_ColorButtons", 3, ":.",  "", 0xFFFF00);
	IPS_SetVariableProfileAssociation("LG_ColorButtons", 4, "::",  "", 0x0000FF);

//Bool Variablen erstellen
	$VariableArrayB = array("bChannelDown", "bChannelUp", "bVolDown", "bVolUp", "bChChange", "bGetChList", "bGetStatus", "bMute", "bPower");
	$Anzahl = count($VariableArrayB);
	$cnt = 0;
	while ($cnt < $Anzahl)
	{
	$VName = $VariableArrayB[$cnt];
	CreateVariableByName($_IPS['SELF'], $VName, 0);
	$IDVariable = @IPS_GetVariableIDByName($VName, $_IPS['SELF']);
	
        $eid = IPS_CreateEvent(0);                          //Ausgelöstes Ereignis
        IPS_SetEventTrigger($eid, 4, $IDVariable);          //Bei Zustand
		IPS_SetEventTriggerValue($eid, true); 				//Nur auf TRUE Werte auslösen
        IPS_SetParent($eid, $_IPS['SELF']);                 //Ereignis zuordnen
        IPS_SetEventActive($eid, true);                     //Ereignis aktivieren
        IPS_SetName($eid,"Trigger");
	$cnt ++;
	}

//Integer Variablen erstellen	
	$VariableArrayI = array("iColorButtons", "iChannel");
	$Anzahl = count($VariableArrayI);
	$cnt = 0;
	while ($cnt < $Anzahl)
	{
	$VName = $VariableArrayI[$cnt];
	CreateVariableByName($_IPS['SELF'], $VName, 1);
	$IDVariable = @IPS_GetVariableIDByName($VName, $_IPS['SELF']);
	
        $eid = IPS_CreateEvent(0);                          //Ausgelöstes Ereignis
        IPS_SetEventTrigger($eid, 2, $IDVariable);          //Bei Grenzüberschreitung
		IPS_SetEventTriggerValue($eid, 0);
        IPS_SetParent($eid, $_IPS['SELF']);                 //Ereignis zuordnen
        IPS_SetEventActive($eid, true);                     //Ereignis aktivieren
        IPS_SetName($eid,"Trigger");
	
	$cnt ++;
	}

//String Variablen erstellen	
	$VariableArrayStr = array("strChannelName");
	$Anzahl = count($VariableArrayStr);
	$cnt = 0;
	while ($cnt < $Anzahl)
	{
	$VName = $VariableArrayStr[$cnt];
	CreateVariableByName($_IPS['SELF'], $VName, 3);
	$IDVariable = @IPS_GetVariableIDByName($VName, $_IPS['SELF']);
	
/*        $eid = IPS_CreateEvent(0);                          //Ausgelöstes Ereignis
        IPS_SetEventTrigger($eid, 1, $IDVariable);          //Bei Variablenänderung
        IPS_SetParent($eid, $_IPS['SELF']);                 //Ereignis zuordnen
        IPS_SetEventActive($eid, true);                     //Ereignis aktivieren
        IPS_SetName($eid,"Trigger");
*/
	$cnt ++; 	
	}
	
//Profile zuordnen
	IPS_SetVariableCustomProfile(@IPS_GetVariableIDByName("iColorButtons",$IPS_SELF), "LG_ColorButtons");
	IPS_SetVariableCustomProfile(@IPS_GetVariableIDByName("iChannel",$IPS_SELF), "LG_ChannelList");
//customAction zuordnen
	IPS_SetVariableCustomAction(@IPS_GetVariableIDByName("iColorButtons",$IPS_SELF), $setValueID);
	IPS_SetVariableCustomAction(@IPS_GetVariableIDByName("iChannel",$IPS_SELF), $setValueID);
}



//zuweisung

$GetStatusID = @IPS_GetVariableIDByName("bGetStatus", $IPS_SELF);  // Status abfragen
$ChannelNameID = @IPS_GetVariableIDByName("strChannelName", $IPS_SELF); // Aktueller Sender
$PowerEventID = @IPS_GetVariableIDByName("bPower",$IPS_SELF);
//$VolumeEventID = @IPS_GetVariableIDByName("iVolume",$IPS_SELF);
$MuteEventID = @IPS_GetVariableIDByName("bMute",$IPS_SELF);
$ChDownEventID = @IPS_GetVariableIDByName("bChannelDown",$IPS_SELF);
$ChUpEventID = @IPS_GetVariableIDByName("bChannelUp",$IPS_SELF);
$ChChangeID = @IPS_GetVariableIDByName("bChChange",$IPS_SELF);
$VolDownEventID = @IPS_GetVariableIDByName("bVolDown",$IPS_SELF);
$VolUpEventID = @IPS_GetVariableIDByName("bVolUp",$IPS_SELF);
$ColorButtonsID = @IPS_GetVariableIDByName("iColorButtons",$IPS_SELF);
$ChannelID = @IPS_GetVariableIDByName("iChannel", $IPS_SELF);

// Steuerung
// Mute (toggle)
if ($_IPS['VARIABLE'] == $MuteEventID)
{
$tv->processCommand(TV_CMD_MUTE_TOGGLE);
}

// Power (1=Ein, 0=Aus) EIN wird nicht unterstützt
if ($_IPS['VARIABLE'] == $PowerEventID)
{
$tv->processCommand(TV_CMD_POWER);
}

// Programm +
if ($_IPS['VARIABLE'] == $ChDownEventID)
{
$tv->processCommand(TV_CMD_CHANNEL_DOWN);
setValue($_IPS['VARIABLE'], false);
}

// Programm -
if ($_IPS['VARIABLE'] == $ChUpEventID)
{
$tv->processCommand(TV_CMD_CHANNEL_UP);
setValue($_IPS['VARIABLE'], false);
}

// Lautstärke +
if ($_IPS['VARIABLE'] == $VolDownEventID)
{
$tv->processCommand(TV_CMD_VOLUME_DOWN);
setValue($_IPS['VARIABLE'], false);
}

// Lautstärke -
if ($_IPS['VARIABLE'] == $VolUpEventID)
{
$tv->processCommand(TV_CMD_VOLUME_UP);
setValue($_IPS['VARIABLE'], false);
}

// Color Buttons
if ($_IPS['VARIABLE'] == $ColorButtonsID)
{
	switch (getValue($_IPS['VARIABLE'])) {
    case 1:
        $tv->processCommand(TV_CMD_RED);
        break;
    case 2:
        $tv->processCommand(TV_CMD_GREEN);
        break;
	case 3:
        $tv->processCommand(TV_CMD_YELLOW);
        break;
    case 4:
        $tv->processCommand(TV_CMD_BLUE);
        break;
	}
setValue($_IPS['VARIABLE'], 0);
}


// Zustandsinformationen
if ($_IPS['VARIABLE'] == $GetStatusID)
{
/*
// Get current volume
	$dummy = $tv->queryData(TV_INFO_VOLUME)->level;
	settype($dummy,"Integer");
	setValue($VolumeEventID, $dummy);
*/	

// Get current channel Nr.
	$dummy = ($tv->queryData(TV_INFO_CURRENT_CHANNEL)->major);
	settype($dummy,"Integer");
	setValue($ChannelID, $dummy);

// Get current channel name
	$dummy = ($tv->queryData(TV_INFO_CURRENT_CHANNEL)->chname);
	settype($dummy,"String");
	setValue($ChannelNameID, $dummy);

setValue($_IPS['VARIABLE'], false);
}

//Auf Programm schalten
if ($_IPS['VARIABLE'] == $ChannelID)
{
	$channels    = $tv->queryData(TV_INFO_CHANNEL_LIST);

	// Search for channel $channelName
	foreach ($channels as $channel) {
		if ($channel->major == GetValue($ChannelID)) {
			// Change channel
			$tv->processCommand(TV_CMD_CHANGE_CHANNEL, $channel);
			break;
		}
	}
setValue($_IPS['VARIABLE'], false);
}


?>

SetValue aktion

<?

 SetValue($_IPS['VARIABLE'], $_IPS['VALUE']);

?>

ich bekomme es nicht hin.

Warning: include(SmartTV): failed to open stream: No such file or directory in C:\IP-Symcon\scripts\39505.ips.php on line 8

Warning: include(): Failed opening ‚SmartTV‘ for inclusion (include_path=’.;C:\php\pear’) in C:\IP-Symcon\scripts\39505.ips.php on line 8

Fatal error: Class ‚SmartTV‘ not found in C:\IP-Symcon\scripts\39505.ips.php on line 14

Scripts sind angelegt… hat jemand eine Idee ?

Hast du das Skript als „SmartTV.PHP“ benannt?

Hallo,
habe das gleiche Problem. Ich glaube, das liegt an dem include-Kommando. Irgendwo hatte ich schon mal was ähnliches, kriegs aber nicht mehr zusammen.
Gruß
Jürgen

ja, anbei mal ein paar Bilder


Aktuell sieht es so aus, klappt aber noch nicht.



<? 
/** 
 * ---------------------------------------- 
 * Example - PHP LG SmartTV API 
 * ---------------------------------------- 
 * https://github.com/SteveWinfield/PHP-LG-SmartTV 
**/ 
include smartTV.php; 
/** 
 * Create instance of TV 
 * @param IP Address of TV 
 * (optional) @param Port of TV (default is 8080) 
**/ 
$tv = new SmartTV('192.168.1.45', 8080);                                                 // new SmartTV('192.168.2.103', 8080) 
/** 
 * Set pairing key (if you don't know the pairing key 
 *                    execute the method ..->displayPairingKey() and it will 
 *                     be shown on your tv) 
 * @param Key 
**/ 
$tv->setPairingKey(696850);                                                        // $tv->displayPairingKey(); 
/** 
 * Authenticate to the tv 
 * @except Login fails (wrong pairing key?) 
**/ 
$setValueID = (58369 /*[Hausautomation\Entertainment\Archiv\LG-TV\SetValue]*/);    //ID von "SetValue" Script" 



Das ist der output:

Notice: Use of undefined constant smartTV - assumed ‚smartTV‘ in C:\IP-Symcon\scripts\39505.ips.php on line 8

Notice: Use of undefined constant php - assumed ‚php‘ in C:\IP-Symcon\scripts\39505.ips.php on line 8

Warning: include(smartTVphp): failed to open stream: No such file or directory in C:\IP-Symcon\scripts\39505.ips.php on line 8

Warning: include(): Failed opening ‚smartTVphp‘ for inclusion (include_path=’.;C:\php\pear’) in C:\IP-Symcon\scripts\39505.ips.php on line 8

Fatal error: Class ‚SmartTV‘ not found in C:\IP-Symcon\scripts\39505.ips.php on line 14

Der include Befehl erwartet einen String. Versuch es mal mit ““.

Gruß

Burkhard

klappt leider nicht.


include smartTV.php; 
/** 
 * Create instance of TV 
 * @param IP Address of TV 
 * (optional) @param Port of TV (default is 8080) 
**/ 
$tv = new SmartTV("192.168.1.45", 8080);                                                 // new SmartTV('192.168.2.103', 8080) 
/** 
 * Set pairing key (if you don't know the pairing key 
 *                    execute the method ..->displayPairingKey() and it will 
 *                     be shown on your tv) 
 * @param Key 

Notice: Use of undefined constant smartTV - assumed ‚smartTV‘ in C:\IP-Symcon\scripts\39505.ips.php on line 8

Notice: Use of undefined constant php - assumed ‚php‘ in C:\IP-Symcon\scripts\39505.ips.php on line 8

Warning: include(smartTVphp): failed to open stream: No such file or directory in C:\IP-Symcon\scripts\39505.ips.php on line 8

Warning: include(): Failed opening ‚smartTVphp‘ for inclusion (include_path=’.;C:\php\pear’) in C:\IP-Symcon\scripts\39505.ips.php on line 8

Fatal error: Class ‚SmartTV‘ not found in C:\IP-Symcon\scripts\39505.ips.php on line 14

Wo liegt denn die „smartTV.php“? Sie muss im scripts Ordner liegen. Wie die Fehlermeldung sagt kann die Datei nicht gefunden/geöffnet werden. In deinem Listing fehlen aber weiterhin die Anführungszeichen.

ok bin einen schritt weiter. Lag tatsächlich daran das es nicht im script Ordner lag.


<? 
/** 
 * ---------------------------------------- 
 * Example - PHP LG SmartTV API 
 * ---------------------------------------- 
 * https://github.com/SteveWinfield/PHP-LG-SmartTV 
**/ 
include "smartTV.php"; 
/** 
 * Create instance of TV 
 * @param IP Address of TV 
 * (optional) @param Port of TV (default is 8080) 
**/ 
$tv = new SmartTV('192.168.1.45', 8080);                                                 // new SmartTV('192.168.2.103', 8080) 
/** 
 * Set pairing key (if you don't know the pairing key 
 *                    execute the method ..->displayPairingKey() and it will 
 *                     be shown on your tv) 
 * @param Key 
**/ 
$tv->setPairingKey(696850);                                                        // $tv->displayPairingKey(); 
/** 
 * Authenticate to the tv 
 * @except Login fails (wrong pairing key?) 
**/ 
$setValueID = (58369 /*[WZ & EZ\LG OLED65B6D\setValue]*/);    //ID von "SetValue" Script" 


jetzt kommt folgende Fehlermeldung:

Fatal error: Call to undefined function extension_loaaded() in C:\IP-Symcon\scripts\smartTV.php on line 12

scheint wohl an curl zu liegen. Wie enable oder installiere ich das ?

Das ist Zeile 12.


if (!extension_loaded('curl')) { 
    die ('You have to install/enable curl in order to use this application.'); 
} 

Curl ist bei der win Variante ips immer dabei.habe grad nen oled Lg bekommen und getestet aber keine Chance. Das könnt ihr knicken… der Zugriff in der Art läuft max mit ganz alten Modellen wie eben 2012 oder 13

Gesendet von iPhone mit Tapatalk

sicher das es nicht geht ? Das war eigentlich mein Plan. LG OLES65B6D ansteuern… das wäre ja doof wenn es nicht klappt. Webos 3.5 ist da ja drauf.