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(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 print_seed(seed): printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5) printer.begin(200) 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
def print_text(): if session.get('logged_in'): if len(request.form['message']) < 200: printer = Adafruit_Thermal('/dev/serial0', 19200, timeout=5) printer.begin() printer.justify('L') printer.println(request.form['message']) printer.setSize('S') printer.println(">> " + datetime.now().strftime("%Y-%m-%d %H:%M:%S") + " " + session.get('user')) printer.justify('C') printer.println("------------------------------") printer.feed(2) printer.sleep() # Tell printer to sleep printer.wake() # Call wake() before printing again, even if reset printer.setDefault() # Restore printer to defaults return redirect(url_for('display_index_page')) else: flash('Le text est trop long, 200 caractères au maximum stp !') return redirect(url_for('display_index_page')) else: return redirect(url_for('login'))
class Printer(object): """This class represents the printer""" def __init__(self, device, baud_rate, timeout): """Printer initialization :param device: Device path :type device: str :param baud: Baud rate :type baud: int :param timeout: Timeout in seconds :type timeout: int """ self.print_size = 384, 384 # max_width=384 self.device = Adafruit_Thermal(device, baud_rate, timeout=timeout) def _calibrate(self): for i in range(0, 256, 15): self.device.begin(i) self.device.println(i) # Print heat time self.device.inverseOn() self.device.print("{:^32}".format("")) # Print 32 spaces (inverted) self.device.inverseOff() self.device.begin() # Reset heat time to default self.device.feed(4) def print_image(self, image_file_path, event): """Print Image :param image_file_path: Image file path :type image_file_path: str """ # print logo self.device.printImage(Image.open(event["logo"]), True) self.device.justify("C") self.device.doubleHeightOn() self.device.println(event["title"]) self.device.doubleHeightOff() self.device.println(datetime.now().strftime("%d-%m-%Y %H:%M:%S")) # time self.device.feed(1) # print picture image_code = os.path.splitext(os.path.basename(image_file_path))[0] image_for_print_path = "{}.print".format(image_file_path) image_for_print = Image.open(image_file_path) # create proxy image for print image_for_print = image_for_print.transpose(Image.ROTATE_180) # rotate image w, h = image_for_print.size image_for_print.crop((int((w - h) / 2), 0, int((w - h) / 2), 0)) image_for_print.thumbnail(self.print_size, Image.ANTIALIAS) # resize image_for_print.save(image_for_print_path, "JPEG") # save self.device.printImage(Image.open(image_for_print_path), True) self.device.feed(1) # print text self.device.println(event["place"]) self.device.feed(1) # line self.device.println("------------------------------") self.device.feed(1) self.device.boldOn() self.device.println("partagez votre") self.device.println("photo avec le code") self.device.boldOff() self.device.doubleHeightOn() self.device.doubleWidthOn() self.device.println(image_code) self.device.doubleWidthOff() self.device.doubleHeightOff() self.device.boldOn() self.device.println("sur") self.device.boldOff() self.device.println("shootomatic.net") self.device.feed(1) # line self.device.println("------------------------------") # space to detach self.device.feed(3) # delete proxy image used for print os.remove(image_for_print_path)
toRet = clamp(toRet, outMin, outMax) return toRet def clamp(val, tmin, tmax): if val > tmax: val = tmax if val < tmin: val = tmin return val uart.setup("UART2") adc.setup() atexit.register(exit_handler) printer = Adafruit_Thermal("/dev/ttyO2", 19200, timeout=5) printer.begin() printer.upsideDownOn() printer.feed(3) printer.print(parse('i am awake and I am APPLE (light)')) printer.feed(1) rPast = 0 rMax = 0 # all-time max sensor reading rMin = 100000 # 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.1 # changed this for vcnl4000, used to be 0.7 while True: checkSensor() time.sleep(0.5)
# # Prints a series of black bars with increasing "heat time" settings. # Because printed sections have different "grip" characteristics than # blank paper, as this progresses the paper will usually at some point # jam -- either uniformly, making a short bar, or at one side or the # other, making a wedge shape. In some cases, the Pi may reset for # lack of power. # # Whatever the outcome, take the last number printed BEFORE any # distorted bar and enter in in Adafruit_Thermal.py as defaultHeatTime # (around line 53). # # You may need to pull on the paper as it reaches the jamming point, # and/or just abort the program, press the feed button and take the # last good number. from __future__ import print_function from Adafruit_Thermal import * printer = Adafruit_Thermal("/dev/ttyO2", 19200, timeout=5) for i in range(0,256,15): printer.begin(i) printer.println(i) # Print heat time printer.inverseOn() printer.print('{:^32}'.format('')) # Print 32 spaces (inverted) printer.inverseOff() printer.begin() # Reset heat time to default printer.feed(4)
#!/usr/bin/env python # -*- coding: utf-8 -*- # utilisation du module from Adafruit_Thermal import * # déclaration objet imprimante printer = Adafruit_Thermal("/dev/ttyUSB0", 9600) # configuration printer.begin(140) # restauration valeurs pas défaut printer.setDefault() # normal printer.println("Normal") # Texte inversé printer.inverseOn() printer.println("Inversion") printer.inverseOff() # tailles double printer.doubleHeightOn() printer.println("Double Hauteur") printer.doubleWidthOn() printer.println("Double Tout") printer.doubleHeightOff() printer.println("Double Largeur") printer.doubleWidthOff()
import RPi.GPIO as GPIO import subprocess, time, Image, socket, random from Adafruit_Thermal import * buttonPin = 18 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) # Enable LED and button (w/pull-up on latter) GPIO.setup(buttonPin, GPIO.IN) prevButtonState = GPIO.input(buttonPin) # Main loop printer.begin(255) while(True): buttonState = GPIO.input(buttonPin) if buttonState != True: reve ='reves/reve-'+ str(random.randint(1,3)) +'.png' printer.printImage(Image.open(reve), True) printer.feed(2)
def get_printer(heat=200): # open the printer itself printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5) printer.begin(heat) return printer
# # Prints a series of black bars with increasing "heat time" settings. # Because printed sections have different "grip" characteristics than # blank paper, as this progresses the paper will usually at some point # jam -- either uniformly, making a short bar, or at one side or the # other, making a wedge shape. In some cases, the Pi may reset for # lack of power. # # Whatever the outcome, take the last number printed BEFORE any # distorted bar and enter in in Adafruit_Thermal.py as defaultHeatTime # (around line 53). # # You may need to pull on the paper as it reaches the jamming point, # and/or just abort the program, press the feed button and take the # last good number. from __future__ import print_function from Adafruit_Thermal import * printer = Adafruit_Thermal("/dev/ttyO2", 19200, timeout=5) for i in range(0, 256, 15): printer.begin(i) printer.println(i) # Print heat time printer.inverseOn() printer.print('{:^32}'.format('')) # Print 32 spaces (inverted) printer.inverseOff() printer.begin() # Reset heat time to default printer.feed(4)
#!/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)
# 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) printer.begin(heatTime=200) 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()) # 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 setup(): global myTwitterStream, myTwitterClient, mySmsStream global lastTwitterCheck, lastSmsCheck global myNeuralNet global PHONE_NUMBER,PHONE_FORMAT global logFile global screen, font, font_title global printer, PRT_MODEL lastTwitterCheck = time() lastSmsCheck = time() with open('secrets.json') as dataFile: data = json.load(dataFile) ## What to search for SEARCH_TERMS = data["search_terms"] PHONE_NUMBER = data["phone_number"] PHONE_FORMAT='({}) {}-{}'.format(PHONE_NUMBER[2:5], PHONE_NUMBER[5:8], PHONE_NUMBER[8:]) PRT_MODEL = data["printer_model"] try: if PRT_MODEL == "adafruit": printer = Adafruit_Thermal(data["usb_port"], 9600, timeout=5) printer.begin(255) elif PRT_MODEL == "epson": printer = File("/dev/usb/lp0") except: print('Error loading serial port...') ## start Twitter stream reader myTwitterStream = TwitterStreamReceiver(app_key = data["twitter"]['CONSUMER_KEY'], app_secret = data["twitter"]['CONSUMER_SECRET'], oauth_token = data["twitter"]['ACCESS_TOKEN'], oauth_token_secret = data["twitter"]['ACCESS_SECRET']) #twitter client to post twitts myTwitterClient = Twython(app_key = data["twitter"]['CONSUMER_KEY'], app_secret = data["twitter"]['CONSUMER_SECRET'], oauth_token = data["twitter"]['ACCESS_TOKEN'], oauth_token_secret = data["twitter"]['ACCESS_SECRET']) streamThread = Thread(target=myTwitterStream.statuses.filter, kwargs={'track':','.join(SEARCH_TERMS)}) streamThread.daemon = True streamThread.setName('TwitterThread') streamThread.start() ## start Twilio client mySmsStream = SMSReceiver(data["twilio"]['ACCOUNT_SID'], data["twilio"]['AUTH_TOKEN']) smsStreamThread = Thread(target=mySmsStream.update) smsStreamThread.daemon = True smsStreamThread.setName('SmsThread') smsStreamThread.start() myNeuralNet = NeuralNetProcessor(data['working_path'], data['model_path'], data['length'], data['temperature']) ## open new file for writing log now = datetime.now(utc) logFile = open("logs/" + now.isoformat() + ".log", "a") #getNeuralNetText('Life is hard') #init pygame pygame.init() pygame.display.set_caption("RapRobot") pygame.mouse.set_visible(False) screen = pygame.display.set_mode(SCREEN_RESOLUTION) screen.fill((0,0,0)) pygame.display.update() font = pygame.font.Font("assets/HN.otf", FONT_SIZE) font_title = pygame.font.Font("assets/HN.otf", FONT_SIZE*2)
#flash LED to notify of captured image GPIO.output(19, True) time.sleep(0.1) GPIO.output(19, False) # Resize the high res photo to create thumbnail Image.open(photoPath + photoName).resize( photoResize, Image.ANTIALIAS).save(photoPath + "thumbnail.jpg") # Rotate the thumbnail for printing Image.open(photoPath + "thumbnail.jpg").transpose(2).save( photoPath + "thumbnail-rotated.bmp") #print the photo try: printer.begin(210) # Warmup time #printer.setTimes(40000, 3000) # Set print and feed times printer.justify('C') # Center alignment printer.feed(1) # Add a blank line printer.printImage( Image.open(photoPath + "thumbnail-rotated.bmp"), True) # Specify thumbnail image to print printer.feed(10) # Add a few blank lines print("printed") except: print("Print Failed") #email photo try: os.system( "mpack -s Yourphoto /home/pi/Documents/Piloroidpics/" +
from Adafruit_Thermal import * maxCol = 32 printer = Adafruit_Thermal("/dev/ttyO2", 19200, timeout=5) printer.begin() printer.upsideDownOn() def parse(text): r = text.split(' ') curLine = '' fin = [] tally = 0 for w in r: if len(w) + len(curLine) > (maxCol - 1): fin.append(curLine) curLine = '' curLine += w else: curLine += ' ' + w # print curLine fin.append(curLine) fin[0] = fin[0].lstrip() fin.reverse() rt = '\n'.join(fin) return rt + '\n'
def print_keypair(pubkey, privkey): # Specify System Font Location and a font to use fontLocation = "/usr/share/fonts/truetype/droid/DroidSansMono.ttf" # open the printer itself printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5) printer.begin(200) finalImgName = "btc" coinName = "btc" printCoinName = finalImgName == "blank" finalImgName += "-wallet" # 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: finalImgName += "-enc" else: finalImgName += "-blank" finalImgName += ".bmp" finalImgFolder = "/home/pi/DIY-Piper/Images/" finalImg = Image.open(finalImgFolder + finalImgName) # ---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_H, 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(fontLocation, 60) draw = ImageDraw.Draw(finalImg) if printCoinName: draw.text((45, 400), coinName, font=font, fill=(0, 0, 0)) font = ImageFont.truetype(fontLocation, 20) startPos = (110, 38) charDist = 15 lineHeight = 23 lastCharPos = 0 keyLength = len(pubkey) 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, 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_H, 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, 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]) # ---end the private key qr code generation and drawing section--- # do the actual printing printer.printImage(finalImg, True) # 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
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/env python import Image, os, sys from Adafruit_Thermal import * printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5) printer.begin(75) # Increase the heat image_path = sys.argv[1] os.system('convert ' + image_path + ' -resize 382x764 tmp.png') printer.printImage(Image.open('tmp.png'), True) printer.feed(2) os.system('rm tmp.png') printer.sleep() # Tell printer to sleep printer.wake() # Call wake() before printing again, even if reset printer.setDefault() # Restore printer to defaults