Пример #1
0
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
Пример #2
0
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")
Пример #3
0
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
Пример #4
0
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 main():
    printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5)
    try:
        image = Image.open(sys.argv[1])
    except Exception as e:
        print(e)
        print("Usage: " + sys.argv[0] + " <filename>")
        sys.exit(1)

    printer.printImage(image, True)
    printer.println()
    printer.println()
Пример #6
0
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)
Пример #7
0
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
Пример #8
0
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
Пример #9
0
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)
Пример #10
0
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)
Пример #11
0
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()
Пример #12
0
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
Пример #13
0
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()
Пример #14
0
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))
Пример #15
0
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
Пример #16
0
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
Пример #17
0
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
Пример #18
0
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
Пример #19
0
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
Пример #20
0
		# Resize of the art image
		imgOeuvre = Image.open('gfx/bearings.png')
		imgOeuvre = imgOeuvre.resize((384,384 ))
		imgOeuvre = imgOeuvre.rotate(90)

		# Resize of the art image
		image = Image.open('gfx/print.png')
		imageRotated = image.resize((384*2,384 ))
		imageRotated = imageRotated.rotate(90)
		imageRotated = imageRotated.convert("L")
		
		# Printing of the two tickets
		# Tickets 1
		printer.println("#stimulix #museomixmtl")
		printer.printImage(imageRotated, True)
		printer.printImage(imgOeuvre, False)
		printer.feed(3)
		time.sleep(5)

		# Tickets 2
		printer.println("#stimulix #museomixmtl")
		printer.printImage(imageRotated, True)
		printer.printImage(imgOeuvre, False)
		printer.feed(3)
		time.sleep(3)

		# remove temporary graph
		os.remove('gfx/print.png')
	else:
		time.sleep(3)
Пример #21
0
img = Image.open("/dev/shm/privkey.png")
if img.size[1] < img.size[0]:
  img2 = img.rotate(270)
else:
  img2 = img

wpercent = (basewidth/float(img2.size[0]))
hsize = int((float(img2.size[1])*float(wpercent)))
img2 = img2.resize((basewidth,hsize), PIL.Image.ANTIALIAS)
img2 = img2.convert('1')
img2.save("/dev/shm/privkey.bmp")

printer.justify('L')
printer.feed(1)
printer.println( "Address:\n\n", addressPrint )
printer.printImage(Image.open("/dev/shm/address.bmp"))
printer.feed(2)
printer.println('_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ');
printer.feed(2)
printer.println( "PrivKey:\n\n", privkeyPrint )
printer.printImage(Image.open("/dev/shm/privkey.bmp"))
printer.justify('C')
printer.println(addressPrint);
printer.feed(3)
printer.setDefault()
printer.sleep()

GPIO.cleanup()

os.unlink('/dev/shm/address.png');
os.unlink('/dev/shm/address.bmp');
Пример #22
0
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)
        wpercent = (basewidth / float(lastPostImg.size[0]))
        hsize = int((float(lastPostImg.size[1]) * float(wpercent)))
        lastPostImgScaled = lastPostImg.resize((basewidth, hsize),
                                               Image.ANTIALIAS)

    # Print last feed, starting with source
    printer.underlineOn()
    #printer.inverseOn()
    printer.print("" + NewsFeed.feed['title'])
    #printer.inverseOff()
    printer.underlineOff()

    printer.print(lastPost.published[0:-6] + '\n' + '\n')

    if lastPostImgScaled != None:
        printer.printImage(lastPostImgScaled, True)

    printer.underlineOn()
    printer.print(lastPost.title + '\n')
    printer.underlineOff()
    printer.print(lastPost.summary_detail['value'] + '\n')

    printer.print('\nDein Kommentar:\n' +
                  '\n................................' +
                  '\n\n...............................' +
                  '\n\n...............................\n' + ' ' + ' \n ')

    printer.feed(3)
    lastPostDate = postDate

lastPostDateStr = str(time.strftime("%d.%m.%Y_%H:%M:%S", lastPostDate))
Пример #24
0
	printer.print('IP address: ' + s.getsockname()[0])
        ip = s.getsockname()[0]
	printer.feed(1)
except:
	printer.boldOn()
	printer.println('Network is unreachable.')
	printer.boldOff()
	printer.print('Connect display and keyboard\n'
	  'for network troubleshooting.')
        printer.print('Shutting down...')
	printer.feed(3)
	exit(0)

# Print greeting image
printer.feed(3)
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)



# Poll initial button state and time
prevButtonState = GPIO.input(buttonPin)
prevTime        = time.time()
tapEnable       = False
Пример #25
0
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
Пример #26
0
print('URL: ' + url)

# Create the canvas
image = Image.new('RGB', (384, 986))
draw = ImageDraw.Draw(image)

# Use the urlPrintout template image
template = Image.open('printer/template/template-urlPrintout.jpg')
image.paste(template, (0, 0))

# Generate the QR code
qr.add_data(url)
qr.make(fit=True)
qrImg = qr.make_image()
image.paste(qrImg, (65, 580))

# Add the url
(x, y) = (50, 830)
color = 'rgb(0, 0, 0)'
font = ImageFont.truetype('printer/fonts/Bitter-Italic.ttf', size=29)
w, h = draw.textsize(url, font=font)
draw.text(((384 - w) / 2, y), url, fill=color, font=font)

# Rotate the image by 180deg, save and print it
image.rotate(180).save('printer/urlPrintout.jpg')
printer.upsideDownOn()
printer.justify('C')
printer.printImage(Image.open('printer/urlPrintout.jpg'), True)
printer.feed(4)
Пример #27
0
    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
prevButtonState = GPIO.input(buttonPin)
prevTime = time.time()
tapEnable = False
holdEnable = False

# Starts the webservice
webservice_thread = threading.Thread(target=server.run_webservice)
webservice_thread.start()

