-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathprojector_slideshow.py
executable file
·1513 lines (1243 loc) · 63.1 KB
/
projector_slideshow.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/env python3
# Slideshow application for the Capra Explorer
# Allows passing through photos with a smooth fading animation
# TODO
# TESTING
# REVIEW
# REMOVE
# Imports
import math
import os
import platform
import psutil
import sys
import time
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PIL import Image
if platform.system() == 'Linux':
from RPi import GPIO
from lsm303d import LSM303D
from classes.led_player import RGB_LED, WHITE_LEDS
import datetime
from enum import IntEnum, unique, auto
from classes.capra_data_types import Picture, Hike
from classes.singleton import Singleton
from classes.sql_controller import SQLController
from classes.ui_components import *
# from PyQt5.QtCore import pyqt5_enable_new_onexit_scheme
# Qt.pyqt5_enable_new_onexit_scheme(True)
# import PIL
# from PIL import ImageTk, Image, ImageQt
# from PIL.ImageQt import ImageQt
# from classes import sql_controller
# import traceback
# PIN and Settings values are stored here
import globals as g
g.init()
print('projector_slideshow.py running...')
# Filewide Statuses
# ----- Hardware -----
rotaryCounter = 0 # Global value for rotary encoder, so ImageBlender thread doesn't need to ask SlideshowWindow
rotaryCounterLast = 0 # Needed to measure the change of the encoder that happens during the Encoder loop
isReadyForNewPicture = True # REVIEW - not sure if nedded, could be a solution
picture = None # REMOVE - not needed anymore. we use ImageBlender
slideshowSoftwareThreadpool = QThreadPool()
slideshowHardwareThreadpool = QThreadPool()
# Statuses
# -----------------------------------------------------------------------------
class StatusOrientation(IntEnum):
LANDSCAPE = 0
PORTRAIT = 1
class StatusPlayPause(IntEnum):
PAUSE = 0
PLAY = 1
class StatusScope(IntEnum):
HIKE = 0
GLOBAL = 1
class StatusMode(IntEnum):
'''The order as described by the integer values is the order
in which the modes will change'''
__order__ = 'TIME COLOR ALTITUDE'
TIME = 0
COLOR = 1
ALTITUDE = 2
class StatusDirection(IntEnum):
NEXT = 0
PREV = 1
# Singleton Status class; starting status values are defined here
class Status(Singleton):
"""
Singleton class containing all status variables for the slideshow
\n\t orientation, playpause, scope, mode, direction
"""
# Class variables, not instance variables
# Define starting status values here
_orientation = StatusOrientation.LANDSCAPE
_playpause = StatusPlayPause.PAUSE
_scope = StatusScope.HIKE
_mode = StatusMode.TIME
_direction = StatusDirection.NEXT
_speed = 1 # only used for Mac/Windows app (since there' no Rotary Encoder to detect speed)
# Eventually maybe we would need to setup this with input from the database
def __init__(self):
super().__init__()
# Orientation
def get_orientation(self) -> StatusOrientation:
return Status()._orientation
def change_orientation(self):
Status()._orientation = StatusOrientation((Status()._orientation + 1) % 2)
def set_orientation_landscape(self):
Status()._orientation = StatusOrientation.LANDSCAPE
def set_orientation_vertical(self):
Status()._orientation = StatusOrientation.PORTRAIT
# Play Pause
def get_playpause(self) -> StatusPlayPause:
return Status()._playpause
def change_playpause(self):
Status()._playpause = StatusPlayPause((Status()._playpause + 1) % 2)
def set_play(self):
Status()._playpause = StatusPlayPause.PLAY
def set_pause(self):
Status()._playpause = StatusPlayPause.PAUSE
# Scope
def get_scope(self) -> StatusScope:
return Status()._scope
def change_scope(self):
Status()._scope = StatusScope((Status()._scope + 1) % 2)
# Mode
def get_mode(self) -> StatusMode:
return Status()._mode
def next_mode(self):
Status()._mode = StatusMode((Status()._mode + 1) % 3)
def set_mode_time(self):
Status()._mode = StatusMode.TIME
def set_mode_color(self):
Status()._mode = StatusMode.COLOR
def set_mode_altitude(self):
Status()._mode = StatusMode.ALTITUDE
# Direction
def get_direction(self) -> StatusDirection:
return Status()._direction
def set_direction_next(self):
Status()._direction = StatusDirection.NEXT
def set_direction_prev(self):
Status()._direction = StatusDirection.PREV
# Speed - Mac/Windows only
def get_speed(self) -> int:
return Status()._speed
def increase_speed(self):
Status()._speed = int(Status()._speed * 2)
if Status()._speed > 256:
Status()._speed = 256
def decrease_speed(self):
Status()._speed = int(Status()._speed / 2)
if Status()._speed < 1:
Status()._speed = 1
# Threads
# -----------------------------------------------------------------------------
class WorkerSignals(QObject):
'''
Defines the signals available from a running worker thread.
Supported signals are:
finished
No data passed, just a notifier of completion
error
`tuple` (exctype, value, traceback.format_exc() )
result
`object` data returned from processing, anything
results
Four `object` data returned from processing, anything
progress
`int` indicating % progress
'''
finished = pyqtSignal()
error = pyqtSignal(tuple)
result = pyqtSignal(object)
results = pyqtSignal(object, object, object, object)
progress = pyqtSignal(int)
'''
Defines status which is checked for in infinite loop
By setting to True, the thread will quit,
and closing of the program won't hang
'''
terminate = False
class RotaryEncoder(QRunnable):
'''Custom thread for the rotary coder, so no signal is ever lost'''
def __init__(self, PIN_A: int, PIN_B: int, *args, **kwargs):
super(RotaryEncoder, self).__init__()
self.RoAPin = PIN_A
self.RoBPin = PIN_B
GPIO.setup(self.RoAPin, GPIO.IN)
GPIO.setup(self.RoBPin, GPIO.IN)
self.signals = WorkerSignals()
self.flag = 0
self.Last_RoB_Status = 0
self.Current_RoB_Status = 0
self.Last_Direction = 0 # 0 for backward, 1 for forward
self.Current_Direction = 0 # 0 for backward, 1 for forward
self.MAXQUEUE = 7
self.lst = list()
self.last_time = datetime.datetime.now().timestamp()
self.speedText = ""
self.average = 0
self.dt = 0
self.multFactor = 1
def calculate_speed(self):
self.dt = round(datetime.datetime.now().timestamp() - self.last_time, 5)
# data sanitation: clean up random stray values that are extremely low
if self.dt < .005:
self.dt = .1
if len(self.lst) > self.MAXQUEUE:
self.lst.pop()
self.lst.insert(0, self.dt)
self.average = sum(self.lst) / len(self.lst)
self.last_time = datetime.datetime.now().timestamp()
# .3 .07 .02
# .1 .05 .02
if self.average >= .3:
self.speedText = "slow"
elif self.average >= .07 and self.average < .3:
self.speedText = "medium"
elif self.average >= .02 and self.average < .07:
self.speedText = "fast"
else:
self.speedText = "super-duper fast"
return self.average, self.speedText, self.dt
# Starting logic comes from the following project:
# https://www.sunfounder.com/learn/Super_Kit_V2_for_RaspberryPi/lesson-8-rotary-encoder-super-kit-for-raspberrypi.html
def rotaryTurn(self):
global rotaryCounter
self.Last_RoB_Status = GPIO.input(self.RoBPin)
while(not GPIO.input(self.RoAPin)):
self.Current_RoB_Status = GPIO.input(self.RoBPin)
self.flag = 1
if self.flag == 1:
Status().set_pause() # Causes the PlayPause thread to not increment the rotary counter
self.flag = 0
if (self.Last_RoB_Status == 0) and (self.Current_RoB_Status == 1):
self.Current_Direction = 1
if (self.Last_RoB_Status == 1) and (self.Current_RoB_Status == 0):
self.Current_Direction = 0
if (self.Current_Direction != self.Last_Direction):
self.lst.clear()
self.average, self.speedText, self.dt = self.calculate_speed()
speed = 0.5 / self.dt
self.multFactor = int(0.5 / self.average)
if (self.multFactor < 1 or self.Current_Direction != self.Last_Direction):
self.multFactor = 1
if (self.Current_Direction == 1):
rotaryCounter = rotaryCounter - 1 * self.multFactor
Status().set_direction_prev()
else:
rotaryCounter = rotaryCounter + 1 * self.multFactor
Status().set_direction_next()
self.Last_Direction = self.Current_Direction
print('rotaryCounter: {g}, diff_time: {d:.4f}, speed: {s:.2f}, MultFactor: {a:.2f} ({st})'.format(g=rotaryCounter, d=self.dt, s=speed, a=self.multFactor, st=self.speedText))
# The counter is never reset, ImageBlender finds difference between this read and the last read
# No signal is ever emitted since rotaryCounter is a global value that is only written to in this thread
# ImageBlender can directly access it safely, at anytime
def clear(self, ev=None):
global rotaryCounter
rotaryCounter = 0
print('rotaryCounter = {g}'.format(g=rotaryCounter))
time.sleep(1)
def run(self):
while True:
self.rotaryTurn()
class HardwareButton(QRunnable):
'''Thread to continually monitor a GPIO PIN, emits signal when button is pressed'''
def __init__(self, PIN: int, *args, **kwargs):
super(HardwareButton, self).__init__()
self.status = False
self.PIN = PIN
GPIO.setup(self.PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
self.signals = WorkerSignals()
def run(self):
while True:
if GPIO.input(self.PIN) == False: # Button press detected
if self.status == False: # Button was just OFF
self.signals.result.emit(True)
self.status = True # Update the status to ON
else: # Button is not pressed
self.status = False
time.sleep(0.05)
class Accelerometer(QRunnable):
'''Thread to monitor the LSM303D accelerometer'''
def __init__(self, address, *args, **kwargs):
super(Accelerometer, self).__init__()
self.lsm = LSM303D(address) # Create accelerometer object from the address (should be 0x1d)
# self.lsm = LSM303D(0x1d) # Change to 0x1e if you have soldered the address jumper
self.lastOrientation = None
self.signals = WorkerSignals()
def run(self):
while True:
try:
xyz = self.lsm.accelerometer()
except Exception as error:
time.sleep(2.0)
continue
raise Exception("Oops! There was no valid accelerometer data.")
ax = round(xyz[0], 7)
ay = round(xyz[1], 7)
az = round(xyz[2], 7)
pitch = round(180 * math.atan(ax/math.sqrt(ay*ay + az*az))/math.pi, 3)
roll = round(180 * math.atan(ay/math.sqrt(ax*ax + az*az))/math.pi, 3)
if abs(pitch) < 20:
if roll < -45: # correct vertical
orientation = StatusOrientation.PORTRAIT
elif roll > 45: # upside-down vertical
orientation = None
else: # horizontal
orientation = StatusOrientation.LANDSCAPE
else:
if roll < -30: # correct vertical
orientation = StatusOrientation.PORTRAIT
elif roll > 30: # upside-down vertical
orientation = None
else: # horizontal
orientation = StatusOrientation.LANDSCAPE
# Check to see if orientation changed
if self.lastOrientation != orientation:
self.lastOrientation = orientation
# Ensure it is a usable orientation
if orientation == StatusOrientation.LANDSCAPE or orientation == StatusOrientation.PORTRAIT:
self.signals.result.emit(orientation)
time.sleep(0.5)
class PlayPause(QRunnable):
'''Thread to continually increment the slideshow while in PLAY'''
def __init__(self, *args, **kwargs):
super(PlayPause, self).__init__()
self.signals = WorkerSignals() # Holds a terminate status, used to kill thread
def run(self):
global rotaryCounter
while True:
if self.signals.terminate: # Garbage collection
break
if Status().get_playpause() == StatusPlayPause.PLAY:
if Status().get_direction() == StatusDirection.NEXT:
rotaryCounter += 1 * Status().get_speed()
elif Status().get_direction() == StatusDirection.PREV:
rotaryCounter -= 1 * Status().get_speed()
# TODO - What should this be?
time.sleep(1.0)
class ImageBlender(QRunnable):
'''Thread to continually tries blending the next image into the current image'''
def __init__(self, sql_cntrl, picture, *args, **kwargs):
super(ImageBlender, self).__init__()
# This thread holds an instance of the SQLController
self.sql_controller = sql_cntrl
# Thread maintains and updates the Picture instance
self.picture = picture # TODO - should I pass in the picture or just access it
# Needed setup
self.signals = WorkerSignals() # Setups signals that will be used to send data back to SlideshowWindow
# Holds a terminate status, used to garbage collect threads
self._skipNextStatus = False # setter via setSkipNext(), decides if _control_rotary_next() is called
self._skipPrevStatus = False # setter via setSkipPrev(), decides if _control_rotary_prev() is called
# Status value for alpha blending
self.alpha = 0.0
# Image blending settings
self.ALPHA_RESET = 0.18 # value alpha is reset to after each new Picture (row)
self.ALPHA_INCREMENT = 0.025 # value alpha is incremented by each blend
self.ALPHA_WAIT = 0.05 # time in ms to wait between blends
self.ALPHA_UPPERBOUND = 0.60 # value of alpha that blend is considered finished
# self.ALPHA_INCREMENT = 0.025 # Rougly 20 frames until the old picture is blurred out
# self.ALPHA_WAIT = 0.05 # 1/20frames
# Load initial image
try:
self.currentf_raw = Image.open(self.picture.cameraf, 'r')
self.nextf_raw = Image.open(self.picture.cameraf, 'r')
self.current1_raw = Image.open(self.picture.camera1, 'r')
self.next1_raw = Image.open(self.picture.camera1, 'r')
self.current2_raw = Image.open(self.picture.camera2, 'r')
self.next2_raw = Image.open(self.picture.camera2, 'r')
self.current3_raw = Image.open(self.picture.camera3, 'r')
self.next3_raw = Image.open(self.picture.camera3, 'r')
except Exception as error:
print('\nError while opening image during ImageBlender construction')
print(error)
def setSkipNext(self):
'''Public function to tell thread we should skip 'next' on the next pass through the loop'''
self._skipNextStatus = True
def setSkipPrev(self):
'''Public function to tell thread we should skip 'previous' on the next pass through the loop'''
self._skipPrevStatus = True
# Public functions to tell thread that we switched orientations
def loadLandscapeImages(self):
'''Public function called upon switching orientations; emits the current landscape images.'''
try:
self.currentf_raw = Image.open(self.picture.cameraf, 'r')
self.nextf_raw = Image.open(self.picture.cameraf, 'r')
except Exception as error:
print('\nError while opening image during loadLandscapeImages()')
print(error)
time.sleep(0.25) # This sleep gives a bit of extra time for the images to update before rotating the view
self.signals.results.emit(self.current1_raw, self.current2_raw, self.current3_raw, self.currentf_raw)
def loadPortraitImages(self):
'''Public function called upon switching orientations; emits the current portrait images.'''
try:
self.current1_raw = Image.open(self.picture.camera1, 'r')
self.next1_raw = Image.open(self.picture.camera1, 'r')
self.current2_raw = Image.open(self.picture.camera2, 'r')
self.next2_raw = Image.open(self.picture.camera2, 'r')
self.current3_raw = Image.open(self.picture.camera3, 'r')
self.next3_raw = Image.open(self.picture.camera3, 'r')
except Exception as error:
print('\nError while opening image during loadLandscapeImages()')
print(error)
time.sleep(0.5) # This sleep gives a bit of extra time for the images to update before rotating the view
self.signals.results.emit(self.current1_raw, self.current2_raw, self.current3_raw, self.currentf_raw)
# Private functions for SQL queries
def _control_skip_next(self):
'''Updates ImageBlender.picture with next skip'''
mode = Status().get_mode()
scope = Status().get_scope()
if scope == StatusScope.HIKE:
if mode == StatusMode.TIME:
self.picture = self.sql_controller.get_next_time_skip_in_hikes(self.picture)
elif mode == StatusMode.ALTITUDE:
self.picture = self.sql_controller.get_next_altitude_skip_in_hikes(self.picture)
elif mode == StatusMode.COLOR:
self.picture = self.sql_controller.get_next_color_skip_in_hikes(self.picture)
elif scope == StatusScope.GLOBAL:
if mode == StatusMode.TIME:
self.picture = self.sql_controller.get_next_time_skip_in_global(self.picture)
elif mode == StatusMode.ALTITUDE:
self.picture = self.sql_controller.get_next_altitude_skip_in_global(self.picture)
elif mode == StatusMode.COLOR:
self.picture = self.sql_controller.get_next_color_skip_in_global(self.picture)
def _control_skip_previous(self):
'''Updates ImageBlender.picture with previous skip'''
mode = Status().get_mode()
scope = Status().get_scope()
if scope == StatusScope.HIKE:
if mode == StatusMode.TIME:
self.picture = self.sql_controller.get_previous_time_skip_in_hikes(self.picture)
elif mode == StatusMode.ALTITUDE:
self.picture = self.sql_controller.get_previous_altitude_skip_in_hikes(self.picture)
elif mode == StatusMode.COLOR:
self.picture = self.sql_controller.get_previous_color_skip_in_hikes(self.picture)
elif scope == StatusScope.GLOBAL:
if mode == StatusMode.TIME:
self.picture = self.sql_controller.get_previous_time_skip_in_global(self.picture)
elif mode == StatusMode.ALTITUDE:
self.picture = self.sql_controller.get_previous_altitude_skip_in_global(self.picture)
elif mode == StatusMode.COLOR:
self.picture = self.sql_controller.get_previous_color_skip_in_global(self.picture)
def _control_rotary_next(self, change: int):
'''Updates ImageBlender.picture with next image
::
change int: size of offset
'''
mode = Status().get_mode()
scope = Status().get_scope()
currentHike = self.picture.hike_id
if scope == StatusScope.HIKE:
if mode == StatusMode.TIME:
self.picture = self.sql_controller.get_next_time_in_hikes(self.picture, change)
elif mode == StatusMode.ALTITUDE:
self.picture = self.sql_controller.get_next_altitude_in_hikes(self.picture, change)
elif mode == StatusMode.COLOR:
self.picture = self.sql_controller.get_next_color_in_hikes(self.picture, change)
# Isn't used for anything, but could be used for splitting up UI updates
if self.picture.hike_id != currentHike:
print('NEXT - NEW HIKE!')
# self.updateScreenHikesNewHike()
# else:
# self.updateScreenHikesNewPictures()
elif scope == StatusScope.GLOBAL:
if mode == StatusMode.TIME:
self.picture = self.sql_controller.get_next_time_in_global(self.picture, change)
elif mode == StatusMode.ALTITUDE:
self.picture = self.sql_controller.get_next_altitude_in_global(self.picture, change)
elif mode == StatusMode.COLOR:
self.picture = self.sql_controller.get_next_color_in_global(self.picture, change)
def _control_rotary_previous(self, change: int):
'''Updates ImageBlender.picture with previous image
::
change int: size of offset
'''
mode = Status().get_mode()
scope = Status().get_scope()
currentHike = self.picture.hike_id
if scope == StatusScope.HIKE:
if mode == StatusMode.TIME:
self.picture = self.sql_controller.get_previous_time_in_hikes(self.picture, change)
elif mode == StatusMode.ALTITUDE:
self.picture = self.sql_controller.get_previous_altitude_in_hikes(self.picture, change)
elif mode == StatusMode.COLOR:
self.picture = self.sql_controller.get_previous_color_in_hikes(self.picture, change)
# Isn't used for anything, but could be used for splitting up UI updates
if self.picture.hike_id != currentHike:
print('PREVIOUS - NEW HIKE!')
# self.updateScreenHikesNewHike()
# else:
# self.updateScreenHikesNewPictures()
elif scope == StatusScope.GLOBAL:
if mode == StatusMode.TIME:
self.picture = self.sql_controller.get_previous_time_in_global(self.picture, change)
elif mode == StatusMode.ALTITUDE:
self.picture = self.sql_controller.get_previous_altitude_in_global(self.picture, change)
elif mode == StatusMode.COLOR:
self.picture = self.sql_controller.get_previous_color_in_global(self.picture, change)
def _emit_result_update_image_and_alpha(self):
'''Emits signal to SlideshowWindow which calls `_new_picture_loaded()`'''
self.signals.result.emit(self.picture) # Emits back to SlideshowWindow
self.alpha = self.ALPHA_RESET # Reset the alpha
# Locally change the next raw image
if Status().get_orientation() == StatusOrientation.LANDSCAPE:
try:
self.nextf_raw = Image.open(self.picture.cameraf, 'r')
except Exception as error:
print('\nError while blending landscape image in: _emit_result_update_image_and_alpha()')
print(error)
elif Status().get_orientation() == StatusOrientation.PORTRAIT:
try:
self.next1_raw = Image.open(self.picture.camera1, 'r')
self.next2_raw = Image.open(self.picture.camera2, 'r')
self.next3_raw = Image.open(self.picture.camera3, 'r')
except Exception as error:
print('\nError while blending vertical images in: _emit_result_update_image_and_alpha()')
print(error)
def run(self):
'''Continually runs blending images together, emiting images back to SlideshowWindow
signals end up calling: `_new_picture_loaded()`, `_load_new_images()`, `_finished_image_blend()`'''
while True:
if self.signals.terminate: # Garbage collection
break
# SQLController will only be called if there has been a hardware signal
# Otherwise, it simply blends the image if alpha is < 0.65
if self._skipNextStatus == True:
self._control_skip_next()
self._emit_result_update_image_and_alpha() # NOTE - emit
self._skipNextStatus = False
elif self._skipPrevStatus == True:
self._control_skip_previous()
self._emit_result_update_image_and_alpha() # NOTE - emit
self._skipPrevStatus = False
else:
global rotaryCounter
global rotaryCounterLast
change = rotaryCounter - rotaryCounterLast
# Changing Pause status for the rotary encoder happens inside RotaryEncoder thread
# Because the logic here is also used for the auto-play functionality; pausing in
# this block causes Play not to work
if change > 0:
# print('POSITIVE')
# print(change)
rotaryCounterLast = rotaryCounter
self._control_rotary_next(change)
self._emit_result_update_image_and_alpha() # NOTE - emit
elif change < 0:
# print('NEGATIVE')
rotaryCounterLast = rotaryCounter
self._control_rotary_previous(abs(change))
self._emit_result_update_image_and_alpha() # NOTE - emit
# Blending happens here
if self.alpha < self.ALPHA_UPPERBOUND:
print('blend')
# Increments the alpha, so the image will slowly blend
# REVIEW - okay it seems like this isn't doing anyting at all
# Wow. this is after the blend function. wow lol, this was unreachable.
# But wait, how is it still blending. OH i guess it is just using
# self.alpha += 0.0001
# self.alpha += 0.04
self.alpha += self.ALPHA_INCREMENT
# Only blends the landscape photo or portrait photos depending on the mode
if Status().get_orientation() == StatusOrientation.LANDSCAPE:
try:
self.currentf_raw = Image.blend(self.currentf_raw, self.nextf_raw, self.alpha)
except Exception as error:
print('\nError while blending landscape:')
print(error)
continue
elif Status().get_orientation() == StatusOrientation.PORTRAIT:
try:
self.current1_raw = Image.blend(self.current1_raw, self.next1_raw, self.alpha)
self.current2_raw = Image.blend(self.current2_raw, self.next2_raw, self.alpha)
self.current3_raw = Image.blend(self.current3_raw, self.next3_raw, self.alpha)
except Exception as error:
print('\nError while blending portrait:')
print(error)
continue
# Emits signal to SlideshowWindow which calls _load_new_images()
self.signals.results.emit(self.current1_raw, self.current2_raw, self.current3_raw, self.currentf_raw)
if self.alpha >= self.ALPHA_UPPERBOUND:
# Emits signal to SlideshowWindow which calls _finished_image_blend()
print(f'Alpha > {self.ALPHA_UPPERBOUND}')
self.signals.finished.emit()
# TODO - still figure out this amount
time.sleep(self.ALPHA_WAIT)
class SlideshowWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super(SlideshowWindow, self).__init__(*args, **kwargs)
# Test counter variable to see the frame rate
self.blendCount = 0
# self.checkForCamera() # TODO - implement Camera detection via Hall Effect sensor
self.loadSavedState() # Loads the state of last picture, mode, and scope
self.setupDB() # Mac/Windows shows the database dialog
self.setupWindowLayout(self.picture)
self.setupUI()
self.setupSoftwareThreads()
if platform.system() == 'Darwin' or platform.system() == 'Windows':
self.setupMenuBar()
if platform.system() == 'Linux':
self.setupGPIO()
self.setupHardwareThreads()
# Setup Helpers
# -------------------------------------------------------------------------
def loadSavedState(self):
# TODO - Pull from the status text file and update the Status() object
self._saved_picture_id = 1
Status().set_mode_time()
def setupDB(self):
'''Initializes the database connection.\n
If on Mac/Windows give dialog box to select database,
otherwise it will use the global defined location for the database'''
# Mac/Windows: select the location
if platform.system() == 'Darwin' or platform.system() == 'Windows':
filename = QFileDialog.getOpenFileName(self, 'Open file', '', 'Database (*.db)')
self.database = filename[0]
self.directory = os.path.dirname(self.database)
else: # Raspberry Pi: preset location
self.database = g.DATAPATH_PROJECTOR + g.DBNAME_MASTER
self.directory = g.DATAPATH_PROJECTOR
print(self.database)
print(self.directory)
self.sql_controller = SQLController(database=self.database, directory=self.directory)
if (self.sql_controller.get_picture_id_count(self._saved_picture_id)):
self.picture = self.sql_controller.get_picture_with_id(self._saved_picture_id)
else:
self.picture = self.sql_controller.get_first_time_picture()
### TODO: TESTING - comment out to speed up program load time
self.uiData = self.sql_controller.preload_ui_data()
self.preload = True
def setupMenuBar(self):
menubar = self.menuBar()
# filemenu = menubar.addMenu('File')
helpmenu = menubar.addMenu('Help')
# File
# exitaction = filemenu.addAction("Change Database")
# exitaction.triggered.connect(self.print_change)
# Help
pathhelp = helpmenu.addAction("Toggle Help Menu")
pathhelp.triggered.connect(self.control_help_menu)
def setupWindowLayout(self, picture: Picture):
'''Setup the window size, title, and container layout'''
self.setWindowTitle("Capra Explorer Slideshow")
self.setGeometry(0, 50, 1280, 720)
# self.setStyleSheet("background-color: black;")
pagelayout = QVBoxLayout()
pagelayout.setContentsMargins(0, 0, 0, 0)
self.stacklayout = QStackedLayout()
pagelayout.addLayout(self.stacklayout)
# Landscape view
# Sets the initial picture to be loaded
self.pictureLandscape = UIImage(picture.cameraf)
self.stacklayout.addWidget(self.pictureLandscape) # Add landscape UIImage to stack layout
# Vertical view
verticallayout = QHBoxLayout()
verticallayout.setContentsMargins(0, 0, 0, 0)
verticallayout.setSpacing(0)
self.pictureVertical1 = UIImage(picture.camera1)
self.pictureVertical2 = UIImage(picture.camera2)
self.pictureVertical3 = UIImage(picture.camera3)
verticallayout.addWidget(self.pictureVertical3)
verticallayout.addWidget(self.pictureVertical2)
verticallayout.addWidget(self.pictureVertical1)
verticalImages = QWidget()
verticalImages.setLayout(verticallayout)
self.stacklayout.addWidget(verticalImages) # Add vertical QWidget of UIImages to stack layout
# Add central widget
centralWidget = QWidget()
centralWidget.setLayout(pagelayout)
self.setCentralWidget(centralWidget)
# Setup the custom UI components that are on top of the slideshow
def setupUI(self):
# Top UI elements
# ---------------------------------------------------------------------
self.topUnderlay = UIUnderlay(self)
# self.leftLabel = UILabelTop(self, '', Qt.AlignLeft)
self.centerLabel = UILabelTopCenter(self, '', '')
self.rightLabel = UILabelTop(self, '', Qt.AlignRight)
# Mode UI element
# self.modeOverlay = UIModeOverlay(self, 'assets/[email protected]')
# New Top UI
# ---------------------------------------------------------------------
self.scopeWidget = UIScope(self)
self.scopeWidget.opacityHide()
self.topMiddleContainer = UIContainer(self, QHBoxLayout(), Qt.AlignHCenter)
hspacer = QSpacerItem(100, 0)
self.topMiddleContainer.layout.addItem(hspacer)
# Color Palette
# self.palette = ColorPalette(self.picture.colors_rgb, self.picture.colors_conf, True)
# self.palette.setGraphicsEffect(UIEffectDropShadow())
# self.topMiddleContainer.layout.addWidget(self.palette)
# New Color Palette
self.colorpalette = ColorPaletteNew(self, False, self.picture.colors_rgb, self.picture.colors_conf)
self.colorpalette.setGraphicsEffect(UIEffectDropShadow())
# Time, Color, Altitude Graphs
# ---------------------------------------------------------------------
spacer = QSpacerItem(0, 25)
self.bottomUIContainer = UIContainer(self, QVBoxLayout(), Qt.AlignBottom)
percent_rank = self.sql_controller.ui_get_percentage_in_hike_with_mode('time', self.picture)
print(f'Rank New: {percent_rank}')
# Speed Indicator
if platform.system() == 'Darwin' or platform.system() == 'Windows':
self.scrollSpeedLabel = UILabelTop(self, f'{Status().get_speed()}x', Qt.AlignLeft)
self.scrollSpeedLabel.setGraphicsEffect(UIEffectDropShadow())
self.bottomUIContainer.layout.addWidget(self.scrollSpeedLabel)
# Altitude Graph
altitudelist = self.sql_controller.ui_get_altitudes_for_hike_sortby('time', self.picture, self.uiData.indexListForHike[self.picture.hike_id])
print(altitudelist)
self.altitudegraph = AltitudeGraph(False, altitudelist, percent_rank, self.picture.altitude)
self.altitudegraph.setGraphicsEffect(UIEffectDropShadow())
self.bottomUIContainer.layout.addWidget(self.altitudegraph)
# self.bottomUIContainer.layout.addItem(spacer)
# Color Bar
colorlist = self.sql_controller.ui_get_colors_for_hike_sortby('time', self.picture, self.uiData.indexListForHike[self.picture.hike_id])
self.colorbar = ColorBar(False, colorlist, percent_rank, self.picture.color_rgb)
self.colorbar.setGraphicsEffect(UIEffectDropShadow())
self.bottomUIContainer.layout.addWidget(self.colorbar)
# Time Bar
self.timebar = TimeBar(True, QColor(62, 71, 47), len(colorlist), percent_rank)
self.timebar.myHide()
self.timebar.setGraphicsEffect(UIEffectDropShadow())
self.bottomUIContainer.layout.addWidget(self.timebar)
# Spacer at bottom
# self.bottomUIContainer.layout.addItem(spacer)
# Fullscreen Components
# ---------------------------------------------------------------------
self.helpMenu = UIHelpMenu(self)
# Portrait UI
# ---------------------------------------------------------------------
self.portraitUIContainerTop = UIContainer(self, QHBoxLayout(), Qt.AlignRight)
self.vlabelCenter = PortraitTopLabel("Altitude")
self.vlabelCenter.setGraphicsEffect(UIEffectDropShadow())
self.portraitUIContainerTop.layout.addWidget(self.vlabelCenter)
self.portraitUIContainerTop.hide()
# Setups up a UI timer for controlling the fade out of UI elements
# ---------------------------------------------------------------------
self.timerFadeOutUI = QTimer()
self.timerFadeOutUI.setSingleShot(True)
self.timerFadeOutUI.timeout.connect(self._fadeOutUI)
# Setup all software threads
# ImageFader - handles the fading between old and new pictures
def setupSoftwareThreads(self):
global slideshowSoftwareThreadpool
# self.threadpoolSoftware = QThreadPool()
slideshowSoftwareThreadpool.setMaxThreadCount(2) # TODO - change if more threads are needed
# ImageFader, sends 3 callbacks
# result() : Picture (row)
# results() : every frame that finished a blend (~20frames per blend)
# finished() : when blending has finished blending two images;
# callback used to know when to fade out UI elements
self.imageBlender = ImageBlender(self.sql_controller, self.picture)
# Receives back from ImageBlender a Picture (row)
self.imageBlender.signals.result.connect(self._new_picture_loaded)
# Receives back from ImageBlender blended Images (Image module); updates Pixmap
self.imageBlender.signals.results.connect(self._load_new_images)
# Receives finished signal, used to fade out UI and print test values
self.imageBlender.signals.finished.connect(self._finished_image_blend)
slideshowSoftwareThreadpool.start(self.imageBlender)
# Play Pause, sends 0 callbacks
self.playPauseThread = PlayPause()
slideshowSoftwareThreadpool.start(self.playPauseThread)
# Setup hardware pins
def setupGPIO(self):
# Set the GPIO mode, alternative is GPIO.BOARD
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
# Rotary Encoder
self.PIN_ROTARY_A = g.ENC1_A
self.PIN_ROTARY_B = g.ENC1_B
# Buttons
self.PIN_ROTARY_BUTT = g.BUTT_ENC1
self.PIN_PREV = g.BUTT_PREV
self.PIN_PLAY_PAUSE = g.BUTT_PLAY_PAUSE
self.PIN_NEXT = g.BUTT_NEXT
self.PIN_MODE = g.BUTT_MODE
self.PIN_HALL_EFFECT = g.HALL_EFFECT_PIN
# Accelerometer
self.PIN_ACCEL = g.ACCEL
# NeoPixels
# self.PIN_NEOPIXELS = g.NEO1
# LED indicators
if platform.system() == 'Linux':
self.ledWhite = WHITE_LEDS(g.WHITE_LED1, g.WHITE_LED2, g.WHITE_LED3)
self.ledWhite.turn_off()
if Status().get_mode() == StatusMode.TIME:
self.ledWhite.set_time_mode()
elif Status().get_mode() == StatusMode.COLOR:
self.ledWhite.set_color_mode()
elif Status().get_mode() == StatusMode.ALTITUDE:
self.ledWhite.set_altitude_mode()
self.ledRGB = RGB_LED(g.RGB2_RED, g.RGB2_GREEN, g.RGB2_BLUE)
self.ledRGB.turn_off()
# if Status().get_scope() == StatusScope.GLOBAL:
# self.ledRGB.turn_teal()
# Test LED - which isn't visible from outside of the case
self.PIN_LED_TEST_RED = g.RGB1_RED
self.PIN_LED_TEST_GREEN = g.RGB1_GREEN
# self.PIN_LED_TEST_BLUE = 0 # Used for sending a signal on startup
GPIO.setup(self.PIN_LED_TEST_RED, GPIO.OUT)
GPIO.setup(self.PIN_LED_TEST_GREEN, GPIO.OUT)
# Setup threads to check for hardware changes
def setupHardwareThreads(self):
global slideshowHardwareThreadpool
# self.threadpool = QThreadPool()
slideshowHardwareThreadpool.setMaxThreadCount(8) # TODO - change if more threads are needed
# Rotary Encoder
self.rotaryEncoder = RotaryEncoder(self.PIN_ROTARY_A, self.PIN_ROTARY_B)
slideshowHardwareThreadpool.start(self.rotaryEncoder)
buttonEncoder = HardwareButton(self.PIN_ROTARY_BUTT)
buttonEncoder.signals.result.connect(self.pressed_encoder)
slideshowHardwareThreadpool.start(buttonEncoder)
# Buttons
buttonMode = HardwareButton(self.PIN_MODE)
buttonMode.signals.result.connect(self.pressed_mode)
slideshowHardwareThreadpool.start(buttonMode)
buttonPrev = HardwareButton(self.PIN_PREV)
buttonPrev.signals.result.connect(self.pressed_prev)
slideshowHardwareThreadpool.start(buttonPrev)
buttonPlayPause = HardwareButton(self.PIN_PLAY_PAUSE)
buttonPlayPause.signals.result.connect(self.pressed_play_pause)
slideshowHardwareThreadpool.start(buttonPlayPause)
buttonNext = HardwareButton(self.PIN_NEXT)
buttonNext.signals.result.connect(self.pressed_next)
slideshowHardwareThreadpool.start(buttonNext)