Ejemplo n.º 1
0
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
Ejemplo n.º 2
0
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
Ejemplo n.º 3
0
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
Ejemplo n.º 4
0
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
Ejemplo n.º 5
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)
Ejemplo n.º 6
0
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()
Ejemplo n.º 7
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()
Ejemplo n.º 8
0
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'))
Ejemplo n.º 9
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)
Ejemplo n.º 10
0
# Texte inversé
printer.inverseOn()
printer.println("Inversion")
printer.inverseOff()

# tailles double
printer.doubleHeightOn()
printer.println("Double Hauteur")
printer.doubleWidthOn()
printer.println("Double Tout")
printer.doubleHeightOff()
printer.println("Double Largeur")
printer.doubleWidthOff()

# alignement
printer.justify('R')  # Right
printer.println("Droite")
printer.justify('C')  # Center
printer.println("Centre")
printer.justify('L')  # Left
printer.println("Gauche")

# gras
printer.boldOn()
printer.println("En gras")
printer.boldOff()

# souligner
printer.underlineOn()
printer.println("Souligne")
printer.underlineOff()
Ejemplo n.º 11
0
class Printer(Thread):
    def __init__(self, headers):
        Thread.__init__(self)

        self.headers = headers
        self.config = json.load(open('/home/pi/bitrepublic/Config.json'))
        self.printerCount = self.config["printer"]["count"]
        self.maxRequestPerSecond = self.config["printer"][
            "maxRequestPerSecond"]
        self.img = Image.open(self.config["printer"]["img"])
        self.address = self.config["requests"]["consume"]["Address"]
        self.minInterval = self.config["printer"]["minInterval"]
        self.maxInterval = max(
            1, 2 * self.printerCount * self.maxRequestPerSecond -
            self.minInterval)
        self.printer = Adafruit_Thermal("/dev/serial0", 19200, timeout=5)

        tmp = min(self.minInterval, self.maxInterval)
        self.maxInterval = max(self.minInterval, self.maxInterval)
        self.minInterval = tmp

        #print("minInterval : "+str(minInterval))
        #print("maxInterval : "+str(maxInterval))

        printer = Adafruit_Thermal("/dev/serial0", 19200, timeout=5)
        #print("Setup: success")
        self.t = Terminal()
        print(self.t.italic('Hi there! : I\'m the Printer'))

    def grabBitsoilAndPrint(self):
        print(self.t.italic('Printer : is there any new bitsoil ?'))
        r = requests.get(self.address,
                         headers=self.headers)  #send the get request.
        if r.status_code == 200:  #checks if the server respond
            jdata = r.json()
            if jdata["data"] != False:  #checks if there is data in the output of the server.
                print(jdata["data"])
                myDate = (jdata["data"]["date"])
                myKey = (jdata["data"]["publicKey"])
                myAmount = (jdata["data"]["bitsoil"])
                print(self.t.italic('Printer : Yes ! so I\'ve to do...'))
                self.printReceipt(myDate, myKey, myAmount)

        else:
            print(r.status_code)

    def printReceipt(self, myDate, myKey, myAmount):
        self.printer.wake(
        )  # Call wake() before printing again, even if reset.

        self.printer.justify('C')
        self.printer.boldOn()
        self.printer.println(myDate)
        self.printer.boldOff()

        self.printer.println('')

        self.printer.justify('C')
        self.printer.println(myKey)

        self.printer.printImage(self.img, True)

        self.printer.setSize('M')
        self.printer.justify('C')
        self.printer.println(format(myAmount, 'f') + ' Bitsoil')
        self.printer.println('--------------------------------')

        self.printer.feed(1)

        self.printer.sleep()  # Tell printer to sleep.
        self.printer.setDefault()  # Restore printer to defaults.
        self.printer.reset(
        )  #if you don't reset, the printer starts to f**k up the receipt.

    def run(self):
        while True:
            self.grabBitsoilAndPrint(
            )  #checks if there is bitsoils available to print, and if there is, it prints it.
            t = random.randint(self.minInterval, self.maxInterval)
            print(
                self.t.italic('Printer : Pfiouf... See you in ' + str(t) +
                              ' seconds'))
            time.sleep(t)  #wait for x seconds before re-checking for bitsoils.
