Skip to content

Commit 9ff6440

Browse files
committed
Clean up / ported new functions to daily-main
Prepped for pull into master
1 parent 18dd7ab commit 9ff6440

22 files changed

+259
-28
lines changed

MessageClass.py

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
import locale
66
from PIL._imaging import font
77
from MessageClass import *
8+
import random
9+
import os
810

911
### error handling
1012
#error class that handles exceptions in pick_item routine
@@ -15,16 +17,26 @@ def __str__(self):
1517
return self.msg
1618
#########################
1719

18-
20+
fonts = ["ArialBd.ttf","Verdana.ttf","ELEPHNT.TTF"]
1921

2022
# define usable fonts
2123
font = ImageFont.truetype('ArialBd.ttf', 14, encoding='unic')
2224
header_font = ImageFont.truetype('Verdana.ttf', 14, encoding='unic')
25+
font2 = ImageFont.truetype('ELEPHNT.ttf', 14, encoding='unic')
2326

2427
# stores pictures usable for messages
25-
Pics = {}
26-
Pics["Rose"]="gfx/rose2.png"
27-
Pics["Schweinchen"]="gfx/Schweinchen.png"
28+
symbol_folder = os.path.dirname(os.path.realpath(__file__)) + "/symbols"
29+
Pics = []
30+
31+
#populate Pics list with symbols
32+
for dirname, dirnames, filenames in os.walk(symbol_folder):
33+
for filename in filenames:
34+
if filename.split(".")[1] == "png":
35+
Pics.append(os.path.join(dirname,filename))
36+
37+
#Pics["Rose"]="gfx/rose2.png"
38+
#Pics["Schweinchen"]="gfx/Schweinchen.png"
39+
#Pics["Kalender"]="gfx/calendar.png"
2840

2941

3042

@@ -39,8 +51,9 @@ def __str__(self):
3951

4052
# Message Styles
4153
Message_Style = {
42-
"Rose":[[msg_header,header_font], msg_spacer, ["png",Pics['Rose']], 30, "text", msg_spacer, [msg_bottom,header_font]],
43-
"Schweinchen":[[msg_header,header_font], msg_spacer, ["png",Pics['Schweinchen']], 30, "text", msg_spacer, [msg_bottom,header_font]]
54+
# "Rose":[[msg_header,header_font], msg_spacer, ["png",Pics['Rose']], 30, "text", msg_spacer, [msg_bottom,header_font]],
55+
# "Schweinchen":[[msg_header,header_font], msg_spacer, ["png",Pics['Schweinchen']], 30, "text", msg_spacer, [msg_bottom,header_font]],
56+
"Random":[[msg_header,header_font], msg_spacer, ["png",random.choice(Pics)], 30, "text", msg_spacer, [msg_bottom,header_font]]
4457
}
4558

4659

MessageClass.pyc

334 Bytes
Binary file not shown.

daily-main.py

Lines changed: 33 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,13 @@
3131
lastId = '1' # State information passed to/from interval script
3232
printer = Adafruit_Thermal("/dev/serial0", 19200, timeout=5)
3333

34+
# set item path
35+
dir_path = os.path.dirname(os.path.realpath(__file__))
36+
item_folder = dir_path + '/items'
37+
38+
# initialize item of the day
39+
picked_item = ""
40+
3441
# Daytime to reset the printer to print the new message of the next day
3542
hrs = 4
3643
mins = 0
@@ -39,7 +46,10 @@
3946
def tap():
4047
print("Button press detected.")
4148
GPIO.output(ledPin, GPIO.HIGH) # LED on while working
42-
subprocess.call(["python", "collected_before.py"])
49+
#subprocess.call(["python", "collected_before.py"])
50+
#print today's message again
51+
if picked_item != "":
52+
printer.printImage(png_from_item(picked_item), True)
4353
GPIO.output(ledPin, GPIO.LOW)
4454

4555

@@ -69,9 +79,20 @@ def interval():
6979
def daily():
7080
print("First button press of the day...")
7181
GPIO.output(ledPin, GPIO.HIGH)
72-
subprocess.call(["python", "daily_message.py"])
82+
#subprocess.call(["python", "daily_message.py"])
83+
printer.printImage(Image.open(png_from_item(picked_item)), True)
7384
GPIO.output(ledPin, GPIO.LOW)
7485

