Page 2 of 2

Re: LG TV via LAN

Posted: Tue Feb 03, 2015 6:23 pm
by mrdavisma
Hi Sem;colon

Thanks for your input on this. After comparing the lgcommander script and this one I had noticed there where some lines missing in the handleCommand. I had been attempting to add them myself but ended up with syntax errors aplenty lol ( I think I will have to buy python for noobs to read on my lunch breaks at work! )

Anyway the downside is after adding your corrected code I am still not getting a response. As before the script is returning a session ID so we know it is communicating with the tv but nothing happen after that, no action on tv nor an error in eg
With my limited experience I even tried changing the handlecommand to be the same as requested here ... yInput.htm

Code: Select all

    <api type="command">
        <value>Value key code of remote Controller</value>
but again no errors nor any action. At least when there were errors I had something to google lol

If you have anymore ideas it would be great but i also understand that as you dont have a tv to test this on it is not easy.


Re: LG TV via LAN

Posted: Tue Feb 03, 2015 8:59 pm
by Sem;colon
hmm, pls try this:

Code: Select all

    import httplib
    import xml.etree.ElementTree as etree
    import socket
    import re
    lgtv = {}
    dialogMsg =""
    headers = {"Content-Type": "application/atom+xml"}

    lgtv["pairingKey"] = "939781"
    #lgtv["ipaddress"] = ""
    lgtv["port"] = 8080


    def getip():
        strngtoXmit =   'M-SEARCH * HTTP/1.1' + '\r\n' + \
                        'HOST:'  + '\r\n' + \
                        'MAN: "ssdp:discover"'  + '\r\n' + \
                        'MX: 2'  + '\r\n' + \
                        'ST: urn:schemas-upnp-org:device:MediaRenderer:1'  + '\r\n' +  '\r\n'
        bytestoXmit = strngtoXmit.encode()
        sock = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
        found = False
        gotstr = 'notyet'
        i = 0
        ipaddress = None
        sock.sendto( bytestoXmit,  ('', 1900 ) )
        while not found and i <= 5 and gotstr == 'notyet':
                gotbytes, addressport = sock.recvfrom(512)
                gotstr = gotbytes.decode()
                i += 1
                sock.sendto( bytestoXmit, ( '', 1900 ) )
            if'LG', gotstr):
                ipaddress, _ = addressport
                found = True
                gotstr = 'notyet'
            i += 1
        if not found :
            print "Lg TV not found"
        return ipaddress

    def displayKey():
        conn = httplib.HTTPConnection( lgtv["ipaddress"], port=lgtv["port"])
        reqKey = "<!--?xml version=\"1.0\" encoding=\"utf-8\"?--><auth><type>AuthKeyReq</type></auth>"
        conn.request("POST", "/roap/api/auth", reqKey, headers=headers)
        httpResponse = conn.getresponse()
        if httpResponse.reason != "OK" :
            print "LG TV: Network error"
        return httpResponse.reason
    def getSessionid():
        conn = httplib.HTTPConnection( lgtv["ipaddress"], port=lgtv["port"])
        pairCmd = "<!--?xml version=\"1.0\" encoding=\"utf-8\"?--><auth><type>AuthReq</type><value>" + lgtv["pairingKey"] + "</value></auth>"
        conn.request("POST", "/roap/api/auth", pairCmd, headers=headers)
        httpResponse = conn.getresponse()
        if httpResponse.reason != "OK" :
            return httpResponse.reason
        tree = etree.XML(
        return tree.find('session').text
    def getPairingKey():
    def handleCommand(cmdcode):
        conn = httplib.HTTPConnection( lgtv["ipaddress"], port=lgtv["port"])
        cmdText = "<!--?xml version=\"1.0\" encoding=\"utf-8\"?--><command><name>HandleKeyInput</name><value>"+cmdcode+"</value></command>"
        conn.request("POST", "/roap/api/command", cmdText, headers=headers)
        httpResponse = conn.getresponse()
    lgtv["ipaddress"] = getip()
    print "LG TV IP: "+lgtv["ipaddress"]
    theSessionid = getSessionid()
    while theSessionid == "Unauthorized" :
        theSessionid = getSessionid()
    if len(theSessionid) < 8 :
        print "LG TV: Could not get Session Id: " + theSessionid
    lgtv["session"] = theSessionid
    result = command

Re: LG TV via LAN

Posted: Wed Feb 04, 2015 5:05 am
by mrdavisma
That's it!

Wow you swapped a couple of words around on the cmdText line and suddenly it all works! Thank you very much Sem;colon for taking the time to look into this and get it working. I had looked for sometime for a way to do this but only ever found dead ends.

I have decided it it finally time to have ago at learning python, I enjoy reading through trying to work out what does what in a script but I would like to be able to have a go at being able to right it now.
If I get any good maybe I will be able to turn this into a plug-in lol

Thank You


Re: LG TV via LAN

Posted: Wed Feb 04, 2015 11:00 am
by Sem;colon
You're welcome!
maybe I will be able to turn this into a plug-in
It's quite simple to trun this script into a plugin, so that would be a nice beginner work I guess :)

Re: LG TV via LAN

Posted: Thu Feb 12, 2015 12:08 pm
by mrdavisma
Well just an update. I guess I wont be turning this into a plug in for the simple reason, there is one available already!!!! and it works very well
After weeks of searching for a solution I never once found this thread. I just happened to chance upon it today while browsing the forum.

I am guessing the forums are not getting indexed very well by google as even doing a search for the thread title + eventghost does not bring up the thread!


Re: LG TV via LAN

Posted: Wed Jul 29, 2015 7:53 pm
by nosehook
I have a Panasocnic viera at home that I have connected to my LAN at home. Would this script work too or do I need something else?

Re: LG TV via LAN

Posted: Sun Dec 06, 2015 6:48 pm
by tricky1024
Has anyone tried to control a 2015 WEBOS LG TV?, I need to turn off the TV over WIFI as CEC does not support this feature.

I have tried this script but looks like WEBOS is different, I have looked at: but am no programmer.

Any help would be great.

Re: LG TV via LAN

Posted: Tue Aug 16, 2016 3:25 pm
by Jefman

I also have a LG of 2015 model (DTV55UF772V) I have tried above python script but get the following when pressing apply:

Python Script
Error compiling script.
Traceback (most recent call last):
IndentationError: unexpected indent (4, line 1)
Error compiling script.
Traceback (most recent call last):
IndentationError: unexpected indent (5, line 1)

When trying the plugin here:

I get this long error message :

Error in Action: "LG-TV 2012 IP: Send Key From List: 4 - Number 2"
Traceback (most recent call last) (1722):
File "C:\Program Files (x86)\EventGhost\eg\Classes\", line 170, in CallWrapper
return self(*args)
File "C:\Program Files (x86)\EventGhost\plugins\LG-2012-IP\", line 245, in __call__
File "C:\Program Files (x86)\EventGhost\plugins\LG-2012-IP\", line 214, in sendCommand
theSessionid = getSessionid()
File "C:\Program Files (x86)\EventGhost\plugins\LG-2012-IP\", line 191, in getSessionid
conn.request("POST", "/roap/api/auth", pairCmd, headers=headers)
File "httplib.pyc", line 910, in request
File "httplib.pyc", line 947, in _send_request
File "httplib.pyc", line 904, in endheaders
File "httplib.pyc", line 776, in _send_output
File "httplib.pyc", line 735, in send
File "httplib.pyc", line 716, in connect
File "socket.pyc", line 514, in create_connection
error: [Errno 10061] No connection could be made because the target machine actively refused it

It seems to me that this has todo with pairing....

Any ideas ?