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 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 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
def printadvice(): # Initialize the printer. Note this will take a few seconds for the printer # to warm up and be ready to accept commands (hence calling it explicitly vs. # automatically in the initializer with the default auto_warm_up=True). printer = Adafruit_Thermal("/dev/serial0", 19200, timeout=5) fortune = random.choice(hints) printer.justify('C') printer.println(' ___ ___ ') printer.println(' /| <⋈> |\ ') printer.println(' /_| : |_\ ') printer.println(' | : | ') printer.println(' |___: __| ') printer.println(' __ __ ') printer.println('| \ \ ___ // ___') printer.println('| |/ . \ <_-<') printer.println('|_|_|_|\___/ /__/') printer.println(' ___ _ ') printer.println('|_ _|<_> ___ ___ ') printer.println(' | | | || . \<_-< ') printer.println(' |_| |_|| _//__/ ') printer.println(' |_| ') printer.feed(1) printer.boldOn() printer.println(fortune) printer.boldOff() printer.feed(2) 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 main(sender, message): print("sender %s message %s" % (sender, message)) printer = Adafruit_Thermal("/dev/serial0", 9600, timeout=5) printer.wake() # Call wake() before printing again, even if reset printer.setDefault() # Restore printer to defaults # Set justification (right, center, left) -- accepts 'L', 'C', 'R' # Set type size, accepts 'S', 'M', 'L' printer.setSize('L') # Lagre printer.justify('C') # Center print_text(printer, "%s\n" % sender, 15) printer.setSize('S') # Small #print_text(printer, "Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit...\n", 15) #print_text(printer, str(message).join("\n"), 15) print_text(printer, "%s\n" % message, 15) printer.setLineHeight(50) #printer.println("<time>") print_text(printer, strftime("%Y-%m-%d\n%H:%M:%S", gmtime())) printer.setLineHeight() # Reset to default printer.feed(4) printer.sleep() # Tell printer to sleep
def __print_poem(poem_text, upc): printer = Adafruit_Thermal("/dev/ttyS0", 19200, timeout=60) printer.setSize('M') printer.justify('C') printer.println("1st Regional Bunny Bank\n\n") printer.println("\n") printer.justify('C') printer.println("================================") printer.justify('C') printer.setSize('M') printer.println(poem_text, length=29) printer.feed(1) printer.setBarcodeHeight(100) printer.printBarcode(upc, printer.UPC_A) #printer.setSize('S') #printer.setSize('S') #printer.println(text_format(TOS_MESSAGE)) printer.feed(30) printer.sleep() printer.wake() printer.setDefault()
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
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 Text(name, theme): printer = Adafruit_Thermal("/dev/serial0", 19200, timeout=5) # Test inverse on & off printer.inverseOn() # printer.println("Inverse ON") # Test character double-height on & off #printer.doubleHeightOn() printer.println("On vous recommande le livre suivant :") #printer.doubleHeightOff() printer.inverseOff() # Set justification (right, center, left) -- accepts 'L', 'C', 'R' # printer.justify('R') # printer.println("Right justified") printer.justify('C') printer.println(name) printer.inverseOn() # printer.println("Inverse ON") # Test character double-height on & off #printer.doubleHeightOn() printer.println("Le thème de ce livre est :") #printer.doubleHeightOff() printer.inverseOff() printer.justify('C') printer.println(theme) # printer.justify('L') # printer.println("Left justified") # Test more styles printer.boldOn() printer.println("Bold text") printer.boldOff() printer.underlineOn() printer.println("Underlined text") printer.underlineOff() printer.setSize('L') # Set type size, accepts 'S', 'M', 'L' printer.println("Large") printer.setSize('M') printer.println("Medium") printer.setSize('S') printer.println("Small") printer.justify('C') printer.println("normal\nline\nspacing") printer.setLineHeight(50) printer.println("Taller\nline\nspacing") printer.setLineHeight() # Reset to default printer.justify('L') # Barcode examples printer.feed(1) # 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) printer.sleep() # Tell printer to sleep printer.wake() # Call wake() before printing again, even if reset printer.setDefault() # Restore printer to defaults
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 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 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
def printerThread(): global imgQueue printer = Adafruit_Thermal("/dev/ttyUSB0", 9600, timeout=5) while True: img = imgQueue.get() if not img: printer.feed(2) else: printer.printImage(img)
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 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
class thermal_printer: def __init__(self): self.printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5) def printImg(self, img, priv_key): self.printer.feed(3) self.printer.printImage(img) # I have some reservation about how to deal with encrypted private key, but need to wait for thermal_printer to look into it. if len(priv_key) <= 51: self.printer.printChar(priv_key[:17]+"\n") self.printer.justify("R") self.printer.printChar(priv_key[17:34]+"\n") self.printer.justify("L") self.printer.printChar(priv_key[34:]+"\m") else: self.printer.println(priv_key)
def printImage(nameImg): printer = Adafruit_Thermal("/dev/serial0", 19200, timeout=5) basewidth = 400 img = Image.open('ThermalVis/images/'+nameImg+'.png') wpercent = (basewidth/float(img.size[0])) hsize = int((float(img.size[1])*float(wpercent))) #bg = Image.new("1", [282 , 271], "white") # Working 'background' image bg = Image.new("1", [basewidth , hsize], "white") # Working 'background' image img = img.resize((basewidth,hsize), Image.ANTIALIAS) img.save('ThermalVis/images/'+nameImg+'.png') imgGray = gray_Scale("ThermalVis/images/"+nameImg+".png") imgGray = Image.open(imgGray) # Crop number bitmaps out of source image printer.printImage(imgGray, True) # This does the printing printer.println() printer.feed(3)
def on_data(self, data): print(1) print(data) print(2) tweet = json.loads(data.strip()) retweeted = tweet.get('retweeted') from_self = tweet.get('user', {}).get('id_str', '') == account_user_id if retweeted is not None and not retweeted and not from_self: tweetId = tweet.get('id_str') screenName = tweet.get('user', {}).get('screen_name') tweetText = tweet.get('text') print(4) tweetText = tweetText.encode('UTF-8') print(tweetText) chatResponse = therapist.respond(tweetText) print(chatResponse) print(5) replyText = '@' + screenName + ' ' + chatResponse print(6) #check if repsonse is over 140 char if len(replyText) > 130: replyText = replyText[0:127] + '...' wrappedTweet = textwrap.fill(tweetText, 32) wrappedReply = textwrap.fill(replyText, 32) printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5) printer.println('Tweet ID: ' + tweetId) printer.println('From: ' + screenName) printer.println('Tweet Text:') printer.println(wrappedTweet) printer.println('Reply Text:') printer.println(wrappedReply) printer.feed(3) # If rate limited, the status posts should be queued up and sent on an interval twitterApi.update_status(status=replyText, in_reply_to_status_id=tweetId) print(7)
def on_data(self, data): print(1) print(data) print(2) tweet = json.loads(data.strip()) retweeted = tweet.get('retweeted') from_self = tweet.get('user',{}).get('id_str','') == account_user_id if retweeted is not None and not retweeted and not from_self: tweetId = tweet.get('id_str') screenName = tweet.get('user',{}).get('screen_name') tweetText = tweet.get('text') print(4) tweetText = tweetText.encode('UTF-8') print(tweetText) chatResponse = therapist.respond(tweetText) print(chatResponse) print(5) replyText = '@' + screenName + ' ' + chatResponse print(6) #check if repsonse is over 140 char if len(replyText) > 130: replyText = replyText[0:127] + '...' wrappedTweet = textwrap.fill(tweetText, 32) wrappedReply = textwrap.fill(replyText, 32) printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5) printer.println('Tweet ID: ' + tweetId) printer.println('From: ' + screenName) printer.println('Tweet Text:') printer.println(wrappedTweet) printer.println('Reply Text:') printer.println(wrappedReply) printer.feed(3) # If rate limited, the status posts should be queued up and sent on an interval twitterApi.update_status(status=replyText, in_reply_to_status_id=tweetId) print(7)
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
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'))
def printCoupon(row): printer = Adafruit_Thermal("/dev/tty.usbserial", 19200, timeout=5) printer.wake() printer.justify('C') printer.setSize('L') printer.println('IUNO Coupon') printer.setSize('S') printer.println('Value: ' + row[2]) qr = qrcode.QRCode( version=4, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=9, border=5, ) qr.add_data(row[1]) qr.make() img = qr.make_image(fill_color="white", back_color="black") print(img.size) printer.printImage(img) printer.println(row[1]) printer.feed(2) # printer.sleep() printer.flush()
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
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
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
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()
class ThermalPrinter: ser = None def __init__(self): if enableSerial: self.printer = Adafruit_Thermal("/dev/ttyS0") def write(self, buffer): if enableSerial: buffer = wordWrap.correctWidth(buffer, 32) self.printer.write(buffer.encode('ascii', errors='ignore')) self.printer.feed() else: print(buffer) def printImage(self, image): if enableSerial: self.printer.printImage(image) self.printer.feed() def thickBar(self): if enableSerial: self.printer.write(const.HORIZONTAL_BAR.encode()) self.printer.feed() def feed(self, linesToFeed): if enableSerial: self.printer.feed(linesToFeed) def resetAll(self): if enableSerial: pass def welcome(self): if enableSerial: self.printer.write( wordWrap.correctWidth(const.WELCOME_MESSAGE.encode(), 30))
def print_image(imagePath="/home/pi/misyu/files/test.jpg"): printer = Adafruit_Thermal("/dev/serial0", 19200) printer.wake() BASE_WIDTH = 384 img = Image.open(imagePath) wpercent = (BASE_WIDTH / float(img.size[0])) hsize = int((float(img.size[1]) * float(wpercent))) img = img.resize((BASE_WIDTH, hsize)) printer.printImage(img) printer.feed(1) printer.setSize('S') printer.println(datetime.now().strftime('%Y-%m-%d %H:%M')) printer.feed(1) printer.println("_______________________________") printer.feed(5) printer.sleep() printer.setDefault()
def print_chat(): printer = Adafruit_Thermal("/dev/serial0", 19200, timeout=5) printer.feed(3) printer.setSize('L') printer.printTHIS("CHATBOTS ON THE RISE") printer.printTHIS("ELIZA (1964)") printer.setDefault() for chat in session['chats']: speaker, message = chat if speaker == "eliza": printer.inverseOn() printer.printTHIS(message) printer.inverseOff() else: printer.printTHIS("> " + message) printer.feed(2) printer.printTHIS(' -- END --') printer.feed(3) session.clear() return redirect('/')
# 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(ledPin, GPIO.OUT) GPIO.setup(fanPin, GPIO.OUT) GPIO.output(fanPin, False) GPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # LED on while working GPIO.output(ledPin, GPIO.HIGH) # Processor load is heavy at startup; wait a moment to avoid # stalling during greeting. time.sleep(5) printer.feed(5) while True: if ( GPIO.input(buttonPin) == False ): print("Printing") sofi() GPIO.output(fanPin, False) print("Printed") time.sleep(.1) if KeyboardInterrupt: GPIO.cleanup()
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
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 __future__ import print_function import RPi.GPIO as GPIO import subprocess, time, socket from PIL import Image from Adafruit_Thermal import * printer = Adafruit_Thermal("/dev/serial0", 19200, timeout=5) printer.printImage(Image.open('gfx/doron_maze.png'), True) printer.feed(5)
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
class Reliquery(object): generators = [ Magic8, Tarot, Potion, Labyrinth, Tiles, Npc, Cave, Diagnostic ] def __init__(self): self.ip = network.ip() self.done = False self.printer = Adafruit_Thermal("/dev/serial0", 19200, timeout=5) self.switch = Button(7) self.led = LED(18) self.button = Button(23) wheelpins = [26, 19, 13, 6, 5, 11, 9, 10] self.wheelbuttons = [Button(n) for n in wheelpins] def feed(self, n): self.printer.feed(n) def println(self, s): self.printer.println(s) def printImage(self, img, LaaT=False): self.printer.printImage(img, LaaT) def generate(self): mode = self.read_mode() if mode < 1 or 8 < mode: self.println("mode selector error (got mode %d)" % mode) else: g = self.generators[mode - 1] if g is None: self.println("no mode configured for mode %d" % mode) else: g.generate(self) self.feed(3) def read_mode(self): for i, b in enumerate(self.wheelbuttons): if b.is_pressed: return i + 1 return 0 def shutdown(self): self.done = True self.led.on() self.println("shutting down...") self.println("(wait 30s before unplugging.)") self.feed(3) call("sync") call(["shutdown", "-h", "now"]) def tap(self): if not self.done: self.led.on() self.generate() self.led.blink(on_time=0.2, off_time=2.0) def print_banner(self): self.println('reliquery (ip: %s)' % self.ip) self.feed(1) self.println('choose a mode; then tap button') self.println('hold button to exit') self.println('have fun!') self.feed(3) def main(self): self.led.on() self.print_banner() self.button.when_released = self.tap self.button.when_held = self.shutdown self.led.blink(on_time=0.2, off_time=2.0) pause()
printer.setSize('L') # Set type size, accepts 'S', 'M', 'L' printer.println("Large") printer.setSize('M') printer.println("Medium") printer.setSize('S') printer.println("Small") printer.justify('C') printer.println("normal\nline\nspacing") printer.setLineHeight(50) printer.println("Taller\nline\nspacing") printer.setLineHeight() # Reset to default printer.justify('L') # Barcode examples printer.feed(1) # 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(2)
# LED on while working GPIO.output(ledPin, GPIO.HIGH) # Processor load is heavy at startup; wait a moment to avoid # stalling during greeting. time.sleep(15) # Show IP address (if network is available) try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('8.8.8.8', 0)) device.boldOn() device.print('My IP address is ' + s.getsockname()[0]) device.boldOff() device.feed(3) except: device.boldOn() device.println('Network is unreachable.') device.boldOff() device.print('Connect display and keyboard\n' 'for network troubleshooting.') device.feed(3) exit(0) # Print greeting image device.printImage(Image.open('gfx/hello.png'), True) device.feed(3) GPIO.output(ledPin, GPIO.LOW) # Poll initial button state and time
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)
#printer.printImage(img, True); while 1: time.sleep(0.5); listDir = os.listdir("nodeImages"); if len(listDir) > 0: for x in range(0,len(listDir)): #for x in range(0,1): #print os.listdir("img")[x] if os.path.isfile("nodeImages/"+listDir[x]): print os.listdir("nodeImages")[x] basewidth = 400; img = Image.open("nodeImages/"+listDir[x]); wpercent = (basewidth/float(img.size[0])); hsize = int((float(img.size[1])*float(wpercent))); img = img.resize((basewidth,hsize)); printer.printImage(img, True); printer.feed(2); print 'nodeImages/'+listDir[x] #printer.printBitmap(width,height,array); #os.renames('nodeImages/'+os.listdir("img")[x],'nodeImages/printed/'+os.listdir("nodeImages")[x]) # print "moved" for y in range(0,len(listDir)): print y print 'nodeImages/'+listDir[y] os.remove('nodeImages/'+listDir[y]);
# # 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)
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) printer.println("is this thing on?") printer.feed(2)
#!/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
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
def timetemp(): API_KEY = "eb8a97364f3e4aec7cd1fbd48a5b149e" LAT = "45.7747" LONG = "4.7787" # 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((data['currently']['temperature'] - 32) * 5 / 9) 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. # This allowed lots of control over kerning and such, and I didn't # want to spend a lot of time hunting down a suitable font with a # permissive license. symbols = Image.open( "ThermalVis/images/timetemp.png") # Bitmap w/all chars & symbols img = Image.new("1", [330, 117], "white") # Working 'background' image draw = ImageDraw.Draw(img) # These are the widths of certain glyphs within the 'symbols' bitmap TimeDigitWidth = [38, 29, 38, 36, 40, 35, 37, 37, 38, 37, 13] TempDigitWidth = [33, 25, 32, 31, 35, 30, 32, 32, 33, 32, 17, 14] DateDigitWidth = [16, 13, 16, 15, 17, 15, 16, 16, 16, 16] HumiDigitWidth = [14, 10, 14, 13, 15, 12, 13, 13, 13, 13, 18] DayWidth = [104, 109, 62, 110, 88, 110, 95] MonthWidth = [53, 52, 60, 67, 59, 63, 59, 56, 51, 48, 54, 53] DirWidth = [23, 35, 12, 27, 15, 33, 19, 41, 23] DirAngle = [23, 68, 113, 157, 203, 247, 293, 336] # 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 # Crop glyph lists (digits, days of week, etc.) TimeDigit = croplist(TimeDigitWidth, 0, 0, 44) TempDigit = croplist(TempDigitWidth, 40, 0, 39) DateDigit = croplist(DateDigitWidth, 75, 0, 18) HumiDigit = croplist(HumiDigitWidth, 75, 180, 16) Day = croplist(DayWidth, 93, 0, 25) Month = croplist(MonthWidth, 93, 175, 24) Dir = croplist(DirWidth, 162, 175, 21) # Crop a few odds-and-ends glyphs (not in lists) Wind = symbols.crop([93, 463, 157, 479]) Humidity = symbols.crop([93, 479, 201, 500]) Kph = symbols.crop([156, 366, 196, 386]) Mph = symbols.crop([156, 387, 203, 407]) # Draw top & bottom bars draw.rectangle([42, 0, 330, 3], fill="black") draw.rectangle([42, 113, 330, 116], fill="black") x = 42 # Initial drawing position y = 12 # 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 # 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 # Render current time (always 24 hour XX:XX format) t = time.localtime() drawNums(time.strftime("%H:%M", t), x, y, TimeDigit) # Determine wider of day-of-week or date (for alignment) s = str(t.tm_mday) # Convert day of month to a string w = MonthWidth[t.tm_mon - 1] + 6 + numWidth(s, DateDigit) if DayWidth[t.tm_wday] > w: w = DayWidth[t.tm_wday] # Draw day-of-week and date x = img.size[0] - w # Left alignment for two lines img.paste(Day[t.tm_wday], (x, y)) # Draw day of week word y += 27 # Next line img.paste(Month[t.tm_mon - 1], (x, y)) # Draw month word x += MonthWidth[t.tm_mon - 1] + 6 # Advance past month drawNums(s, x, y, DateDigit) # Draw day of month x = 42 # Position for temperature y = 67 # Degrees to string, remap '-' glyph, append degrees glyph s = str(temperature).replace('-', ';') + ':' drawNums(s, x, y, TempDigit) # Determine wider of humidity or wind info s = str(humidity) + ':' # Appends percent glyph s2 = str(windSpeed) winDirNum = 0 # Wind direction glyph number if windSpeed > 0: 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] 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/serial0", 19200, timeout=5) printer.printImage(img, True) printer.feed(3)
def main(): printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5) deg = chr(0xf8) # Degree symbol on thermal printer events = get_events() # Print heading printer.setSize('M') printer.justify('C') printer.println( datetime.datetime.today().date().strftime("%A, %B %-d, %Y") ) printer.justify('L') printer.setSize('S') # Print schedule printer.boldOn() printer.underlineOn() printer.justify('C') printer.println("Today's Schedule") printer.justify('L') printer.underlineOff() printer.boldOff() printer.feed(1) if not events: printer.println('No scheduled events today.') printer.feed(1) for event in events: start = dateutil.parser.parse(event['start'].get('dateTime', event['start'].get('date'))).strftime("%-I:%M%p") end = dateutil.parser.parse(event['end'].get('dateTime', event['end'].get('date'))).strftime("%-I:%M%p") location = event.get('location', '') printer.println(event['summary']) if start == end: if location: printer.println(start + ", " + location) else: printer.println(start) else: if location == "": printer.println(start + " - " + end) else: printer.println(start + " - " + end + ", " + location) printer.feed(1) printer.feed(1) # Print weather weather = get_weather() printer.boldOn() printer.underlineOn() printer.justify('C') printer.println("Today's Weather") printer.justify('L') printer.underlineOff() printer.boldOff() printer.feed(1) printer.println("Temperature: " + str(weather.temp_now) + ". Feels like " + str(weather.feels_like_now)) printer.feed(1) printer.println("Today: " + weather.weather_today) printer.feed(1) printer.println("Tonight: " + weather.weather_tonight) printer.feed(1) downcase_first = lambda s: s[:1].lower() + s[1:] if s else '' printer.println("Tomorrow: " + weather.weather_tomorrow + " Tomorrow night, " + downcase_first(weather.weather_tomorrow_night)) printer.feed(1) printer.feed(2)
# 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(ledPin, GPIO.OUT) GPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # LED on while working GPIO.output(ledPin, GPIO.HIGH) # Processor load is heavy at startup; wait a moment to avoid # stalling during greeting. # time.sleep(30) # Print greeting image printer.feed(1) printer.printImage(Image.open('40in20out_logo.bmp'), True) printer.feed(1) printer.print("40in20out") printer.feed(1) printer.print("Presented by...") printer.feed(1) printer.printImage(Image.open('totemasset_logo.bmp'), True) printer.feed(2) GPIO.output(ledPin, GPIO.LOW) # Show IP address (if network is available) try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('8.8.8.8', 0)) printer.print('My IP address is ' + s.getsockname()[0])
try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('8.8.8.8', 0)) print('My IP address is ' + s.getsockname()[0]) #printer.feed(3) except: printer.boldOn() println('Network is unreachable.') printer.boldOff() print('Connect display and keyboard\n' 'for network troubleshooting.') #printer.feed(3) exit(0) # Print greeting image '''printer.printImage(Image.open('gfx/hello.png'), True) printer.feed(3) GPIO.output(ledPin, GPIO.LOW)''' # Poll initial button state and time prevButtonState = GPIO.input(buttonPin) prevTime = time.time() tapEnable = False holdEnable = False # Main loop while(True): # Poll current button state and time buttonState = GPIO.input(buttonPin) t = time.time()
GPIO.setup(ledPin, GPIO.OUT) GPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # LED on while working GPIO.output(ledPin, GPIO.HIGH) # Processor load is heavy at startup; wait a moment to avoid # stalling during greeting. time.sleep(30) # Show IP address (if network is available) try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('8.8.8.8', 0)) printer.print('My IP address is ' + s.getsockname()[0]) printer.feed(3) except: printer.boldOn() printer.println('Network is unreachable.') printer.boldOff() printer.print('Connect display and keyboard\n' 'for network troubleshooting.') printer.feed(3) exit(0) # Print greeting image printer.printImage(Image.open('gfx/hello.png'), True) printer.feed(3) GPIO.output(ledPin, GPIO.LOW) # Poll initial button state and time
# Example command: @spyderbotpython print this: hello # Returns @spyderbotpython: @{user} asked me to print "hello" # Which will be printed on the printer attached to spyderbot x = easeInOutSine printer = Adafruit_Thermal("/dev/ttyUSB0", 19200, timeout=5) # Store the tokens to your machine as environment variables oauth_access_token = os.environ.get('oauth_access_token') print oauth_access_token bot_user_token = os.environ.get('bot_user_token') print bot_user_token printer.println("I'm Alive") printer.feed(6) slack_client = SlackClient(bot_user_token) spyderbot_id = None websocket.enableTrace(True) # Global constants RTM_READ_DELAY = 1 PRINT_COMMAND = "print" DELETE_COMMAND = "delete" MENTION_REGEX = "^<@(|[WU].+?)>(.*)" image_types = ["png", "jpg"] # Parses a command to spyderbot slackbot and returns the message text
'Accept-Encoding' : 'gzip', 'Authorization' : 'Bearer ' + token}) # Display results. --------------------------------------------------------- maxId = data['search_metadata']['max_id_str'] for tweet in data['statuses']: printer.inverseOn() printer.print(' ' + '{:<31}'.format(tweet['user']['screen_name'])) printer.inverseOff() printer.underlineOn() printer.print('{:<32}'.format(tweet['created_at'])) printer.underlineOff() # max_id_str is not always present, so check tweet IDs as fallback id = tweet['id_str'] if(id > maxId): maxId = id # String compare is OK for this # Remove HTML escape sequences # and remap Unicode values to nearest ASCII equivalents printer.print(unidecode( HTMLParser.HTMLParser().unescape(tweet['text']))) printer.feed(3) print(maxId) # Piped back to calling process
# # 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)