-
Notifications
You must be signed in to change notification settings - Fork 0
/
locate.py
78 lines (61 loc) · 2.09 KB
/
locate.py
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
import socket
import re
from utils import update_config
from functools import wraps
import signal
"""
Module for locating roku device and saving device stats to redis store
"""
# raises TimeoutError after user specified timeout
class TimeoutError(Exception): pass
def timeout(seconds, error_message = 'Function call timed out'):
def decorated(func):
def _handle_timeout(signum, frame):
raise TimeoutError(error_message)
def wrapper(*args, **kwargs):
signal.signal(signal.SIGALRM, _handle_timeout)
signal.alarm(seconds)
try:
result = func(*args, **kwargs)
finally:
signal.alarm(0)
return result
return wraps(func)(wrapper)
return decorated
############ Locate Roku Devices #################
# @timeout(10)
def locate_device():
ssdpRequest = "M-SEARCH * HTTP/1.1\r\n" + \
"HOST: 239.255.255.250:1900\r\n" + \
"Man: \"ssdp:discover\"\r\n" + \
"MX: 5\r\n" + \
"ST: roku:ecp\r\n\r\n"
socket.setdefaulttimeout(10)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
sock.sendto(ssdpRequest, ("239.255.255.250", 1900))
msg = {
'success': False,
'data': None
}
while True:
try:
resp = sock.recv(1024)
match = re.match(r'.*USN: uuid:roku:ecp:([\w\d]{12}).*LOCATION: http://([\d\.]*):(\d*)', resp, re.S)
host = match.group(2)
port = match.group(3)
# update config
update_config({'host': host, 'port': int(port), 'connected': 1})
# update resp
msg.update({'success': True, 'data': resp})
break
except socket.timeout:
update_config({'connected': 0})
continue
except KeyboardInterrupt:
print 'Exiting...'
break
return msg
if __name__ == '__main__':
locate_device()