Putting more things in try/catch
[gc-dialer] / src / alarm_handler.py
1 #!/usr/bin/env python
2
3 import os
4 import time
5 import datetime
6 import ConfigParser
7
8 import dbus
9 import osso.alarmd as alarmd
10
11
12 class AlarmHandler(object):
13
14         _INVALID_COOKIE = -1
15         _TITLE = "Dialcentral Notifications"
16         _LAUNCHER = os.path.abspath(os.path.join(os.path.dirname(__file__), "alarm_notify.py"))
17         _REPEAT_FOREVER = -1
18         _DEFAULT_FLAGS = (
19                 alarmd.ALARM_EVENT_NO_DIALOG |
20                 alarmd.ALARM_EVENT_NO_SNOOZE |
21                 alarmd.ALARM_EVENT_CONNECTED
22         )
23
24         def __init__(self):
25                 self._recurrence = 5
26
27                 bus = dbus.SystemBus()
28                 self._alarmdDBus = bus.get_object("com.nokia.alarmd", "/com/nokia/alarmd");
29                 self._alarmCookie = self._INVALID_COOKIE
30                 self._launcher = self._LAUNCHER
31
32         def load_settings(self, config, sectionName):
33                 try:
34                         self._recurrence = config.getint(sectionName, "recurrence")
35                         self._alarmCookie = config.getint(sectionName, "alarmCookie")
36                         launcher = config.get(sectionName, "notifier")
37                         if launcher:
38                                 self._launcher = launcher
39                 except ConfigParser.NoOptionError:
40                         pass
41
42         def save_settings(self, config, sectionName):
43                 config.set(sectionName, "recurrence", str(self._recurrence))
44                 config.set(sectionName, "alarmCookie", str(self._alarmCookie))
45                 launcher = self._launcher if self._launcher != self._LAUNCHER else ""
46                 config.set(sectionName, "notifier", launcher)
47
48         def apply_settings(self, enabled, recurrence):
49                 if recurrence != self._recurrence or enabled != self.isEnabled:
50                         if self.isEnabled:
51                                 self._clear_alarm()
52                         if enabled:
53                                 self._set_alarm(recurrence)
54                 self._recurrence = int(recurrence)
55
56         @property
57         def recurrence(self):
58                 return self._recurrence
59
60         @property
61         def isEnabled(self):
62                 return self._alarmCookie != self._INVALID_COOKIE
63
64         def _get_start_time(self, recurrence):
65                 now = datetime.datetime.now()
66                 startTimeMinute = now.minute + recurrence
67                 now.replace(minute=startTimeMinute)
68                 timestamp = int(time.mktime(now.timetuple()))
69                 return timestamp
70
71         def _set_alarm(self, recurrence):
72                 assert 1 <= recurrence, "Notifications set to occur too frequently: %d" % recurrence
73                 alarmTime = self._get_start_time(recurrence)
74
75                 #Setup the alarm arguments so that they can be passed to the D-Bus add_event method
76                 action = []
77                 action.extend(['flags', self._DEFAULT_FLAGS])
78                 action.extend(['title', self._TITLE])
79                 action.extend(['path', self._launcher])
80                 action.extend([
81                         'arguments',
82                         dbus.Array(
83                                 [alarmTime, int(27)],
84                                 signature=dbus.Signature('v')
85                         )
86                 ])  #int(27) used in place of alarm_index
87
88                 event = []
89                 event.extend([dbus.ObjectPath('/AlarmdEventRecurring'), dbus.UInt32(4)])
90                 event.extend(['action', dbus.ObjectPath('/AlarmdActionExec')])  #use AlarmdActionExec instead of AlarmdActionDbus
91                 event.append(dbus.UInt32(len(action) / 2))
92                 event.extend(action)
93                 event.extend(['time', dbus.Int64(alarmTime)])
94                 event.extend(['recurr_interval', dbus.UInt32(recurrence)])
95                 event.extend(['recurr_count', dbus.Int32(self._REPEAT_FOREVER)])
96
97                 self._alarmCookie = self._alarmdDBus.add_event(*event);
98
99         def _clear_alarm(self):
100                 if self._alarmCookie == self._INVALID_COOKIE:
101                         return
102                 deleteResult = self._alarmdDBus.del_event(dbus.Int32(self._alarmCookie))
103                 self._alarmCookie = self._INVALID_COOKIE
104                 assert deleteResult != -1, "Deleting of alarm event failed"
105
106
107 def main():
108         import ConfigParser
109         import constants
110         try:
111                 import optparse
112         except ImportError:
113                 return
114
115         parser = optparse.OptionParser()
116         parser.add_option("-x", "--display", action="store_true", dest="display", help="Display data")
117         parser.add_option("-e", "--enable", action="store_true", dest="enabled", help="Whether the alarm should be enabled or not", default=False)
118         parser.add_option("-d", "--disable", action="store_false", dest="enabled", help="Whether the alarm should be enabled or not", default=False)
119         parser.add_option("-r", "--recurrence", action="store", type="int", dest="recurrence", help="How often the alarm occurs", default=5)
120         (commandOptions, commandArgs) = parser.parse_args()
121
122         alarmHandler = AlarmHandler()
123         config = ConfigParser.SafeConfigParser()
124         config.read(constants._user_settings_)
125         alarmHandler.load_settings(config, "alarm")
126
127         if commandOptions.display:
128                 print "Alarm (%s) is %s for every %d minutes" % (
129                         alarmHandler._alarmCookie,
130                         "enabled" if alarmHandler.isEnabled else "disabled",
131                         alarmHandler.recurrence,
132                 )
133         else:
134                 isEnabled = commandOptions.enabled
135                 recurrence = commandOptions.recurrence
136                 alarmHandler.apply_settings(isEnabled, recurrence)
137
138                 alarmHandler.save_settings(config, "alarm")
139                 configFile = open(constants._user_settings_, "wb")
140                 try:
141                         config.write(configFile)
142                 finally:
143                         configFile.close()
144
145
146 if __name__ == "__main__":
147         main()