Skip to content

Commit 16b30d1

Browse files
authored
Add files via upload
1 parent b8bdca0 commit 16b30d1

File tree

4 files changed

+90
-90
lines changed

4 files changed

+90
-90
lines changed

Adafruit_Thermal.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ class Adafruit_Thermal(Serial):
5050
lineSpacing = 8
5151
barcodeHeight = 50
5252
printMode = 0
53-
defaultHeatTime = 180
53+
defaultHeatTime = 120
5454
firmwareVersion = 268
5555
writeToStdout = False
5656

@@ -549,11 +549,8 @@ def printBitmap(self, w, h, bitmap, LaaT=False):
549549
# passing the result to this function.
550550
def printImage(self, image_file, LaaT=False):
551551
from PIL import Image
552+
# image = Image.open(image_file)
552553
image = image_file
553-
554-
if isinstance(image_file, str):
555-
image = Image.open(image_file)
556-
557554
if image.mode != '1':
558555
image = image.convert('1')
559556

forecast.py

Lines changed: 55 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -1,74 +1,72 @@
1-
#!/usr/bin/python
2-
3-
# Weather forecast for Raspberry Pi w/Adafruit Mini Thermal Printer.
4-
# Retrieves data from DarkSky.net's API, prints current conditions and
5-
# forecasts for next two days. See timetemp.py for a different
6-
# weather example using nice bitmaps.
7-
# Written by Adafruit Industries. MIT license.
8-
#
9-
# Required software includes Adafruit_Thermal and PySerial libraries.
10-
# Other libraries used are part of stock Python install.
11-
#
12-
# Resources:
13-
# http://www.adafruit.com/products/597 Mini Thermal Receipt Printer
14-
# http://www.adafruit.com/products/600 Printer starter pack
15-
161
from __future__ import print_function
172
from Adafruit_Thermal import *
183
from datetime import date
19-
from datetime import datetime
204
import calendar
21-
import urllib, json
5+
import urllib.request
6+
import json
227

23-
API_KEY = "YOUR_API_KEY"
8+
printer = Adafruit_Thermal("/dev/serial0", 19200, timeout=5)
9+
def getLink(dailyOrHourly):
10+
latitude = "38.8894" #limit to four decimal digits
11+
longitude = "-77.0352" #limit to four decimal digits
12+
mainLink = "https://api.weather.gov/points/" + latitude + "," + longitude
13+
response_main = urllib.request.urlopen(mainLink)
14+
raw_data_main = response_main.read().decode()
15+
data_main = json.loads(raw_data_main)
16+
properties_main = data_main['properties']
17+
dailyLink = properties_main["forecast"]
18+
hourlyLink = properties_main["forecastHourly"]
19+
if dailyOrHourly == "daily":
20+
return dailyLink
21+
elif dailyOrHourly == "hourly":
22+
return hourlyLink
2423

25-
LAT = "40.726019"
26-
LONG = "-74.00536"
24+
url_daily = getLink("daily")
25+
response_daily = urllib.request.urlopen(url_daily)
26+
# status & reason
27+
# print(response_daily.status, response_daily.reason)
2728

28-
# Dumps one forecast line to the printer
29-
def forecast(idx):
29+
raw_data_daily = response_daily.read().decode()
30+
data_daily = json.loads(raw_data_daily)
31+
forecast_periods_daily = data_daily['properties']['periods']
3032

31-
date = datetime.fromtimestamp(int(data['daily']['data'][idx]['time']))
3233

33-
day = calendar.day_name[date.weekday()]
34-
lo = data['daily']['data'][idx]['temperatureMin']
35-
hi = data['daily']['data'][idx]['temperatureMax']
36-
cond = data['daily']['data'][idx]['summary']
37-
printer.print(day + ': low ' + str(lo) )
38-
printer.print(deg)
39-
printer.print(' high ' + str(hi))
40-
printer.print(deg)
41-
printer.println(' ' + cond.replace(u'\u2013', '-').encode('utf-8')) # take care of pesky unicode dash
34+
current_period_isDayTime = forecast_periods_daily[0]['isDaytime']
4235

43-
printer = Adafruit_Thermal("/dev/serial0", 19200, timeout=5)
44-
deg = chr(0xf8) # Degree symbol on thermal printer
36+
if current_period_isDayTime:
37+
day_index = 0
38+
night_index = 1
39+
else:
40+
day_index = 1
41+
night_index = 0
4542

46-
url = "https://api.darksky.net/forecast/"+API_KEY+"/"+LAT+","+LONG+"?exclude=[alerts,minutely,hourly,flags]&units=us"
47-
response = urllib.urlopen(url)
48-
data = json.loads(response.read())
43+
day_name = forecast_periods_daily[day_index]['name']
44+
hi_temp = forecast_periods_daily[day_index]['temperature']
45+
night_name = forecast_periods_daily[night_index]['name']
46+
lo_temp = forecast_periods_daily[night_index]['temperature']
47+
current_detailed_forecast = forecast_periods_daily[0]['detailedForecast']
4948

