Skip to content
This repository has been archived by the owner on May 16, 2023. It is now read-only.

Commit

Permalink
Merges changes from upstream Adafruit lib
Browse files Browse the repository at this point in the history
Signed-off-by: zachwick <[email protected]>
  • Loading branch information
zachwick committed Jan 23, 2018
2 parents 2a2e883 + 8165c22 commit 18b998e
Show file tree
Hide file tree
Showing 10 changed files with 784 additions and 778 deletions.
1,391 changes: 696 additions & 695 deletions Adafruit_Thermal/Adafruit_Thermal.py

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion examples/calibrate.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
from __future__ import print_function
from Adafruit_Thermal import *

printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5)
printer = Adafruit_Thermal("/dev/serial0", 19200, timeout=5)

for i in range(0,256,15):
printer.begin(i)
Expand Down
59 changes: 30 additions & 29 deletions examples/forecast.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#!/usr/bin/python

# Weather forecast for Raspberry Pi w/Adafruit Mini Thermal Printer.
# Retrieves data from Yahoo! weather, prints current conditions and
# Retrieves data from DarkSky.net's API, prints current conditions and
# forecasts for next two days. See timetemp.py for a different
# weather example using nice bitmaps.
# Written by Adafruit Industries. MIT license.
Expand All @@ -14,51 +14,52 @@
# http://www.adafruit.com/products/600 Printer starter pack

from __future__ import print_function
import urllib, time
from Adafruit_Thermal import *
from xml.dom.minidom import parseString
from datetime import date
from datetime import datetime
import calendar
import urllib, json

# WOEID indicates the geographic location for the forecast. It is
# not a ZIP code or other common indicator. Instead, it can be found
# by 'manually' visiting http://weather.yahoo.com, entering a location
# and requesting a forecast, then copy the number from the end of the
# current URL string and paste it here.
WOEID = '2459115'
API_KEY = "YOUR_API_KEY"

LAT = "40.726019"
LONG = "-74.00536"

# Dumps one forecast line to the printer
def forecast(idx):
tag = 'yweather:forecast'
day = dom.getElementsByTagName(tag)[idx].getAttribute('day')
lo = dom.getElementsByTagName(tag)[idx].getAttribute('low')
hi = dom.getElementsByTagName(tag)[idx].getAttribute('high')
cond = dom.getElementsByTagName(tag)[idx].getAttribute('text')
printer.print(day + ': low ' + lo )
printer.print(deg)
printer.print(' high ' + hi)
printer.print(deg)
printer.println(' ' + cond)

printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5)
date = datetime.fromtimestamp(int(data['daily']['data'][idx]['time']))

day = calendar.day_name[date.weekday()]
lo = data['daily']['data'][idx]['temperatureMin']
hi = data['daily']['data'][idx]['temperatureMax']
cond = data['daily']['data'][idx]['summary']
printer.print(day + ': low ' + str(lo) )
printer.print(deg)
printer.print(' high ' + str(hi))
printer.print(deg)
printer.println(' ' + cond.replace(u'\u2013', '-').encode('utf-8')) # take care of pesky unicode dash

printer = Adafruit_Thermal("/dev/serial0", 19200, timeout=5)
deg = chr(0xf8) # Degree symbol on thermal printer

# Fetch forecast data from Yahoo!, parse resulting XML
dom = parseString(urllib.urlopen(
'http://weather.yahooapis.com/forecastrss?w=' + WOEID).read())
url = "https://api.darksky.net/forecast/"+API_KEY+"/"+LAT+","+LONG+"?exclude=[alerts,minutely,hourly,flags]&units=us"
response = urllib.urlopen(url)
data = json.loads(response.read())

# Print heading
printer.inverseOn()
printer.print('{:^32}'.format(
dom.getElementsByTagName('description')[0].firstChild.data))
printer.print('{:^32}'.format("DarkSky.Net Forecast"))
printer.inverseOff()

# Print current conditions
printer.boldOn()
printer.print('{:^32}'.format('Current conditions:'))
printer.boldOff()
printer.print('{:^32}'.format(
dom.getElementsByTagName('pubDate')[0].firstChild.data))
temp = dom.getElementsByTagName('yweather:condition')[0].getAttribute('temp')
cond = dom.getElementsByTagName('yweather:condition')[0].getAttribute('text')


temp = data['currently']['temperature']
cond = data['currently']['summary']
printer.print(temp)
printer.print(deg)
printer.println(' ' + cond)
Expand Down
5 changes: 3 additions & 2 deletions examples/iot_printer.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@

from __future__ import print_function
import RPi.GPIO as GPIO
import subprocess, time, Image, socket
import subprocess, time, socket
from PIL import Image
from Adafruit_Thermal import *

ledPin = 18
Expand All @@ -26,7 +27,7 @@
nextInterval = 0.0 # Time of next recurring operation
dailyFlag = False # Set after daily trigger occurs
lastId = '1' # State information passed to/from interval script
printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5)
printer = Adafruit_Thermal("/dev/serial0", 19200, timeout=5)


# Called when button is briefly tapped. Invokes time/temperature script.
Expand Down
4 changes: 2 additions & 2 deletions examples/printertest.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from Adafruit_Thermal import *

printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5)
printer = Adafruit_Thermal("/dev/serial0", 19200, timeout=5)

# Test inverse on & off
printer.inverseOn()
Expand Down Expand Up @@ -61,7 +61,7 @@
import gfx.adaqrcode as adaqrcode
printer.printBitmap(adaqrcode.width, adaqrcode.height, adaqrcode.data)
printer.println("Adafruit!")
printer.feed(1)
printer.feed(2)

printer.sleep() # Tell printer to sleep
printer.wake() # Call wake() before printing again, even if reset
Expand Down
4 changes: 2 additions & 2 deletions examples/sudoku-gfx.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,9 @@
from __future__ import print_function
import sys, os, random, getopt, re
from Adafruit_Thermal import *
import Image
from PIL import Image

printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5)
printer = Adafruit_Thermal("/dev/serial0", 19200, timeout=5)
bg = Image.new("1", [384, 426], "white") # Working 'background' image
img = Image.open('gfx/sudoku.png') # Source bitmaps
xcoord = [ 15, 55, 95, 139, 179, 219, 263, 303, 343 ]
Expand Down
2 changes: 1 addition & 1 deletion examples/sudoku-txt.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
import sys, os, random, getopt, re
from Adafruit_Thermal import *

printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5)
printer = Adafruit_Thermal("/dev/serial0", 19200, timeout=5)

def main():
printer.setLineHeight(24) # So graphical chars fit together
Expand Down
91 changes: 47 additions & 44 deletions examples/timetemp.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#!/usr/bin/python

# Current time and temperature display for Raspberry Pi w/Adafruit Mini
# Thermal Printer. Retrieves data from Yahoo! weather, prints current
# Thermal Printer. Retrieves data from DarkSky.net's API, prints current
# conditions and time using large, friendly graphics.
# See forecast.py for a different weather example that's all text-based.
# Written by Adafruit Industries. MIT license.
Expand All @@ -15,31 +15,32 @@

from __future__ import print_function
from Adafruit_Thermal import *
from xml.dom.minidom import parseString
import Image, ImageDraw, time, urllib
import time, urllib, json
from PIL import Image, ImageDraw

# WOEID indicates the geographic location for the forecast. It is
# not a ZIP code or other common indicator. Instead, it can be found
# by 'manually' visiting http://weather.yahoo.com, entering a location
# and requesting a forecast, then copy the number from the end of the
# current URL string and paste it here.
WOEID = '2459115'
API_KEY = "YOUR_API_KEY"

# Fetch weather data from Yahoo!, parse resulting XML
dom = parseString(urllib.urlopen(
'http://weather.yahooapis.com/forecastrss?w=' + WOEID).read())
LAT = "40.726019"
LONG = "-74.00536"

# Fetch weather data from DarkSky, parse resulting JSON
url = "https://api.darksky.net/forecast/"+API_KEY+"/"+LAT+","+LONG+"?exclude=[alerts,minutely,hourly,flags]&units=us"
response = urllib.urlopen(url)
data = json.loads(response.read())

# Extract values relating to current temperature, humidity, wind
temperature = int(dom.getElementsByTagName(
'yweather:condition')[0].getAttribute('temp'))
humidity = int(dom.getElementsByTagName(
'yweather:atmosphere')[0].getAttribute('humidity'))
windSpeed = int(dom.getElementsByTagName(
'yweather:wind')[0].getAttribute('speed'))
windDir = int(dom.getElementsByTagName(
'yweather:wind')[0].getAttribute('direction'))
windUnits = dom.getElementsByTagName(
'yweather:units')[0].getAttribute('speed')

temperature = int(data['currently']['temperature'])
humidity = int(data['currently']['humidity'] * 100);
windSpeed = int(data['currently']['windSpeed'])
windDir = data['currently']['windBearing']
windUnits = "mph"

# print(temperature)
# print(humidity)
# print(windSpeed)
# print(windDir)
# print(windUnits)

# Although the Python Imaging Library does have nice font support,
# I opted here to use a raster bitmap for all of the glyphs instead.
Expand All @@ -62,11 +63,11 @@

# Generate a list of sub-image glyphs cropped from the symbols image
def croplist(widths, x, y, height):
list = []
for i in range(len(widths)):
list.append(symbols.crop(
[x, y+i*height, x+widths[i], y+(i+1)*height]))
return list
list = []
for i in range(len(widths)):
list.append(symbols.crop(
[x, y+i*height, x+widths[i], y+(i+1)*height]))
return list

# Crop glyph lists (digits, days of week, etc.)
TimeDigit = croplist(TimeDigitWidth, 0, 0, 44)
Expand All @@ -91,20 +92,20 @@ def croplist(widths, x, y, height):

# Paste a series of glyphs (mostly numbers) from string to img
def drawNums(str, x, y, list):
for i in range(len(str)):
d = ord(str[i]) - ord('0')
img.paste(list[d], (x, y))
x += list[d].size[0] + 1
return x
for i in range(len(str)):
d = ord(str[i]) - ord('0')
img.paste(list[d], (x, y))
x += list[d].size[0] + 1
return x

# Determine total width of a series of glyphs in string
def numWidth(str, list):
w = 0 # Cumulative width
for i in range(len(str)):
d = ord(str[i]) - ord('0')
if i > 0: w += 1 # Space between digits
w += list[d].size[0] # Digit width
return w
w = 0 # Cumulative width
for i in range(len(str)):
d = ord(str[i]) - ord('0')
if i > 0: w += 1 # Space between digits
w += list[d].size[0] # Digit width
return w

# Render current time (always 24 hour XX:XX format)
t = time.localtime()
Expand Down Expand Up @@ -134,12 +135,13 @@ def numWidth(str, list):
s2 = str(windSpeed)
winDirNum = 0 # Wind direction glyph number
if windSpeed > 0:
for winDirNum in range(len(DirAngle) - 1):
if windDir < DirAngle[winDirNum]: break
for winDirNum in range(len(DirAngle) - 1):
if windDir < DirAngle[winDirNum]: break
winDirNum+=1
w = Humidity.size[0] + 5 + numWidth(s, HumiDigit)
w2 = Wind.size[0] + 5 + numWidth(s2, HumiDigit)
if windSpeed > 0:
w2 += 3 + Dir[winDirNum].size[0]
w2 += 3 + Dir[winDirNum].size[0]
if windUnits == 'kph': w2 += 3 + Kph.size[0]
else: w2 += 3 + Mph.size[0]
if w2 > w: w = w2
Expand All @@ -154,14 +156,15 @@ def numWidth(str, list):
y += 23 # And advance to next line
img.paste(Wind, (x, y))
x += Wind.size[0] + 5

if windSpeed > 0:
img.paste(Dir[winDirNum], (x, y))
x += Dir[winDirNum].size[0] + 3
img.paste(Dir[winDirNum], (x, y))
x += Dir[winDirNum].size[0] + 3
x = drawNums(s2, x, y, HumiDigit) + 3
if windUnits == 'kph': img.paste(Kph, (x, y))
else: img.paste(Mph, (x, y))

# Open connection to printer and print image
printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5)
printer = Adafruit_Thermal("/dev/serial0", 19200, timeout=5)
printer.printImage(img, True)
printer.feed(3)
2 changes: 1 addition & 1 deletion examples/twitter.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@

# Other globals. You probably won't need to change these. -----------------

printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5)
printer = Adafruit_Thermal("/dev/serial0", 19200, timeout=5)
host = 'api.twitter.com'
authUrl = '/oauth2/token'
searchUrl = '/1.1/search/tweets.json?'
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ def readme():
return f.read()

setup(name='Adafruit_Thermal',
version='1.0.0',
version='1.1.0',
description='Library for controlling Adafruit Thermal Printers',
url='https://github.com/bareo/Python-Thermal-Printer',
author='zach wick',
Expand Down

0 comments on commit 18b998e

Please sign in to comment.