Restore seriesTitle checking for push.
[pyTivo/wmcbrine.git] / beacon.py
blobee6e64a58c9e8d595922cc1c531181fc28474543
1 import re
2 import struct
3 from socket import *
4 from threading import Timer
6 import config
8 class Beacon:
10 UDPSock = socket(AF_INET, SOCK_DGRAM)
11 UDPSock.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
12 services = []
14 def add_service(self, service):
15 self.services.append(service)
16 self.send_beacon()
18 def format_services(self):
19 return ';'.join(self.services)
21 def format_beacon(self, conntype, services=True):
22 beacon = ['tivoconnect=1',
23 'swversion=1',
24 'method=%s' % conntype,
25 'identity=%s' % config.getGUID(),
26 'machine=%s' % gethostname(),
27 'platform=pc']
29 if services:
30 beacon.append('services=' + self.format_services())
31 else:
32 beacon.append('services=TiVoMediaServer:0/http')
34 return '\n'.join(beacon)
36 def send_beacon(self):
37 beacon_ips = config.getBeaconAddresses()
38 for beacon_ip in beacon_ips.split():
39 if beacon_ip != 'listen':
40 try:
41 self.UDPSock.sendto(self.format_beacon('broadcast'),
42 (beacon_ip, 2190))
43 except error, e:
44 print e
46 def start(self):
47 self.send_beacon()
48 self.timer = Timer(60, self.start)
49 self.timer.start()
51 def stop(self):
52 self.timer.cancel()
54 def listen(self):
55 """ For the direct-connect, TCP-style beacon """
56 import thread
58 def server():
59 TCPSock = socket(AF_INET, SOCK_STREAM)
60 TCPSock.bind(('', 2190))
61 TCPSock.listen(5)
63 while True:
64 # Wait for a connection
65 client, address = TCPSock.accept()
67 # Accept the client's beacon
68 client_length = struct.unpack('!I', client.recv(4))[0]
69 client_message = client.recv(client_length)
71 # Send ours
72 message = self.format_beacon('connected')
73 client.send(struct.pack('!I', len(message)))
74 client.send(message)
75 client.close()
77 thread.start_new_thread(server, ())
79 def get_name(self, address):
80 """ Exchange beacons, and extract the machine name. """
81 our_beacon = self.format_beacon('connected', False)
82 machine_name = re.compile('machine=(.*)\n').search
84 try:
85 tsock = socket()
86 tsock.connect((address, 2190))
88 tsock.send(struct.pack('!I', len(our_beacon)))
89 tsock.send(our_beacon)
91 length = struct.unpack('!I', tsock.recv(4))[0]
92 tivo_beacon = tsock.recv(length)
94 tsock.close()
96 name = machine_name(tivo_beacon).groups()[0]
97 except:
98 name = address
100 return name
102 if __name__ == '__main__':
103 b = Beacon()
105 b.add_service('TiVoMediaServer:9032/http')
106 b.send_beacon()