86+
# takes a file path and return ready-to-print png image, converting text files by invoking MessageClass
87+
def png_from_item(picked_item):
88+
if picked_item.rsplit(".",1)[1] == "png":
89+
print "Image printed..."
90+
return Image.open(picked_item)
91+
elif picked_item.rsplit(".",1)[1] == "txt":
92+
textfile_handle = open(picked_item, "r")
93+
textfile_output = "".join(textfile_handle.readlines())
94+
random_font = ImageFont.truetype(random.choice(fonts), 14, encoding='unic')
95+
return Message(textfile_output,random.choice(Message_Style.values())).BuildMessage(random_font)
7596

7697
# Initialization
7798

@@ -112,7 +133,8 @@ def daily():
112133
exit(0)
113134

114135
# Print greeting image.
115-
printer.print('Started at ' + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
136+
#printer.print('Started at ' + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
137+
printer.printImage(Image.open('gfx/helloworld.png'), True)
116138
printer.feed(3)
117139
GPIO.output(ledPin, GPIO.LOW)
118140

@@ -163,6 +185,14 @@ def daily():
163185
l = time.localtime()
164186
if (60 * l.tm_hour + l.tm_min) > (60 * hrs + mins) and (60 * l.tm_hour + l.tm_min) < (60 * hrs + mins + 2):
165187
dailyFlag = False
188+
#clear current item of the day by moving file to 'used' bin
189+
###if picked_item != "":
190+
### move_to_bin(picked_item)
191+
# pick item of the day
192+
picked_item = filewalker.pick_item(item_folder,date.today())
193+
# print item of the day
194+
printer.printImage(png_from_item(picked_item), True)
195+
166196

167197
# LED blinks while idle, for a brief interval every 2 seconds.
168198
# Pin 18 is PWM-capable and a "sleep throb" would be nice, but

daily_message_tester.py

Lines changed: 39 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -19,27 +19,48 @@
1919

2020
###printer.setSize('L') # Set type size, accepts 'S', 'M', 'L'
2121
#printer.println(filewalker.pick_random_pic(item_folder))
22+
23+
24+
# takes a file path and return ready-to-print png image, converting text files by invoking MessageClass
25+
def png_from_item(picked_item):
26+
if picked_item.rsplit(".",1)[1] == "png":
27+
print "Image printed..."
28+
return Image.open(picked_item)
29+
elif picked_item.rsplit(".",1)[1] == "txt":
30+
textfile_handle = open(picked_item, "r")
31+
textfile_output = "".join(textfile_handle.readlines())
32+
random_font = ImageFont.truetype(random.choice(fonts), 14, encoding='unic')
33+
return Message(textfile_output,random.choice(Message_Style.values())).BuildMessage(random_font)
34+
35+
36+
# choose a file
2237
picked_item = filewalker.pick_item(item_folder,date.today())
2338

39+
#convert to png
40+
png_from_item(picked_item).show()
41+
42+
2443
#process according to file type
25-
print "picked item: " + picked_item
26-
print picked_item.rsplit(".",1)[1]
27-
print "png?" + str(picked_item.rsplit(".",1)[1] == "png")
28-
print "txt?" + str(picked_item.rsplit(".",1)[1] == "txt")
29-
30-
if picked_item.rsplit(".",1)[1] == "png":
31-
###printer.printImage(Image.open(filewalker.pick_item(item_folder)), True)
32-
print "Image printed..."
33-
elif picked_item.rsplit(".",1)[1] == "txt":
34-
textfile_handle = open(picked_item, "r")
35-
textfile_output = "".join(textfile_handle.readlines())
36-
#print textfile_output
37-
print textfile_output
38-
XX = Message(textfile_output,random.choice(Message_Style.values()))
39-
XX.print_me()
40-
#XY = Message("This is the text! I see what you did there...",Message_Style["Schweinchen"])
41-
XX.BuildMessage(font).show()
42-
#returned_image = msg_block2png(Message, font, wrap_limit, offset_x, offset_y)
44+
# print "picked item: " + picked_item
45+
# print picked_item.rsplit(".",1)[1]
46+
# print "png?" + str(picked_item.rsplit(".",1)[1] == "png")
47+
# print "txt?" + str(picked_item.rsplit(".",1)[1] == "txt")
48+
49+
# if picked_item.rsplit(".",1)[1] == "png":
50+
# ###printer.printImage(Image.open(filewalker.pick_item(item_folder)), True)
51+
# print "Image printed..."
52+
# elif picked_item.rsplit(".",1)[1] == "txt":
53+
# textfile_handle = open(picked_item, "r")
54+
# textfile_output = "".join(textfile_handle.readlines())
55+
# #print textfile_output
56+
# print textfile_output
57+
# XX = Message(textfile_output,random.choice(Message_Style.values()))
58+
# XX.print_me()
59+
# #XY = Message("This is the text! I see what you did there...",Message_Style["Schweinchen"])
60+
# random_font = ImageFont.truetype(random.choice(fonts), 14, encoding='unic')
61+
# #XX.BuildMessage(random_font).show()
62+
# Message(textfile_output,random.choice(Message_Style.values())).BuildMessage(random_font).show()
63+
# #returned_image = msg_block2png(Message, font, wrap_limit, offset_x, offset_y)
4364

4465
###printer.println('Now printing text file:')
4566
###printer.println(textfile_output)

gfx/calendar.png

8.19 KB
Loading

gfx/hands_love.png

4.25 KB
Loading

gfx/helloworld.png

50.3 KB
Loading
File renamed without changes.
File renamed without changes.

legacy/main.py

Lines changed: 166 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,166 @@
1+
#!/usr/bin/python
2+
3+
# Main script for Adafruit Internet of Things Printer 2. Monitors button
4+
# for taps and holds, performs periodic actions (Twitter polling by default)
5+
# and daily actions (Sudoku and weather by default).
6+
# Written by Adafruit Industries. MIT license.
7+
#
8+
# MUST BE RUN AS ROOTi (due to GPIO access)
9+
#
10+
# Required software includes Adafruit_Thermal, Python Imaging and PySerial
11+
# libraries. Other libraries used are part of stock Python install.
12+
#
13+
# Resources:
14+
# http://www.adafruit.com/products/597 Mini Thermal Receipt Printer
15+
# http://www.adafruit.com/products/600 Printer starter pack
16+
17+
from __future__ import print_function
18+
import RPi.GPIO as GPIO
19+
import subprocess, time, Image, socket
20+
from Adafruit_Thermal import *
21+
22+
ledPin = 18
23+
buttonPin = 23
24+
holdTime = 2 # Duration for button hold (shutdown)
25+
tapTime = 0.01 # Debounce time for button taps
26+
nextInterval = 0.0 # Time of next recurring operation
27+
dailyFlag = False # Set after daily trigger occurs
28+
lastId = '1' # State information passed to/from interval script
29+
printer = Adafruit_Thermal("/dev/serial0", 19200, timeout=5)
30+
31+
32+
# Called when button is briefly tapped. Invokes time/temperature script.
33+
def tap():
34+
GPIO.output(ledPin, GPIO.HIGH) # LED on while working
35+
subprocess.call(["python", "timetemp.py"])
36+
GPIO.output(ledPin, GPIO.LOW)
37+
38+
39+
# Called when button is held down. Prints image, invokes shutdown process.
40+
def hold():
41+
GPIO.output(ledPin, GPIO.HIGH)
42+
printer.printImage(Image.open('gfx/goodbye.png'), True)
43+
printer.feed(3)
44+
subprocess.call("sync")
45+
subprocess.call(["shutdown", "-h", "now"])
46+
GPIO.output(ledPin, GPIO.LOW)
47+
48+
49+
# Called at periodic intervals (30 seconds by default).
50+
# Invokes twitter script.
51+
def interval():
52+
GPIO.output(ledPin, GPIO.HIGH)
53+
p = subprocess.Popen(["python", "twitter.py", str(lastId)],
54+
stdout=subprocess.PIPE)
55+
GPIO.output(ledPin, GPIO.LOW)
56+
return p.communicate()[0] # Script pipes back lastId, returned to main
57+
58+
59+
# Called once per day (6:30am by default).
60+
# Invokes weather forecast and sudoku-gfx scripts.
61+
def daily():
62+
GPIO.output(ledPin, GPIO.HIGH)
63+
subprocess.call(["python", "forecast.py"])
64+
subprocess.call(["python", "sudoku-gfx.py"])
65+
GPIO.output(ledPin, GPIO.LOW)
66+
67+
68+
# Initialization
69+
70+
# Use Broadcom pin numbers (not Raspberry Pi pin numbers) for GPIO
71+
GPIO.setmode(GPIO.BCM)
72+
73+
# Enable LED and button (w/pull-up on latter)
74+
GPIO.setup(ledPin, GPIO.OUT)
75+
GPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
76+
77+
# LED on while working
78+
GPIO.output(ledPin, GPIO.HIGH)
79+
80+
# Processor load is heavy at startup; wait a moment to avoid
81+
# stalling during greeting.
82+
time.sleep(30)
83+
84+
# Show IP address (if network is available)
85+
try:
86+
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
87+
s.connect(('8.8.8.8', 0))
88+
printer.print('My IP address is ' + s.getsockname()[0])
89+
printer.feed(3)
90+
except:
91+
printer.boldOn()
92+
printer.println('Network is unreachable.')
93+
printer.boldOff()
94+
printer.print('Connect display and keyboard\n'
95+
'for network troubleshooting.')
96+
printer.feed(3)
97+
exit(0)
98+
99+
# Print greeting image
100+
printer.printImage(Image.open('gfx/hello.png'), True)
101+
printer.feed(3)
102+
GPIO.output(ledPin, GPIO.LOW)
103+
104+
# Poll initial button state and time
105+
prevButtonState = GPIO.input(buttonPin)
106+
prevTime = time.time()
107+
tapEnable = False
108+
holdEnable = False
109+
110+
# Main loop
111+
while(True):
112+
113+
# Poll current button state and time
114+
buttonState = GPIO.input(buttonPin)
115+
t = time.time()
116+
117+
# Has button state changed?
118+
if buttonState != prevButtonState:
119+
prevButtonState = buttonState # Yes, save new state/time
120+
prevTime = t
121+
else: # Button state unchanged
122+
if (t - prevTime) >= holdTime: # Button held more than 'holdTime'?
123+
# Yes it has. Is the hold action as-yet untriggered?
124+
if holdEnable == True: # Yep!
125+
hold() # Perform hold action (usu. shutdown)
126+
holdEnable = False # 1 shot...don't repeat hold action
127+
tapEnable = False # Don't do tap action on release
128+
elif (t - prevTime) >= tapTime: # Not holdTime. tapTime elapsed?
129+
# Yes. Debounced press or release...
130+
if buttonState == True: # Button released?
131+
if tapEnable == True: # Ignore if prior hold()
132+
tap() # Tap triggered (button released)
133+
tapEnable = False # Disable tap and hold
134+
holdEnable = False
135+
else: # Button pressed
136+
tapEnable = True # Enable tap and hold actions
137+
holdEnable = True
138+
139+
# LED blinks while idle, for a brief interval every 2 seconds.
140+
# Pin 18 is PWM-capable and a "sleep throb" would be nice, but
141+
# the PWM-related library is a hassle for average users to install
142+
# right now. Might return to this later when it's more accessible.
143+
if ((int(t) & 1) == 0) and ((t - int(t)) < 0.15):
144+
GPIO.output(ledPin, GPIO.HIGH)
145+
else:
146+
GPIO.output(ledPin, GPIO.LOW)
147+
148+
# Once per day (currently set for 6:30am local time, or when script
149+
# is first run, if after 6:30am), run forecast and sudoku scripts.
150+
l = time.localtime()
151+
if (60 * l.tm_hour + l.tm_min) > (60 * 6 + 30):
152+
if dailyFlag == False:
153+
daily()
154+
dailyFlag = True
155+
else:
156+
dailyFlag = False # Reset daily trigger
157+
158+
# Every 30 seconds, run Twitter scripts. 'lastId' is passed around
159+
# to preserve state between invocations. Probably simpler to do an
160+
# import thing.
161+
if t > nextInterval:
162+
nextInterval = t + 30.0
163+
result = interval()
164+
if result is not None:
165+
lastId = result.rstrip('\r\n')
166+
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.

main.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ def daily():
6262
GPIO.output(ledPin, GPIO.HIGH)
6363
subprocess.call(["python", "forecast.py"])
6464
subprocess.call(["python", "sudoku-gfx.py"])
65+
6566
GPIO.output(ledPin, GPIO.LOW)
6667

6768

@@ -97,7 +98,7 @@ def daily():
9798
exit(0)
9899

99100
# Print greeting image
100-
printer.printImage(Image.open('gfx/hello.png'), True)
101+
printer.printImage(Image.open('gfx/helloworld.png'), True)
101102
printer.feed(3)
102103
GPIO.output(ledPin, GPIO.LOW)
103104

stdout.png

6.36 KB
Loading

symbols/Schweinchen.png

17.2 KB
Loading

symbols/angel.png

19.8 KB
Loading

symbols/calendar.png

8.19 KB
Loading

symbols/dove.png

26.1 KB
Loading

symbols/floral1.png

164 KB
Loading

symbols/rose2.png

8.17 KB
Loading

0 commit comments

Comments
 (0)