# Main loop
while (True):
Пример #28
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", baudrate=19200, timeout=5)
printer.printImage(img, True)
printer.feed(3)
Пример #29
0
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
Пример #30
0
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('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()
Пример #31
0
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'), False)
printer.feed(3)

# 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()
    '''
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", 9600, timeout=5)

# Use Broadcom pin numbers (not Raspberry Pi pin numbers) for GPIO
GPIO.setmode(GPIO.BCM)

IMAGE = Image.open('IMG/PostkarteBlume2.jpg')
IMAGE_90 = IMAGE.rotate(90, expand=True)

# Print greeting image
printer.printImage(IMAGE_90, True)
printer.feed(3)
Пример #33
0
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()
Пример #34
0
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)
Пример #35
0
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)
Пример #36
0
try:
	s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
	s.connect(('8.8.8.8', 0))
	printer.print('\nMy 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
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()
Пример #37
0
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:
    printer.printImage(Image.open('export.png'), True)
    # printer.printImage(Image.open('emilie-1.png'), True)
    # printer.printImage(Image.open('emilie-0.png'), True)
    printer.feed(3)
    time.sleep(5)
Пример #38
0
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
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()
Пример #39
0
#!/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)
Пример #40
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

# module Adafruit
from Adafruit_Thermal import *

# module Python Imaging
import Image

# configuration
printer = Adafruit_Thermal("/dev/ttyUSB0", 9600, timeout=5)
printer.begin(140)

# un texte
printer.println("Voici une image :")
printer.feed(1)

# une image
printer.printImage(Image.open('image.png'), True)
printer.feed(2)
Пример #41
0
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
Пример #42
0
# 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.feed(1)
except:
    printer.boldOn()
    printer.println('Network is unreachable.')
    printer.boldOff()
    printer.feed(3)
    exit(0)

# Print greeting image
printer.print('"PinnwandConnection" ist ein \nProjekt von studio-johey.de')
printer.feed(1)
printer.printImage(Image.open('JoHey_Black_ThermoPrint.jpg'), True)
printer.feed(3)

# Main loop
while(True):
  # Poll current time
    t = time.time()

  # Once per day (currently set for 6:30am local time, or when script
  # is first run, if after 6:30am), run forecast and sudoku scripts.
##  l = time.localtime()
##  if (60 * l.tm_hour + l.tm_min) > (60 * 8 + 00):
##    if dailyFlag == False:
##      daily()
##      dailyFlag = True
##  else:
Пример #43
0
		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)
Пример #44
0
# print all of the images!
for i in sys.argv[1:]:
    if i[0] == '-':
        if i[1] == 'n':
            no_print = 1
        elif i[1] == 'u':
            upscale = 1
        continue

    im = Image.open(i)

    #im = im.transpose(Image.ROTATE_90)#.transpose(Image.FLIP_TOP_BOTTOM)

    print("OLDSIZE", im.size)
    if im.size[0] > max_width or (upscale and im.size[0] < max_width):
        newsize = (max_width, int(float(im.size[1]) / (float(im.size[0]) / max_width)))
        print("NEWSIZE", newsize)
        im = im.resize(newsize, Image.ANTIALIAS)

    # PIL algorithm: convert to greyscale then convert to mono with dithering
    im = im.convert('1')


    im.save("p.jpg", "jpeg")
    if not no_print:
        printer = Adafruit_Thermal(timeout=5)
        printer.printImage(im, False)
        printer.feedRows(50)

Пример #45
0
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
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()
Пример #46
0
            #print("Message #:", i[0])
            #print("Message Timestamp:", i[1])
            #print("Message Type:", i[2])
            #print("Message Action:", i[3])
            #print('')
            #print("Message #:", i[0])
            print(i[1])
            #print("Message Type:", i[2])
            print(i[2])
            print(i[3])
            print('')
            
            if i[2] == "T":
                #printer.doubleWidthOn()
                #printer.inverseOn()
                printer.printImage(Image.open('40in20out_trade.bmp'), True)
                printer.feed(1)
                printer.inverseOn()
                printer.print ('{:<32}'.format(i[1]))
                #printer.print(i[1])
                printer.inverseOff()
                printer.feed(1)
                printer.boldOn()
                printer.print(i[3])
                printer.boldOff()
                #printer.doubleWidthOff()
                printer.feed(3)

            if i[2] == "2":
                #printer.doubleWidthOn()
                #printer.inverseOn()
Пример #47
0
    printer.print('Welcome to the Tatadada Table! \n 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/welcome.png'), True)
# printer.feed(3)

printer.printImage(Image.open('gfx/logo-tatadada.png'), True)
printer.feed(3)

#printer.printImage(Image.open('gfx/ladybug.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):
Пример #48
0
#!/usr/bin/python

import subprocess, time, Image, socket
from Adafruit_Thermal import *


import time
from subprocess import call

call(["rm","snap.jpg"])
time.sleep(1)

call(["uvccapture","-S40","-C100", "-G80", "-B70", "-x320", "-y240", "-v", "-m"])
time.sleep(3)



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


printer.printImage(Image.open('snap.jpg'), False)
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
Пример #49
0
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)
Пример #50
0
#!/usr/bin/python

import sys
sys.path.append("/home/pi/git/Python-Thermal-Printer")

import Image
from Adafruit_Thermal import *

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

printer.justify('C')
printer.boldOn()
printer.setSize('L')
printer.println("Tim Sucks")
printer.feed(1)

image = Image.open('gfx/art.png')
image = image.rotate(90,expand=1)
(width, height) = image.size
scaledWidth = 384
scaleRatio = scaledWidth / width
scaledHeight = int(height * scaledWidth / width)
image = image.resize((scaledWidth,scaledHeight))
printer.printImage(image,True)

printer.feed(1)
printer.setDefault() # Restore printer to defaults
Пример #51
0
(x, y) = (50, 385)
color = 'rgb(0, 0, 0)'
font = ImageFont.truetype('printer/fonts/Bitter-Bold.ttf', size=36)
w, h = draw.textsize(name, font=font)
draw.text(((384-w)/2, y), name, fill=color, font=font)

# Add the voicemsg length to the canvas, e.g. length = '4:20s'
(x, y) = (115, 265)
w, h = draw.textsize(length, font=font)
draw.text((x, y), length, fill=color, font=font)

# Add the date and time to the canvas, e.g. date = '07.03.19 | 15:10'
(x, y) = (115, 230)
font = ImageFont.truetype('printer/fonts/Bitter-Italic.ttf', size=30)
w, h = draw.textsize(date, font=font)
draw.text((x, y), date, fill=color, font=font)

# Rotate the image by 180deg and save it next to the voicemsg file
image.rotate(180).save(filePath)

# Print the Barcode, e.g. barcode = '151023'
printer.upsideDownOn()
printer.justify('C')
printer.setBarcodeHeight(100)
printer.printBarcode(bytes(barcode), printer.CODE128)
printer.feed(3)

# Load the generated image and print it
printer.printImage(Image.open(filePath), True)
printer.feed(6)
Пример #52
0
from Adafruit_Thermal import *
import sys

import qrcode

qr = qrcode.QRCode(
    version=1,
    error_correction=qrcode.constants.ERROR_CORRECT_L,
    box_size=3,
    border=4,
)
qr.add_data(sys.argv[1])
qr.make(fit=True)

img = qr.make_image(fill_color="black", back_color="white")

printer = Adafruit_Thermal("/dev/ttyUSB0", 9600, timeout=3000)
from sampleqr import *
printer.printImage(img)
printer.feed(2)
Пример #53
0
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])
        ip = s.getsockname()[0]
Пример #54
0
    camera.capture(stream, format='jpeg', use_video_port=True)
    t2 = time.time()
    stream.seek(0) # "Rewind" the stream to the beginning so we can read its content
    image_source = Image.open(stream)
    imageResized = image_source.resize((WIDTH, HEIGHT), Image.ANTIALIAS)
    imageEnancer = ImageEnhance.Contrast(imageResized)
    imageContrasted = imageEnancer.enhance(2)
    imageInverted = PIL.ImageOps.invert(imageContrasted)
    imagedithered = imageInverted.convert('1') # convert image to black or white
    
#    GPIO.output(22, 1)
    lcd.write(imagedithered.tobytes())
#    GPIO.output(22, 0)
    
    stream.seek(0) # "Rewind" the stream to the beginning so we can read its content
    
    print('capture time: %f, process time %f' % (t1 - t2, time.time() - t2))
    t1 = time.time()
    
    imageRotated = image_source.rotate(90)
    printer = Adafruit_Thermal("/dev/ttyAMA0", 115200, timeout=0, rtscts=True)
    printer.printImage(imageRotated, False)
    printer.feed(3)

finally:
    GPIO.cleanup()
    camera.close()

if __name__ == '__main__':
    pass
Пример #55
0
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)
printer.begin() # Reset default heat time

Пример #56
0
from PIL import Image
from Adafruit_Thermal import *

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


def printHeadline(headline):
    printer.boldOn()
    printer.underlineOn()
    printer.println(headline)
    printer.boldOff()
    printer.underlineOff()


printer.printImage(Image.open('python/gfx/pitimes.png'), True)

printer.justify("C")
printer.println("Tuesday, November 21")
printer.justify("L")

printer.feed(2)

printer.println(
    "Tonight: Mostly clear, with a low around 26. Northwest wind 10 to 15 mph, with gusts as high as 20 mph."
)

printer.feed(2)

printHeadline(
    "Cook County commissioners approve 2018 budget with over 300 layoffs")
Пример #57
0
##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)

#import gfx.aaa as smile
#printer.printBitmap(smile.width, smile.height, smile.data, LaaT=True)

#import gfx.dither as smile
#printer.printBitmap(smile.width, smile.height, smile.data, LaaT=True)
from PIL import Image
imgpath = "static/symbols/aaa.png"
symbolimg = Image.open(imgpath)
printer.printImage(symbolimg)
#print("printed")

## 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
Пример #58
0
#!/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