aboutsummaryrefslogtreecommitdiff
path: root/client/ur_fuzzy_alarm_clock.py
blob: 1f0775d310665c4c6a1513c3fba60545acd1b26d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
#!/usr/bin/env python

import datetime
import sys

try:
    import urwid
except ImportError:
    sys.stderr.write('This program needs urwid\n')
    sys.exit(1)

try:
    import serial
except ImportError:
    sys.stderr.write('This program needs pySerial\n')
    sys.exit(1)

class FuzzyAlarmClock:

    def __init__(self,device):
        try:
            self.serial = serial.Serial(device,9600,timeout=5)
        except serial.serialutil.SerialException:
            sys.stderr.write('No such serial device '+device+'\n')
            sys.exit(1)

    def set_time_to_now(self):
        now = 's'+datetime.datetime.now().strftime("%y%m%d%u%H%M%S")
        self.serial.write(now)

    def read_alarms(self,n):
        data = []
        self.serial.flushInput()
        self.serial.write('p')
        for i in xrange(n):
            data.append(self.serial.readline())
        for i in xrange(n):
            data[i] = data[i].split(' ')[2:-1]
            days = []
            for j in xrange(8):
                days.append(bool(int(data[i][0]) & 2**j))
            days = days[7:8] + days[:7]
            data[i] = days+data[i][1:]
        return data

    def set_alarm(self,alarm,values):
        s = 'a'+str(alarm)
        b0 = 0
        for i,bit in enumerate(values[1:8] + values[0:1]):
            b0 += bit << i
        s += "%02x"%(b0)
        for val in values[8:]:
            s += "%02x"%(val)
        self.serial.write(s)

class ModEdit(urwid.IntEdit):

    def __init__(self,mod,caption="",default=None,offset=0):
        self.mod = mod
        self.offset = offset

        super(ModEdit,self).__init__(caption,default)

    def insert_text(self,text):
        super(ModEdit,self).insert_text(text)
        self.set_edit_text(str((self.value() - self.offset)% self.mod+self.offset))


class Alarm:

    def __init__(self,aid,fac):
        self.w_aid = urwid.Text(str(aid))
        self.w_repeat = urwid.CheckBox("")
        self.w_mon = urwid.CheckBox("")
        self.w_tue = urwid.CheckBox("")
        self.w_wed = urwid.CheckBox("")
        self.w_thu = urwid.CheckBox("")
        self.w_fri = urwid.CheckBox("")
        self.w_sat = urwid.CheckBox("")
        self.w_sun = urwid.CheckBox("")
        self.w_month = ModEdit(12,offset=1)
        self.w_day = ModEdit(31,offset=1)
        self.w_hour = ModEdit(24,default=0)
        self.w_minute = ModEdit(60,default=0)

        self.widgets = urwid.Columns([self.w_aid, 
            self.w_repeat,
            self.w_mon,
            self.w_tue,
            self.w_wed,
            self.w_thu,
            self.w_fri,
            self.w_sat,
            self.w_sun,
            self.w_month,
            self.w_day,
            self.w_hour,
            self.w_minute,
            ], 
                dividechars=1)

    def set_values(self,values):
        self.w_repeat.set_state(values[0])
        self.w_mon.set_state(values[1])
        self.w_tue.set_state(values[2])
        self.w_wed.set_state(values[3])
        self.w_thu.set_state(values[4])
        self.w_fri.set_state(values[5])
        self.w_sat.set_state(values[6])
        self.w_sun.set_state(values[7])
        self.w_month.set_edit_text(values[8])
        self.w_day.set_edit_text(values[9])
        self.w_hour.set_edit_text(values[10])
        self.w_minute.set_edit_text(values[11])

    def get_values(self):
        return [
                self.w_repeat.get_state(),
                self.w_mon.get_state(),
                self.w_tue.get_state(),
                self.w_wed.get_state(),
                self.w_thu.get_state(),
                self.w_fri.get_state(),
                self.w_sat.get_state(),
                self.w_sun.get_state(),
                self.w_month.value(),
                self.w_day.value(),
                self.w_hour.value(),
                self.w_minute.value(),
                ]


class UI:

    def __init__(self,fac):
        self.fac = fac

        self.alarm_number=4

        self.frame = self.build_ui()
        self.loop = urwid.MainLoop(self.frame,self.palette,unhandled_input=self.read_commands)

    def build_ui(self):
        self.palette = [
                ('header', 'light gray', 'dark blue'),
                ('footer', 'dark cyan', 'black')
                ]

        self.alarms = []
        for i in xrange(self.alarm_number):
            self.alarms.append(Alarm(i,self.fac))
        
        alarm_headers = urwid.Columns([
            urwid.Text('#'),
            urwid.Text('rep'),
            urwid.Text('Mon'),
            urwid.Text('Tue'),
            urwid.Text('Wed'),
            urwid.Text('Thu'),
            urwid.Text('Fri'),
            urwid.Text('Sat'),
            urwid.Text('Sun'),
            urwid.Text('mm'),
            urwid.Text('dd'),
            urwid.Text('HH'),
            urwid.Text('MM'),
            ],dividechars=1)
        self.main_body = urwid.ListBox([alarm_headers]+[al.widgets for al in self.alarms])

        footer = urwid.Text('a, b, c')
        footer_map = urwid.AttrMap(footer,'footer')

        header = urwid.Text('q: Quit  r: Read  s: Set  n: time=Now  ?:Help')
        header_map = urwid.AttrMap(header,'header')

        ui = urwid.Frame(self.main_body,footer=footer_map,header=header_map)
        return ui

    def read_commands(self,cmd):
        {'n': self.fac.set_time_to_now,
                'r': self.read_alarms,
                's': self.set_alarms,
                '?': self.print_help,
                'q': self.quit
                }.get(cmd,self.do_nothing)()

    def do_nothing(self):
        pass

    def read_alarms(self):
        alarms = self.fac.read_alarms(self.alarm_number)

        for i, al in enumerate(alarms):
            self.alarms[i].set_values(al)

    def set_alarms(self):
        for i,alarm in enumerate(self.alarms):
            self.fac.set_alarm(i,alarm.get_values())

    def print_help(self):
        pass

    def quit(self):
        raise urwid.ExitMainLoop()
    
    def run(self):
        self.loop.run()


def main():
    fac = FuzzyAlarmClock('/dev/ttyUSB0')
    ui = UI(fac)
    ui.run()

if __name__ == '__main__': main()