Ejemplo n.º 12
0
                time.sleep(0.1)
                GPIO.output(19, False)

                # Resize the high res photo to create thumbnail
                Image.open(photoPath + photoName).resize(
                    photoResize,
                    Image.ANTIALIAS).save(photoPath + "thumbnail.jpg")
                # Rotate the thumbnail for printing
                Image.open(photoPath + "thumbnail.jpg").transpose(2).save(
                    photoPath + "thumbnail-rotated.bmp")

                #print the photo
                try:
                    printer.begin(210)  # Warmup time
                    #printer.setTimes(40000, 3000) # Set print and feed times
                    printer.justify('C')  # Center alignment
                    printer.feed(1)  # Add a blank line
                    printer.printImage(
                        Image.open(photoPath + "thumbnail-rotated.bmp"),
                        True)  # Specify thumbnail image to print
                    printer.feed(10)  # Add a few blank lines
                    print("printed")
                except:
                    print("Print Failed")

                #email photo
                try:
                    os.system(
                        "mpack -s Yourphoto /home/pi/Documents/Piloroidpics/" +
                        photoName + "*****@*****.**")
                    print("Emailed!")
printer.inverseOn()
printer.println("Inverse ON")
printer.inverseOff()

# Test character double-height on & off
printer.doubleHeightOn()
printer.println("Double Height ON")
printer.doubleHeightOff()

# Test character double-width on & off
printer.doubleWidthOn()
printer.println("Double Width ON")
printer.doubleWidthOff()

# Set justification (right, center, left) -- accepts 'L', 'C', 'R'
printer.justify('R')
printer.println("Right justified")
printer.justify('C')
printer.println("Center justified")
printer.justify('L')
printer.println("Left justified")

# Test more styles
printer.boldOn()
printer.println("Bold text")
printer.boldOff()

printer.underlineOn()
printer.println("Regular underlined text")
printer.underlineOff()
Ejemplo n.º 14
0
import sys
from datetime import datetime
from time import sleep
from Adafruit_Thermal import *

padding = int(sys.argv[1])
linebreaks = int(sys.argv[2])

printer = Adafruit_Thermal("COM4", 9600, timeout=5)
printer.begin()
printer.wake()

printer.inverseOn()
printer.println(datetime.now().strftime('%d-%m-%Y %H:%M:%S'))
printer.inverseOff()

for i in range (3, sys.argv.__len__()):
    if i == 3 or i == 6 or i == 9 or i == 12 or i == 15 or i == 18 or i == 21 or i == 24 or i == 27 or i == 30 or i == 33 or i == 36 or i == 39 or i == 42:
        printer.justify(sys.argv[i])

    if i == 4 or i == 7 or i == 10 or i == 13 or i == 16 or i == 19 or i == 22 or i == 25 or i == 28 or i == 31 or i == 34 or i == 37 or i == 40 or i == 43:
        printer.setSize(sys.argv[i])
        
    if i == 5 or i == 8 or i == 11 or i == 14 or i == 17 or i == 20 or i == 23 or i == 26 or i == 29 or i == 32 or i == 35 or i == 38 or i == 41 or i == 44:
        printer.println(sys.argv[i])

    printer.feed(linebreaks)

