-
Notifications
You must be signed in to change notification settings - Fork 1
/
selfie.py
executable file
·440 lines (366 loc) · 8.95 KB
/
selfie.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
import pygame
import os.path
import time
import datetime
import picamera
import RPi.GPIO as GPIO
import urllib
import shutil
from twython import Twython, TwythonError
import statusfinder
# eventTypes
EVENT_NONE = 0
EVENT_RED_SHORT = 1 # red button pressed once
EVENT_RED_LONG = 2 # red button pressed for several seconds
EVENT_BLACK_SHORT = 3 # same as above
EVENT_BLACK_LONG = 4
EVENT_QUIT = 5
# states
STATE_NONE = 0
STATE_STARTUP = 1 # startup screen
STATE_PREVIEW = 2 # capture preview
STATE_TAKE_PHOTO = 3 # take a photo
STATE_DISPLAY = 4 # photo display
STATE_TWEET = 5 # tweet photo
STATE_TWEET_PHOTO = 6 # successful tweet (message)
STATE_DELETE_PHOTO = 7 # delete a photo (message)
STATE_NEXT_PHOTO = 8 # flip to next (message)
# colors
COLOR_BLACK = pygame.Color(0,0,0)
COLOR_WHITE = pygame.Color(255,255,255)
COLOR_RED = pygame.Color(255,0,0)
COLOR_SKY = pygame.Color(135,206,250)
COLOR_GRAY = pygame.Color(119,136,153)
COLOR_OLIVE = pygame.Color(107,142,35)
pygame.init()
screen = pygame.display.set_mode((0,0))
state = STATE_STARTUP
#globals
redLED = 4
greenLED = 17
redButton = 24
blackButton = 23
mx = 0 # message position (x)
my = 0 # message position (y)
startTime = 0 # timer functions
endTime = 0 # timer functions
buttonWaitTime = 3
hasWifi = False
takenImages = []
savedImages = []
rootDir = "/home/pi/usbdrv/"
takenImagesDir = rootDir + "taken_images/"
sentImagesDir = rootDir + "sent_images/"
imageIndex = -1
keys = []
username = "<no wifi>"
status = "no wifi"
# GPIO variables and initialization
def initGPIO():
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(redLED, GPIO.OUT)
GPIO.setup(greenLED, GPIO.OUT)
GPIO.setup(redButton, GPIO.IN)
GPIO.setup(blackButton, GPIO.IN)
GPIO.output(greenLED, False)
GPIO.output(redLED, False)
# init pygame, any other screen stuff
def initScreen():
global font
pygame.mouse.set_visible(0)
pygame.font.init()
font = pygame.font.Font(None,36)
# keys are in a 4-line file
# line 1 = apiKey, line 2 = apiSecret, line 3 = accessToken, line 4 = access secret
def initTwitter():
global keys
global api
global username
global hasWifi
global status
f = open("keys.txt","r")
for line in f:
keys.append( line.rstrip('\n'))
f.close()
api = Twython(keys[0],keys[1],keys[2],keys[3])
try:
details = api.show_user(screen_name='SelfiesBot')
username = details['name']
status = "Connected"
hasWifi = True
except TwythonError as e:
username = "exception"
status = "No Wifi"
hasWifi = False
def debounce():
time.sleep(0.05)
def getTimeStamp():
ts = time.time()
return datetime.datetime.fromtimestamp(ts).strftime('%Y%m%d%H%M%S')
def getEvent():
# ESCAPE KEY exits program
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
return EVENT_QUIT
# check GPIO -- do debouce or something
if GPIOCheck(redButton) == True:
return EVENT_RED_SHORT
elif GPIOCheck(blackButton) == True:
return EVENT_BLACK_SHORT
return EVENT_NONE
def GPIOCheck(buttonType):
global buttonWaitTime
buttonLong = False
if GPIO.input(buttonType) == True:
debounce()
startTime = time.time()
if buttonType == redButton:
GPIO.output(redLED, True)
elif buttonType == blackButton:
GPIO.output(greenLED,True)
while GPIO.input(buttonType) == True:
if time.time() > startTime + buttonWaitTime:
if buttonLong == False:
buttonHeld(buttonType)
buttonLong = True
GPIO.output(redLED,False)
GPIO.output(greenLED,False)
if buttonLong == False:
return True
# maps buttons to state changes
def buttonPressed(currentState, eventType):
newState = currentState
# red button (quick press)
if eventType == EVENT_RED_SHORT:
if currentState == STATE_STARTUP:
newState = STATE_PREVIEW
elif currentState == STATE_PREVIEW:
newState = STATE_TAKE_PHOTO
elif currentState == STATE_DISPLAY:
newState = STATE_TWEET
elif eventType == EVENT_BLACK_SHORT:
if currentState == STATE_STARTUP:
newState = STATE_DISPLAY
elif currentState == STATE_DISPLAY:
newState = STATE_NEXT_PHOTO
elif currentState == STATE_TWEET:
newState = STATE_DISPLAY
return newState
def buttonHeld(buttonType):
global state
if buttonType == redButton:
if state == STATE_DISPLAY:
deletePhoto()
changeState(STATE_DISPLAY)
elif state == STATE_TWEET:
tweetPhoto()
changeState(STATE_STARTUP)
elif buttonType == blackButton:
if state == STATE_DISPLAY:
changeState(STATE_STARTUP)
if state == STATE_STARTUP:
initTwitter()
changeState(STATE_STARTUP)
def stateStartup():
global keys
global username
global status
background(COLOR_GRAY)
resetMXY()
if hasWifi == True:
message(username)
message(status)
else:
message(status)
message(username)
#s = statusfinder.getNextStatus()
#message(s)
#statusfinder.saveStatus(s)
# prints out our keys
#for i in range(0,len(keys)):
# message(keys[i])
updateScreen()
def statePreview():
global status
background(COLOR_BLACK)
updateScreen()
camera.start_preview()
if hasWifi == True:
status = "Connected"
else:
status = "No wifi"
def stateDisplay():
global imageIndex
global status
if hasWifi == True:
status = "Connected"
else:
status = "No wifi"
background(COLOR_OLIVE)
loadImages()
resetMXY()
drawImage()
displayImageFiles()
if imageIndex >= 0:
message( "Showing: " + takenImages[imageIndex])
updateScreen()
def displayImageFiles():
global takenImages
global imageIndex
loadImages()
if len(takenImages) == 0:
message("No images")
else:
message("Images")
for i in range(0,len(takenImages)):
message(takenImages[i])
message(" ")
def drawImage():
if imageIndex >= 0:
im = pygame.image.load(takenImagesDir+takenImages[imageIndex])
im = pygame.transform.scale(im, (400,300))
screen.blit(im,(100,160))
def stateTweet():
background(COLOR_SKY)
resetMXY()
message("Hold RED button down to Tweet this image")
drawImage()
updateScreen()
def tweetPhoto():
global api
global status
success = False
message("Tweeting")
updateScreen()
msg = getRandomMessage()
if not imageIndex == -1:
try:
photoFilePath = takenImagesDir+takenImages[imageIndex]
photo = open(photoFilePath,'rb')
tweet = statusfinder.getNextStatus()
api.update_status_with_media(media=photo,status=tweet)
# this is just a photo
#api.update_status_with_media(media=photo)
shutil.move(photoFilePath,sentImagesDir+takenImages[imageIndex])
status = tweet
success = True
statusfinder.saveStatus(tweet)
except TwythonError as e:
message("Error")
status = "Error Tweeting"
updateScreen()
success = False
time.sleep(1)
return success
def getRandomMessage():
return "Sunday Funday"
def deletePhoto():
global takenImagesDir
global takenImages
if imageIndex == -1:
message("No photos to delete")
else:
os.remove(takenImagesDir + takenImages[imageIndex])
message("Deleting photo")
updateScreen()
time.sleep(1)
def takePhoto():
# take photo here
ts = getTimeStamp()
camera.capture(takenImagesDir + ts + ".jpg")
message("Took photo: " + ts)
updateScreen()
time.sleep(1)
def nextPhoto():
# load next photo in list
global imageIndex
if imageIndex >= 0:
imageIndex = imageIndex + 1
if imageIndex == len(takenImages):
imageIndex = 0
message("Next photo")
updateScreen()
time.sleep(1)
def background(color):
global screen
screen.fill(color)
def message(msg):
global screen
global font
global mx
global my
text = font.render(msg, True, COLOR_WHITE)
textPos = text.get_rect()
textPos.left = mx
textPos.top = my
screen.blit(text, textPos)
advanceMY()
def updateScreen():
pygame.display.update()
def resetMXY():
global mx
global my
mx = 5
my = 5
def advanceMY():
global my
my = my + 30
# load image names from disk
def loadImages():
global takenImagesDir
global takenImages
global imageIndex
takenImages = os.listdir(takenImagesDir)
if len(takenImages) == 0:
imageIndex = -1
elif imageIndex == -1:
imageIndex = len(takenImages)-1
elif imageIndex >= len(takenImages):
imageIndex = len(takenImages)-1
def changeState(newState):
global state
state = newState
# transitional states: messages or activities
if state == STATE_TAKE_PHOTO:
takePhoto()
state = STATE_DISPLAY
if state == STATE_TWEET_PHOTO:
tweetPhoto()
state = STATE_STARTUP
if state == STATE_DELETE_PHOTO:
deletePhoto()
state = STATE_DISPLAY
if state == STATE_NEXT_PHOTO:
nextPhoto()
state = STATE_DISPLAY
# display states
if state == STATE_STARTUP:
stateStartup()
elif state == STATE_DISPLAY:
camera.stop_preview()
stateDisplay()
elif state == STATE_PREVIEW:
statePreview()
elif state == STATE_TWEET:
stateTweet()
# startup
initGPIO()
initScreen()
initTwitter()
stateStartup()
# main loop
done = False
with picamera.PiCamera() as camera:
camera.resolution = (1280,720)
while not done:
eventType = getEvent()
stateChanged = False
if eventType == EVENT_QUIT:
done = True
elif not eventType == EVENT_NONE:
oldState = state
state = buttonPressed(state, eventType)
if not oldState == state:
changeState(state)