50-
# Print heading
51-
printer.inverseOn()
52-
printer.print('{:^32}'.format("DarkSky.Net Forecast"))
53-
printer.inverseOff()
54-
55-
# Print current conditions
56-
printer.boldOn()
57-
printer.print('{:^32}'.format('Current conditions:'))
58-
printer.boldOff()
49+
url_hourly = getLink("hourly")
50+
response_hourly = urllib.request.urlopen(url_hourly)
51+
# status & reason
52+
#print(response_hourly.status, response_hourly.reason)
5953

54+
raw_data_hourly = response_hourly.read().decode()
55+
data_hourly = json.loads(raw_data_hourly)
56+
forecast_periods_hourly = data_hourly['properties']['periods']
57+
temperature = forecast_periods_hourly[0]['temperature']
6058

61-
temp = data['currently']['temperature']
62-
cond = data['currently']['summary']
63-
printer.print(temp)
64-
printer.print(deg)
65-
printer.println(' ' + cond)
59+
d = date.today()
60+
week_day = calendar.day_name[date(d.year,d.month,d.day).weekday()]
61+
month_text = calendar.month_name[d.month]
62+
printer.underlineOn()
63+
printer.print("It's " + week_day + ", " + month_text + " " + str(d.day) + "\n")
64+
printer.underlineOff()
6665
printer.boldOn()
67-
68-
# Print forecast
69-
printer.print('{:^32}'.format('Forecast:'))
66+
printer.print(day_name + "'s Forecast \n")
7067
printer.boldOff()
71-
forecast(0)
72-
forecast(1)
73-
68+
printer.print("Current temperature: " + str(temperature) + " F \n")
69+
printer.print("High temperature: " + str(hi_temp) + " F \n")
70+
printer.print("Low temperature: " + str(lo_temp) + " F \n")
71+
printer.print(current_detailed_forecast + "\n")
7472
printer.feed(3)

main.py

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
#!/usr/bin/python
1+
#!/usr/bin/python3
22

33
# Main script for Adafruit Internet of Things Printer 2. Monitors button
44
# for taps and holds, performs periodic actions (Twitter polling by default)
@@ -19,6 +19,8 @@
1919
import subprocess, time, socket
2020
from PIL import Image
2121
from Adafruit_Thermal import *
22+
from datetime import date
23+
import calendar
2224

2325
ledPin = 18
2426
buttonPin = 23
@@ -33,7 +35,7 @@
3335
# Called when button is briefly tapped. Invokes time/temperature script.
3436
def tap():
3537
GPIO.output(ledPin, GPIO.HIGH) # LED on while working
36-
subprocess.call(["python", "timetemp.py"])
38+
subprocess.call(["python3", "forecast.py"])
3739
GPIO.output(ledPin, GPIO.LOW)
3840

3941

