-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslideR.py
1531 lines (1341 loc) · 56.6 KB
/
slideR.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
# Slide timelapse controller for Raspberry Pi
# This must run as root (sudo python slideR.py) due to framebuffer, etc.
#
# http://www.adafruit.com/products/998 (Raspberry Pi Model B)
# http://www.adafruit.com/products/1601 (PiTFT Mini Kit)
#
# Prerequisite tutorials: aside from the basic Raspbian setup and PiTFT setup
# http://learn.adafruit.com/adafruit-pitft-28-inch-resistive-touchscreen-display-raspberry-pi
#
# slideR.py by Dave Creith (dave@creith.net)
#
# based on lapse.py by David Hunt (dave@davidhunt.ie)
# based on cam.py by Phil Burgess / Paint Your Dragon for Adafruit Industries.
# BSD license, all text above must be included in any redistribution.
import wiringpi2
import atexit
import cPickle as pickle
import errno
import fnmatch
import io
import os
import pygame
import threading
import signal
import sys
import time
from pygame.locals import *
from subprocess import call
from datetime import datetime, timedelta
# UI classes ---------------------------------------------------------------
# Icon is a very simple bitmap class, just associates a name and a pygame
# image (PNG loaded from icons directory) for each.
# There isn't a globally-declared fixed list of Icons. Instead, the list
# is populated at runtime from the contents of the 'icons' directory.
class Icon:
def __init__(self, name):
self.name = name
try:
self.bitmap = pygame.image.load(iconPath + '/' + name + '.png')
except:
pass
# Button is a simple tappable screen region. Each has:
# - bounding rect ((X,Y,W,H) in pixels)
# - optional background color and/or Icon (or None), always centered
# - optional foreground Icon, always centered
# - optional single callback function
# - optional single value passed to callback
# Occasionally Buttons are used as a convenience for positioning Icons
# but the taps are ignored. Stacking order is important; when Buttons
# overlap, lowest/first Button in list takes precedence when processing
# input, and highest/last Button is drawn atop prior Button(s). This is
# used, for example, to center an Icon by creating a passive Button the
# width of the full screen, but with other buttons left or right that
# may take input precedence (e.g. the Effect labels & buttons).
# After Icons are loaded at runtime, a pass is made through the global
# buttons[] list to assign the Icon objects (from names) to each Button.
class Button:
def __init__(self, rect, **kwargs):
self.rect = rect # Bounds
self.color = None # Background fill color, if any
self.iconBg = None # Background Icon (atop color fill)
self.iconFg = None # Foreground Icon (atop background)
self.bg = None # Background Icon name
self.fg = None # Foreground Icon name
self.callback = None # Callback function
self.value = None # Value passed to callback
for key, value in kwargs.iteritems():
if key == 'color': self.color = value
elif key == 'bg' : self.bg = value
elif key == 'fg' : self.fg = value
elif key == 'cb' : self.callback = value
elif key == 'value': self.value = value
def selected(self, pos):
x1 = self.rect[0]
y1 = self.rect[1]
x2 = x1 + self.rect[2] - 1
y2 = y1 + self.rect[3] - 1
if ((pos[0] >= x1) and (pos[0] <= x2) and
(pos[1] >= y1) and (pos[1] <= y2)):
if self.callback:
if self.value is None: self.callback()
else: self.callback(self.value)
return True
return False
def draw(self, screen):
if self.color:
screen.fill(self.color, self.rect)
if self.iconBg:
screen.blit(self.iconBg.bitmap,
(self.rect[0]+(self.rect[2]-self.iconBg.bitmap.get_width())/2,
self.rect[1]+(self.rect[3]-self.iconBg.bitmap.get_height())/2))
if self.iconFg:
screen.blit(self.iconFg.bitmap,
(self.rect[0]+(self.rect[2]-self.iconFg.bitmap.get_width())/2,
self.rect[1]+(self.rect[3]-self.iconFg.bitmap.get_height())/2))
def setBg(self, name):
if name is None:
self.iconBg = None
else:
for i in icons:
if name == i.name:
self.iconBg = i
break
# UI callbacks -------------------------------------------------------------
# These are defined before globals because they're referenced by items in
# the global buttons[] list.
def backlightCallback(n): # toggle the screen backlight on and off
global backlightState
if backlightState==0:
backlightState=1
os.system("echo '1' > /sys/class/gpio/gpio252/value")
else:
backlightState=0
os.system("echo '0' > /sys/class/gpio/gpio252/value")
def gpioCleanup(n):
print 'GPIO Clean up'
gpio.digitalWrite(Pins['Shutter'],gpio.LOW)
gpio.digitalWrite(Pins['Focus'],gpio.LOW)
gpio.digitalWrite(Pins['LedR'],gpio.LOW)
gpio.digitalWrite(Pins['LedG'],gpio.LOW)
gpio.digitalWrite(Pins['LedB'],gpio.LOW)
gpio.digitalWrite(Pins['MotorA1'],gpio.LOW)
gpio.digitalWrite(Pins['MotorA2'],gpio.LOW)
gpio.digitalWrite(Pins['MotorB1'],gpio.LOW)
gpio.digitalWrite(Pins['MotorB2'],gpio.LOW)
gpio.pinMode(Pins['Shutter'],gpio.INPUT)
gpio.pinMode(Pins['Focus'],gpio.INPUT)
gpio.pinMode(Pins['LedR'],gpio.INPUT)
gpio.pinMode(Pins['LedG'],gpio.INPUT)
gpio.pinMode(Pins['LedB'],gpio.INPUT)
gpio.pinMode(Pins['MotorA1'],gpio.INPUT)
gpio.pinMode(Pins['MotorA2'],gpio.INPUT)
gpio.pinMode(Pins['MotorB1'],gpio.INPUT)
gpio.pinMode(Pins['MotorB2'],gpio.INPUT)
def shutdownPi(n): # return to previous screen or shutdown Pi
global screenMode
if n==-1:
screenMode = 1
elif n==1:
screen.blit(img,
((320 - img.get_width() ) / 2,
(240 - img.get_height()) / 2))
myfont = pygame.font.SysFont('Arial', smallfont)
myfont.set_bold(False)
msgString = 'Turn Power Off In 15 Seconds'
label = myfont.render(msgString, 1, (fontcolour))
screen.blit(label, (xPos(msgString,0,screenMode,myfont), 90))
pygame.display.update()
saveBasic()
saveState('shutdownPi')
time.sleep(5)
gpioCleanup
# shutdown the Raspberry Pi
# sys.exit()
os.system("sudo shutdown -h now")
time.sleep(10)
def left(delay, steps): # drive motor forwards a number of steps
global forwardSeq
for i in range(steps):
for step in forwardSeq:
stepMotor(step)
time.sleep(delay)
return (i + 1)
def right(delay, steps): # drive motor backwards a number of steps
global reverseSeq
for i in range(steps):
for step in reverseSeq:
stepMotor(step)
time.sleep(delay)
return ((i + 1) * -1)
def stepMotor(step): # drive motor
global Pins
gpio.digitalWrite(Pins['MotorA1'], step[0] == '1')
gpio.digitalWrite(Pins['MotorA2'], step[1] == '1')
gpio.digitalWrite(Pins['MotorB1'], step[2] == '1')
gpio.digitalWrite(Pins['MotorB2'], step[3] == '1')
def travelRail(delay, steps): # stop on 0 steps
global slideState
if steps > 0:
slideState['Sliding'] = True
if slideState['DirectionLeft']:
stepsTaken = left(delay, steps)
else:
stepsTaken = right(delay, steps)
slideState['Sliding'] = False
slideState['Position'] = slideState['Position'] + stepsTaken
else:
slideState['Sliding'] = False
stepMotor('0000')
saveState('travelrail')
def positionCallback(n): # set the slide end positions
global slideBasic
global slideState
global dictIdx
global numberstring
global screenMode
global returnScreen
if n == 1: # set left slide position for program
slideState['Left'] = slideState['Position']
elif n == 2: # set right slide position for program
slideState['Right'] = slideState['Position']
elif n == 3: # set the left step point directly
dictIdx='Left'
numberstring = str(slideState[dictIdx])
screenMode = 2
returnScreen = 4
elif n == 4: # set the right step point directly
dictIdx='Right'
numberstring = str(slideState[dictIdx])
screenMode = 2
returnScreen = 4
elif n == 5: # set left maximum slide position
slideBasic['MaxLeft'] = slideState['Position']
elif n == 6: # set right maximum slide position
slideBasic['MaxRight'] = 0
slideState['Position'] = 0
elif n == 7: # set the max left end point directly
dictIdx='MaxLeft'
numberstring = str(slideBasic[dictIdx])
screenMode = 2
returnScreen = 6
elif n == 8: # set the max right end point directly
dictIdx='MaxRight'
numberstring = str(slideBasic[dictIdx])
screenMode = 2
returnScreen = 6
saveBasic()
saveState('positionCallback')
def rotationCallback(n): # set the rotation positions
global slideBasic
global slideState
def slideCallback(n): # set the slide motor direction and run the motor
global slideBasic
global slideState
global siStart
global siStop
siStart = 0
siStop = 1
# 1 is left
# 2 is right
# 3 is left end (program end)
# 4 is right end (program end)
# 0 is change set direction
# change motor direction
# if motor is running then shut it off
# if motor is not running then start it
if n == 0:
if slideState['Sliding']:
travelRail(slideBasic['MinDelay'],0)
if slideState['DirectionLeft']:
slideState['DirectionLeft'] = False
else:
slideState['DirectionLeft'] = True
elif n == 1:
slideState['DirectionLeft'] = True
if slideState['Sliding']:
travelRail(slideBasic['MinDelay'],0)
else:
travelRail(slideBasic['MinDelay'],1)
elif n == 2:
slideState['DirectionLeft'] = False
if slideState['Sliding']:
travelRail(slideBasic['MinDelay'],0)
else:
travelRail(slideBasic['MinDelay'],1)
elif n == 3:
slideMovement = slideState['Left'] - slideState['Position']
if slideMovement > 0:
slideState['DirectionLeft'] = True
else:
slideState['DirectionLeft'] = False
if slideState['Sliding']:
travelRail(slideBasic['MinDelay'],0)
else:
travelRail(slideBasic['MinDelay'],abs(slideMovement))
elif n == 4:
slideMovement = slideState['Position'] - slideState['Right']
if slideMovement < 0:
slideState['DirectionLeft'] = True
else:
slideState['DirectionLeft'] = False
if slideState['Sliding']:
travelRail(slideBasic['MinDelay'],0)
else:
travelRail(slideBasic['MinDelay'],abs(slideMovement))
elif n == 5:
slideMovement = slideBasic['MaxLeft'] - slideState['Position']
if slideMovement > 0:
slideState['DirectionLeft'] = True
else:
slideState['DirectionLeft'] = False
if slideState['Sliding']:
travelRail(slideBasic['MinDelay'],0)
else:
travelRail(slideBasic['MinDelay'],abs(slideMovement))
elif n == 6:
slideMovement = slideState['Position'] - slideBasic['MaxRight']
if slideMovement < 0:
slideState['DirectionLeft'] = True
else:
slideState['DirectionLeft'] = False
if slideState['Sliding']:
travelRail(slideBasic['MinDelay'],0)
else:
travelRail(slideBasic['MinDelay'],abs(slideMovement))
def numericCallback(n): # keypad capture
global screenMode
global returnScreen
global numberstring
global slideState
global slideBasic
global dictIdx
if n < 10: # capture keystroke to value (0-9)
numberstring = numberstring + str(n)
elif n == 10: # clear value
numberstring = numberstring[:-1*(len(numberstring))]
elif n == 11: # cancel update
screenMode = returnScreen
elif n == 12: # return value as int
screenMode = returnScreen
if numberstring:
numeric = int(numberstring)
if screenMode == 1:
slideState[dictIdx] = numeric
elif screenMode == 4:
slideState[dictIdx] = numeric
elif screenMode == 6:
slideBasic[dictIdx] = numeric
elif n == 13: # return value as float (shutter & settling values)
screenMode = returnScreen
if len(numberstring) > 0:
numeric = float(numberstring)
slideState[dictIdx] = numeric
elif n == 14: # return value as fraction of second (float)
screenMode = returnScreen
if len(numberstring) > 0:
numeric = 1 / float(numberstring)
slideState[dictIdx] = numeric
def programCallback(n): # select a parameter and goto keypad (-1 returns to screen 0)
global screenMode
global slideState
if n == -1:
screenMode = 1
saveState('programCallback')
reasonableValues()
if timelapseSettings(): # Calculate timelapse execution values
taskIndicator = 'stopped'
if n == 0:
screenMode = 1
reasonableValues()
if timelapseSettings(): # Calculate timelapse execution values
taskIndicator = 'stopped'
def valuesCallback(n): # select a parameter and goto keypad (-1 returns to screen 0)
global screenMode
global returnScreen
global numberstring
global numeric
global slideState
global dictIdx
if n == -1:
screenMode = 0
saveState('valuesCallback')
reasonableValues()
if timelapseSettings(): # Calculate timelapse execution values
taskIndicator = 'stopped'
if n == 0:
screenMode = 0
reasonableValues()
if timelapseSettings(): # Calculate timelapse execution values
taskIndicator = 'stopped'
if n == 1:
dictIdx='Shutter'
# set the source icon here
sValue = float(slideState[dictIdx])
if (sValue < 1):
numberstring = str(int(1 / sValue))
else:
numberstring = str(int(slideState[dictIdx]))
screenMode = 3
returnScreen = 1
elif n == 2:
dictIdx='Timespan'
numberstring = str(slideState[dictIdx])
screenMode = 2
returnScreen = 1
elif n == 3:
dictIdx='Images'
numberstring = str(slideState[dictIdx])
screenMode = 2
returnScreen = 1
elif n == 5:
dictIdx='Settle'
sValue = float(slideState[dictIdx])
if (sValue < 1):
numberstring = str(int(1 / sValue))
else:
numberstring = str(int(slideState[dictIdx]))
screenMode = 3
returnScreen = 1
def viewCallback(n): # Set branch to screen
global screenMode
global siStart
global siStop
siStart = 0
siStop = 1
if n is 1: # Gear icon - branch to parameters
screenMode = 1
elif n is 4: # Travel rail - branch to rail parameters
screenMode = 4
elif n is 5: # Rotate camera - branch to rotate parameters
screenMode = 5
elif n is 6: # Maximum rail parameters
screenMode = 6
elif n is 7: # Shutdown Pi - branch to shutdown screen
screenMode = 7
def startCallback(n): # start/Stop the timelapse thread
# threadExited - initiated as False
# - set to True in timelapse when image count exhausted
# - set to False here when starting a thread
# busy - initiated as False
# - set to False here when explicitly ending the thread with keypad 'Stop'
# - set to True at start of timelapse, False at completion
global t, busy, threadExited
global slideState
global startTime
global doneNotify
global siStart
global siStop
siStart = 0
siStop = 1
midPoint = (((slideState['Left'] - slideState['Right']) / 2) + slideState['Right'])
# if right of middle then start at the right, if left of middle start at left
if ((slideState['Position'] <= midPoint) &
(slideState['Position'] != slideState['Right'])):
slideCallback(4)
if ((slideState['Position'] > midPoint) &
(slideState['Position'] != slideState['Left'])):
slideCallback(3)
if (slideState['Position']) == slideState['Right']:
slideState['DirectionLeft'] = True
else:
slideState['DirectionLeft'] = False
saveState('startCallback 1')
if n == 1:
# print 'setLED 4'
setLED('running')
if busy == False:
if (threadExited == True):
# Re-instanciate the object for the next start
t = threading.Thread(target=timeLapse)
threadExited = False
t.start()
# startTime = time.time()
if n == 0:
if busy == True:
busy = False
t.join()
slideState['CurrentImage'] = 0
slideState['State'] = 0
saveState('startCallback 2')
taskIndicator = 'done'
startTime = 0.0
doneNotify = time.time() + (30 * 1) # set done LED show delay
# Re-instanciate the object for the next time around.
t = threading.Thread(target=timeLapse)
def setspeedCallback(n): # determine the step time
# 0 or cancel is irrelevant for this screen as changes are already loaded
global screenMode
global returnScreen
global numberstring
global numeric
global slideState
global dictIdx
if n == -1:
screenMode = 4
saveBasic()
saveState('setspeedCallback')
reasonableValues()
if timelapseSettings(): # Calculate timelapse execution values
taskIndicator = 'stopped'
if n == 0:
screenMode = 4
reasonableValues()
if timelapseSettings(): # Calculate timelapse execution values
taskIndicator = 'stopped'
if n == 1: # run for slideBasic['Steps'] and find time
if slideBasic['Steps'] < (slideBasic['MaxLeft'] - slideState['Position']):
slideState['DirectionLeft'] = 1
elif slideBasic['Steps'] > slideState['Position']:
slideState['DirectionLeft'] = 0
else:
slideBasic['Steps'] = slideState['Position']
slideState['DirectionLeft'] = 0
startTime = time.time()
travelRail(slideBasic['MinDelay'], slideBasic['Steps'])
endTime = time.time()
elapsedTime = abs(endTime - startTime)
sec = timedelta(seconds=int(elapsedTime))
d = datetime(1,1,1) + sec
if d.hour > 0:
labeltext = '%dh%dm%ds' % (d.hour, d.minute, d.second)
else:
labeltext = '%dm%ds' % (d.minute, d.second)
if elapsedTime == 0: elapsedTime = 0.1
slideBasic['StepTime'] = (elapsedTime / slideBasic['Steps'])
returnScreen = 6
elif n == 3:
dictIdx='Steps'
numberstring = str(slideBasic[dictIdx])
screenMode = 2
returnScreen = 6
def timeLapse(): # execute the timelapse (separate thread)
global busy, threadExited
# threadExited - initiated as False
# - set to True here when image count exhausted
# - set to False in on 'Start' from keypad when starting a thread
# busy - initiated as False
# - set to False when explicitly ending the thread with keypad 'Stop'
# - set to True here at start, False at completion
# - breaks loop when False
global slideState
global slideBasic
global Pins
global settlingTime
global shutterTime
global focusPause
global taskIndicator
global doneNotify
global startTime
# set copies of the following to isolate operation from setup
# images, motorpin
# travelpulse, focusPause, shutterTime
busy = True
slideState['State'] = 1
startTime = time.time()
for i in range( 1 , slideState['Images'] + 1 ):
if busy == False:
break
# move slide forward on all but first image
if i!=1:
taskIndicator = 'travel'
travelRail(slideState['Delay'], slideState['PulseSteps'])
taskIndicator = 'settling'
time.sleep(settlingTime)
taskIndicator = 'fire'
# trigger the focus
gpio.digitalWrite(Pins['Focus'],gpio.HIGH)
time.sleep(focusPause)
# trigger the shutter
gpio.digitalWrite(Pins['Shutter'],gpio.HIGH)
time.sleep(shutterTime)
gpio.digitalWrite(Pins['Shutter'],gpio.LOW)
gpio.digitalWrite(Pins['Focus'],gpio.LOW)
slideState['CurrentImage'] = i
# startTime = time.time()
saveState('timelapse loop')
slideState['CurrentImage'] = 0
slideState['State'] = 0
saveState('timelapse done')
doneNotify = time.time() + (30 * 1) # set done LED show delay
taskIndicator = 'done'
busy = False
threadExited = True
def is_integer(s):
try:
int(s)
return True
except ValueError:
return False
def is_float(s):
try:
float(s)
return True
except ValueError:
return False
def reasonableValues():
global slideState
global slideBasic
global focusPause
if not is_float(slideBasic['StepTime']): slideBasic['StepTime'] = 0.020
if not is_float(slideBasic['MinDelay']): slideBasic['MinDelay'] = 0.002
if not is_integer(slideBasic['MaxLeft']): slideBasic['MaxLeft'] = 200
if not is_integer(slideBasic['MaxRight']): slideBasic['MaxRight'] = 0
if not is_integer(slideBasic['MaxCCW']): slideBasic['MaxCCW'] = 100
if not is_integer(slideBasic['MaxCW']): slideBasic['MaxCW'] = 0
if not is_integer(slideBasic['Steps']): slideBasic['Steps'] = 10
# Min 20 milliseconds
# Max 1 day
if slideBasic['StepTime']<0.010: slideBasic['StepTime'] = 0.010
elif slideBasic['StepTime']>0.5: slideBasic['StepTime'] = 0.010
if slideBasic['MinDelay']<0.002: slideBasic['MinDelay'] = 0.002
elif slideBasic['MinDelay']>86400: slideBasic['MinDelay'] = 0.002
# Motorsteps
if slideBasic['MaxLeft'] > 5000:
slideBasic['MaxLeft'] = 5000
if slideBasic['MaxRight'] < 1:
slideBasic['MaxRight'] = 0
# Motorsteps
if slideBasic['Steps'] > int((slideBasic['MaxLeft'] / 2) + 1):
slideBasic['Steps'] = int((slideBasic['MaxLeft'] / 2) + 1)
if slideBasic['Steps'] < 1:
slideBasic['Steps'] = int((slideBasic['MaxLeft'] / 2) + 1)
if not is_float(slideState['Shutter']): slideState['Shutter'] = 1 / 60
if not is_float(slideState['Settle']): slideState['Settle'] = 0
if not is_float(slideState['Delay']): slideState['Delay'] = 0.020
if not is_integer(slideState['Images']): slideState['Images'] = 60
if not is_integer(slideState['Timespan']): slideState['Timespan'] = 30
if not is_integer(slideState['ShootTime']): slideState['ShootTime'] = 10
if not is_integer(slideState['Left']): slideState['Left'] = 100
if not is_integer(slideState['Right']): slideState['Right'] = 10
if not is_integer(slideState['CCW']): slideState['CCW'] = 100
if not is_integer(slideState['CW']): slideState['CW'] = 0
if not is_integer(slideState['PulseSteps']): slideState['PulseSteps'] = 2
if not is_integer(slideState['Position']): slideState['Position'] = 2
if not is_integer(slideState['Rotation']): slideState['Rotation'] = 2
if not is_integer(slideState['CurrentImage']):slideState['CurrentImage'] = 0
# Min 1/8000s
# Max 90 seconds
if slideState['Shutter']==0: slideState['Shutter'] = 1 / 60
elif slideState['Shutter']<(1/8000): slideState['Shutter'] = 1 / 60
elif slideState['Shutter']>90: slideState['Shutter'] = 1 / 60
# Min 1 image
# Max 500 images
if slideState['Images']==0 or slideState['Images'] > 500:
slideState['Images'] = 10
# Min 1 minute
# Max 24 hours
if slideState['Timespan']<(1): slideState['Timespan'] = 30
elif slideState['Timespan']>1440: slideState['Timespan'] = 60
# Min 20 milliseconds
# Max 1 day
if slideState['Delay']<0.002: slideState['Delay'] = 0.002
elif slideState['Delay']>86400: slideState['Delay'] = 0.002
if slideState['Left'] > slideBasic['MaxLeft']:
slideState['Left'] = slideBasic['MaxLeft']
if slideState['Right'] < slideBasic['MaxRight']:
slideState['Right'] = slideBasic['MaxRight']
if slideState['Position'] > slideBasic['MaxLeft']:
slideState['Position'] = slideBasic['MaxLeft']
if slideState['Position'] < slideBasic['MaxRight']:
slideState['Position'] = slideBasic['MaxRight']
# Motorsteps
if slideState['PulseSteps'] < 1: slideState['PulseSteps'] = 1
elif slideState['PulseSteps'] > slideState['Left']:
slideState['PulseSteps'] = 1
def timelapseSettings():
global slideState
global slideBasic
global settlingTime
global shutterTime
global focusPause
#debug
#debugState('befoe timelapseSettings')
#debugBasic('before timelapseSettings')
#debug
intervals = int(slideState['Images']) - 1
if intervals < 1:
intervals = 1
# calc frame time
settlingTime = float(slideState['Settle']) # time to wait before firing shutter
shutterTime = float(slideState['Shutter']) # shutter speed
frameTime = (shutterTime + settlingTime + focusPause) # time for 1 image in seconds
slideState['ShootTime'] = frameTime * int(slideState['Images']) # time for all images in seconds
totalSteps = slideState['Left'] - slideState['Right']
if totalSteps == 0: totalSteps = 1
slideState['PulseSteps'] = int(totalSteps / intervals)
pulseTime = slideState['PulseSteps'] * slideBasic['StepTime']
motorTime = pulseTime * intervals
runTime = slideState['ShootTime'] + motorTime
extraTime = (slideState['Timespan'] * 60) - runTime
factoredSteps = totalSteps * stepFactor
slideState['Delay'] = slideBasic['MinDelay']
errFound = False
if extraTime < 0:
errFound = True
sec = timedelta(seconds=int(runTime / 1000))
d = datetime(1,1,1) + sec
if d.hour > 0:
errmsg = 'Min timespan of %dh%dm%ds' % (d.hour, d.minute, d.second)
else:
errmsg = 'Min timespan of %dm%ds' % (d.minute, d.second)
else:
slideState['Delay'] = slideState['Delay'] + round(extraTime / factoredSteps,3)
#debug
#debugState('after timelapseSettings')
#debugBasic('after timelapseSettings')
#debug
#print "settlingTime...." + str(settlingTime)
#print "shutterTime....." + str(shutterTime)
#print "focusPause......" + str(focusPause)
#print "frameTime......." + str(frameTime)
#print "totalSteps......" + str(totalSteps)
#print "motorTime......." + str(motorTime)
#print "runTime........." + str(runTime)
#print "extraTime......." + str(extraTime)
#debug
return errFound
def xPos(lbl,j,s,mf): # determine starting x co-ordinate to place text
# lbl->text, j->justification, s->screen, mf->font
labelwidth = mf.size(lbl)[0]
l = [5,65,5,5,65,65,65,5] # leftmost co-ordinates for screens 0->7
r = [320,260,320,320,260,260,260,320] # rightmost co-ordinates for screens 0->7
if j==-1:
x = l[s]
elif j==1:
x = r[s] - (labelwidth + 5)
if x < 0:
x = 160
else:
x = int((320 - labelwidth) / 2)
if x < 0:
x = 0
return x
def setLED(a):
global lastRGB
#print 'setLED.....' + str(lastRGB) + ' a..' + str(a)
if a!=lastRGB:
lastRGB = a
if a=='start': # white
gpio.digitalWrite(Pins['LedR'],gpio.HIGH)
gpio.digitalWrite(Pins['LedG'],gpio.HIGH)
gpio.digitalWrite(Pins['LedB'],gpio.HIGH)
elif a=='ready': # blue
gpio.digitalWrite(Pins['LedR'],gpio.LOW)
gpio.digitalWrite(Pins['LedG'],gpio.LOW)
gpio.digitalWrite(Pins['LedB'],gpio.HIGH)
elif a=='running': # green
gpio.digitalWrite(Pins['LedR'],gpio.LOW)
gpio.digitalWrite(Pins['LedG'],gpio.HIGH)
gpio.digitalWrite(Pins['LedB'],gpio.LOW)
elif a=='done': # red
gpio.digitalWrite(Pins['LedR'],gpio.HIGH)
gpio.digitalWrite(Pins['LedG'],gpio.LOW)
gpio.digitalWrite(Pins['LedB'],gpio.LOW)
elif a=='magenta': # magenta
gpio.digitalWrite(Pins['LedR'],gpio.HIGH)
gpio.digitalWrite(Pins['LedG'],gpio.LOW)
gpio.digitalWrite(Pins['LedB'],gpio.HIGH)
elif a=='cyan': # cyan
gpio.digitalWrite(Pins['LedR'],gpio.LOW)
gpio.digitalWrite(Pins['LedG'],gpio.HIGH)
gpio.digitalWrite(Pins['LedB'],gpio.HIGH)
else: # yellow
gpio.digitalWrite(Pins['LedR'],gpio.HIGH)
gpio.digitalWrite(Pins['LedG'],gpio.HIGH)
gpio.digitalWrite(Pins['LedB'],gpio.LOW)
def signal_handler(signal, frame):
print 'got SIGTERM'
pygame.quit()
sys.exit()
# Global stuff -------------------------------------------------------------
t = threading.Thread(target=timeLapse)
busy = False
threadExited = False
backlightState=1
screenMode = 0 # Current screen mode; default = viewfinder
screenModePrior = -1 # Prior screen mode (for detecting changes)
returnScreen = 0
iconPath = 'icons' # Subdirectory containing UI bitmaps (PNG format)
lastRGB = ""
doneNotify = time.time() # set done notify to now
blackfont = (0, 0, 0)
whitefont = (255, 255, 255)
fontcolour = whitefont
smallfont = 24
mediumfont = 30
largefont = 50
numeric = 0 # number from numeric keypad
numberstring = '0'
# GPIO Pin Assignment (piWiring - RPi B v2)
# Regular 02 03 04 07 08 09 10 11 14 15 17 18 22 23 24 25 27
# Extended 28 29 30 31
# screen pins 07 08 09 10 11 24 25
# used pins 02 03 17 18 22 27
# used extended pins 28 29 30
# available pins 04(GPCLK0) 14(TXD) 15(RXD) 23
# available extended pins 31
Pins = {'Shutter': 02,
'Focus': 03,
'MotorA1': 17,
'MotorA2': 18,
'MotorB1': 22,
'MotorB2': 27,
'LedR': 28, # waiting
'LedG': 29, # running
'LedB': 30} # done
backlightpin = 252
#Stepper motor drive sequence
#Full step
forwardSeq = ['1000', '0001', '0100', '0010']
reverseSeq = ['0110', '0101', '1001', '1010']
stepFactor = 4
#Half step
#forwardSeq = ['1010', '1000', '1001', '0001', '0101', '0100', '0110', '0010']
#reverseSeq = ['0010', '0110', '0100', '0101', '0001', '1001', '1000', '1010']
#stepFactor = 8
consumedTime = 0.0
startTime = 0.0
# fall back defaults - to be removed
settlingTime = 0.2
shutterTime = 2.0
# defined focus pause in milliseconds
focusPause = 0.3
taskIndicator = 'done'
lastTask = taskIndicator
dictIdx = 'Shutter'
slideBasic = {'MaxLeft': 100,
'MaxRight': 0,
'MaxCCW': 100,
'MaxCW': 0,
'StepTime': 0.020,
'MinDelay': 0.002,
'Steps': 10}
# seconds -> MinDelay, StepTime
# steps -> MaxLeft, MaxRight, MaxCCW, MaxCW, Steps
# MaxLeft, MaxRight -> set on basic set up
# MinDelay -> minimum to run stepper motor (set here)
# Steps -> steps to take for basic setup (entered)
slideState= {'State': 0,
'Shutter': 2.0,
'Timespan': 60,
'Images': 120,
'Settle': 1,
'Delay': 30,
'ShootTime': 3600,
'Left': 100,
'Right': 0,
'CCW': 100,
'CW': 0,
'PulseSteps': 1,
'Position': 10,
'Rotation': 0,
'CurrentImage': 0,
'Sliding': False,
'DirectionLeft': True,
'Calling': 'default'}
# state indicates whether times is complete (0) or in progress (1)
# minutes -> Timespan
# seconds -> Shutter, Settle, Shoottime
# milliseconds -> Delay (during motor step)
# count -> Images, CurrentImage
# steps -> Left, Right, PulseSteps, Position, CCW, CW, Rotation
# alternate icons to denote progress and toggled options
siStart = 0
siStop = 1
motorDirection = 1
aiKeypad = { 'Shutter': pygame.image.load(iconPath + '/shutter.png'),
'Timespan': pygame.image.load(iconPath + '/timespan.png'),
'Images': pygame.image.load(iconPath + '/images.png'),
'Settle': pygame.image.load(iconPath + '/settle.png'),
'Steps': pygame.image.load(iconPath + '/steps.png'),
'Left': pygame.image.load(iconPath + '/leftpgm.png'),
'Right': pygame.image.load(iconPath + '/rightpgm.png'),
'MaxLeft': pygame.image.load(iconPath + '/leftrail.png'),
'MaxRight': pygame.image.load(iconPath + '/rightrail.png')}
aiProgress = {'stopping': pygame.image.load(iconPath + '/stopping.png'),
'settling': pygame.image.load(iconPath + '/settling.png'),
'fire': pygame.image.load(iconPath + '/fire.png'),
'travel': pygame.image.load(iconPath + '/travel.png'),
'done': pygame.image.load(iconPath + '/blank60.png')}
aiSpin = {1: pygame.image.load(iconPath + '/spin/travel1.png'),
2: pygame.image.load(iconPath + '/spin/travel2.png'),
3: pygame.image.load(iconPath + '/spin/travel3.png'),
4: pygame.image.load(iconPath + '/spin/travel4.png'),
5: pygame.image.load(iconPath + '/spin/travel5.png'),
6: pygame.image.load(iconPath + '/spin/travel6.png'),
7: pygame.image.load(iconPath + '/spin/travel7.png'),
8: pygame.image.load(iconPath + '/spin/travel8.png'),
9: pygame.image.load(iconPath + '/spin/travel9.png'),
10: pygame.image.load(iconPath + '/spin/travel10.png'),
11: pygame.image.load(iconPath + '/spin/travel11.png'),
12: pygame.image.load(iconPath + '/spin/travel12.png')}
spinIt = 1
aiRecover = {0: pygame.image.load(iconPath + '/start.png'),
1:pygame.image.load(iconPath + '/stop.png'),
2:pygame.image.load(iconPath + '/restart.png'),
3:pygame.image.load(iconPath + '/reset.png')}