-
Notifications
You must be signed in to change notification settings - Fork 0
/
tftthread.py
1748 lines (1440 loc) · 76 KB
/
tftthread.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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
# TFT running both input and output
# Also handles volume slider (right side)
# Alarm cancelling (Center when alarm playing)
# Menus (Center when alarm Not playing)
# radio control (left side)
# 27/03/2020 - Actually uses SCREEN_HEIGHT and SCREEN_WIDTH
# 18/10/2020 - Blanks the entire volume area to avoid leaving bits behind
# 18/10/2020 - Moved setting & adding to extra message into a function
# 26/01/2021 - Moved player monitoring to player Thread
# Message creation & store moved to each thread
# 26/05/2021 - Volume slider is now changing volumepercent i.e. usable volume
# 30/05/2021 - Only try for weather if its been setup
# 11/09/2021 - Added mqtt input & output of display colour
# 23/11/2021 - Fixed colour output on mqtt on startup
#from LCDControl.LCDControl import LCDControl
#import gaugette.rotary_encoder
import time
import datetime
#import pytz
import threading
import MenuControl
import Settings
#from InputWorker import InputWorker
import logging
import os
import pygame
from pygame.locals import *
import math
log = logging.getLogger('root')
SCREEN_WIDTH = 480
SCREEN_HEIGHT = 320
CONTROL_ZONE = SCREEN_WIDTH / 6
import colours
# index meanings for onscreen buttons etx
KEY_ControlType =0
KEY_UpButtonarea=1
KEY_UpButton=2
KEY_DownButtonarea=3
KEY_DownButton=4
KEY_SelectButtonarea=5
KEY_scrollsurface=6
KEY_fontlineheight=7
KEY_SelectedValue=8
KEY_OldSelectedValue=9
KEY_MinValue=10
KEY_MaxValue=11
KEY_xs =12
KEY_ys = 13
KEY_yoffset = 14
KEYSelectAction = 15
#
# Date convenience methods
#
def suffix(d):
return 'th' if 11<=d<=13 else {1:'st',2:'nd',3:'rd'}.get(d%10, 'th')
def formatDate(dateObj):
message = dateObj.strftime("%a ")
message+= dateObj.strftime("%d").lstrip("0")
message+= suffix(dateObj.day)
message+= dateObj.strftime(" %B")
return message
# Ensure PiTFT is usable
os.putenv('SDL_VIDEODRIVER','fbcon')
os.putenv('SDL_FBDEV','/dev/fb1')
os.putenv('SDL_MOUSEDRV','TSLIB')
os.putenv('SDL_MOUSEDEV','/dev/input/touchscreen')
pygame.init()
pygame.mixer.quit()
#
# Class dealing with displaying relevant information on the LCD screen
#
class TFTThread(threading.Thread):
def __init__(self,Callback, Settings): #alarmThread,Callback, media, weather):
threading.Thread.__init__(self)
self.alarmThread = None #alarmThread
self.stopping=False
self.lcd = self
self.caller = Callback
self.media = None #media
self.mqttbroker = None
self.message=""
self.volumebar = False
self.SleepTime = 1 # sleep less when volume shown
self.MenuWaiting = False
self.settings = Settings #Settings.Settings()
self.checkmessage = 20 # Time between message updates
#~ os.putenv('SDL_VIDEODRIVER','fbcon')
#~ os.putenv('SDL_FBDEV','/dev/fb1')
#~ os.putenv('SDL_MOUSEDRV','TSLIB')
#~ os.putenv('SDL_MOUSEDEV','/dev/input/touchscreen')
self.tftScreen = pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT))
pygame.mouse.set_visible(False)
# Fill with black
self.tftScreen.fill((0,0,0))
pygame.display.update()
self.oldExtraText = ""
self.ExtraTextoffset = 0
self.oldExtrawidth = 0
#~ fontlist = pygame.font.get_fonts()
#~ for fontname in fontlist:
#~ print fontname
self.CurrentVolume = int(self.settings.get('volumepercent'))
self.VisibleVolume = self.CurrentVolume
self.ClockFontName = None
self.newvolume = self.CurrentVolume
self.ChooseFonts()
#~ self.font_normal_bold.set_italic(True)
self.weather = None #weather
#Start menu thread (Later)
#self.menu = MenuControl.MenuControl(self, media, weather, Callback)
#self.menu.setDaemon(True)
self.menu = None
# self.lcd = LCDControl()
# self.lcd.white()
#~ self.setMessage("Booting up...")
# self.rotor = InputWorker(self)
# self.rotor.start()
self.SegmentGap = 20
self.segmentwidth = 60
self.segmentheight = 60
self.Clockformat = int(self.settings.get('clock_format'))
self.pausedState = False
self.LastTime = None
self.Lasthourtens = -1
self.Lasthoutunits = -1
self.Lastmintens = -1
self.Lastminunits = -1
self.Lastsecstens = -1
self.Lastsecsunits = -1
self.VisibleVolume = False
self.ExtraMessage = ""
self.ClockColour = self.settings.getcolour('clock_colour')
#~ self.ShowClock = True
# def setBrightness(self,brightness):
# We get passes a value from 0 - 15, which we need to scale to 0-255 before passing to LCDControl
# colVal = int(255 * (float(brightness)/15))
# self.lcd.setColour(colVal,colVal,colVal)
def SetClockColour(self, colourValue):
# Input is 3 value csv String "R,G,B"
# ClockColour variable is a 3 part tupple (R, G, B)
try:
colourRGB = colourValue.split(",")
self.settings.set('clock_colour', str(colourRGB[0])+","+str(colourRGB[1])+","+str(colourRGB[2]))
except ValueError:
log.warn("Could not decode '%s' as colour. Using default",colourValue)
self.ClockColour = self.settings.getcolour('clock_colour')
if (self.mqttbroker != None):
colourR, colourG, colourB = self.settings.getcolour('clock_colour')
self.mqttbroker.publish("display/colourRGB", str(colourR)+","+str(colourG)+","+str(colourB))
self.mqttbroker.publish("display/colorRGB", str(colourR)+","+str(colourG)+","+str(colourB))
def publish(self):
self.publishtext() #mqttbroker.publish("radio/text", self.ExtraMessage)
self.publishname() #mqttbroker.publish("radio/name", self.message + " ")
self.publishcolour()
def publishcolour(self):
colourR, colourG, colourB = self.settings.getcolour('clock_colour')
self.mqttbroker.publish("display/colourRGB", str(colourR)+","+str(colourG)+","+str(colourB))
self.mqttbroker.publish("display/colorRGB", str(colourR)+","+str(colourG)+","+str(colourB))
def publishtext(self):
self.mqttbroker.publish("radio/text", self.ExtraMessage)
def publishname(self):
self.mqttbroker.publish("radio/name", self.message + " ")
def on_message(self, topic ,payload):
method = topic[0:topic.find("/")] # before first "/"
item = topic[topic.rfind("/")+1:] # after last "/"
log.info("TFT method='%s', item='%s'", method, item)
done = False
try:
if (method == "display"):
if (item == "colourrgb") or (item == "colorrgb"):
log.debug("colour = '%s'", payload)
#RGBcolour = payload.split(",")
try:
self.SetClockColour(payload)
#self.settings.set('clock_colour', str(RGBcolour[0])+","+str(RGBcolour[1])+","+str(RGBcolour[2]))
#self.ClockColour = self.settings.getcolour('clock_colour')
except ValueError:
log.warn("Could not decode %s as colour", payload)
done = True
except Exception as e:
log.debug("on_message Error: %s" , e)
return done # not for me
# From clock thread
def ClockSegment(self, Segment, newvalue, oldSegmentvalue):
y = 160 - (self.segmentheight)
if (self.Clockformat == 6):
x = 240 + ((-4 + Segment) * (self.segmentwidth + self.SegmentGap)) # + (Segment * (self.segmentwidth + self.SegmentGap))
else:
x = 240 + int((-2.5 + Segment) * (self.segmentwidth + self.SegmentGap)) # + (Segment * (self.segmentwidth + self.SegmentGap))
if oldSegmentvalue != newvalue:
if oldSegmentvalue != -1:
self.lcd.Segmentdigit(x,y,(0,0,0), oldSegmentvalue, self.segmentwidth, self.segmentheight,8)
self.lcd.Segmentdigit(x,y,self.ClockColour, newvalue, self.segmentwidth, self.segmentheight,8)
return newvalue
def paused(self, State):
self.pausedState = State
if (self.pausedState == False):
self.Lasthourtens = -1
self.Lasthoutunits = -1
self.Lastmintens = -1
self.Lastminunits = -1
self.Lastsecstens = -1
self.Lastsecsunits = -1
self.Clockformat = int(self.settings.get('clock_format'))
if (self.Clockformat == 4):
self.segmentwidth = 60
self.segmentheight = 60
else:
self.segmentwidth = 40
self.segmentheight = 40
def SetExtraMessage(self,NewMessage, CheckInterval = -1):
self.ExtraMessage = NewMessage
if (CheckInterval != -1) :
self.checkmessage = CheckInterval
if (self.mqttbroker != None):
self.publishtext()
def AddToExtraMessage(self,NewMessage, CheckInterval = -1):
self.ExtraMessage += NewMessage
if (CheckInterval != -1) :
self.checkmessage = CheckInterval
if (self.mqttbroker != None):
self.publishtext()
def SetConfig(self, alarmThread, media, weather, brightnessthreadptr, mqttbroker): #Remaining info to allow startup
self.alarmThread = alarmThread
self.media = media
self.weather = weather
self.brightness = brightnessthreadptr
# Startup Menu Thread
self.menu = MenuControl.MenuControl(self, self.media, self.weather, self.caller, self.brightness)
#self.menu.setDaemon(True)
self.mqttbroker = mqttbroker
def ChooseFonts(self):
if (self.settings.getorset('menu_font','') == ""):
MenuFontName = None
getfont = None #pygame.font.match_font(MenuFontName)
getfont_bold = None #pygame.font.match_font(MenuFontName, True)
fontsize = 42
else:
MenuFontName = self.settings.get('menu_font')
getfont = pygame.font.match_font(MenuFontName)
getfont_bold = pygame.font.match_font(MenuFontName, True)
fontsize = 32
self.font_normal = pygame.font.Font(getfont,fontsize)
self.font_normal_bold = pygame.font.Font(getfont_bold,fontsize)
self.font_large = pygame.font.Font(getfont,50)
self.font_largeButton = pygame.font.Font(getfont,90)
if (self.settings.getorset('clock_font','dseg7modern') == ""):
self.ClockFontName = None
self.font_big = pygame.font.Font(None,130)
else:
self.ClockFontName = self.settings.get('clock_font')
getfont = pygame.font.match_font(self.ClockFontName) # "dseg14modern")
self.font_big = pygame.font.Font(getfont,130)
def SetBigMessage(self,newMessage,center=False, colour = (255,255,255), ExtraText= "" ):
# ExtraText will scroll along the bottom of the screen if its too long
# returns true if this should happen (Need to call this more often in that case)
area = []
if newMessage != self.message: # Clear screen and put on it the new message
self.message = newMessage
#area =
self.tftScreen.fill((0,0,0))
text_surface = self.font_big.render(newMessage, True, colour)
rect = text_surface.get_rect(center=(SCREEN_WIDTH/2,SCREEN_HEIGHT/2))
area.append( self.tftScreen.blit(text_surface,rect))
if (self.volumebar == True):
if (abs(self.newvolume - self.CurrentVolume) > 1):
area.append(self.VolumeSlider(self.CurrentVolume, colours.BLACK))
self.CurrentVolume = self.newvolume
#~ self.VolumeSlider(self.CurrentVolume, colours.GREEN)
area.append(self.VolumeSlider(self.CurrentVolume, colours.GREEN))
if (ExtraText != ""):
#if (ExtraText != self.oldExtraText):
#self.oldExtraText = ExtraText
lineheight = self.font_normal.get_linesize()
area.append(pygame.draw.rect(self.tftScreen,colours.BLACK,(0,SCREEN_HEIGHT-lineheight,SCREEN_WIDTH,lineheight)))
#self.oldExtrawidth = text_surface.get_width()
text_surface = self.font_normal.render(ExtraText, True, colour)
rect = text_surface.get_rect(left=10-self.ExtraTextoffset,bottom=SCREEN_HEIGHT)
area.append( self.tftScreen.blit(text_surface,rect))
# If we have extra text work out how long it is for scrolling
if (ExtraText != self.oldExtraText):
self.ExtraTextoffset = -1
self.oldExtraText = ExtraText
self.oldExtrawidth = text_surface.get_width()
if self.oldExtrawidth > self.tftScreen.get_width():
self.ExtraTextoffset = 0
#self.oldExtrawidth = self.oldExtrawidth + self.tftScreen.get_width()
#~ log.debug("big text %d", self.oldExtrawidth)
if self.ExtraTextoffset != -1:
self.ExtraTextoffset += 2
if self.ExtraTextoffset > self.oldExtrawidth:
self.ExtraTextoffset = 0
pygame.display.update(area)
# Return True if we have scrolling extra text
return (self.ExtraTextoffset != -1)
def Segmentdigit(self,x,y,colour, newdigit,width=20,height=40,linewidth=4):
#~ if (self.ClockFontName != None):
#~ if (newdigit == 10):
#~ newdigit = ":"
#~ else:
#~ newdigit = str(newdigit)
#~ text_surface = self.font_big.render(newdigit, True, colour)
#~ rect = text_surface.get_rect(left=x,top=y)
#~ self.tftScreen.blit(text_surface,rect)
#~ else:
if newdigit == 0:
pygame.draw.lines(self.tftScreen,colour,False,[[x,y],[x+width,y],[x+width,y+height+height],[x,y+height+height],[x,y]],linewidth)
elif newdigit == 1:
pygame.draw.lines(self.tftScreen,colour,False,[[x+width,y],[x+width,y+height+height]],linewidth)
elif newdigit == 2:
pygame.draw.lines(self.tftScreen,colour,False,[[x,y],[x+width,y],[x+width,y+height],[x,y+height],[x,y+height+height],[x+width,y+height+height]],linewidth)
elif newdigit == 3:
pygame.draw.lines(self.tftScreen,colour,False,[[x,y],[x+width,y],[x+width,y+height+height],[x,y+height+height]],linewidth)
pygame.draw.lines(self.tftScreen,colour,False,[[x,y+height],[x+width,y+height]],linewidth)
elif newdigit == 4:
pygame.draw.lines(self.tftScreen,colour,False,[[x,y],[x,y+height],[x+width,y+height],[x+width,y+height+height]],linewidth)
pygame.draw.lines(self.tftScreen,colour,False,[[x+width,y],[x+width,y+height]],linewidth)
elif newdigit == 5:
pygame.draw.lines(self.tftScreen,colour,False,[[x+width,y],[x,y],[x,y+height],[x+width,y+height],[x+width,y+height+height],[x,y+height+height]],linewidth)
elif newdigit == 6:
pygame.draw.lines(self.tftScreen,colour,False,[[x+width,y],[x,y],[x,y+height+height],[x+width,y+height+height],[x+width,y+height],[x,y+height],[x,y+height+height]],linewidth)
elif newdigit == 7:
pygame.draw.lines(self.tftScreen,colour,False,[[x,y],[x+width,y],[x+width,y+height+height]],linewidth)
elif newdigit == 8:
pygame.draw.lines(self.tftScreen,colour,False,[[x,y],[x+width,y],[x+width,y+height+height],[x,y+height+height],[x,y]],linewidth)
pygame.draw.lines(self.tftScreen,colour,False,[[x,y+height],[x+width,y+height]],linewidth)
elif newdigit == 9:
pygame.draw.lines(self.tftScreen,colour,False,[[x+width,y+height],[x,y+height],[x,y],[x+width,y],[x+width,y+height+height],[x,y+height+height]],linewidth)
elif newdigit == 10:
pygame.draw.circle(self.tftScreen,colour, [x+int(width/2),y+int(height/2)], linewidth)
pygame.draw.circle(self.tftScreen,colour, [x+int(width/2),y+int(height/2)+height], linewidth)
elif (newdigit != -1):
pygame.draw.lines(self.tftScreen,colour,False,[[x,y],[x+width,y],[x+width,y+height],[x,y+height],[x,y+height+height]],linewidth)
pygame.display.flip()
def setMessage(self,newMessage,center=False, colour = colours.RED):
if newMessage != self.message:
self.message = newMessage
if (self.mqttbroker != None):
self.publishname()
area = self.tftScreen.fill((0,0,0))
text_surface = self.font_normal.render(newMessage, True, colour)
rect = text_surface.get_rect(center=(240,160))
area = area.union(self.tftScreen.blit(text_surface,rect))
if (self.volumebar == True):
if (abs(self.newvolume - self.CurrentVolume) > 1):
area = area.union(self.VolumeSlider(self.CurrentVolume, colours.BLACK))
self.CurrentVolume = self.newvolume
#~ self.VolumeSlider(self.CurrentVolume, GREEN)
area = area.union(self.VolumeSlider(self.CurrentVolume, colours.GREEN))
pygame.display.update(area)
#~ self.ShowClock = False
def DisplayMenu(self, Title, newMessage, colour = colours.RED, Highlight = -1, MenuValues = None, highlightcolour = colours.BLUE, ExtraMessage = "", displayoffset = 0):
self.tftScreen.fill((0,0,0))
lineno=0
yoffset = 5 + displayoffset
leftMargin = 5
MenuValuesMargin = 240
noofvalues = -1
if MenuValues != None:
noofvalues = len(MenuValues)
self.showvolume(False)
#log.debug ("Displaying %s", Title)
# find menu items width
listwidth = 0
lineheight = self.font_normal.get_linesize()
for textline in newMessage:
valuewidth, valueheight = self.font_normal.size(textline)
#if (valueheight > fontlineheight):
# fontlineheight = valueheight
if (valuewidth > listwidth):
listwidth = valuewidth
if (Title != ""):
text_surface = self.font_normal.render(Title, True, highlightcolour)
rect = text_surface.get_rect(left=5,top=yoffset + (lineheight * lineno))
self.tftScreen.blit(text_surface,rect)
yoffset = yoffset + lineheight
leftMargin = 20
# where to put any values
MenuValuesMargin = leftMargin + listwidth + 10 # gap
# Display Each menu item and any values
for textline in newMessage:
if (Highlight == lineno):
text_surface = self.font_normal_bold.render(textline, True, highlightcolour)
else:
text_surface = self.font_normal.render(textline, True, colour)
rect = text_surface.get_rect(left=leftMargin,top=yoffset + (lineheight * lineno))
self.tftScreen.blit(text_surface,rect)
# Display menu items value if supplied
if (MenuValues != None) and (lineno < noofvalues):
text_surface = self.font_normal.render(MenuValues[lineno], True, colour)
rect = text_surface.get_rect(left=MenuValuesMargin,top=yoffset + (lineheight * lineno))
self.tftScreen.blit(text_surface,rect)
lineno = lineno + 1
# Always have "Back" as the last item
#if (textline != "Back"):
# text_surface = self.font_normal.render("Back", True, colour)
# rect = text_surface.get_rect(left=leftMargin,top=yoffset + (self.font_normal.get_linesize() * lineno))
# self.tftScreen.blit(text_surface,rect)
# lineno = lineno + 1
# Extra Info. Needa better place for this!
if (ExtraMessage != ""):
text_surface = self.font_normal.render(ExtraMessage, True, colour)
rect = text_surface.get_rect(left=240,top=yoffset + (lineheight * lineno))
self.tftScreen.blit(text_surface,rect)
lineno = lineno + 1
pygame.display.update()
iSize = (lineheight * (lineno+1)) - SCREEN_HEIGHT
if iSize < 0:
iSize = 0
return lineheight, iSize
def DisplayLabel(self, x,y,Text,colour = colours.RED):
if (Text != ""):
text_surface = self.font_normal.render(Text, True, colour)
if (x == SCREEN_WIDTH): # center it
Textwidth, Textheight = self.font_normal.size(Text)
x = (SCREEN_WIDTH/2) - (Textwidth/2)
if (x<0) and (y>0):
rect = text_surface.get_rect(right=SCREEN_WIDTH+x,top=y)
elif (x<0) and (y<0):
rect = text_surface.get_rect(right=SCREEN_WIDTH+x,bottom=SCREEN_HEIGHT+y)
elif (x>0) and (y<0):
rect = text_surface.get_rect(left=x,bottom=SCREEN_HEIGHT+y)
else:
rect = text_surface.get_rect(left=x,top=y)
area = self.tftScreen.blit(text_surface,rect)
return area
return None
def DisplayButton(self, x,y,Text,Action = None,colour = colours.WHITE, backcolour = colours.GREY):
if (Text != ""):
Textwidth, Textheight = self.font_normal.size(Text)
Textwidth += 8
Textheight +=8
text_surface = self.font_normal.render(Text, True, colour)
#pygame.draw.rect(text_surface,border,(0,0,Textwidth-1,Textheight-1,1))
area = []
if (x<0) and (y<0):
rect = text_surface.get_rect(right=SCREEN_WIDTH+x+4,bottom=SCREEN_HEIGHT+y-4, width=Textwidth, height=Textheight)
area = pygame.draw.rect(self.tftScreen,backcolour,(SCREEN_WIDTH-Textwidth+x,SCREEN_HEIGHT-Textheight+y,Textwidth-1,Textheight-1),0)
pygame.draw.rect(self.tftScreen,colour,(SCREEN_WIDTH-Textwidth+x,SCREEN_HEIGHT-Textheight+y,Textwidth-1,Textheight-1),1)
else:
rect = text_surface.get_rect(left=x+4,top=y+4, width=Textwidth, height=Textheight)
area = pygame.draw.rect(self.tftScreen,backcolour,(x,y,Textwidth-1,Textheight-1),0)
pygame.draw.rect(self.tftScreen,colour,(x,y,Textwidth-1,Textheight-1),1)
area = area.union(self.tftScreen.blit(text_surface,rect))
return [3, area, Action, x, y]
return [None, Action]
def DisplayBigButton(self, x,y,Text,Action = None,colour = colours.WHITE, backcolour = colours.GREY):
if (Text != ""):
Textwidth, Textheight = self.font_largeButton.size(Text)
Textwidth += 8
Textheight +=8
text_surface = self.font_largeButton.render(Text, True, colour)
#pygame.draw.rect(text_surface,border,(0,0,Textwidth-1,Textheight-1,1))
area = []
if x >= SCREEN_WIDTH:
x = (SCREEN_WIDTH/2)-(Textwidth/2)
if (x<0) and (y<0):
rect = text_surface.get_rect(right=SCREEN_WIDTH+x+4,bottom=SCREEN_HEIGHT+y-4, width=Textwidth, height=Textheight)
area = pygame.draw.rect(self.tftScreen,backcolour,(SCREEN_WIDTH-Textwidth+x,SCREEN_HEIGHT-Textheight+y,Textwidth-1,Textheight-1),0)
pygame.draw.rect(self.tftScreen,colour,(SCREEN_WIDTH-Textwidth+x,SCREEN_HEIGHT-Textheight+y,Textwidth-1,Textheight-1),1)
else:
rect = text_surface.get_rect(left=x+4,top=y+4, width=Textwidth, height=Textheight)
area = pygame.draw.rect(self.tftScreen,backcolour,(x,y,Textwidth-1,Textheight-1),0)
pygame.draw.rect(self.tftScreen,colour,(x,y,Textwidth-1,Textheight-1),1)
area = area.union(self.tftScreen.blit(text_surface,rect))
return [3, area, Action, x, y]
return [None, Action]
def DisplayImageButton(self, x,y,ImageName,Action = None,colour = colours.WHITE, backcolour = colours.GREY, ImagePath = "/usr/share/icons/Adwaita/48x48/actions/"):
# Returns a list of [Rect, Action ptr]
if (ImageName != ""):
if ImagePath == "":
home_dir = os.path.expanduser('~')
Image = os.path.join(home_dir, ImageName)
elif ImagePath[0] == ".":
home_dir = os.path.expanduser('~')
Image = os.path.join(home_dir, ImagePath[1:])
Image = os.path.join(home_dir, ImageName)
else:
Image = os.path.join(ImagePath, ImageName)
ImageSurface = pygame.image.load(Image)
Imagewidth, Imageheight = ImageSurface.get_size()
Imagewidth += 8
Imageheight +=8
#pygame.draw.rect(text_surface,border,(0,0,Textwidth-1,Textheight-1,1))
outerarea = None
if (x<0) and (y<0):
rect = ImageSurface.get_rect(right=SCREEN_WIDTH+x+4,bottom=SCREEN_HEIGHT+y-4, width=Imagewidth, height=Imageheight)
if colour != None:
outerarea = pygame.draw.rect(self.tftScreen,colour,(SCREEN_WIDTH-Imagewidth+x,SCREEN_HEIGHT-Imageheight+y,Imagewidth-1,Imageheight-1),0)
if backcolour != None:
pygame.draw.rect(self.tftScreen,backcolour,(SCREEN_WIDTH-Imagewidth+x,SCREEN_HEIGHT-Imageheight+y,Imagewidth-1,Imageheight-1),1)
else:
rect = ImageSurface.get_rect(left=x+4,top=y+4, width=Imagewidth, height=Imageheight)
if colour != None:
outerarea = pygame.draw.rect(self.tftScreen,colour,(x,y,Imagewidth-1,Imageheight-1),1)
if backcolour != None:
pygame.draw.rect(self.tftScreen,backcolour,(x,y,Imagewidth-1,Imageheight-1),0)
area = (self.tftScreen.blit(ImageSurface,rect))
if outerarea != None:
area = area.union(outerarea)
return [3, area, Action,x,y]
return [3, None, Action,x,y]
def ControlRadio(self, colour = colours.WHITE):
def ControlRadioPlay(Control):
if (self.media.playerActive() == False):
self.media.playStation(Controls[3][KEY_SelectedValue])
return "Playing"
else:
return "Already Playing"
def ControlRadioStop(Control):
if (self.media.playerActive() != False):
self.media.stopPlayer()
return "Stopped"
else:
return "Already Stopped"
def ControlRadioPause(Control):
if self.media.pausePlayer() == 1:
log.info("Pause")
return "Paused"
else:
log.info("UnPause")
return "Playing"
def ControlRadioClose(Control):
self.MenuWaiting = False
return "Closing Menu"
def ControlRadioSetStation(Control):
# Control[KEY_SelectedValue]
self.settings.set('station', Control[KEY_SelectedValue])
return self.settings.getStationName(self.settings.getInt('station'))
self.caller.pauseclock(True)
self.tftScreen.fill((0,0,0))
dimcolour = (colour[0]/2, colour[1]/2, colour[2]/2)
Controls = []
# Controls along the bottom of the screen
x = 30
y = SCREEN_HEIGHT - 80
#~ ControlPlay = self.DisplayImageButton(x,y,"media-playback-start.png", ControlRadioPlay)
ControlPlay = self.DisplayImageButton(x,y,"play.png", ControlRadioPlay, colour = None, backcolour=None, ImagePath ="/home/pi/Images")
Controls.append(ControlPlay)
x += ControlPlay[1][2]+20
#~ ControlStop = self.DisplayImageButton(x,y,"media-playback-stop.png", ControlRadioStop)
ControlStop = self.DisplayImageButton(x,y,"stop.png", ControlRadioStop, colour = None, backcolour=None, ImagePath ="/home/pi/Images")
Controls.append(ControlStop)
x += ControlStop[1][2]+20
ControlPause = self.DisplayImageButton(x,y,"pause.png", ControlRadioPause, colour = None, backcolour=None, ImagePath ="/home/pi/Images")
Controls.append(ControlPause)
x += ControlPause[1][2]+20
#~ self.DisplayLabel(150,100,"Station",colours.GREEN)
#SxtationList = []
#for stationname in self.settings.STATIONS:
# SxtationList.append(stationname['name'])
DefaultStation = self.settings.getInt('station')
radioselector = self.DisplaySelectValueFromList("",75, 120, DefaultStation, self.settings.getStationList(), colour, ControlRadioSetStation)
Controls.append(list(radioselector))
CloseArea = self.DisplayButton(-30,-30,"Close", ControlRadioClose)
Controls.append(CloseArea)
pygame.display.update()
NewValues = self.HandleGUI(Controls, colour, dimcolour, Statusx = SCREEN_WIDTH, Statusy = 20)
log.info(NewValues)
self.caller.pauseclock(False)
def HandleGUI(self,Controls, colour = colours.WHITE, dimcolour = colours.GREY, Statusx = -20, Statusy = 20):
StartDrag = -1 # tapped on scroll value and dragged
self.MenuWaiting = True
menuTimeout = 0
LOOP_TIME=float(0.1)
gadgetcount = len(Controls)-1
calcTimeout = self.settings.getInt('menu_timeout')*(1/LOOP_TIME) # We're unlikely to update this on the fly
#~ gadgetcount = len(valueListSize)
controlcount = len(Controls)
StatusMessage = ""
LastStatusMessage = ""
LastStatusarea = None
while (self.MenuWaiting == True) or (self.stopping == True):
time.sleep(LOOP_TIME)
if menuTimeout > calcTimeout:
#self.exitMenu()
self.MenuWaiting = False
else:
menuTimeout = menuTimeout + 1
for event in pygame.event.get():
if (event.type is QUIT):
self.MenuWaiting = False
elif (event.type is MOUSEBUTTONUP) and (StartDrag == -1):
menuTimeout = 0
area = None
for ControlNo in range(0,controlcount):
Control = Controls[ControlNo]
if Control[KEY_ControlType] == 3: # Text or Image based button
if (Control[1].collidepoint(event.pos)) and (Control[2] != None):
#~ Button in loop
StatusMessage = Control[2](Control)
elif (Control[KEY_ControlType] == 1) or (Control[KEY_ControlType] == 2): # Scrollable selector
# ControlType, UpButtonarea,UpButton, DownButtonarea,DownButton, SelectButtonarea, scrollsurface, fontlineheight, SelectedValue, OldSelectedValue, MinValue, MaxValue
area = None
if (Control[KEY_UpButtonarea].collidepoint(event.pos)):
if (Control[KEY_SelectedValue] < Control[KEY_MaxValue]): # valueListSize[button]):
Control[KEY_SelectedValue] += 1
area = pygame.draw.polygon(self.tftScreen,dimcolour, Control[KEY_UpButton],0) # UpButtons[button]
ScrollDirection = +1
elif (Control[KEY_DownButtonarea].collidepoint(event.pos)):
if (Control[KEY_SelectedValue] > Control[KEY_MinValue]): # SelectedValues[button] > 0):
Controls[ControlNo][KEY_SelectedValue] -= 1
area = pygame.draw.polygon(self.tftScreen,dimcolour,Control[KEY_DownButton] ,0) # DownButtons[button]
ScrollDirection = -1
# we never get here as this is a scroll start point
#~ elif (Control[KEY_SelectButtonarea].collidepoint(event.pos)):
#~ log.info("Scroll in loop")
#~ StatusMessage = Control[KEYSelectAction](Control[KEY_SelectedValue])
#~ log.info("StatusMessage %s", StatusMessage)
if (Control[KEY_SelectedValue] != Control[KEY_OldSelectedValue]):
pygame.display.update(area) # draw button push
offset = 0
Controls[ControlNo][KEY_OldSelectedValue]= Control[KEY_SelectedValue]
# scroll the value surface under the select area the right number of values
#~ self.tftScreen.set_clip(SelectButtonareas[button])
self.tftScreen.set_clip(Control[KEY_SelectButtonarea])
while (offset < Control[KEY_fontlineheight]): #fontlineheights[button]):
rect = Control[KEY_scrollsurface].get_rect(left=Control[KEY_xs],top=Control[KEY_ys]-Control[KEY_yoffset])
area = self.tftScreen.blit(Control[KEY_scrollsurface],rect)
pygame.display.update(area)
offset = offset + 1
Control[KEY_yoffset] = Control[KEY_yoffset] + ScrollDirection
pygame.time.wait(3)
self.tftScreen.set_clip(None)
# Leave Shaded the scroll buttons at top and bottom of the list
if (Control[KEY_SelectedValue] == Control[KEY_MinValue]):
area = pygame.draw.polygon(self.tftScreen,dimcolour, Control[KEY_DownButton],0)
else:
area = pygame.draw.polygon(self.tftScreen,colour, Control[KEY_DownButton],0)
if (Control[KEY_SelectedValue] == Control[KEY_MaxValue]):
area = area.union(pygame.draw.polygon(self.tftScreen,dimcolour, Control[KEY_UpButton],0))
else:
area = area.union(pygame.draw.polygon(self.tftScreen,colour, Control[KEY_UpButton],0))
pygame.display.update(area)
# if mid drag
elif (StartDrag != -1):
if (event.type is MOUSEMOTION):
dragchange = dragy - event.pos[1]
if abs(dragchange) > StartDrag[KEY_fontlineheight]:
movement = int(dragchange / StartDrag[KEY_fontlineheight])
Newplace = StartDrag[KEY_SelectedValue] + movement
if (Newplace < StartDrag[KEY_MinValue]):
Newplace = StartDrag[KEY_MinValue]
elif (Newplace >= StartDrag[KEY_MaxValue]):
Newplace = StartDrag[KEY_MaxValue]
#~ log.debug("scroll %d moves to %d", movement, Newplace)
StartDrag[KEY_SelectedValue] = Newplace
ScrollDirection = math.copysign(1,movement)
if StartDrag[KEY_OldSelectedValue] != StartDrag[KEY_SelectedValue]:
offset = 0
ChangeAmount = abs(StartDrag[KEY_SelectedValue] - StartDrag[KEY_OldSelectedValue]) # might be less then "movement"
StartDrag[KEY_OldSelectedValue] = StartDrag[KEY_SelectedValue]
self.tftScreen.set_clip(StartDrag[KEY_SelectButtonarea])
while (offset < (StartDrag[KEY_fontlineheight] * ChangeAmount)):
rect = StartDrag[KEY_scrollsurface].get_rect(left=StartDrag[KEY_xs],top=StartDrag[KEY_ys]-StartDrag[KEY_yoffset])
area = self.tftScreen.blit(StartDrag[KEY_scrollsurface],rect)
pygame.display.update(area)
offset = offset + 1
StartDrag[KEY_yoffset] = StartDrag[KEY_yoffset] + ScrollDirection
pygame.time.wait(3)
self.tftScreen.set_clip(None)
# Leave Shaded the scroll buttons at top and bottom of the list
if (StartDrag[KEY_SelectedValue] == StartDrag[KEY_MinValue]):
area = pygame.draw.polygon(self.tftScreen,dimcolour, StartDrag[KEY_DownButton],0)
else:
area = pygame.draw.polygon(self.tftScreen,colour, StartDrag[KEY_DownButton],0)
if (StartDrag[KEY_SelectedValue] == StartDrag[KEY_MaxValue]):
area = area.union(pygame.draw.polygon(self.tftScreen,dimcolour, StartDrag[KEY_UpButton],0))
else:
area = area.union(pygame.draw.polygon(self.tftScreen,colour, StartDrag[KEY_UpButton],0))
pygame.display.update(area)
dragy = event.pos[1]
elif (event.type is MOUSEBUTTONUP):
StartDrag = -1
for ControlNo in range(0,controlcount):
Control = Controls[ControlNo]
# if still in select area, must be a tap
if (Control[KEY_ControlType] == 1) or (Control[KEY_ControlType] == 2):
if (Control[KEY_SelectButtonarea].collidepoint(event.pos)) and (Control[KEYSelectAction] != None):
#~ log.debug("Tap Scroll in loop")
StatusMessage = Control[KEYSelectAction](Control)
#~ log.debug("End drag")
elif (event.type is MOUSEBUTTONDOWN):
menuTimeout = 0
area = None
# Check in start of scroll areas
for ControlNo in range(0,controlcount):
Control = Controls[ControlNo]
#~ for Control in Controls
if (Control[KEY_ControlType] == 1) or (Control[KEY_ControlType] == 2): # Scrollable selector
area = None
if (Control[KEY_SelectButtonarea].collidepoint(event.pos)):
#~ log.debug("Started dragging")
dragx, dragy = event.pos
StartDrag = Control
if StatusMessage != "":
if LastStatusMessage != StatusMessage:
if LastStatusarea != None:
area = pygame.draw.rect(self.tftScreen,(0,0,0),LastStatusarea,0)
#~ pygame.draw.rect(self.tftScreen,(0,0,0),(x,y,Textwidth-1,Textheight-1),1)
#~ area = area.union(self.tftScreen.blit(text_surface,rect))
pygame.display.update(area)
LastStatusMessage = StatusMessage
LastStatusarea = self.DisplayLabel(Statusx, Statusy, StatusMessage, colours.GREEN)
pygame.display.update(LastStatusarea)
currentValues = []
for ControlNo in range(0,controlcount):
Control = Controls[ControlNo]
if Control[KEY_ControlType] == 3: # Text or Image based button
currentValues.append("")
elif (Control[KEY_ControlType] == 1) or (Control[KEY_ControlType] == 2): # Scrollable selector
currentValues.append(Control[KEY_SelectedValue])
self.tftScreen.fill((0,0,0))
pygame.display.update()
return currentValues
def ChangeAlarmSettings(self,alarmno):
"""Allows changing of daily alarm settings"""
def ChangeAlarmSettingsSave(Control):
# Control[KEY_SelectedValue]
log.info("set %d is %s:%s%s with '%s'", alarmno, str(Controls[0][KEY_SelectedValue]), str(Controls[1][KEY_SelectedValue]),
str(Controls[2][KEY_SelectedValue]), str(Controls[3][KEY_SelectedValue]))
if int(Controls[0][KEY_SelectedValue]) < 10:
self.settings.set('alarm_weekday_' + str(alarmno),"0" + str(Controls[0][KEY_SelectedValue]) + ":" + str(Controls[1][KEY_SelectedValue]) + str(Controls[2][KEY_SelectedValue]))
else:
self.settings.set('alarm_weekday_' + str(alarmno),str(Controls[0][KEY_SelectedValue]) + ":" + str(Controls[1][KEY_SelectedValue]) + str(Controls[2][KEY_SelectedValue]))
self.settings.set('alarm_station_' + str(alarmno), str(Controls[3][KEY_SelectedValue]))
#~ Control[KEY_OldSelectedValue] = Control[KEY_SelectedValue]
self.MenuWaiting = False
return "Saveing & Closing Menu"
def ChangeAlarmSettingsCancel(Control):
self.MenuWaiting = False
return "Closing Menu"
FullDaynames = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
colour = colours.WHITE
self.tftScreen.fill((0,0,0))
# give it a title of the day
self.DisplayLabel(SCREEN_WIDTH,5,"Alarm settings for " + FullDaynames[alarmno],colours.GREEN)
valuewidth, valueheight = self.font_large.size("23")
alarmtime = self.settings.get('alarm_weekday_' + str(alarmno))
alarmhours,alarmminutes = alarmtime.split(":")
alarmmintens = int(int(alarmminutes) / 10)
alarmminsunits = int(alarmminutes) % 10
# This needs to be a station number
alarmstation = int(self.settings.get('alarm_station_' + str(alarmno)))
#~ AllButtons = []
Controls = []
#~ UpButtons = []
#~ UpButtonareas = []
#~ DownButtons = []
#~ DownButtonareas = []
#~ SelectButtonareas = []
#~ scrollsurfaces = []
#~ fontlineheights = []
#~ SelectedValues = []
#~ OldSelectedValues = []
#~ valueListSize = []
#~ xs = []
#~ ys = []
#~ valuewidth, valueheight = self.font_large.size("23")
y = 80
x = 120
#~ hourselector = self.DisplayScrollValue(x,y,int(alarmhours),0,23,colour)
hourlist = []
for anhour in range(0,24):
hourlist.append(str(100+anhour)[1:])
hourselector = self.DisplaySelectValueFromList("",x, y, int(alarmhours), hourlist, colour)
Controls.append(list(hourselector))
#~ xs.append(x)
#~ ys.append(y)
#~ #ControlType, UpButtonarea,UpButton, DownButtonarea,DownButton, SelectButtonarea, scrollsurface, fontlineheight = hourselector
#~ UpButtonareas.append(hourselector[1])
#~ UpButtons.append(hourselector[2])
#~ DownButtonareas.append(hourselector[3])
#~ DownButtons.append(hourselector[4])
#~ SelectButtonareas.append(hourselector[5])
#~ scrollsurfaces.append(hourselector[6])
#~ fontlineheights.append(hourselector[7])
#~ SelectedValues.append(int(alarmhours))
#~ OldSelectedValues.append(int(alarmhours))
#~ valueListSize.append(23)
x += hourselector[5][2] + 8
#~ x += valuewidth + 5
#~ valuewidth, valueheight = self.font_large.size("8")
#~ tensselector = self.DisplayScrollValue(x,y,int(alarmmintens),0,5,colour)
tensselector = self.DisplaySelectValueFromList("",x, y, int(alarmmintens), ["0","1","2","3","4","5"], colour)
Controls.append(list(tensselector))
#~ xs.append(x)
#~ ys.append(y)
#~ # ControlType, UpButtonarea,UpButton, DownButtonarea,DownButton, SelectButtonarea, scrollsurface, fontlineheight = tensselector
#~ UpButtonareas.append(tensselector[1])
#~ UpButtons.append(tensselector[2])
#~ DownButtonareas.append(tensselector[3])
#~ DownButtons.append(tensselector[4])
#~ SelectButtonareas.append(tensselector[5])
#~ scrollsurfaces.append(tensselector[6])
#~ fontlineheights.append(tensselector[7])
#~ SelectedValues.append(int(alarmmintens))
#~ OldSelectedValues.append(int(alarmmintens))
#~ valueListSize.append(5)
x += tensselector[5][2] + 8
#~ x += valuewidth + 5
#~ unitsselector = self.DisplayScrollValue(x,y,int(alarmminsunits),0,9,colour)
unitsselector = self.DisplaySelectValueFromList("",x, y, int(alarmminsunits), ["0","1","2","3","4","5","6","7","8","9"], colour)
Controls.append(list(unitsselector))
#~ xs.append(x)
#~ ys.append(y)
#~ # ControlType, UpButtonarea,UpButton, DownButtonarea,DownButton, SelectButtonarea, scrollsurface, fontlineheight = unitsselector
#~ UpButtonareas.append(unitsselector[1])
#~ UpButtons.append(unitsselector[2])
#~ DownButtonareas.append(unitsselector[3])
#~ DownButtons.append(unitsselector[4])
#~ SelectButtonareas.append(unitsselector[5])
#~ scrollsurfaces.append(unitsselector[6])
#~ fontlineheights.append(unitsselector[7])
#~ SelectedValues.append(int(alarmminsunits))
#~ OldSelectedValues.append(int(alarmminsunits))
#~ valueListSize.append(9)
self.DisplayLabel(20,140,"Station",colours.GREEN)
StationList = self.settings.getAllStationInfo()
#for stationname in self.settings.STATIONS:
# StationList.append(stationname['name'])
radioselector = self.DisplaySelectValueFromList("",10, 220, alarmstation, StationList, colour)
Controls.append(list(radioselector))
#~ xs.append(70)
#~ ys.append(190)
#~ # ControlType, UpButtonarea,UpButton, DownButtonarea,DownButton, SelectButtonarea, scrollsurface, fontlineheight = radioselector
#~ UpButtonareas.append(radioselector[1])
#~ UpButtons.append(radioselector[2])
#~ DownButtonareas.append(radioselector[3])
#~ DownButtons.append(radioselector[4])
#~ SelectButtonareas.append(radioselector[5])
#~ scrollsurfaces.append(radioselector[6])
#~ fontlineheights.append(radioselector[7])
#~ SelectedValues.append(alarmstation)
#~ OldSelectedValues.append(alarmstation)
#~ valueListSize.append(len(StationList)-1)
SaveArea = self.DisplayButton(-5,-55,"Save", ChangeAlarmSettingsSave)
Controls.append(SaveArea)