@@ -51,7 +53,7 @@ def hold():
5153
# Invokes twitter script.
5254
def interval():
5355
GPIO.output(ledPin, GPIO.HIGH)
54-
p = subprocess.Popen(["python", "twitter.py", str(lastId)],
56+
p = subprocess.Popen(["python3", "twitter.py", str(lastId)],
5557
stdout=subprocess.PIPE)
5658
GPIO.output(ledPin, GPIO.LOW)
5759
return p.communicate()[0] # Script pipes back lastId, returned to main
@@ -61,8 +63,11 @@ def interval():
6163
# Invokes weather forecast and sudoku-gfx scripts.
6264
def daily():
6365
GPIO.output(ledPin, GPIO.HIGH)
64-
subprocess.call(["python", "forecast.py"])
65-
subprocess.call(["python", "sudoku-gfx.py"])
66+
subprocess.call(["python3", "forecast.py"])
67+
d = date.today()
68+
weekday = calendar.day_name[date(d.year,d.month,d.day).weekday()]
69+
if weekday == "Saturday" or weekday == "Sunday":
70+
subprocess.call(["python3", "sudoku-gfx.py"])
6671
GPIO.output(ledPin, GPIO.LOW)
6772

6873

@@ -159,9 +164,9 @@ def daily():
159164
# Every 30 seconds, run Twitter scripts. 'lastId' is passed around
160165
# to preserve state between invocations. Probably simpler to do an
161166
# import thing.
162-
if t > nextInterval:
163-
nextInterval = t + 30.0
164-
result = interval()
165-
if result is not None:
166-
lastId = result.rstrip('\r\n')
167+
# if t > nextInterval:
168+
# nextInterval = t + 30.0
169+
# result = interval()
170+
# if result is not None:
171+
# lastId = result.rstrip('\r\n')
167172

sudoku-gfx.py

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
#!/usr/bin/python
1+
#!/usr/bin/python3
22
#
33
# Sudoku Generator and Solver in 250 lines of python
44
# Copyright (c) 2006 David Bau. All rights reserved.
@@ -55,22 +55,22 @@ def main():
5555

5656
def makepuzzle(board):
5757
puzzle = []; deduced = [None] * 81
58-
order = random.sample(xrange(81), 81)
58+
order = random.sample(range(81), 81)
5959
for pos in order:
6060
if deduced[pos] is None:
6161
puzzle.append((pos, board[pos]))
6262
deduced[pos] = board[pos]
6363
deduce(deduced)
6464
random.shuffle(puzzle)
65-
for i in xrange(len(puzzle) - 1, -1, -1):
65+
for i in range(len(puzzle) - 1, -1, -1):
6666
e = puzzle[i]; del puzzle[i]
6767
rating = checkpuzzle(boardforentries(puzzle), board)
6868
if rating == -1: puzzle.append(e)
6969
return boardforentries(puzzle)
7070

7171
def ratepuzzle(puzzle, samples):
7272
total = 0
73-
for i in xrange(samples):
73+
for i in range(samples):
7474
state, answer = solveboard(puzzle)
7575
if answer is None: return -1
7676
total += len(state)
@@ -113,7 +113,7 @@ def deduce(board):
113113
stuck, guess, count = True, None, 0
114114
# fill in any spots determined by direct conflicts
115115
allowed, needed = figurebits(board)
116-
for pos in xrange(81):
116+
for pos in range(81):
117117
if None == board[pos]:
118118
numbers = listbits(allowed[pos])
119119
if len(numbers) == 0: return []
@@ -122,13 +122,13 @@ def deduce(board):
122122
guess, count = pickbetter(guess, count, [(pos, n) for n in numbers])
123123
if not stuck: allowed, needed = figurebits(board)
124124
# fill in any spots determined by elimination of other locations
125-
for axis in xrange(3):
126-
for x in xrange(9):
125+
for axis in range(3):
126+
for x in range(9):
127127
numbers = listbits(needed[axis * 9 + x])
128128
for n in numbers:
129129
bit = 1 << n
130130
spots = []
131-
for y in xrange(9):
131+
for y in range(9):
132132
pos = posfor(x, y, axis)
133133
if allowed[pos] & bit: spots.append(pos)
134134
if len(spots) == 0: return []
@@ -141,11 +141,11 @@ def deduce(board):
141141

142142
def figurebits(board):
143143
allowed, needed = [e is None and 511 or 0 for e in board], []
144-
for axis in xrange(3):
145-
for x in xrange(9):
144+
for axis in range(3):
145+
for x in range(9):
146146
bits = axismissing(board, x, axis)
147147
needed.append(bits)
148-
for y in xrange(9):
148+
for y in range(9):
149149
allowed[posfor(x, y, axis)] &= bits
150150
return allowed, needed
151151

@@ -161,17 +161,17 @@ def axisfor(pos, axis):
161161

162162
def axismissing(board, x, axis):
163163
bits = 0
164-
for y in xrange(9):
164+
for y in range(9):
165165
e = board[posfor(x, y, axis)]
166166
if e is not None: bits |= 1 << e
167167
return 511 ^ bits
168168

169169
def listbits(bits):
170-
return [y for y in xrange(9) if 0 != bits & 1 << y]
170+
return [y for y in range(9) if 0 != bits & 1 << y]
171171

172172
def allowed(board, pos):
173173
bits = 511
174-
for axis in xrange(3):
174+
for axis in range(3):
175175
x = axisfor(pos, axis)
176176
bits &= axismissing(board, x, axis)
177177
return bits
@@ -183,22 +183,22 @@ def pickbetter(b, c, t):
183183
else: return (b, c + 1)
184184

185185
def entriesforboard(board):
186-
return [(pos, board[pos]) for pos in xrange(81) if board[pos] is not None]
186+
return [(pos, board[pos]) for pos in range(81) if board[pos] is not None]
187187

188188
def boardforentries(entries):
189189
board = [None] * 81
190190
for pos, n in entries: board[pos] = n
191191
return board
192192

193193
def boardmatches(b1, b2):
194-
for i in xrange(81):
194+
for i in range(81):
195195
if b1[i] != b2[i]: return False
196196
return True
197197

198198
def printboard(board):
199199
bg.paste(img, (0, 0)) # Numbers are cropped off right side
200-
for row in xrange(9):
201-
for col in xrange(9):
200+
for row in range(9):
201+
for col in range(9):
202202
n = board[posfor(row, col)]
203203
if n is not None:
204204
bg.paste(numbers[n], (xcoord[col], ycoord[row]))

0 commit comments

Comments
 (0)