Ticket #296: sleep-proxy.py

File sleep-proxy.py, 3.5 KB (added by ajmas, 2 years ago)

Python file for testing fucntionality

Line 
1import dbus
2import gobject
3import sys
4import avahi
5import os
6from dbus.mainloop.glib import DBusGMainLoop
7from socket import gethostname;
8
9serviceName = " " + gethostname()
10serviceType = "_sleep-proxy._udp" # See http://www.dns-sd.org/ServiceTypes.html
11servicePort = 1234
12serviceTXT = "" #somethingcrazy" #TXT record for the service
13
14domain = "" # Domain to publish on, default to .local
15host = "" # Host to publish records for, default to localhost
16
17group = None #our entry group
18rename_count = 12 # Counter so we only rename after collisions a sensible number of times
19
20def add_service():
21    global group, serviceName, serviceType, servicePort, serviceTXT, domain, host
22    if group is None:
23        group = dbus.Interface(
24                bus.get_object( avahi.DBUS_NAME, server.EntryGroupNew()),
25                avahi.DBUS_INTERFACE_ENTRY_GROUP)
26        group.connect_to_signal('StateChanged', entry_group_state_changed)
27
28    print "Adding service '%s' of type '%s' ..." % (serviceName, serviceType)
29
30    group.AddService(
31            avahi.IF_UNSPEC,    #interface
32            avahi.PROTO_UNSPEC, #protocol
33            dbus.UInt32(0),                  #flags
34            serviceName, serviceType,
35            domain, host,
36            dbus.UInt16(servicePort),
37            avahi.string_array_to_txt_array(serviceTXT))
38    group.Commit()
39
40def remove_service():
41    global group
42
43    if not group is None:
44        group.Reset()
45
46def server_state_changed(state):
47    if state == avahi.SERVER_COLLISION:
48        print "WARNING: Server name collision"
49        remove_service()
50    elif state == avahi.SERVER_RUNNING:
51        add_service()
52
53def entry_group_state_changed(state, error):
54    global serviceName, server, rename_count
55
56    print "state change: %i" % state
57
58    if state == avahi.ENTRY_GROUP_ESTABLISHED:
59        print "Service established."
60    elif state == avahi.ENTRY_GROUP_COLLISION:
61
62        rename_count = rename_count - 1
63        if rename_count > 0:
64            name = server.GetAlternativeServiceName(name)
65            print "WARNING: Service name collision, changing name to '%s' ..." % name
66            remove_service()
67            add_service()
68
69        else:
70            print "ERROR: No suitable service name found after %i retries, exiting." % n_rename
71            main_loop.quit()
72    elif state == avahi.ENTRY_GROUP_FAILURE:
73        print "Error in group state changed", error
74        main_loop.quit()
75        return
76
77
78def getMacAddress():
79    if sys.platform == 'win32':
80        for line in os.popen("ipconfig /all"):
81            if line.lstrip().startswith('Physical Address'):
82                mac = line.split(':')[1].strip().replace('-',':')
83                break
84    else:
85        for line in os.popen("/sbin/ifconfig"):
86            if line.find('Ether') > -1:
87                mac = line.split()[4]
88                break
89    return mac
90
91
92if __name__ == '__main__':
93    DBusGMainLoop( set_as_default=True )
94
95    mac_addr = getMacAddress().upper()
96    parts = mac_addr.split(':')
97    serviceName = parts[0] + "-" + parts[3] + "-" + parts[4] + "-" + parts[5] + serviceName
98
99    main_loop = gobject.MainLoop()
100    bus = dbus.SystemBus()
101
102    server = dbus.Interface(
103            bus.get_object( avahi.DBUS_NAME, avahi.DBUS_PATH_SERVER ),
104            avahi.DBUS_INTERFACE_SERVER )
105
106    server.connect_to_signal( "StateChanged", server_state_changed )
107    server_state_changed( server.GetState() )
108
109
110    try:
111        main_loop.run()
112    except KeyboardInterrupt:
113        pass
114
115    if not group is None:
116        group.Free()