Created
January 28, 2019 16:07
-
-
Save zhsj/a1b1704fdf7148e07730790b0a59705b to your computer and use it in GitHub Desktop.
play url on tv
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
from contextlib import contextmanager | |
import re | |
import select | |
import socket | |
import sys | |
import urllib.request | |
@contextmanager | |
def send_udp(_from, to, packet): | |
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) | |
sock.bind(_from) | |
sock.sendto(packet.encode(), to) | |
yield sock | |
sock.close() | |
def discover(): | |
payload = "\r\n".join([ | |
'M-SEARCH * HTTP/1.1', | |
'User-Agent: TestProgram/0.1', | |
'HOST: 239.255.255.250:1900', | |
'Accept: */*', | |
'MAN: "ssdp:discover"', | |
'ST: urn:schemas-upnp-org:service:AVTransport:1', | |
'MX: 3', | |
'', | |
'']) | |
_from = ("192.168.1.101", 0) | |
to = ("239.255.255.250", 1900) | |
with send_udp(_from, to, payload) as s: | |
while True: | |
r, w, x = select.select([s], [], [s], 1) | |
if s in r: | |
data, addr = s.recvfrom(1024) | |
addr = re.search('(http://[^/]*/)', data.decode()).group(1) | |
return addr | |
def set_uri(uri, device): | |
payload = ''.join([ | |
"<?xml version='1.0' encoding='utf-8'?>", | |
'<SOAP-ENV:Envelope ' | |
'xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" ' | |
'SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">', | |
'<SOAP-ENV:Body>', | |
'<m:SetAVTransportURI ' | |
'xmlns:m="urn:schemas-upnp-org:service:AVTransport:1">', | |
'<InstanceID>0</InstanceID>', | |
'<CurrentURI>{}</CurrentURI>'.format(uri), | |
'<CurrentURIMetaData></CurrentURIMetaData>', | |
'</m:SetAVTransportURI>', | |
'</SOAP-ENV:Body>', | |
'</SOAP-ENV:Envelope>' | |
]).encode() | |
headers = { | |
'SOAPAction': '"urn:schemas-upnp-org:service:' | |
'AVTransport:1#SetAVTransportURI"', | |
'Content-Type': 'text/xml' | |
} | |
device_addr = device + '_urn:schemas-upnp-org:service:AVTransport_control' | |
req = urllib.request.Request(device_addr, data=payload, headers=headers) | |
resp = urllib.request.urlopen(req) | |
print('Server response code:', resp.getcode()) | |
if __name__ == '__main__': | |
uri = 'http://192.168.1.101:2015/t1/index.m3u8' | |
if len(sys.argv) == 2: | |
uri = sys.argv[1] | |
device = discover() | |
set_uri(uri, device) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment