def upload_file(): if request.method == 'POST': uploadedFile = request.files['file'] printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5) printer.printImage(Image.open(uploadedFile), True) printer.feed(10) redirect("/printer")
def printout(): if request.method == 'POST': printText=request.form['printtext'] printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5) printer.println(printText) printer.feed(10) redirect("/printer")
def main(): # Get the current time, format it as the file name timeNow = makeTimeStamp() fileToSave = savePath + timeNow + EXTENSION # Find the unprint picture fileList = findFileInOrder() if (len(fileList)==0): takePicture(fileToSave) printImage(fileToSave, timeNow, timeNow, 'lobby') else: result = getFileToPrint(fileList) if result is None: takePicture(fileToSave) printImage(fileToSave, timeNow, timeNow, 'lobby') else: fileToPrint = printPath + '/' + result + EXTENSION # Take the current picture takePicture(fileToSave) # Print the unprint picture printImage(fileToPrint, result, timeNow, 'A10') # Upload the current picture try: uploadFile(fileToSave, timeNow, EXTENSION) except: printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5) printer.println("Error Upload")
def get_printer(heat=200): global printer if printer: return printer else: # open the printer itself printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5) printer.begin(200)
def genAndPrintKeys(curbtc, inputamt, numCopies, password, lcd): remPubKey = False remPrivKey = False #open serial number file which tracks the serial number snumfile = open('serialnumber.txt', 'r+') snum = snumfile.read() #open the printer itself printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5) #load a blank image of the paper wallet with no QR codes or keys on it which we will draw on finalImg = Image.open("btc-wallet-blank.bmp") lcd_display(lcd, "Generating", "address") #this actually generates the keys. see the file genkeys.py or genkeys_forget.py import genkeys as btckeys btckeys.genKeys() if btckeys.keysAreValid == False: printer.write("Error: The generated keys (public/private) are not the correct length. Please try again.") #import wallet_enc as WalletEnc #encrypt the keys if needed #if(password != ""): # privkey = WalletEnc.pw_encode(btckeys.privkey, password) #else: privkey = btckeys.privkey rememberKeys = False sqlitePubKey = "" sqlitePrivKey = "" strToWrite = "" if remPubKey: strToWrite = "\nPublic Key: "+btckeys.pubkey sqlitePubKey = btckeys.pubkey rememberKeys = True if remPrivKey: strToWrite = strToWrite + "\nPrivate Key: "+privkey sqlitePrivKey = privkey rememberKeys = True if rememberKeys == True: #store it to the sqlite db con = None try: con = sqlite3.connect('/home/pi/build/Piper/keys.db3') con.execute("INSERT INTO keys (serialnum, public, private) VALUES (?,?,?)", (snum, sqlitePubKey, sqlitePrivKey)) except sqlite3.Error, e: print "Error %s:" % e.args[0] sys.exit(1) finally:
def genAndPrintKeys(remPubKey, remPrivKey, numCopies, password): #open serial number file which tracks the serial number # snumfile = open('serialnumber.txt', 'r+') # snum = snumfile.read() #open the printer itself printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5) printer.begin(200) #this actually generates the keys. see the file genkeys.py or genkeys_forget.py import genkeys as btckeys btckeys.genKeys() import wallet_enc as WalletEnc #encrypt the keys if needed if(password != ""): privkey = WalletEnc.pw_encode(btckeys.pubkey, btckeys.privkey, password) else: privkey = btckeys.privkey rememberKeys = False sqlitePubKey = "" sqlitePrivKey = "" strToWrite = "" if remPubKey: strToWrite = "\nPublic Key: "+btckeys.pubkey sqlitePubKey = btckeys.pubkey rememberKeys = True if remPrivKey: strToWrite = strToWrite + "\nPrivate Key: "+privkey sqlitePrivKey = privkey rememberKeys = True if rememberKeys == True: #store it in a flat file on the sd card f = open("keys.txt", 'a+') strToWrite = strToWrite f.write(strToWrite); f.write("\n---------------------------------\n") f.close() #do the actual printing for x in range(0, numCopies): #piper.print_keypair(pubkey, privkey, leftBorderText) print_keypair(btckeys.pubkey, privkey)
def genAndPrintKeys(remPubKey, remPrivKey, numCopies, password): #open serial number file which tracks the serial number snumfile = open('serialnumber.txt', 'r+') snum = snumfile.read() #open the printer itself printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5) #this actually generates the keys. see the file genkeys.py or genkeys_forget.py import genkeys as btckeys btckeys.genKeys() if btckeys.keysAreValid == False: printer.write("Error: The generated keys (public/private) are not the correct length. Please try again.") import wallet_enc as WalletEnc #encrypt the keys if needed if(password != ""): privkey = WalletEnc.pw_encode(btckeys.pubkey, btckeys.privkey, password) else: privkey = btckeys.privkey rememberKeys = False sqlitePubKey = "" sqlitePrivKey = "" strToWrite = "" if remPubKey: strToWrite = "\nPublic Key: "+btckeys.pubkey sqlitePubKey = btckeys.pubkey rememberKeys = True if remPrivKey: strToWrite = strToWrite + "\nPrivate Key: "+privkey sqlitePrivKey = privkey rememberKeys = True if rememberKeys == True: #store it to the sqlite db con = None try: con = sqlite3.connect('/home/pi/Printer/keys.db3') con.execute("INSERT INTO keys (serialnum, public, private) VALUES (?,?,?)", (snum, sqlitePubKey, sqlitePrivKey)) except sqlite3.Error, e: print "Error %s:" % e.args[0] sys.exit(1) finally:
def print_image(filename): printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5) printer.feed(5) image = Image.open(filename) image = image.rotate(90, expand=1) image = ImageEnhance.Contrast(image).enhance(1.3) # add contrast printer.printImage(image, True) printer.feed(5)
def print_seed(seed): printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5) printer.println(seed) printer.feed(3) printer.setDefault() # Restore printer to defaults
def encodeQRAndPrint(ttp): qrSize = (340, 340) finalImg = Image.new("RGB", (384, 440), "white") finalImg.paste(getQR(ttp, qrSize), (30, 55)) printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5) printer.printImage(finalImg, True) printer.feed(3) printer.setDefault() # Restore printer to defaults
# http://www.adafruit.com/products/597 Mini Thermal Receipt Printer # http://www.adafruit.com/products/600 Printer starter pack from __future__ import print_function import RPi.GPIO as GPIO import subprocess, time, Image, socket from Adafruit_Thermal import * ledPin = 18 buttonPin = 23 holdTime = 2 # Duration for button hold (shutdown) tapTime = 0.01 # Debounce time for button taps 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) # Called when button is briefly tapped. Invokes time/temperature script. def tap(): # GPIO.output(ledPin, GPIO.HIGH) # LED on while working p = subprocess.Popen(["python", "twitter.py", str(lastId)], stdout=subprocess.PIPE) return p.communicate()[0] # Script pipes back lastId, returned to main # GPIO.output(ledPin, GPIO.LOW) # Called when button is held down. Prints image, invokes shutdown process. def hold(): # GPIO.output(ledPin, GPIO.HIGH) # printer.printImage(Image.open('gfx/goodbye.png'), True)
# weather example using nice bitmaps. # Written by Adafruit Industries. MIT license. # # Required software includes Adafruit_Thermal and PySerial libraries. # Other libraries used are part of stock Python install. # # Resources: # http://www.adafruit.com/products/597 Mini Thermal Receipt Printer # http://www.adafruit.com/products/600 Printer starter pack from __future__ import print_function from random import choice from Adafruit_Thermal import * import urllib, json printer = Adafruit_Thermal("/dev/serial0", 19200, timeout=5) url = "https://niceties.herokuapp.com" response = urllib.urlopen(url) data = json.loads(response.read()) recursors = ["Bobby (Robert) DeLanghe"] # Print nice thing printer.inverseOn() printer.print(' ' + choice(recursors) + ' \n') printer.inverseOff() printer.print(data) # Print feed printer.feed(6)
from Adafruit_Thermal import * from PIL import Image printer = Adafruit_Thermal("/dev/serial0", 9600, timeout=5) printer.justify('C') printer.println("Here's a maze!") printer.feed(1) printer.printImage(Image.open('maze.png'), True) printer.feed(2)
import json import os import requests import RPi.GPIO as IO import time from unidecode import unidecode consumer_key = os.environ['CONSUMER_KEY'] consumer_secret = os.environ['CONSUMER_SECRET'] url = os.environ['URL'] title = os.environ['TITLE'] subtitle = os.environ['SUBTITLE'] author = os.environ['AUTHOR'] # Initialize printer printer = Adafruit_Thermal("/dev/serial0", 19200, timeout=5) # Print welcome message printer.print(unidecode(HTMLParser.HTMLParser().unescape(title))) printer.feed(1) printer.print(unidecode(HTMLParser.HTMLParser().unescape(subtitle))) printer.feed(1) printer.print(unidecode(HTMLParser.HTMLParser().unescape(author))) printer.feed(1) printer.print(unidecode(HTMLParser.HTMLParser().unescape('2018')))
def encodeQRAndPrintText(headerText, ttp): qrSize = (340, 340) finalImg = Image.new("RGB", (384, 440), "white") finalImg.paste(getQR(ttp, qrSize), (30, 55)) printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5) dividerLine = Image.new("RGB", (384, 6), "black") dividerLine.paste(Image.new("RGB", (384, 3), "white"), (0, 0)) printer.printImage(dividerLine, True) printer.println(headerText) printer.println(ttp) printer.printImage(finalImg, True) printer.println(ttp) printer.printImage(dividerLine, True) printer.feed(3) printer.setDefault() # Restore printer to defaults
from __future__ import print_function import RPi.GPIO as GPIO import subprocess, time, Image, socket from Adafruit_Thermal import * printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5) # Print greeting image # Because the hello/goodbye images are overall fairly light, we can # get away with using a darker heat time for these, then reset to the # default afterward. ht = printer.defaultHeatTime * 2 if(ht > 255): ht = 255 printer.begin(ht) # Set temporary dark heat time image_file = Image.open('gfx/partlycloudy.gif') image_100 = image_file.resize((100,100),Image.ANTIALIAS) image_200 = image_file.resize((200,200),Image.ANTIALIAS) image_file = image_file.convert('L') image_100 = image_100.convert('L') image_200 = image_200.convert('L') printer.print("Image 50x50") printer.printImage(image_file, True) printer.feed(3) printer.print("Image 100x100") printer.printImage(image_100, True) printer.feed(3) printer.print("Image 200x200") printer.printImage(image_200, True) printer.feed(3)
#!/usr/bin/python from Adafruit_Thermal import * printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5) printer.setDefault() printer.setTimes(33000, 2500) # CODE39 is the most common alphanumeric barcode printer.printBarcode("ADAFRUT", printer.CODE39) printer.setBarcodeHeight(100) # Print UPC line on product barcodes printer.printBarcode("123456789123", printer.UPC_A) # Print the 75x75 pixel logo in adalogo.py import gfx.adalogo as adalogo printer.printBitmap(adalogo.width, adalogo.height, adalogo.data) # Print the 135x135 pixel QR code in adaqrcode.py import gfx.adaqrcode as adaqrcode printer.printBitmap(adaqrcode.width, adaqrcode.height, adaqrcode.data) printer.println("Adafruit!") printer.feed(1) printer.sleep() # Tell printer to sleep printer.wake() # Call wake() before printing again, even if reset printer.setDefault() # Restore printer to defaults
import datetime import json import feedparser import settings PATH_TO_PRINTER = os.path.join(os.getcwd(),'Python-Thermal-Printer') sys.path.append(PATH_TO_PRINTER) from Adafruit_Thermal import * printer = Adafruit_Thermal("/dev/ttyUSB0", 9600, timeout=5) try: import argparse flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() except ImportError: flags = None # If modifying these scopes, delete your previously saved credentials # at ~/.credentials/calendar-python-quickstart.json SCOPES = 'https://www.googleapis.com/auth/calendar.readonly' CLIENT_SECRET_FILE = 'client_secret.json' APPLICATION_NAME = 'Google Calendar API Python Quickstart' def get_weather(): camb_city_id = '4931972'
printer.print(day) printer.print(':') printer.boldOff() printer.print(' low ') printer.print(lo) printer.print(deg) printer.print(' high ') printer.print( hi) printer.println(deg) printer.print(' AM: ') printer.println(amCond) printer.print(' PM: ') printer.println(pmCond) return printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5) deg = chr(0xf8) # Degree symbol on thermal printer # Fetch forecast data from Yahoo!, parse resulting XML # grw - May 15, 2015 # Added try except logic to handle connection errors # grw - Apr 19, 2016 # Updated Yahoo API query to new YQL format # grw - Jan 5, 2018 # Switched to AccurWeather API and JSON try: query_url = 'http://dataservice.accuweather.com/forecasts/v1/daily/5day/' + LOCID + '?apikey=' + APIKEY print(query_url)
#!/usr/bin/python from Adafruit_Thermal import * printer = Adafruit_Thermal("/dev/ttyUSB0", 19200, timeout=5) printer.wake() # Call wake() before printing again, even if reset printer.setDefault() # Restore printer to defaults ## centre all text - initially small size printer.justify('C') printer.setSize('S') ## print logo bitmap import gfx.logo as logo printer.printBitmap(logo.width, logo.height, logo.data) printer.feed(2) ## first_name, suburb - small bold printer.boldOn() printer.println("Steve from Sumner said: ") printer.boldOff() printer.feed(1) ## title - large printer.setSize('L') # Set type size, accepts 'S', 'M', 'L' printer.println("Climb or sit on the most lovely tree") printer.feed(1) ## what_makes_it_awesome - normal printer.setSize('S')
def print_seed(seed): printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5) printer.println(seed) printer.feed(3) printer.sleep() # Tell printer to sleep printer.wake() # Call wake() before printing again, even if reset printer.setDefault() # Restore printer to defaults
printer.print(':') printer.boldOff() printer.print(' low ') printer.print(lo) printer.print(deg) printer.print(' high ') printer.print(hi) printer.println(deg) printer.print(' AM: ') printer.println(amCond) printer.print(' PM: ') printer.println(pmCond) return printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5) deg = chr(0xf8) # Degree symbol on thermal printer # Fetch forecast data from Yahoo!, parse resulting XML # grw - May 15, 2015 # Added try except logic to handle connection errors # grw - Apr 19, 2016 # Updated Yahoo API query to new YQL format # grw - Jan 5, 2018 # Switched to AccurWeather API and JSON try: query_url = 'http://dataservice.accuweather.com/forecasts/v1/daily/5day/' + LOCID + '?apikey=' + APIKEY # print(query_url)
#!/usr/bin/python from __future__ import print_function import RPi.GPIO as GPIO import subprocess, time, Image, socket from Adafruit_Thermal import * printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5) printer.begin(60) printer.printImage(Image.open('gfx/hello.png'), True) printer.print('Hello World blabla blabla blabla') printer.feed(3)
# http://www.adafruit.com/products/597 Mini Thermal Receipt Printer # http://www.adafruit.com/products/600 Printer starter pack from __future__ import print_function import RPi.GPIO as GPIO import subprocess, time, Image, socket from Adafruit_Thermal import * ledPin = 18 buttonPin = 23 holdTime = 2 # Duration for button hold (shutdown) tapTime = 0.01 # Debounce time for button taps 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) # Called when button is briefly tapped. Invokes time/temperature script. def tap(): GPIO.output(ledPin, GPIO.HIGH) # LED on while working subprocess.call(["python", "timetemp.py"]) GPIO.output(ledPin, GPIO.LOW) # Called when button is held down. Prints image, invokes shutdown process. def hold(): GPIO.output(ledPin, GPIO.HIGH) printer.printImage(Image.open("gfx/goodbye.png"), True) printer.feed(3) subprocess.call("sync")
import RPi.GPIO as GPIO import subprocess import time import Image import socket import random from Adafruit_Thermal import * ledPin = 18 buttonPin = 23 holdTime = 2 # Duration for button hold (shutdown) tapTime = 0.01 # Debounce time for button taps 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) isPlayning = False currentSong = ' ' # Called when button is briefly tapped. Invokes time/temperature script. def tap(play): GPIO.output(ledPin, GPIO.HIGH) # LED on while working # subprocess.call(["python", "timetemp.py"]) if (play == False): subprocess.call("mpc stop", shell=True) else: subprocess.call("mpc play", shell=True) # # currentSong = subprocess.call("mpc current", shell=True) # p = Popen(['program', 'arg1'], stdin=PIPE, stdout=PIPE, stderr=PIPE)
import os from PIL import Image import text2png_tester from MessageClass import * import random import locale print("Starting up....") ledPin = 18 buttonPin = 23 holdTime = 2 # Duration for button hold (shutdown) tapTime = 0.01 # Debounce time for button taps 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/serial0", 19200, timeout=5) #get locale for date display locale.setlocale(locale.LC_ALL, '') # set item path dir_path = os.path.dirname(os.path.realpath(__file__)) item_folder = dir_path + '/items' # initialize item of the day picked_item = "" # Daytime to reset the printer to print the new message of the next day hrs = 4 mins = 0
# http://www.adafruit.com/products/597 Mini Thermal Receipt Printer # http://www.adafruit.com/products/600 Printer starter pack from __future__ import print_function import RPi.GPIO as GPIO import subprocess, time, Image, socket from Adafruit_Thermal import * ledPin = 18 buttonPin = 23 holdTime = 2 # Duration for button hold (shutdown) tapTime = 0.01 # Debounce time for button taps 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) # Called when button is briefly tapped. Invokes time/temperature script. def tap(): GPIO.output(ledPin, GPIO.HIGH) # LED on while working subprocess.call(["python", "40in20out_positions.py"]) GPIO.output(ledPin, GPIO.LOW) # Called when button is held down. Prints image, invokes shutdown process. def hold(): GPIO.output(ledPin, GPIO.HIGH) printer.printImage(Image.open('goodbye40in20out.png'), True) printer.feed(3) subprocess.call("sync")
import time import math import numpy import os from easing import * from motions import * from Adafruit_Thermal import * import xbox printer = Adafruit_Thermal("/dev/ttyUSB0", 19200, timeout=5) speed = 300 for m in robot.motors: # Note that we always provide an alias for all motors. m.compliant = False m.set_moving_speed = 10 robot.m1.moving_speed = 200 robot.m2.moving_speed = 40 robot.m3.moving_speed = 40 print("starting") def remap(OldValue, OldMin, OldMax, NewMin, NewMax): OldRange = (OldMax - OldMin) NewRange = (NewMax - NewMin) NewValue = (((OldValue - OldMin) * NewRange) / OldRange) + NewMin return NewValue
#!/usr/bin/python from Adafruit_Thermal import * printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5, heattime=255, dtr=18) printer.reset() printer.setDefault() ## Test inverse on & off #printer.inverseOn() #printer.println("Inverse ON") #printer.inverseOff() # ## Test character double-height on & off #printer.doubleHeightOn() #printer.println("Double Height ON") #printer.doubleHeightOff() # ## Set justification (right, center, left) -- accepts 'L', 'C', 'R' #printer.justify('R') #printer.println("Right justified") #printer.justify('C') #printer.println("Center justified") #printer.justify('L') #printer.println("Left justified") # ## Test more styles #printer.boldOn() #printer.println("Bold text") #printer.boldOff() #
consumer_secret = 'PUT_YOUR_CONSUMER_SECRET_HERE' bearer_token = base64.b64encode('{}:{}'.format( consumer_key, consumer_secret).encode('utf8')) # queryString can be any valid Twitter API search string, including # boolean operators. See http://dev.twitter.com/docs/using-search # for options and syntax. Funny characters do NOT need to be URL # encoded here -- urllib takes care of that. #queryString = 'from:W_SK include_entities=true' queryString2 = "%23nordendof&include_entities=true" # Other globals. You probably won't need to change these. ----------------- printer = Adafruit_Thermal("/dev/serial0", 9600, timeout=5) host = 'api.twitter.com' authUrl = '/oauth2/token' searchUrl = '/1.1/search/tweets.json?' agent = 'Gutenbird v1.0' # lastID is command line value (if passed), else 1 if len(sys.argv) > 1: lastId = sys.argv[1] else: lastId = '1' #lastId = '1131332578047406081' #TEST ID! after which there should be nthng #lastId = '1' # Initiate an HTTPS connection/request, uncompress and JSON-decode results def issueRequestAndDecodeResponse(method, url, body, headers): connection = http.client.HTTPSConnection(host) connection.request(method, url, body, headers)
def mapVals(val, inMin, inMax, outMin, outMax): toRet = float(outMin + float(outMax - outMin) * float(float(val - inMin) / float(inMax - inMin))) return clamp(toRet, outMin, outMax) def clamp(val, tmin, tmax): if val > tmax: val = tmax if val < tmin: val = tmin return val uart.setup("UART2") printer = Adafruit_Thermal("/dev/ttyO2", 19200, timeout=5) printer.begin() printer.upsideDownOn() printer.feed(3) printer.print(parse('i am awake and I am MUG (thermal)')) printer.feed(1) rPast = 0 rMax = 0 # all-time max sensor reading rMin = 0 # all-time min sensor reading WINDOW_SIZE = 30 # size of moving-window avg noop = 0 # number of intervals passed without a trigger noop_threshold = 480 emission_threshold = 0.7 while True: checkSensor()
def splitAndPrint(ttp, k, n): print "Thing to split: " + ttp #first, split it up secret = Secret.from_printable_ascii(ttp) shares = secret.split(int(k), int(n)) #now convert to QR codes and print the shares print shares printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5) qrSize = (340, 340) ctr = 0 qrImg = {} for shr in shares: print "Share: " + shr finalImg = Image.new("RGB", (384, 440), "white") finalImg.paste(getQR(shr, qrSize), (30, 55)) qrImg[shr] = finalImg dividerLine = Image.new("RGB", (384, 6), "black") dividerLine.paste(Image.new("RGB", (384, 3), "white"), (0, 0)) for shr in shares: printer.printImage(dividerLine, True) printer.println("This is a share in a " + k + " of " + n + "\nthreshold scheme") printer.println(shr) printer.printImage(qrImg[shr], True) printer.println(shr) printer.println("Shamir's Secret Sharing") printer.printImage(dividerLine, True) printer.feed(3) printer.setDefault() # Restore printer to defaults
import subprocess import time from Adafruit_Thermal import * import RPi.GPIO as GPIO import threading import sys GPIO.setmode(GPIO.BCM) PRINTER_GPIO = 27 GPIO.setup(PRINTER_GPIO, GPIO.OUT, pull_up_down=GPIO.PUD_UP) printer = Adafruit_Thermal("/dev/ttyUSB0", 19200, timeout=5) def check_print_cut(): result = "" while result.find("1st"): result = subprocess.check_output(['lpstat', '-o']) print(result) sys.stdout.flush() time.sleep(0.5) print("pulsing") sys.stdout.flush() GPIO.output(PRINTER_GPIO, GPIO.LOW) t1 = threading.Thread(target=check_print_cut) t1.start() printer.wake() printer.println("Open City") printer.println("Test") printer.println("1")
#!/usr/bin/python from __future__ import print_function from Adafruit_Thermal import * from random import choice printer = Adafruit_Thermal("/dev/serial0", 19200, timeout=5) jokes = [['Where does a vampire water-ski', 'On Lake Erie.'], ['Where do baby ghosts go during the day', 'To the day-scare center.'], ['What do ghosts serve for dessert', 'Ice scream.'], ['Which story do the little witches like to hear at bedtime', 'Ghoul Deluxe and the Three Scares.'], ['What are the days of the vampire week', 'Moon-day, Tooth-day, Veins-day, Thirst-day, and Fright-day.'], ['What did the skeleton say to the vampire', 'You suck.'], ['Why did the mummy call the doctor', 'Because he was coffin.'], ["What do you call a witch's garage", 'The broom closet.'], ['Who was the most famous French skeleton', 'Napoleon Bone-apart.'], ['Why did the dyslexic vampire starve to death', "He couldn't find any doolb."], ['Why do mummies make excellent spies', "They're good at keeping things under wraps."], ['What type of pet dog do vampires like the best', 'Bloodhounds.'], ["Why can't a skeleton have fingers more than 11 inches long", 'Because 12 inches is a foot.'], ['What is Transylvania', 'Vampire terror-tory.'], ['Why are most monsters covered in wrinkles', 'Have you ever tried to iron a monster?'], ["What do you call someone who puts poison in a person's corn flakes", 'A cereal killer.'],
"When you are not around, I tell all my robot friends how great you are.", "Your face. I like it.", "If I had legs, I would give you a standing ovation.", "Watch out. I am gonna kiss you.", "10 out of 10.", "Error 404: You are too great to compliment. There are no words.", "Beep boop bop beep boop. (That’s robot for “You are super awesome!”)", "You are a gentleman and a scholar.", "You have the most boop-worthy nose.", "I am sure everyone around you is intimidated by your high intellect." ] # Randomize and put into a string compliment = random.choice(compliments) # Wrap selected string. wrapper = textwrap.TextWrapper(width=50) final = wrapper.fill(text=compliment) printer = Adafruit_Thermal("/dev/serial0", 19200, timeout=5) # Test inverse on & off printer.feed(2) printer.inverseOn() printer.println(final) printer.inverseOff() printer.feed(4) printer.sleep() # Tell printer to sleep printer.wake() # Call wake() before printing again, even if reset printer.setDefault() # Restore printer to defaults
WOEID = '766273' # 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) 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?u=c&w=' + WOEID).read()) # Print heading printer.inverseOn() printer.print('{:^32}'.format( dom.getElementsByTagName('description')[0].firstChild.data)) printer.inverseOff() # Print current conditions printer.boldOn() printer.print('{:^32}'.format('Current conditions:'))
def print_keypair(pubkey, privkey, leftBorderText, curbtc, inputamt, tx_hash): #open the printer itself printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5) #load a blank image of the paper wallet with no QR codes or keys on it which we will draw on if(len(privkey) <= 51): finalImg = Image.open("/home/pi/build/Piper/btc-wallet-blank.bmp") else: finalImg = Image.open("/home/pi/build/Piper/btc-wallet-enc.bmp") #---begin the public key qr code generation and drawing section--- #we begin the QR code creation process #feel free to change the error correct level as you see fit qr = qrcode.QRCode( version=None, error_correction=qrcode.constants.ERROR_CORRECT_M, box_size=10, border=0, ) qr.add_data(pubkey) qr.make(fit=True) pubkeyImg = qr.make_image() #resize the qr code to match our design pubkeyImg = pubkeyImg.resize((175,175), Image.NEAREST) font = ImageFont.truetype("/usr/share/fonts/ttf/ubuntu-font-family-0.80/UbuntuMono-R.ttf", 20) draw = ImageDraw.Draw(finalImg) startPos=(110,38) charDist=15 lineHeight=23 lastCharPos=0 keyLength = len(pubkey) print keyLength while(keyLength % 17 != 0): pubkey += " " keyLength = len(pubkey) #draw 2 lines of 17 characters each. keyLength always == 34 so keylength/17 == 2 for x in range(0,keyLength/17): lastCharPos=0 #print a line for y in range(0, 17): theChar = pubkey[(x*17)+y] charSize = draw.textsize(theChar, font=font) #if y is 0 then this is the first run of this loop, and we should use startPos[0] for the x coordinate instead of the lastCharPos if y == 0: draw.text((startPos[0],startPos[1]+(lineHeight*x)),theChar, font=font, fill=0) lastCharPos = startPos[0]+charSize[0]+(charDist-charSize[0]) else: draw.text((lastCharPos,startPos[1]+(lineHeight*x)),theChar, font=font, fill=0) lastCharPos = lastCharPos + charSize[0] + (charDist-charSize[0]) #draw the QR code on the final image finalImg.paste(pubkeyImg, (150, 106)) #---end the public key qr code generation and drawing section--- #---begin the private key qr code generation and drawing section--- #we begin the QR code creation process #feel free to change the error correct level as you see fit qr = qrcode.QRCode( version=None, error_correction=qrcode.constants.ERROR_CORRECT_M, box_size=10, border=0, ) qr.add_data(privkey) qr.make(fit=True) privkeyImg = qr.make_image() #resize the qr code to match our design privkeyImg = privkeyImg.resize((220,220), Image.NEAREST) #draw the QR code on the final image finalImg.paste(privkeyImg, (125, 560)) startPos=(110,807) charDist=15 lineHeight=23 lastCharPos=0 keyLength = len(privkey) while(keyLength % 17 != 0): privkey += " " keyLength = len(privkey) #draw 2 lines of 17 characters each. keyLength always == 34 so keylength/17 == 2 for x in range(0,keyLength/17): lastCharPos=0 #print a line for y in range(0, 17): theChar = privkey[(x*17)+y] charSize = draw.textsize(theChar, font=font) #print charSize if y == 0: draw.text((startPos[0],startPos[1]+(lineHeight*x)),theChar, font=font, fill=0) lastCharPos = startPos[0]+charSize[0]+(charDist-charSize[0]) else: draw.text((lastCharPos,startPos[1]+(lineHeight*x)),theChar, font=font, fill=0) lastCharPos = lastCharPos + charSize[0] + (charDist-charSize[0]) #---end the private key qr code generation and drawing section--- #create the divider rightMarkText = "ArchReactor.org" font = ImageFont.truetype("/usr/share/fonts/ttf/swansea.ttf", 20) rightMarkSize = draw.textsize(rightMarkText, font=font) leftMarkOrigin = (10, 15) rightMarkOrigin = (384-rightMarkSize[0]-10, 15) dividerLineImg = Image.open("/home/pi/build/Piper/dividerline.bmp") draw = ImageDraw.Draw(dividerLineImg) draw.text(leftMarkOrigin, leftBorderText, font=font, fill=0) draw.text(rightMarkOrigin,rightMarkText, font=font, fill=0) #finalImg.save('file.png') #dividerLineImg.save('file2.png') #do the actual printing usd = 1.0/float(curbtc) returnamt = usd*float(inputamt) printer.println("1BTC=$"+str(curbtc)) printer.println("1USD=B"+str(usd)) printer.println("Input=$"+str(inputamt)) printer.println("Return=B"+str(returnamt)) printer.println("Transaction Hash: "+str(tx_hash)) printer.printImage(finalImg) #if(len(privkey) <= 51): # printer.println(privkey[:17]+"\n") # printer.justify('R') # printer.println(privkey[17:34]+"\n") # printer.justify('L') # printer.println(privkey[34:]+"\n") #else: # printer.println(privkey) #print the divider line printer.printImage(dividerLineImg) #print some blank space so we can get a clean tear of the paper printer.feed(3) printer.sleep() # Tell printer to sleep printer.wake() # Call wake() before printing again, even if reset printer.setDefault() # Restore printer to defaults
import time import boxid cBoxID = boxid.box() ledPin = 18 buttonPin = 23 holdTime = 2 # Duration for button hold (shutdown) tapTime = 0.01 # Debounce time for button taps nextInterval = 0.0 # Time of next recurring operation logonFlag = False # Set after daily trigger occurs dailyFlag = False # Set after daily trigger occurs eodailyFlag = False # Set after EOD trigger occurs refreshrate = 60 # refresh rate for twitter - recall is throttled by the Twitter Search API to 1 search every 2 seconds lastId = '1' # State information passed to/from interval script printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5) printed_messages = [] #function to find new messages def get_messages(): #open 40in20out f = urllib.urlopen('http://www.40in20out.com/subscribers/messages.xml') #get text from /sub/messages2 text = str(f.read().decode('utf-8')) #create a list for all the messages on the site messages = [] #run this loop while there are still more messages left to parse while text.find('messages') != -1: #parse the messages to find message_number, message_timestamp, message_type, and message_action message_number = text[text.find('messages msgnum="')+17:text.find('messages msgnum="')+23]
def print_password(headerText, ttp): dividerLine = Image.new("RGB", (384, 6), "black") dividerLine.paste(Image.new("RGB", (384, 4), "white"), (0, 0)) #create the divider bottomDividerLineImg = Image.open("/home/pi/Printer/dividerline.bmp") font = ImageFont.truetype("/usr/share/fonts/ttf/swansea.ttf", 20) draw = ImageDraw.Draw(bottomDividerLineImg) rightMarkText = "Piperwallet.com" rightMarkSize = draw.textsize(rightMarkText, font=font) leftMarkOrigin = (10, 15) rightMarkOrigin = (384 - rightMarkSize[0] - 10, 15) draw.text(leftMarkOrigin, headerText, font=font, fill=(0, 0, 0)) draw.text(rightMarkOrigin, rightMarkText, font=font, fill=(0, 0, 0)) printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5) printer.printImage(dividerLine, True) printer.println("Password: ") printer.println(ttp) printer.printImage(bottomDividerLineImg, True) printer.feed(3) printer.setDefault() # Restore printer to defaults
def generate_post(): with open('/home/yuri/mashbotv2/cleaned.txt') as f: text = f.read() text_model = markovify.Text(text, state_size=2) mash_text = text_model.make_short_sentence(129) # was 140 wrapped_text = textwrap.fill(mash_text, 32) output_text = "@acoluthon " + mash_text printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5) printer.setDefault() printer.justify('L') printer.feed(3) printer.boldOn() printer.setSize('M') printer.println("Mash Note") printer.setSize('S') printer.boldOff() printer.println(wrapped_text) printer.feed(2) # Write the status to a file, for debugging with open('/home/yuri/mashbotv2/history.txt', 'a') as f: f.write('mashed: ' + mash_text + ' | tweeted: ' + output_text + '\n') return output_text
#!/usr/bin/python from Adafruit_Thermal import * import os import Image import filewalker from datetime import date printer = Adafruit_Thermal("/dev/serial0", 19200, timeout=5) dir_path = os.path.dirname(os.path.realpath(__file__)) item_folder = dir_path + '/items' #item_folder = "C:/Users/Christian/Documents/GitHub/PiPrinter/items" print "Script started..." printer.setSize('L') # Set type size, accepts 'S', 'M', 'L' #printer.println(filewalker.pick_random_pic(item_folder)) picked_item = filewalker.pick_item(item_folder, date.today()) #process according to file type print "picked item: " + picked_item print picked_item.rsplit(".", 1)[1] print "png?" + str(picked_item.rsplit(".", 1)[1] == "png") print "txt?" + str(picked_item.rsplit(".", 1)[1] == "txt") if picked_item.rsplit(".", 1)[1] == "png": printer.printImage(Image.open(filewalker.pick_item(item_folder)), True) print "Image printed..." elif picked_item.rsplit(".", 1)[1] == "txt": textfile_handle = open(picked_item, "r")
def print_keypair(pubkey, privkey): #open the printer itself printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5) #load a blank image of the paper wallet with no QR codes or keys on it which we will draw on finalImg = Image.open("/home/pi/Printer/btc-wallet-blank.bmp") #---begin the public key qr code generation and drawing section--- #we begin the QR code creation process #feel free to change the error correct level as you see fit qr = qrcode.QRCode( version=None, error_correction=qrcode.constants.ERROR_CORRECT_M, box_size=10, border=0, ) qr.add_data(pubkey) qr.make(fit=True) pubkeyImg = qr.make_image() #resize the qr code to match our design pubkeyImg = pubkeyImg.resize((175,175), Image.NEAREST) font = ImageFont.truetype("/usr/share/fonts/ttf/ubuntu-font-family-0.80/UbuntuMono-R.ttf", 20) draw = ImageDraw.Draw(finalImg) startPos=(110,38) charDist=15 lineHeight=23 lastCharPos=0 keyLength = len(pubkey) #draw 2 lines of 17 characters each. keyLength always == 34 so keylength/17 == 2 for x in range(0,keyLength/17): lastCharPos=0 #print a line for y in range(0, 17): theChar = pubkey[(x*17)+y] charSize = draw.textsize(theChar, font=font) #if y is 0 then this is the first run of this loop, and we should use startPos[0] for the x coordinate instead of the lastCharPos if y == 0: draw.text((startPos[0],startPos[1]+(lineHeight*x)),theChar, font=font, fill=(0,0,0)) lastCharPos = startPos[0]+charSize[0]+(charDist-charSize[0]) else: draw.text((lastCharPos,startPos[1]+(lineHeight*x)),theChar, font=font, fill=(0,0,0)) lastCharPos = lastCharPos + charSize[0] + (charDist-charSize[0]) #draw the QR code on the final image finalImg.paste(pubkeyImg, (150, 106)) #---end the public key qr code generation and drawing section--- #---begin the private key qr code generation and drawing section--- #we begin the QR code creation process #feel free to change the error correct level as you see fit qr = qrcode.QRCode( version=None, error_correction=qrcode.constants.ERROR_CORRECT_M, box_size=10, border=0, ) qr.add_data(privkey) qr.make(fit=True) privkeyImg = qr.make_image() #resize the qr code to match our design privkeyImg = privkeyImg.resize((220,220), Image.NEAREST) startPos=(110,807) charDist=15 lineHeight=23 lastCharPos=0 keyLength = len(privkey) #draw 2 lines of 17 characters each. keyLength always == 34 so keylength/17 == 2 for x in range(0,keyLength/17): lastCharPos=0 #print a line for y in range(0, 17): theChar = privkey[(x*17)+y] charSize = draw.textsize(theChar, font=font) #print charSize if y == 0: draw.text((startPos[0],startPos[1]+(lineHeight*x)),theChar, font=font, fill=(0,0,0)) lastCharPos = startPos[0]+charSize[0]+(charDist-charSize[0]) else: draw.text((lastCharPos,startPos[1]+(lineHeight*x)),theChar, font=font, fill=(0,0,0)) lastCharPos = lastCharPos + charSize[0] + (charDist-charSize[0]) #draw the QR code on the final image finalImg.paste(privkeyImg, (125, 560)) #---end the private key qr code generation and drawing section--- #create the divider rightMarkText = "Piperwallet.com" font = ImageFont.truetype("/usr/share/fonts/ttf/swansea.ttf", 20) rightMarkSize = draw.textsize(rightMarkText, font=font) rightMarkOrigin = (384-rightMarkSize[0]-10, 10) dividerLineImg = Image.open("/home/pi/Printer/dividerline.bmp") #font = ImageFont.truetype("/home/pi/Helvetica.ttf", 20) draw = ImageDraw.Draw(dividerLineImg) draw.text(rightMarkOrigin,rightMarkText, font=font, fill=(255,255,255)) #do the actual printing printer.printImage(finalImg) printer.printChar(privkey[:17]+"\n") printer.justify('R') printer.printChar(privkey[17:34]+"\n") printer.justify('L') printer.printChar(privkey[34:]+"\n") #print the divider line time.sleep(0.4) printer.printImage(dividerLineImg) #print some blank space so we can get a clean tear of the paper time.sleep(0.4) printer.feed(1) time.sleep(0.4) printer.feed(1) time.sleep(0.4) printer.feed(1) printer.sleep() # Tell printer to sleep printer.wake() # Call wake() before printing again, even if reset printer.setDefault() # Restore printer to defaults
import json from django.http import HttpResponse from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from Adafruit_Thermal import * printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5) # Create your views here. def list_manager(request): return render(request, 'listManager.html') @csrf_exempt def print_list(request): list_data = json.loads(request.body) printer.setLineHeight() printer.setSize('L') printer.justify('C') printer.println("My Grocery List") printer.feed() printer.justify('L') printer.setSize('M') for item in list_data: length = len(item["name"]) printer.println(item["name"] + " " * (25 - length) + item["amount"])
if windDir < DirAngle[winDirNum]: break 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] if windUnits == 'kph': w2 += 3 + Kph.size[0] else: w2 += 3 + Mph.size[0] if w2 > w: w = w2 # Draw humidity and wind x = img.size[0] - w # Left-align the two lines y = 67 img.paste(Humidity, (x, y)) x += Humidity.size[0] + 5 drawNums(s, x, y, HumiDigit) x = img.size[0] - w # Left-align again 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 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.printImage(img, True) printer.feed(3)
def print_message(message="", date=datetime.now().strftime('%d-%b @ %H:%M')): printer = Adafruit_Thermal("/dev/serial0", 19200) printer.wake() printer.setSize('M') printer.println(message) printer.feed(1) printer.setSize('S') printer.println(date) printer.feed(1) printer.println("_______________________________") printer.feed(5) printer.sleep() printer.setDefault()
def printImage(fileToPrint, result, timeNow, location): def imageProcessing(fileToPrint): img = Image.open(fileToPrint) img = img.filter(ImageFilter.EDGE_ENHANCE_MORE) img = img.filter(ImageFilter.SHARPEN) img = img.filter(ImageFilter.MedianFilter) img = img.rotate(180) return img def getTimeElapsed(fileToPrint): text = '' now = datetime.now() last = parseTimeStamp(fileToPrint) timeElapsed = now - last seconds = int(timeElapsed.seconds) minutes = int(round(seconds/60)) hours = int(round(seconds/3600)) days = int(timeElapsed.days) # days and hours if (days > 0): if (days == 1): text += str(days)+'day ' else: text += str(days)+'days ' if (hours > 0): if (hours == 1): text += str(hours)+'hour ' else: text += str(hours)+'hours ' elif (days == 0): # hours and minutes if (hours > 0): if (hours == 1): text += str(hours)+'hour ' else: text += str(hours)+'hours ' minutes = minutes - 60*hours if (minutes > 0): if (minutes == 1): text += str(minutes)+'minute ' else: text += str(minutes)+'minutes ' else: # minutes and seconds if (minutes > 0): if (minutes == 1): text += str(minutes)+'minute ' else: text += str(minutes)+'minutes ' seconds = seconds - minutes*60 if (seconds > 0): if (seconds == 1): text += str(seconds)+'second ' else: text += str(seconds)+'seconds ' # seconds else: text += str(seconds)+'seconds ' text += 'ago @'+location return text def getTimeNow(timeNow): text ='Printed at ' timeNow = parseTimeStamp(timeNow) year = timeNow.year month = timeNow.month day = timeNow.day hour = timeNow.hour minute = timeNow.minute text += fmt(year)+'.'+fmt(month)+'.'+fmt(day)+' ' text += fmt(hour)+':'+fmt(minute) return text image = imageProcessing(fileToPrint) printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5) printer.printImage(image, True) # This does the printing printer.upsideDownOn() printer.justify('C') timeElapsed = getTimeElapsed(result) printer.println(timeElapsed) timeNow = getTimeNow(timeNow) printer.println(timeNow) printer.upsideDownOff() printer.feed(3)
#!/usr/bin/python from Adafruit_Thermal import * printer = Adafruit_Thermal("/dev/ttyO2", 19200, timeout=5) # Test inverse on & off printer.inverseOn() printer.println("Inverse ON") printer.inverseOff() # Test character double-height on & off printer.doubleHeightOn() printer.println("Double Height ON") printer.doubleHeightOff() # Set justification (right, center, left) -- accepts 'L', 'C', 'R' printer.justify('R') printer.println("Right justified") printer.justify('C') printer.println("Center justified") printer.justify('L') printer.println("Left justified") # Test more styles printer.boldOn() printer.println("Bold text") printer.boldOff() printer.underlineOn() printer.println("Underlined text")
# forecasts for next two days. See timetemp.py for a different # weather example using nice bitmaps. # Written by Adafruit Industries. MIT license. # # Required software includes Adafruit_Thermal and PySerial libraries. # Other libraries used are part of stock Python install. # # Resources: # http://www.adafruit.com/products/597 Mini Thermal Receipt Printer # http://www.adafruit.com/products/600 Printer starter pack from __future__ import print_function import urllib2, urllib, json, time from Adafruit_Thermal import * printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5) deg = chr(0xf8) # Degree symbol on thermal printer # Fetch forecast data from Yahoo!, parse resulting XML baseurl = "https://www.prevision-meteo.ch/services/json/gradignan" result = urllib2.urlopen(baseurl).read() data = json.loads(result) # Print heading printer.inverseOn() head = data["city_info"]["name"] + " le " + data["fcst_day_0"]["date"] printer.println('{:^32}'.format(head)) printer.inverseOff() # Print current conditions printer.boldOn()
# http://www.adafruit.com/products/597 Mini Thermal Receipt Printer # http://www.adafruit.com/products/600 Printer starter pack from __future__ import print_function import RPi.GPIO as GPIO import subprocess, time, Image, socket, os from Adafruit_Thermal import * buttonPin = 23 holdTime = 2 # Duration for button hold (shutdown) tapTime = 0.01 # Debounce time for button taps 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) # Initialization # Use Broadcom pin numbers (not Raspberry Pi pin numbers) for GPIO GPIO.setmode(GPIO.BCM) # Processor load is heavy at startup; wait a moment to avoid # stalling during greeting. time.sleep(3) # Print greeting image while(True): if os.path.exists('gfx/print.png'):
# Configurable globals. Edit to your needs. ------------------------------- # Twitter application credentials -- see notes above -- DO NOT SHARE. consumer_key = 'KEY' consumer_secret = 'SECRET' # queryString can be any valid Twitter API search string, including # boolean operators. See https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets # for options and syntax. Funny characters do NOT need to be URL # encoded here -- urllib takes care of that. queryString = 'from:year_progress' # Other globals. You probably won't need to change these. ----------------- printer = Adafruit_Thermal("/dev/serial0", 19200, timeout=5) host = 'api.twitter.com' authUrl = '/oauth2/token' searchUrl = '/1.1/search/tweets.json?' agent = 'Gutenbird v1.0' # lastID is command line value (if passed), else 1 if len(sys.argv) > 1: lastId = sys.argv[1] else: lastId = '1' # Initiate an HTTPS connection/request, uncompress and JSON-decode results def issueRequestAndDecodeResponse(method, url, body, headers): connection = httplib.HTTPSConnection(host) connection.request(method, url, body, headers) response = connection.getresponse() if response.status != 200: # This is OK for command-line testing, otherwise
# Configurable globals. Edit to your needs. ------------------------------- # Twitter application credentials -- see notes above -- DO NOT SHARE. consumer_key = 'PUT_YOUR_CONSUMER_KEY_HERE' consumer_secret = 'PUT_YOUR_CONSUMER_SECRET_HERE' # queryString can be any valid Twitter API search string, including # boolean operators. See http://dev.twitter.com/docs/using-search # for options and syntax. Funny characters do NOT need to be URL # encoded here -- urllib takes care of that. queryString = 'from:Adafruit' # Other globals. You probably won't need to change these. ----------------- printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5) host = 'api.twitter.com' authUrl = '/oauth2/token' searchUrl = '/1.1/search/tweets.json?' agent = 'Gutenbird v1.0' # lastID is command line value (if passed), else 1 if len(sys.argv) > 1: lastId = sys.argv[1] else: lastId = '1' # Initiate an HTTPS connection/request, uncompress and JSON-decode results def issueRequestAndDecodeResponse(method, url, body, headers): connection = httplib.HTTPSConnection(host) connection.request(method, url, body, headers) response = connection.getresponse() if response.status != 200: # This is OK for command-line testing, otherwise
from __future__ import print_function import RPi.GPIO as GPIO import subprocess, time, socket from PIL import Image from Adafruit_Thermal import * ledPin = 18 buttonPin = 23 holdTime = 2 # Duration for button hold (shutdown) tapTime = 0.01 # Debounce time for button taps 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/serial0", 19200, timeout=5) # Called when button is briefly tapped. Invokes kitten printing script. def tap(): GPIO.output(ledPin, GPIO.HIGH) # LED on while working subprocess.call(["python3", "kitten_printer.py"]) GPIO.output(ledPin, GPIO.LOW) # Called when button is held down. Prints image, invokes shutdown process. def hold(): GPIO.output(ledPin, GPIO.HIGH) printer.printImage('gfx/goodbye.png', True) printer.feed(3) subprocess.call("sync")
# Main Script (Modified) # Juan Carlos Herrera from __future__ import print_function import RPi.GPIO as GPIO import subprocess, time, Image, socket from Adafruit_Thermal import * ledPin = 18 buttonPin = 23 holdTime = 2 # Duration for button hold (shutdown) tapTime = 0.01 # Debounce time for button taps 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) # Called when button is briefly tapped. Invokes time/temperature script. def tap(): GPIO.output(ledPin, GPIO.HIGH) # LED on while working subprocess.call(["python", "fortune.py"]) subprocess.call(["python", "timetemp.py"]) GPIO.output(ledPin, GPIO.LOW) # Called when button is held down. Prints image, invokes shutdown process. def hold(): GPIO.output(ledPin, GPIO.HIGH) printer.printImage(Image.open('gfx/goodbye.png'), True) printer.feed(3)
#!/usr/bin/python from Adafruit_Thermal import * printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5) # Reset printer printer.wake() printer.flush() printer.setDefault() # Test inverse on & off printer.inverseOn() printer.println("Inverse ON") printer.inverseOff() # Test character double-height on & off printer.doubleHeightOn() printer.println("Double Height ON") printer.doubleHeightOff() # Test character double-width on & off printer.doubleWidthOn() printer.println("Double Width ON") printer.doubleWidthOff() # Set justification (right, center, left) -- accepts 'L', 'C', 'R' printer.justify('R') printer.println("Right justified") printer.justify('C') printer.println("Center justified")
# On a command line without any arguments, prints text for a # random sudoku puzzle, with an estimate of its difficulty. # On a command line with a filename, solves the given puzzles # (files should look like the text generated by the generator). # # Adapted for Adafruit_Thermal library by Phil Burgess for Adafruit # Industries. This version uses bitmaps (in the 'gfx' subdirectory) # to render the puzzle rather than text symbols. See sudoku-txt # for a different Sudoku example that's all text-based. from __future__ import print_function import sys, os, random, getopt, re from Adafruit_Thermal import * from PIL import Image 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 ] ycoord = [ 56, 96, 136, 180, 220, 260, 304, 344, 384 ] numbers = [] def main(): # Crop number bitmaps out of source image for i in range(9): numbers.append(img.crop([384, i*28, 410, (i+1)*28])) args = sys.argv[1:] if len(args) > 0: puzzles = [loadboard(filename) for filename in args] else: puzzles = [makepuzzle(solution([None] * 81))]
# Configurable globals. Edit to your needs. ------------------------------- # Twitter application credentials -- see notes above -- DO NOT SHARE. consumer_key = 'PUT_YOUR_CONSUMER_KEY_HERE' consumer_secret = 'PUT_YOUR_CONSUMER_SECRET_HERE' # queryString can be any valid Twitter API search string, including # boolean operators. See http://dev.twitter.com/docs/using-search # for options and syntax. Funny characters do NOT need to be URL # encoded here -- urllib takes care of that. queryString = 'from:Adafruit' # Other globals. You probably won't need to change these. ----------------- printer = Adafruit_Thermal(timeout=5) host = 'api.twitter.com' authUrl = '/oauth2/token' searchUrl = '/1.1/search/tweets.json?' agent = 'Gutenbird v1.0' # lastID is command line value (if passed), else 1 if len(sys.argv) > 1: lastId = sys.argv[1] else: lastId = '1' # Initiate an HTTPS connection/request, uncompress and JSON-decode results def issueRequestAndDecodeResponse(method, url, body, headers): connection = httplib.HTTPSConnection(host) connection.request(method, url, body, headers) response = connection.getresponse() if response.status != 200: # This is OK for command-line testing, otherwise
def printHDMWalletSeed(headerText, seed, xpub): qrSize = (170, 170) qrPad = 10 finalImg = Image.new("RGB", (384, qrSize[1]), "white") finalImg.paste(getQR(seed, qrSize), (qrPad, 0)) finalImg.paste(getQR(xpub, qrSize), (qrSize[0] + qrPad * 2 + 14, 0)) printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5) dividerLine = Image.new("RGB", (384, 6), "black") dividerLine.paste(Image.new("RGB", (384, 4), "white"), (0, 0)) printer.printImage(dividerLine, True) printer.println(headerText) printer.println("Seed Mnemonic: " + seed + '\n') printer.println("xpub: " + xpub + '\n') printer.printImage(finalImg, True) printer.feed(1) printer.printImage(dividerLine, True) printer.feed(3) printer.setDefault() # Restore printer to defaults