Initial release
[netstory] / src / opt / netstory / netstoryd.py
1 #!/usr/bin/env python
2
3 # This file is part of NetStory.
4 # Author: Jere Malinen <jeremmalinen@gmail.com>
5   
6
7 from datetime import datetime
8 import os
9 import time
10
11 import gconf
12
13 import settings
14
15
16 SLEEP_TIME = 3600
17 # prevents from writing e.g. 22:49:59 and 23:00:00 
18 # (case when time has changed during sleep)
19 NEXT_SLEEP_ATLEAST = 1800  
20 # prevents from writing first line e.g. 22:59:30 and next would be 23:00:00
21 # (case starting daemon hh:59:00-hh:59:59)
22 FIRST_SLEEP_ATLEAST = 60   
23
24
25 def log_loop():
26     try:
27         f = open(settings.DATA, 'a')
28         print 'Writing to: ' + settings.DATA
29         first = True
30         while 1:
31             next_sleep = SLEEP_TIME - time.time() % SLEEP_TIME
32             if next_sleep > NEXT_SLEEP_ATLEAST or \
33                (first and next_sleep > FIRST_SLEEP_ATLEAST):
34                 download, upload = read_counters()
35                 write_data(f, download, upload)
36                 first = False
37             time.sleep(next_sleep) #sleep until next interval
38     except KeyboardInterrupt:
39         print 'Stopped'
40
41 def read_counters():
42     client = gconf.client_get_default()
43     download = client.get_string(settings.GPRS_HOME_DOWNLOAD)
44     upload = client.get_string(settings.GPRS_HOME_UPLOAD)
45     return (download, upload)
46     
47 def write_data(f, download, upload):
48     if check(download) and check(upload):
49         f.write('%s,%s,%s\n' % 
50                 (datetime.now().strftime(settings.DATA_TIME_FORMAT), 
51                 download, upload))
52         f.flush()
53         os.fsync(f.fileno())
54         
55 def check(value='1'):
56     try:
57         int(value)
58         return True
59     except TypeError, e:
60         print e
61     except ValueError, e:
62         print e
63     return False
64
65 if __name__ == "__main__":
66     if not os.path.exists(settings.DIR):
67         os.mkdir(settings.DIR)
68     log_loop()