Serengeti
Anmeldungsdatum: 24. Februar 2008
Beiträge: 1927
|
Diese Script (https://github.com/eclair4151/SmartCrypto) erlaubt es mir den TV per Konsole zu steuern.
Beim Ausführen dieses Scriptes erhalte ich alle Daten um mich mit dem TV verbinden zu können (ctx und sessionid)
Anschliessend beweisst mir das Script, dass es funktioniert indem es die Lautstärke reduziert. Wie kann ich nun aber mit den Angaben den TV umschalten ohne dass der TV nun jedes Mal ein neues Pairing macht?
am liebsten wäre es ich könnte das Script mit Argumenten öffnen bsp. python script KEY_VOLDOWN 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143 | from __future__ import print_function
import crypto
import sys
import re
from command_encryption import AESCipher
import requests
import time
import websocket
UserId = "654321"
AppId = "12345"
deviceId = "7e509404-9e7c-46a4-8f6f-e2a9668ad184"
tvIP = "192.168.12.20"
tvPort = "8080"
ctx = "60141f3934272db1d3536c7833d2c2aa"
session_id = "2"
lastRequestId = 0
def getFullUrl(urlPath):
global tvIP, tvPort
return "http://"+tvIP+":"+tvPort+urlPath
def GetFullRequestUri(step, appId, deviceId):
return getFullUrl("/ws/pairing?step="+str(step)+"&app_id="+appId+"&device_id="+deviceId)
def ShowPinPageOnTv():
requests.post(getFullUrl("/ws/apps/CloudPINPage"), "pin4")
def CheckPinPageOnTv():
full_url = getFullUrl("/ws/apps/CloudPINPage")
page = requests.get(full_url).text
output = re.search('state>([^<>]*)</state>', page, flags=re.IGNORECASE)
if output is not None:
state = output.group(1)
print("Current state: "+state)
if state == "stopped":
return True
return False
def FirstStepOfPairing():
global AppId, deviceId;
firstStepURL = GetFullRequestUri(0,AppId, deviceId)+"&type=1"
firstStepResponse = requests.get(firstStepURL).text
def StartPairing():
global lastRequestId
lastRequestId=0
if CheckPinPageOnTv():
print("Pin NOT on TV")
ShowPinPageOnTv()
else:
print("Pin ON TV");
def HelloExchange(pin):
global AppId, deviceId, lastRequestId, UserId
hello_output = crypto.generateServerHello(UserId,pin)
if not hello_output:
return False
content = "{\"auth_Data\":{\"auth_type\":\"SPC\",\"GeneratorServerHello\":\"" + hello_output['serverHello'].hex().upper() + "\"}}"
secondStepURL = GetFullRequestUri(1, AppId, deviceId)
secondStepResponse = requests.post(secondStepURL, content).text
print('secondStepResponse: ' + secondStepResponse)
output = re.search('request_id.*?(\d).*?GeneratorClientHello.*?:.*?(\d[0-9a-zA-Z]*)', secondStepResponse, flags=re.IGNORECASE)
if output is None:
return False
requestId = output.group(1)
clientHello = output.group(2)
lastRequestId = int(requestId)
return crypto.parseClientHello(clientHello, hello_output['hash'], hello_output['AES_key'], UserId)
def AcknowledgeExchange(SKPrime):
global lastRequestId, AppId, deviceId;
serverAckMessage = crypto.generateServerAcknowledge(SKPrime)
content="{\"auth_Data\":{\"auth_type\":\"SPC\",\"request_id\":\"" + str(lastRequestId) + "\",\"ServerAckMsg\":\"" + serverAckMessage + "\"}}"
thirdStepURL = GetFullRequestUri(2, AppId, deviceId)
thirdStepResponse = requests.post(thirdStepURL, content).text
if "secure-mode" in thirdStepResponse:
print("TODO: Implement handling of encryption flag!!!!")
sys.exit(-1)
output = re.search('ClientAckMsg.*?:.*?(\d[0-9a-zA-Z]*).*?session_id.*?(\d)', thirdStepResponse, flags=re.IGNORECASE)
if output is None:
print("Unable to get session_id and/or ClientAckMsg!!!");
sys.exit(-1)
clientAck = output.group(1)
if not crypto.parseClientAcknowledge(clientAck, SKPrime):
print("Parse client ac message failed.")
sys.exit(-1)
sessionId=output.group(2)
print("sessionId: "+sessionId)
return sessionId
def ClosePinPageOnTv():
full_url = getFullUrl("/ws/apps/CloudPINPage/run");
requests.delete(full_url)
return False
def send_command(session_id, ctx, key_command):
ctx = ctx.upper()
millis = int(round(time.time() * 1000))
step4_url = 'http://' + tvIP + ':8000/socket.io/1/?t=' + str(millis)
websocket_response = requests.get(step4_url)
websocket_url = 'ws://' + tvIP + ':8000/socket.io/1/websocket/' + websocket_response.text.split(':')[0]
print(websocket_url)
aesLib = AESCipher(ctx, session_id)
connection = websocket.create_connection(websocket_url)
time.sleep(0.35)
# need sleeps cuz if you send commands to quick it fails
connection.send('1::/com.samsung.companion')
# pairs to this app with this command.
time.sleep(0.35)
connection.send(aesLib.generate_command(key_command))
time.sleep(0.35)
connection.close()
StartPairing()
ctx = False
SKPrime = False
while not ctx:
tvPIN = input("Please enter pin from tv: ")
print("Got pin: '"+tvPIN+"'\n")
FirstStepOfPairing()
output = HelloExchange(tvPIN)
if output:
ctx = output['ctx'].hex()
SKPrime = output['SKPrime']
print("ctx: " + ctx)
print("Pin accepted :)\n")
else:
print("Pin incorrect. Please try again...\n")
currentSessionId = AcknowledgeExchange(SKPrime)
print("SessionID: " + str(currentSessionId))
ClosePinPageOnTv()
print("Authorization successfull :)\n")
print('Attempting to send command to tv')
send_command(currentSessionId, ctx, 'KEY_VOLDOWN')
|
|
NORACSA
Anmeldungsdatum: 31. Januar 2010
Beiträge: 180
|
Doc_Symbiosis schrieb: Du musst dann halt die Verwendung von Parametern einbauen: https://www.python-kurs.eu/parameter.php
Spezifisch ist von dieser Seite das "Kapitel" "Übergabe von Argumenten" wichtig!
|
Serengeti
(Themenstarter)
Anmeldungsdatum: 24. Februar 2008
Beiträge: 1927
|
Danke sehr.
Das funktioniert jetzt recht gut Ich habe nur noch ein Problem.
Zwischen dem Einschalten des TV gerätes und der ersten erfolgreichen übertragung dauert es etwa 1min.
Dazwischen erhalte ich diese Fehlermeldung
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62 | Attempting to send command KEY_VOLDOWN to tv
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/urllib3/connection.py", line 159, in _new_conn
(self._dns_host, self.port), self.timeout, **extra_kw)
File "/usr/lib/python3/dist-packages/urllib3/util/connection.py", line 80, in create_connection
raise err
File "/usr/lib/python3/dist-packages/urllib3/util/connection.py", line 70, in create_connection
sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 600, in urlopen
chunked=chunked)
File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 354, in _make_request
conn.request(method, url, **httplib_request_kw)
File "/usr/lib/python3.7/http/client.py", line 1244, in request
self._send_request(method, url, body, headers, encode_chunked)
File "/usr/lib/python3.7/http/client.py", line 1290, in _send_request
self.endheaders(body, encode_chunked=encode_chunked)
File "/usr/lib/python3.7/http/client.py", line 1239, in endheaders
self._send_output(message_body, encode_chunked=encode_chunked)
File "/usr/lib/python3.7/http/client.py", line 1026, in _send_output
self.send(msg)
File "/usr/lib/python3.7/http/client.py", line 966, in send
self.connect()
File "/usr/lib/python3/dist-packages/urllib3/connection.py", line 181, in connect
conn = self._new_conn()
File "/usr/lib/python3/dist-packages/urllib3/connection.py", line 168, in _new_conn
self, "Failed to establish a new connection: %s" % e)
urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPConnection object at 0x75e79b90>: Failed to establish a new connection: [Errno 111] Connection refused
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/requests/adapters.py", line 449, in send
timeout=timeout
File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 638, in urlopen
_stacktrace=sys.exc_info()[2])
File "/usr/lib/python3/dist-packages/urllib3/util/retry.py", line 398, in increment
raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='192.168.1.220', port=8000): Max retries exceeded with url: /socket.io/1/?t=1593243626782 (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x75e79b90>: Failed to establish a new connection: [Errno 111] Connection refused'))
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/pi/SmartCrypto/PySmartCrypto/tv.py", line 50, in <module>
send_command(session_id, ctx, args.key)
File "/home/pi/SmartCrypto/PySmartCrypto/tv.py", line 31, in send_command
websocket_response = requests.get(step4_url)
File "/usr/lib/python3/dist-packages/requests/api.py", line 75, in get
return request('get', url, params=params, **kwargs)
File "/usr/lib/python3/dist-packages/requests/api.py", line 60, in request
return session.request(method=method, url=url, **kwargs)
File "/usr/lib/python3/dist-packages/requests/sessions.py", line 533, in request
resp = self.send(prep, **send_kwargs)
File "/usr/lib/python3/dist-packages/requests/sessions.py", line 646, in send
r = adapter.send(request, **kwargs)
File "/usr/lib/python3/dist-packages/requests/adapters.py", line 516, in send
raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPConnectionPool(host='192.168.12.20', port=8000): Max retries exceeded with url: /socket.io/1/?t=1593243626782 (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x75e79b90>: Failed to establish a new connection: [Errno 111] Connection refused'))
|
Am liebsten wäre mir einfach das script würde warten bis es den Tastendruck übergeben kann. Oder es sagt mir einfach dass ich noch warten soll.
|
Serengeti
(Themenstarter)
Anmeldungsdatum: 24. Februar 2008
Beiträge: 1927
|
Also das hat jetzt sowas von gar nicht funktioniert. Egal welche Variante ich da ausprobiert habe, das Script ist nicht mehr durchgelaufen. Ich lasse es nun so wie es ist, ich kann mit den Fehlermeldungen leben. Danke für die Unterstützung
|
snafu1
Anmeldungsdatum: 5. September 2007
Beiträge: 2123
Wohnort: Gelsenkirchen
|
Serengeti schrieb: Zwischen dem Einschalten des TV gerätes und der ersten erfolgreichen übertragung dauert es etwa 1min.
Dazwischen erhalte ich diese Fehlermeldung
Die Fehlermeldungen deuten darauf hin, dass das Gerät nicht sofort nach dem Einschalten bereit für eine Verbindung ist. Als Lösung kannst du ihn entweder diese eine Minute warten lassen mit sleep() oder die Anzahl der Verbindungsversuche deutlich erhöhen. Bei der zweiten Variante versucht er es halt etliche Male bis irgendwann eine Verbindung zustande kommt, während er bei deiner ersten Variante möglicherweise unnötig lange wartet.
|