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
|
# Copyright (C) 2012 Aleksey Lim
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import logging
from sugar_network.toolkit import pipe
_LOOKUP_RESULT_LOCAL = 8
_PROTO_UNSPEC = -1
_IF_UNSPEC = -1
_DBUS_NAME = 'org.freedesktop.Avahi'
_DBUS_INTERFACE_SERVICE_BROWSER = 'org.freedesktop.Avahi.ServiceBrowser'
_logger = logging.getLogger('zeroconf')
def browse_workstations():
_logger.info('Start browsing hosts using Avahi')
# Run zeroconf loop in a subprocess to avoid dbus loop collisions
for event in pipe.fork(_browser):
if event['state'] == 'resolve':
yield event['address']
def _browser():
import dbus
import gobject
from dbus.mainloop.glib import threads_init, DBusGMainLoop
gobject.threads_init()
threads_init()
DBusGMainLoop(set_as_default=True)
bus = dbus.SystemBus()
server = dbus.Interface(bus.get_object(_DBUS_NAME, '/'),
'org.freedesktop.Avahi.Server')
def ItemNew_cb(interface, protocol, name, stype, domain, flags):
if flags & _LOOKUP_RESULT_LOCAL:
return
_logger.debug('Got new workstation: %s', name)
server.ResolveService(interface, protocol, name, stype, domain,
_PROTO_UNSPEC, 0, reply_handler=ResolveService_cb,
error_handler=error_handler_cb)
def ResolveService_cb(interface, protocol, name, type_, domain,
host, aprotocol, address, port, txt, flags):
_logger.debug('Got new address: %s', address)
pipe.feedback('resolve', address=str(address))
def ItemRemove_cb(interface, protocol, name, type_, domain, *args):
_logger.debug('Got removed workstation: %s', name)
def error_handler_cb(error, *args):
_logger.warning('ResolveService failed: %s', error)
browser = dbus.Interface(
bus.get_object(_DBUS_NAME,
server.ServiceBrowserNew(_IF_UNSPEC, _PROTO_UNSPEC,
'_workstation._tcp', 'local', 0)),
_DBUS_INTERFACE_SERVICE_BROWSER)
browser.connect_to_signal('ItemNew', ItemNew_cb)
browser.connect_to_signal('ItemRemove', ItemRemove_cb)
gobject.MainLoop().run()
if __name__ == '__main__':
from pprint import pprint
logging.basicConfig(level=logging.DEBUG)
for __ in browse_workstations():
pprint(__)
|