printer.feed(padding)
printer.feed(2)
Ejemplo n.º 15
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)
Ejemplo n.º 16
0
def main():
    p = Adafruit_Thermal()
    p.setDefault()
    p.setSize('L')
    p.println('Calendar')

    creds = None
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)

        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('calendar', 'v3', credentials=creds)

    now = datetime.utcnow().isoformat() + 'Z'
    timeMax = (datetime.utcnow() +
               timedelta(days=config.calendar_days)).isoformat() + 'Z'
    event_results = service.events().list(calendarId='primary',
                                          timeMin=now,
                                          timeMax=timeMax,
                                          singleEvents=True,
                                          orderBy='startTime').execute()
    events = event_results.get('items', [])

    p.setSize('M')
    if not events:
        p.println("Nothing to do... chill out!")

    for event in events:
        # print(event)
        start_d_in = event['start'].get('date')
        start_dt_in = event['start'].get('dateTime')

        start_t_out = None
        if start_dt_in is not None:
            start_dt = dateutil.parser.parse(start_dt_in)
            start_d_out = start_dt.strftime(config.date_format)
            start_t_out = start_dt.strftime(config.time_format)
        else:
            start_d_out = dateutil.parser.parse(start_d_in).strftime(
                config.date_format)

        p.boldOn()
        p.underlineOn()
        p.justify('L')
        if start_t_out is not None:
            p.print(start_t_out)
            p.print(' ')

        p.println(start_d_out)
        p.boldOff()
        p.underlineOff()

        p.justify('R')
        p.println(event['summary'])

    p.setDefault()
    p.sleep()
Ejemplo n.º 17
0
def print_keypair(pubkey, privkey, leftBorderText):

    #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/Printer/btc-wallet-blank.bmp")
    else:
        finalImg = Image.open("/home/pi/Printer/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)

    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_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, 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---

#create the divider
    rightMarkText = "Piperwallet.com"

    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/Printer/dividerline.bmp")

    draw = ImageDraw.Draw(dividerLineImg)
    draw.text(leftMarkOrigin, leftBorderText, font=font, fill=(0, 0, 0))
    draw.text(rightMarkOrigin, rightMarkText, font=font, fill=(0, 0, 0))

    #do the actual printing

    printer.printImage(finalImg)

    if (len(privkey) <= 51):
        printer.printChar(privkey[:17] + "\n")
        printer.justify('R')
        printer.printChar(privkey[17:34] + "\n")
        printer.justify('L')
        printer.printChar(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
Ejemplo n.º 18
0
if __name__ == '__main__':
	# new videocapture object
	cap = cv2.VideoCapture(0)

	# Create a Adafruit_Thermal object that we can use for printing
	printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5)		

	# python-tesseract initialization
	api = tesseract.TessBaseAPI()
	api.SetOutputName("hacker_u")
	api.Init(".","eng",tesseract.OEM_DEFAULT)
	api.SetPageSegMode(tesseract.PSM_AUTO)

	printer.boldOn()	# Make text bold
	printer.setSize('L')    # Set type size, accepts 'S', 'M', 'L'
	printer.justify('C')	# Center the text to leave lots of whitespace 

	while(True):
		''' Prompt the user to enter some text to be recognized by python-tesseract '''
		text_to_print = raw_input("Enter text: ")	
		
		# Alert user that we are printing
		print("Printing...")	
	
		''' Print the user's text out '''
		printer.println(text_to_print)
		
		time.sleep(1)	
		
		print "Tear off the printed text from printer and show it to the webcam!"
		print "Press 'q' to snap the picture"
Ejemplo n.º 19
0
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)
Ejemplo n.º 20
0
# On a command line with a filename, solves the given puzzles
# (files should look like the text generated by the generator).
#
# Adapted for Adafruit_Thermal library by Phil Burgess for Adafruit
# Industries.  This version uses bitmaps (in the 'gfx' subdirectory)
# to render the puzzle rather than text symbols.  See sudoku-txt
# for a different Sudoku example that's all text-based.

from Adafruit_Thermal import *
import SteriLogo as logo
from subprocess import call
import sys, getopt


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

# Test inverse on & off
printer.inverseOn()

printer.inverseOff()

call(["echo"," 1 >> /dev/ttyS1"])


 # Test more styles
printer.justify('L')
printer.boldOn()
printer.println(str(sys.argv[1]))
printer.boldOff()
printer.feed(1)
Ejemplo n.º 21
0
# print List Ingles.
result = []
for i in range(0, 9):
    printer.println(lista[i][0].encode("ascii", "ignore"))
    result.append(lista[i][1].encode("ascii", "ignore"))
    worksheet.update_cell(lista[i][4], 3, int(lista[i][2]) + 1)

result.append("\n")

