4 from threading
import Timer
10 UDPSock
= socket(AF_INET
, SOCK_DGRAM
)
11 UDPSock
.setsockopt(SOL_SOCKET
, SO_BROADCAST
, 1)
14 def add_service(self
, service
):
15 self
.services
.append(service
)
18 def format_services(self
):
19 return ';'.join(self
.services
)
21 def format_beacon(self
, conntype
, services
=True):
22 beacon
= ['tivoconnect=1',
24 'method=%s' % conntype
,
25 'identity=%s' % config
.getGUID(),
26 'machine=%s' % gethostname(),
30 beacon
.append('services=' + self
.format_services())
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':
41 self
.UDPSock
.sendto(self
.format_beacon('broadcast'),
48 self
.timer
= Timer(60, self
.start
)
55 """ For the direct-connect, TCP-style beacon """
59 TCPSock
= socket(AF_INET
, SOCK_STREAM
)
60 TCPSock
.bind(('', 2190))
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
)
72 message
= self
.format_beacon('connected')
73 client
.send(struct
.pack('!I', len(message
)))
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
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
)
96 name
= machine_name(tivo_beacon
).groups()[0]
102 if __name__
== '__main__':
105 b
.add_service('TiVoMediaServer:9032/http')