-
Notifications
You must be signed in to change notification settings - Fork 0
/
clock.py
336 lines (267 loc) · 8.95 KB
/
clock.py
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
import smbus
import datetime
import os, sys, re
from time import time, sleep
from evdev import InputDevice, categorize, ecodes
from threading import Thread,Timer
from subprocess import call,check_output,Popen
def delay(time):
sleep(time/1000.0)
def delayMicroseconds(time):
sleep(time/1000000.0)
mode = "Test"
data = "...wait..."
counter = 0
bouncer = -1
alarm_time = "99:99"
fifo_path = "/tmp/pianobar"
def revert():
global mode, data, screen, counter
curr_time = "{}".format(str(datetime.datetime.now().hour) + ":" + str(datetime.datetime.now().minute).rjust(2,'0'))
if playing == True:
mode = " Music"
counter = 0
data = get_song_data()
else:
mode = ""
data = ""
screen.display_data("{}{}".format(curr_time,mode), data)
def music_control(parm):
global data, playing, pianobar, fifo
if not os.path.exists(fifo_path):
os.mkfifo(fifo_path)
print("fifo created")
if "play" in parm:
print("play passed")
if playing == False:
pianobar = Popen("pianobar", close_fds=True)
sleep(2.0)
print("Pianobar started with PID {}".format(pianobar.pid))
fifo = open(fifo_path, "w")
else:
fifo.write("n") #next
playing = True
data = "Starting Music..."
#sleep(5)
#data = get_song_data()
if "stop" in parm:
print("stop passed")
playing = False
fifo.write("q") #quit
pianobar.terminate()
data = " Play >"
def alarm_control(parm):
global alarm_time
if parm == "set":
alarm_time = "16:13"
call("echo '{}' > /media/Alarm/.alarm_time".format(alarm_time), shell=True)
if parm == "delete":
alarm_time = "99:99"
call("rm /media/Alarm/.alarm_time", shell=True)
def get_song_data():
global counter
artist = ""
title = ""
with open('/home/pi/.config/pianobar/nowplaying') as playstatus:
for line in playstatus:
if re.search('artist=',line):
artist = line.replace('artist=','')
if re.search('title=',line):
title = line.replace('title=','')
song_info = "{} - {}".format(artist,title).decode('unicode_escape').encode('ascii','ignore')
return song_info.replace('\n','')
def show_volume():
vol_check = check_output(["sh", "-c", "'pactl list sinks | grep '^[[:space:]]Volume:' | head -n $(( $SINK + 1 )) | tail -n 1 '"])
vol = re.search(".*\ \d*%.*", vol_check)
return "{:^16}".format(vol)
def scroll(text):
global counter, bouncer
if len(text) <= 16:
return text
else:
if counter == 0 or len(text) - counter < 16:
bouncer = bouncer * -1
counter += 1 * bouncer
#print(text[counter:])
return text[counter:]
class KeyListener(Thread):
def __init__(self,mode):
Thread.__init__(self)
self.mode = mode
def run(self):
global mode, data, screen
dev = InputDevice('/dev/input/event0')
for event in dev.read_loop():
if event.type == ecodes.EV_KEY:
if event.value != 0L:
continue
if event.code in (113,114,115):
print(mode, event.code, event.value)
try:
t.cancel()
except:
print("no timer")
t = Timer(5, revert)
t.start()
handleKeypress(event.code)
def handleKeypress(code):
global mode, data
if code==113:
if mode == "":
mode = " Music"
data = "< Stop Play >"
return
elif "Music" in mode:
if "Play" in data:
mode = " Alarm"
data = "< Set Delete >"
else:
mode = " Music"
data = "< Stop Play >"
return
elif "Alarm" in mode:
mode = ""
data = ""
return
if code==114:
print("down in {} mode".format(mode))
if mode == "":
mode = " Volume"
data = show_volume()
return
elif "Volume" in mode:
call(["pactl","set-sink-volume","alsa_output.usb-1130_USB_AUDIO-00.analog-stereo","-5%"])
data = show_volume()
return
elif "Music" in mode:
# stop music
music_control("stop")
return
elif "Alarm" in mode:
alarm_control("set")
return
if code==115:
print("up in {} mode".format(mode))
if mode == "":
mode = " Volume"
data = show_volume()
return
elif "Volume" in mode:
call(["pactl","set-sink-volume","alsa_output.usb-1130_USB_AUDIO-00.analog-stereo","+5%"])
data = show_volume()
return
elif "Music" in mode:
# play or skip music
music_control("play")
return
elif "Alarm" in mode:
alarm_control("delete")
return
def main():
global mode, data, screen, playing, alarm_time
playing = False
try:
call(["pactl","set-sink-volume","alsa_output.usb-1130_USB_AUDIO-00.analog-stereo","25%"])
except:
print("Music not available!")
try:
alarm_time = check_output(["cat","/media/Alarm/.alarm_time"]).replace('\n','')
except:
alarm_time = "99:99"
screen = Screen(bus=1, addr=0x27, cols=16, rows=2)
screen.disable_backlight()
screen.enable_backlight()
curr_time = "{}".format(str(datetime.datetime.now().hour) + ":" + str(datetime.datetime.now().minute).rjust(2,'0'))
mode = ""
data = ""
screen.display_data("{}{}".format(curr_time,mode), data)
myKeyListener = KeyListener(mode=mode)
myKeyListener.daemon = True
myKeyListener.start()
while True:
curr_time = "{}".format(str(datetime.datetime.now().hour) + ":" + str(datetime.datetime.now().minute).rjust(2,'0'))
if playing == True:
data = get_song_data()
data_disp = scroll(data)
try:
oldTime
oldMode
oldData
except:
oldTime = curr_time
oldMode = mode
oldData = data_disp
if oldTime != curr_time or oldMode != mode or oldData != data_disp:
oldTime = curr_time
oldMode = mode
oldData = data_disp
#print("time = {}, {} mode = {}, {} data = {}, {}".format(curr_time, oldTime, mode, oldMode, data_disp, oldData))
#print("alarm = {} current = {}".format(alarm_time, curr_time))
if curr_time[0:5] == alarm_time[0:5]:
music_control("play")
sleep(3)
data_disp = "WAKE UP!"
screen.display_data("{}{}".format(curr_time,mode), data_disp)
sleep(1)
class Screen():
enable_mask = 1<<2
rw_mask = 1<<1
rs_mask = 1<<0
backlight_mask = 1<<3
data_mask = 0x00
def __init__(self, cols = 16, rows = 2, addr=0x27, bus=1):
self.cols = cols
self.rows = rows
self.bus_num = bus
self.bus = smbus.SMBus(self.bus_num)
self.addr = addr
self.display_init()
def enable_backlight(self):
self.data_mask = self.data_mask|self.backlight_mask
def disable_backlight(self):
self.data_mask = self.data_mask& ~self.backlight_mask
def display_data(self, *args):
self.clear()
for line, arg in enumerate(args):
self.cursorTo(line, 0)
self.println(arg[:self.cols].ljust(self.cols))
def cursorTo(self, row, col):
offsets = [0x00, 0x40, 0x14, 0x54]
self.command(0x80|(offsets[row]+col))
def clear(self):
self.command(0x10)
def println(self, line):
for char in line:
self.print_char(char)
def print_char(self, char):
char_code = ord(char)
self.send(char_code, self.rs_mask)
def display_init(self):
delay(1.0)
self.write4bits(0x30)
delay(4.5)
self.write4bits(0x30)
delay(4.5)
self.write4bits(0x30)
delay(0.15)
self.write4bits(0x20)
self.command(0x20|0x08)
self.command(0x04|0x08, delay=80.0)
self.clear()
self.command(0x04|0x02)
delay(3)
def command(self, value, delay = 50.0):
self.send(value, 0)
delayMicroseconds(delay)
def send(self, data, mode):
self.write4bits((data & 0xF0)|mode)
self.write4bits((data << 4)|mode)
def write4bits(self, value):
value = value & ~self.enable_mask
self.expanderWrite(value)
self.expanderWrite(value | self.enable_mask)
self.expanderWrite(value)
def expanderWrite(self, data):
self.bus.write_byte_data(self.addr, 0, data|self.data_mask)
if __name__ == "__main__":
main()