# print List spaon
for i in range(10, 19):
    printer.println(lista[i][1].encode("ascii", "ignore"))
    result.append(lista[i][0].encode("ascii", "ignore"))
    worksheet.update_cell(lista[i][4], 3, int(lista[i][2]) + 1)

printer.justify("L")
# print reslt
printer.println("********************************")
printer.println("")

for i in range(len(result)):
    printer.print_(result[i])
    printer.print_(" | ")

printer.feed(1)
printer.printImage(Image.open("gfx/goodbye.png"), True)
time.sleep(20)
printer.feed(3)
subprocess.call("sync")
subprocess.call(["shutdown", "-h", "now"])
		print(url)
		width = payload['image']['width']
		height = payload['image']['height']
		try:
			headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_4) AppleWebKit/600.5.17 (KHTML, like Gecko) Version/8.0.5 Safari/600.5.17'}
			req = urllib2.Request(url, None, headers)
			data = urllib2.urlopen(req).read()
			img = Image.open(StringIO(data))
			img = aspect_fit(img, 384, 384)
			img = img.convert('1') # convert to B&W (use 'L' for monochrome)
			printer.printImage(img, True)
		except Exception, e:
			# The image is not valid
			print(e)

	printer.justify('C')
	printer.boldOn()
	printer.setSize('S')
	printer.println("Greetings from")
	printer.setSize('L')
	printer.println('@' + str(username))
	printer.setSize('S')
   
	caption = payload['caption']
	printer.feed(1)
	printer.println('"' + caption.encode('cp437', 'ignore') + '"')
	printer.feed(1)
	printer.setSize('S')
	printer.boldOff()
	printer.underlineOn()
	printer.println('www.technocreatives.com')
Ejemplo n.º 23
0
def main():
    creds = None
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.json', 'w') as token:
            token.write(creds.to_json())

    try:
        service = build('tasks', 'v1', credentials=creds)

        tasklists = service.tasklists().list(maxResults=10).execute().get(
            'items', [])

        p = Adafruit_Thermal()
        p.setDefault()
        p.setSize('M')
        p.justify('C')

        if not tasklists:
            p.println('No task lists found.')
            return
        else:
            p.println('Tasks')

        p.setSize('S')

        #        print('Task lists:')
        for tasklist in tasklists:
            #            print(u'{0} ({1})'.format(tasklist['title'], tasklist['id']))

            tasks = service.tasks().list(
                tasklist=tasklist['id']).execute().get('items', [])
            for task in sorted(tasks, key=lambda t: t.get('order', '')):
                task_title = task.get('title', '-')
                task_status = task.get('status', None)
                task_due = task.get('due', None)

                if task_due is not None:
                    task_due_s = dateutil.parser.parse(task_due).strftime(
                        config.date_format)
                    p.boldOn()
                    p.underlineOn()
                    p.justify('R')
                    p.println(task_due_s)

                p.boldOff()
                p.underlineOff()
                p.justify('L')
                p.print('[ ] ')

                p.println(task_title)
        p.println('')  # make some space

    except HttpError as err:
        print(err)
Ejemplo n.º 24
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
Ejemplo n.º 25
0
def __print_new_account_info(account_number, pin_number, tos):
    printer = Adafruit_Thermal("/dev/ttyS0", 19200, timeout=60)

    printer.setSize('M')
    printer.justify('C')
    printer.println("1st Regional Bunny Bank\n\n")

    printer.boldOn()
    printer.println("================================")
    printer.boldOff()

    printer.boldOn()
    printer.boldOn()
    printer.println("================================")
    printer.boldOff()
    printer.println("================================")
    printer.boldOff()
    printer.setSize('S')
    printer.justify('C')
    printer.println("Here at 1st Regional BB")
    printer.println("we're proud to provide you")
    printer.println("with words when you're")
    printer.println("struggling to find them.")

    printer.justify('C')
    printer.println("================================")

    printer.justify('C')
    printer.setSize('S')
    printer.println("Account #")
    printer.setSize('M')
    printer.println(account_number)
    printer.setSize('S')
    printer.println("Pin #")
    printer.setSize('M')
    printer.println(pin_number)
    printer.setSize('S')
    printer.println("================================")

    printer.justify('L')
    printer.println("\n")
    printer.println("With your new account you")
    printer.println("have the following options:")

    printer.boldOn()
    printer.println("1. Deposit")
    printer.boldOff()
    printer.println("Your balance is increased by one")
    printer.println("and the poem is printed.")

    printer.boldOn()
    printer.println("2. Withdraw Personal")
    printer.boldOff()
    printer.println("Your balance is not affected")
    printer.println("and the poems are printed")

    printer.boldOn()
    printer.println("3. Withdraw Community")
    printer.boldOff()
    printer.println("Your balance is decreased by x")
    printer.println("and the poems are printed")
    printer.println("\n\n\n")
    printer.println("--------------------------------")
    printer.println("--------------------------------")
    printer.println(text_format(TERMS_OF_SERVICE))
    printer.println("--------------------------------")

    printer.feed(30)
