Added docstrings for DBusMio and others.
[cnetworkmanager.git] / cnetworkmanager
blob3651566ea03d0540a3d646451de2d6274e049bb5
1 #!/usr/bin/python
2 VERSION = "0.20"
4 import sys
5 import time
6 import dbus
7 from networkmanager import NetworkManager
8 from networkmanager.monitor import Monitor
9 from networkmanager.applet import NetworkManagerSettings, SYSTEM_SERVICE, USER_SERVICE
10 from networkmanager.applet.service import NetworkManagerUserSettings
11 import networkmanager.applet.settings as settings
13 # must be set before we ask for signals
14 from dbus.mainloop.glib import DBusGMainLoop
15 DBusGMainLoop(set_as_default=True)
16 # for calling quit
17 import gobject
18 loop = gobject.MainLoop()
19 LOOP = False
21 from optparse import OptionParser
23 op = OptionParser(version="%prog " + VERSION)
25 # TODO http://docs.python.org/lib/optparse-adding-new-types.html
26 op.add_option("-w", "--wifi",
27 choices=["0","1","off","on","no","yes","false","true"],
28 metavar="BOOL",
29 help="Enable or disable wireless")
30 op.add_option("-o", "--online",
31 choices=["0","1","off","on","no","yes","false","true"],
32 metavar="BOOL",
33 help="Enable or disable network at all")
34 op.add_option("--state",
35 action="store_true", default=False,
36 help="Print the NM state")
37 op.add_option("--whe", "--wireless-hardware-enabled",
38 action="store_true", default=False,
39 help="Print whether the WiFi is enabled")
41 op.add_option("-d", "--device-list", "--dev",
42 action="store_true", default=False,
43 help="List devices")
44 op.add_option("--device-info", "--di",
45 help="Info about device DEV (by interface or UDI(TODO))",
46 metavar="DEV")
48 op.add_option("-a", "--ap-list", "--ap", "-n", "--nets",# -n is a stopgap
49 action="store_true", default=False,
50 help="List access points")
51 op.add_option("--ap-info", "--ai",
52 help="Info about access point AP (by hw address or UDI(TODO))",
53 metavar="AP")
55 op.add_option("-u", "--usrcon",
56 action="store_true", default=False,
57 help="List user connection settings")
58 op.add_option("-s", "--syscon",
59 action="store_true", default=False,
60 help="List system connection settings")
62 op.add_option("-c", "--actcon",
63 action="store_true", default=False,
64 help="List active connections")
66 op.add_option("--demo",
67 action="store_true", default=False,
68 help="Run a random demonstration of the API")
69 op.add_option("--activate-connection",
70 help="activate the KIND(user/system) connection ID on device DEV using APMAC.",
71 metavar="[KIND],ID,[DEV],[APMAC]")
72 op.add_option("-m", "--monitor",
73 action="store_true", default=False,
74 help="loop to show dbus signals")
76 op.add_option("-C", "--connect",
77 help="Connect to a wireless network SSID (creating the configuration using the key options below)",
78 metavar="SSID")
79 op.add_option("--unprotected",
80 action="store_true", default=False,
81 help="network does not require a key")
82 op.add_option("--wep-hex",
83 metavar="KEY",
84 help="use this WEP key of 26 hex digits")
85 op.add_option("--wep-pass",
86 metavar="KEY",
87 help="use this WEP passphrase")
88 op.add_option("--wpa-psk-hex",
89 metavar="KEY",
90 help="use this WPA key of 64 hex digits")
91 op.add_option("--wpa-pass",
92 metavar="KEY",
93 help="use this WPA passphrase")
95 (options, args) = op.parse_args()
97 nm = NetworkManager()
99 true_choices = ["1", "on", "yes", "true"]
100 if options.wifi != None:
101 nm["WirelessEnabled"] = options.wifi in true_choices
102 if options.online != None:
103 nm.Sleep(not options.online in true_choices)
104 if options.state:
105 print nm["State"]
106 if options.whe:
107 print nm["WirelessHardwareEnabled"]
108 # style option: pretend that properties are methods (er, python properties)
109 # nm["WirelessEnabled"] -> nm.WirelessEnabled() (er, nm.WirelessEnabled )
111 if options.device_list:
112 devs = nm.GetDevices()
113 for dev in devs:
114 print dev["Interface"], dev["DeviceType"], dev["State"]
116 # --device-info, TODO clean up
117 def get_device(dev_spec, hint):
118 candidates = []
119 # print "Hint:", hint
120 devs = NetworkManager().GetDevices()
121 for dev in devs:
122 # print dev
123 if dev._settings_type() == hint:
124 candidates.append(dev)
125 # print "Candidates:", candidates
126 if len(candidates) == 1:
127 return candidates[0]
128 for dev in devs:
129 if dev["Interface"] == dev_spec:
130 return dev
131 print "Device '%s' not found" % dev_spec
132 return None
134 def dump_prop(obj, prop_name):
135 print "%s: %s" %(prop_name, obj[prop_name])
137 def dump_props(obj, *prop_names):
138 for prop_name in prop_names:
139 dump_prop(obj, prop_name)
141 def dump_ap(ap):
142 dump_props(ap, "Flags", "WpaFlags", "RsnFlags",
143 "Ssid", "Frequency", "HwAddress",
144 "Mode", "MaxBitrate", "Strength")
146 if options.device_info != None:
147 d = get_device(options.device_info, "no hint")
148 if d == None:
149 print "not found"
150 else:
151 dump_props(d, "Udi", "Interface", "Driver", "Capabilities",
152 "Ip4Address", "State", "Ip4Config", "Dhcp4Config",
153 "Managed", "DeviceType")
154 if d._settings_type() == "802-11-wireless":
155 dump_props(d, "Mode", "WirelessCapabilities")
156 aap = d["ActiveAccessPoint"]
157 for ap in d.GetAccessPoints():
158 print " AP:", ap.object_path
159 if ap.object_path == aap.object_path:
160 print " ACTIVE"
161 dump_ap(ap)
162 else:
163 dump_prop(d, "Carrier")
165 if options.ap_list or options.ap_info != None:
166 devs = nm.GetDevices()
167 for dev in filter(lambda d: d._settings_type() == "802-11-wireless", devs):
168 aap = dev["ActiveAccessPoint"]
169 for ap in dev.GetAccessPoints():
170 is_active = ap.object_path == aap.object_path
171 if options.ap_list:
172 active = "*" if is_active else " "
173 print ap["HwAddress"], active, ap["Ssid"]
174 elif ap["HwAddress"] == options.ap_info:
175 print "Active:", is_active
176 dump_ap(ap)
178 #def is_opath(x):
179 # return is_instance(x, str) and x[0] == "/"
181 # move this to networkmanagersettings
182 def get_connection(svc, conn_spec):
183 # if is_opath(conn_spec):
184 # return conn_spec
185 applet = NetworkManagerSettings(svc)
186 for conn in applet.ListConnections():
187 cs = conn.GetSettings()
188 if cs["connection"]["id"] == conn_spec:
189 return conn
190 print "Connection '%s' not found" % conn_spec
191 return None
193 def get_connection_devtype(conn):
194 cs = conn.GetSettings()
195 return cs["connection"]["type"]
197 def list_conections(svc):
198 acs = nm["ActiveConnections"]
199 acos = map(lambda a: a["Connection"].object_path, acs)
201 applet = NetworkManagerSettings(svc)
202 for conn in applet.ListConnections():
203 cs = conn.GetSettings()
204 active = "*" if conn.object_path in acos else " "
205 print active, cs["connection"]["id"], cs["connection"]["type"]
207 if options.usrcon:
208 list_conections(USER_SERVICE)
209 if options.syscon:
210 list_conections(SYSTEM_SERVICE)
212 # this shows we do need to add __str__ to the objects
213 if options.actcon:
214 acs = nm["ActiveConnections"]
215 for ac in acs:
216 cid = ac["Connection"].GetSettings()["connection"]["id"]
217 try:
218 apmac = ac["SpecificObject"]["HwAddress"]
219 except: # no AP for wired. TODO figure out "/" object
220 apmac = ""
221 devs = ", ".join(map(lambda d: d["Interface"], ac["Devices"]))
222 hdr = "(has default route)" if ac["Default"] else ""
223 print ac["State"], cid, apmac, devs, hdr
225 if options.monitor:
226 m = Monitor()
227 LOOP = True
229 def print_state_changed(*args):
230 print time.strftime("(%X)"),
231 print "State:", ", ".join(map(str,args))
233 if options.connect != None:
234 ssid = options.connect
235 try:
236 us = NetworkManagerUserSettings([]) # request_name may fail
237 except dbus.exceptions.NameExistsException, e:
238 print "Another applet is running:", e
239 sys.exit(1)
241 c = None
242 if options.unprotected:
243 c = settings.WiFi(ssid)
244 if options.wep_hex != None:
245 c = settings.Wep(ssid, "", options.wep_hex)
246 if options.wep_pass != None:
247 c = settings.Wep(ssid, options.wep_pass)
248 if options.wpa_psk_hex != None:
249 c = settings.WpaPsk(ssid, "", options.wpa_psk_hex)
250 if options.wpa_pass != None:
251 c = settings.WpaPsk(ssid, options.wpa_pass)
252 if c == None:
253 print "Error, connection settings not specified"
254 sys.exit(1)
256 svc = USER_SERVICE
257 svc_conn = us.addCon(c.conmap)
258 hint = svc_conn.settings["connection"]["type"]
259 dev = get_device("", hint)
260 appath = "/"
261 nm._connect_to_signal("StateChanged", print_state_changed)
262 # must be async because ourselves are providing the service
263 dummy_handler = lambda *args: None
264 nm.ActivateConnection(svc, svc_conn, dev, appath,
265 reply_handler=dummy_handler,
266 error_handler=dummy_handler)
267 LOOP = True
269 if options.activate_connection != None:
270 (svc, conpath, devpath, appath) = options.activate_connection.split(',')
271 if svc == "" or svc == "user":
272 svc = USER_SERVICE
273 elif svc == "system":
274 svc = SYSTEM_SERVICE
276 conn = get_connection(svc, conpath)
277 hint = get_connection_devtype(conn)
278 dev = get_device(devpath, hint)
279 if appath == "":
280 appath = "/"
281 nm._connect_to_signal("StateChanged", print_state_changed)
282 # TODO make it accept both objects and opaths
283 nm.ActivateConnection(svc, conn, dev, appath)
284 # TODO (optionally) block only until a stable state is reached
285 LOOP = True
288 ######## demo ##########
290 from dbusclient import DBusMio
291 mio = DBusMio(dbus.SystemBus(), "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager")
292 i = mio.Introspect()
293 d = mio.GetDevices()
295 if options.demo:
296 nm = NetworkManager()
298 # TODO: generic signal (adapt cnm monitor), print name and args
300 nm["WirelessEnabled"] = "yes"
302 devs = nm.GetDevices()
304 for d in devs:
305 print "\n DEVICE"
306 # TODO: find API for any object
307 d._connect_to_signal("StateChanged", print_state_changed)
309 LOOP = True
310 ######## demo end ##########
312 # TODO wrap this
313 if LOOP:
314 try:
315 print "Entering mainloop"
316 loop.run()
317 except KeyboardInterrupt:
318 print "Loop exited"