c09aabc12b4bd2689f30196af4082016d0a5f5c5
[platform/upstream/connman.git] / test / test-counter
1 #!/usr/bin/python
2
3 import sys
4 import gobject
5
6 import dbus
7 import dbus.service
8 import dbus.mainloop.glib
9
10 def make_bytes_readable(bytes):
11         SUFFIXES = [ 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB' ]
12         size = 1024
13
14         if bytes < size:
15                 return ''
16
17         for suffix in SUFFIXES:
18                 if bytes > size * 1024:
19                         size = size * 1024
20                         continue
21
22                 return '%.1f %s' % (bytes / float(size), suffix)
23
24         return ''
25
26 def print_stats(stats):
27         keys = list(stats.keys())
28         keys.sort()
29
30         for key in keys:
31                 val = int(stats[key])
32                 str = "    %s = %s" % (key, val)
33
34                 if key in ["RX.Bytes", "TX.Bytes"]:
35                         hstr = make_bytes_readable(val)
36                         if hstr:
37                                 str = "%s (%s)" % (str, hstr)
38
39                 print(str)
40
41 class Counter(dbus.service.Object):
42         @dbus.service.method("net.connman.Counter",
43                                 in_signature='', out_signature='')
44         def Release(self):
45                 print("Release")
46                 mainloop.quit()
47
48         @dbus.service.method("net.connman.Counter",
49                                 in_signature='oa{sv}a{sv}', out_signature='')
50         def Usage(self, path, home, roaming):
51                 print("%s" % (path))
52
53                 if len(home) > 0:
54                         print("  Home")
55                         print_stats(home)
56                 if len(roaming) > 0:
57                         print("  Roaming")
58                         print_stats(roaming)
59
60 if __name__ == '__main__':
61         dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
62
63         bus = dbus.SystemBus()
64         manager = dbus.Interface(bus.get_object('net.connman', "/"),
65                                         'net.connman.Manager')
66
67         period = 2
68         if len(sys.argv) > 1:
69                 period = sys.argv[1]
70
71         path = "/test/counter%s" % period
72         object = Counter(bus, path)
73
74         manager.RegisterCounter(path, dbus.UInt32(10), dbus.UInt32(period))
75
76         mainloop = gobject.MainLoop()
77         mainloop.run()
78
79         #manager.UnregisterCounter(path)