Adding the webvideo plugin.
[pyTivo.git] / beacon.py
blobc32251485f2ba743b8e13a964fc11b75a5274cc4
1 from socket import *
2 from threading import Timer
3 import config
5 class Beacon:
7 UDPSock = socket(AF_INET, SOCK_DGRAM)
8 UDPSock.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
9 services = []
11 def add_service(self, service):
12 self.services.append(service)
13 self.send_beacon()
15 def format_services(self):
16 return ';'.join(self.services)
18 def format_beacon(self, conntype):
19 beacon = []
21 guid = config.getGUID()
23 beacon.append('tivoconnect=1')
24 beacon.append('swversion=1')
25 beacon.append('method=%s' % conntype)
26 beacon.append('identity=%s' % guid)
28 beacon.append('machine=%s' % gethostname())
29 beacon.append('platform=pc')
30 beacon.append('services=' + self.format_services())
32 return '\n'.join(beacon)
34 def send_beacon(self):
35 beacon_ips = config.getBeaconAddresses()
36 for beacon_ip in beacon_ips.split():
37 if beacon_ip != 'listen':
38 try:
39 self.UDPSock.sendto(self.format_beacon('broadcast'),
40 (beacon_ip, 2190))
41 except error, e:
42 print e
44 def start(self):
45 self.send_beacon()
46 self.timer = Timer(60, self.start)
47 self.timer.start()
49 def stop(self):
50 self.timer.cancel()
52 def listen(self):
53 """For the direct-connect, TCP-style beacon"""
54 import thread
56 def server():
57 import struct
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 print client_length
73 # Send ours
74 message = self.format_beacon('connected')
75 client.send(struct.pack('!I', len(message)))
76 client.send(message)
77 client.close()
79 thread.start_new_thread(server, ())
81 if __name__ == '__main__':
82 b = Beacon()
84 b.add_service('TiVoMediaServer:9032/http')
85 b.send_beacon()