Ejemplo n.º 26
0
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")
printer.println(
    "CHICAGO - The Cook County commissioners unanimously passed the 2018 budget Tuesday, cutting $200 million and over 300 jobs in the process."
Ejemplo n.º 27
0
p.println('Todo')

for i in api.items.all():
    # print(i)

    date_str = i['due']
    if date_str:
        date_str = date_str['date']
    if date_str:
        due_date = dateutil.parser.parse(date_str)
    else:
        due_date = None

    p.boldOn()
    p.underlineOn()
    p.justify('L')
    p.print('[ ] ')
    if due_date:
        p.println(due_date.strftime(config.date_format))
    else:
        p.println('')

    p.boldOff()
    p.underlineOff()

    p.justify('R')

    content = unicodedata.normalize(
        'NFD', i['content']).encode('ascii', 'ignore')
    p.println(content)
Ejemplo n.º 28
0
#!/usr/bin/python

from Adafruit_Thermal import *

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

printer.justify('C')
# Print the 135x135 pixel QR code in adaqrcode.py
import gfx.adaqrcode as adaqrcode
printer.printBitmap(adaqrcode.width, adaqrcode.height, adaqrcode.data)
printer.sleep()  # Tell printer to sleep
printer.wake()  # Call wake() before printing again, even if reset
printer.setDefault()  # Restore printer to defaults
Ejemplo n.º 29
0
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)
Ejemplo n.º 30
0
from Adafruit_Thermal import *

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

# Test inverse on & off
printer.inverseOn()
printer.println("Inverse ON")
printer.inverseOff()

# Test character double-height on & off
printer.doubleHeightOn()
printer.println("Double Height ON")
printer.doubleHeightOff()

# Set justification (right, center, left) -- accepts 'L', 'C', 'R'
printer.justify('R')
printer.println("Right justified")
printer.justify('C')
printer.println("Center justified")
printer.justify('L')
printer.println("Left justified")

# Test more styles
printer.boldOn()
printer.println("Bold text")
printer.boldOff()

printer.underlineOn()
printer.println("Underlined text")
printer.underlineOff()
Ejemplo n.º 31
0
    # we want to see if lastSplitIdx equals the last index of enumerate(spaceIndexes)
    # if they DON'T equal, we want to append the rest of our message
    if spaceIndexes[lastSplitIdx] != spaceIndexes[-1]:
        # start at the lastSplitIdx
        startIdx = spaceIndexes[lastSplitIdx]
        # go from the startIdx to the end
        element = fortune[startIdx:]
        # push to queue
        queue.append(element)

# ADAFRUIT INITIALIZATION

from Adafruit_Thermal import *
# grab printer
printer = Adafruit_Thermal("/dev/serial0", 19200, timeout=5)

printer.feed(1)  # whitespace at the top of the print
printer.justify('C')  # justify center
printer.setSize('M')  # Mid size text
printer.boldOn()  # bold the text in this

# from our built queue array, go through and print each line.
for element in queue:
    printer.println(element)

printer.boldOff()  # remove the bold
printer.feed(5)  # whitespace at the bottom of the print
printer.sleep()  # Tell printer to sleep
printer.wake()  # Call wake() before printing again, even if reset
printer.setDefault()  # Restore printer to defaults