Exemplo n.º 1
0
def main():
    parser = ArgumentParser(
        description="Print an illustration for a proxy by ID")
    parser.add_argument("id", help="ID of the proxy to print")
    parser.add_argument("-d",
                        "--database-path",
                        help="Path to RandomProxyPrinter basic database",
                        required=True,
                        dest="database_path")
    parser.add_argument("-p",
                        "--printer",
                        help="Path to printer device",
                        required=True)
    parser.add_argument("-r",
                        "--printer-baudrate",
                        help="Printer baudrate",
                        default=19200,
                        dest="baudrate")

    args = parser.parse_args()

    printer = Serial(args.printer, baudrate=args.baudrate)
    connection = connect(args.database_path)
    connection.row_factory = Row
    cursor = connection.cursor()

    cursor.execute("SELECT illustration FROM proxies WHERE id = ?",
                   (args.id, ))
    row = cursor.fetchone()

    printer.image(Image.open(BytesIO(row["illustration"])),
                  impl="bitImageColumn")
Exemplo n.º 2
0
 def __init__(self, printerConf):
     self.p = Serial(devfile=printerConf['dev'],
                     baudrate=[
                         int(printerConf['baudrate'])
                         if 'baudrate' in printerConf else 9600
                     ][0])
     self.p.open()
     self.printerWidth = printerConf['printerWidth']
     self.basedir = dirname(realpath(__file__)) + sep + pardir + sep
     self.printerConf = printerConf
Exemplo n.º 3
0
 def __init__(self, logger, config, printq):
     self.logger = logger
     self.cf = config
     self.printq = printq
     #self.p = None
     self.p = Serial(devfile='/dev/ttyUSB1',
                     baudrate=38400,
                     bytesize=8,
                     parity='N',
                     stopbits=1,
                     timeout=1.00,
                     dsrdtr=False,
                     profile="TM-T88II")
     self.pprint = printerpreter(self.p)  # pretty printer
Exemplo n.º 4
0
 def _connect_serial(self, **kwargs):
     """Initializes the __printer instance with Serial printer
        @param: port
        @param: baudrate
        @retrurn: Serial()
     """
     return Serial(kwargs['port'], baudrate=kwargs['baudrate'])
Exemplo n.º 5
0
    def __init__(self):
        diretorio = os.path.dirname(os.path.abspath(__file__))
        configFile = cfgprsr.ConfigParser()

        configFile.read(diretorio + '/config.ini')
        self.printer_type = configFile['PRINTER']['tipo']
        self.printer_device = configFile['PRINTER']['dispositivo']
        self.printer_vid = int(configFile['PRINTER']['vid'], 16)
        self.printer_pid = int(configFile['PRINTER']['pid'], 16)
        self.printer_baudrate = int(configFile['PRINTER']['baudrate'])
        self.printer_timeout = int(configFile['PRINTER']['timeout'])
        self.printer_parity = configFile['PRINTER']['parity']

        try:
            if self.printer_type.lower() == 'serial':
                self.printer = Serial(devfile=self.printer_device,
                                  baudrate=int(self.printer_baudrate),
                                  timeout=int(self.printer_timeout),
                                  parity=self.printer_parity)

                self.printer.open()
            elif self.printer_type.lower() == 'usb':
                self.printer = Usb(idVendor=self.printer_vid,
                                   idProduct=self.printer_pid)

            self.printer.codepage = 'CP860'


        except Exception as e:
            logger.logError("Erro ao comunicar com a impressora.    -    Details: {}".format(str(e)))
Exemplo n.º 6
0
class bonprinter:
    def __init__(self, logger, config, printq):
        self.logger = logger
        self.cf = config
        self.printq = printq
        #self.p = None
        self.p = Serial(devfile='/dev/ttyUSB1',
                        baudrate=38400,
                        bytesize=8,
                        parity='N',
                        stopbits=1,
                        timeout=1.00,
                        dsrdtr=False,
                        profile="TM-T88II")
        self.pprint = printerpreter(self.p)  # pretty printer

    def brrr(self, context):
        for item in self.printq:
            if item['printed'] is False:
                context.bot.send_message(chat_id=item['id'], text=printing_text)
                self.printq.update(tdbop.set("printed", True), Query().date == item['date'])
                # mark as printed so errors dont result in infinite loops
                if item['text'] is not None:
                    self.pprint.printbon(item['text'])
                if item['image'] is not None:
                    self.p.image(item['image'], impl='bitImageRaster')
                self.p.text("\n------------------------------------------\n")
                if self.cf['auto_cut'] is True:
                    self.p.cut(mode='FULL', feed=True, lines=4)
                if item['image'] is not None:
                    sleep(2)  # timeout so printer can cool down
Exemplo n.º 7
0
 def __init__(self, *args, **kwargs):
     self.eprint = None
     self.vendor_product = None
     if device_type == "usb":
         printers = self.connected_usb_devices()
         if printers:
             printer = printers[0]
             idVendor = printer.get("vendor")
             idProduct = printer.get("product")
             kwargs["in_ep"] = printer.get("in_ep", 0x82)
             kwargs["out_ep"] = printer.get("out_ep", 0x01)
             kwargs["timeout"] = 0
             POSDriver.__init__(self, idVendor, idProduct, **kwargs)
     elif device_type == "serial":
         kwargs["devfile"] = config.get("escpos_driver",
                                        "serial_device_name")
         kwargs["baudrate"] = config.getint("escpos_driver",
                                            "serial_baudrate")
         kwargs["bytesize"] = config.getint("escpos_driver",
                                            "serial_bytesize")
         kwargs["timeout"] = config.getint("escpos_driver",
                                           "serial_timeout")
         POSDriver.__init__(self, **kwargs)
     elif device_type == "win32":
         kwargs["printer_name"] = config.get("escpos_driver",
                                             "printer_name")
         POSDriver.__init__(self, **kwargs)
     ThreadDriver.__init__(self, *args, **kwargs)
Exemplo n.º 8
0
class Imprimir:
    def __init__(self, porta_serial):
        self.p = Serial(porta_serial)
        self.p.charcode("MULTILINGUAL")
        self.nome_serial = porta_serial

    def imprimir_texto(self, texto):
        self.p.text(str(texto))
        self.p.cut()

    def imprimir_imagem(self, imagem):
        self.p.image(str(imagem))
        self.p.cut()

    def imprimir_qr_code(self, texto):
        self.p.qr(str(texto))
        self.p.cut()

    def retornar_impressora(self):
        return str(self.nome_serial)
Exemplo n.º 9
0
from escpos.printer import Serial
p = Serial(devfile='/dev/rfcomm0',
           baudrate=9600,
           bytesize=8,
           parity='N',
           stopbits=1,
           timeout=1.00,
           dsrdtr=True)
def printval(product,quantity,amount,billdate):
    p.set(align='right',text_type='B')
    p.text('            Unpluged\n')
    p.text("\n")
    p.text('Dt:'+billdate+'\n')
    p.text('Item: '+product+'\n')
    p.text("Quantitty: "+str(quantity)+"       "+'Price: '+str(amount)+"\n")
    #p.text('Thanks for using Unplugged')
Exemplo n.º 10
0
def print_list(list):
    p = Serial(devfile="/dev/ttyUSB0",
               baudrate=38400,
               bytesize=8,
               parity='N',
               stopbits=1,
               timeout=1.00,
               dsrdtr=True)
    p.set('center', 'B', 'B', 2, 2)
    p.text(f"{list.name}\n")
    p.set('left', 'A', 'normal', 1, 1)
    for item in list.items:
        p.text(f"[  ] {item.name}\n")
    date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    p.set('right', 'B', 'normal', 1, 1)
    p.text(f"\nas of {date}\n")
    p.cut()
Exemplo n.º 11
0
import json
from datetime import datetime

import websockets
from escpos.printer import Serial

from items import generate_items_text_lines
from printing_parts import *

LOGO_IMAGE_PATH = '/home/kraken/printing/bosch-printing/bosch_logo/bosch-logo.png'

# Init printer with: 9600 Baud, 8N1, Flow Control Enabled
printer = Serial(devfile='/dev/ttyUSB0',
                 baudrate=19200,
                 bytesize=8,
                 parity='N',
                 stopbits=1,
                 timeout=1.00,
                 dsrdtr=True)


async def print_content(websocket, path):
    # Receive
    content = await websocket.recv()
    content = json.loads(content)
    print('GOT: {}'.format(content))
    print("GOT at: ", datetime.now().time())

    # Calculate items text
    items_text_lines = generate_items_text_lines(content['items'])
Exemplo n.º 12
0
def main():
    parser = ArgumentParser(description="Random proxy printer daemon")
    parser.add_argument("-d",
                        "--database-path",
                        help="Path to random proxy printer SQLite database",
                        required=True,
                        dest="database_path")
    parser.add_argument("-k",
                        "--knob",
                        help="Path to input event device for the knob",
                        required=True)
    parser.add_argument("-b",
                        "--button",
                        help="Path to input event device for the button",
                        required=True)
    parser.add_argument("-a",
                        "--display-address",
                        help="I2C address for the seven segment display",
                        dest="display_address",
                        required=True)
    parser.add_argument("-p",
                        "--printer",
                        help="Path to printer device",
                        required=True)
    parser.add_argument("-r",
                        "--printer-baudrate",
                        help="Printer baudrate",
                        default=19200,
                        dest="baudrate")
    parser.add_argument("-v", "--verbose", action="store_true")

    args = parser.parse_args()

    logger = getLogger("proxy_printer")
    logger.setLevel(DEBUG)

    console_handler = StreamHandler()
    if args.verbose:
        console_handler.setLevel(DEBUG)
    else:
        console_handler.setLevel(ERROR)
    logger.addHandler(console_handler)

    display = SevenSegment.SevenSegment(address=int(args.display_address, 16))
    display.begin()
    display.clear()

    knob = InputDevice(args.knob)
    knob.grab()

    button = InputDevice(args.button)
    button.grab()

    printer = Serial(args.printer, baudrate=args.baudrate)
    printer.hw("RESET")

    connection = connect(args.database_path)
    connection.row_factory = Row

    proxy_printer = RandomProxyPrinter(printer, display, knob, button,
                                       connection, asyncio, logger)
    register(proxy_printer.clear_display)
    proxy_printer.run()
Exemplo n.º 13
0
# GLOBALS AND SERIAL PORT REFERENCE
#------------------------------------------------------------

# for usb-to-serial adapter if used
USB_TO_SERIAL_PORT = "/dev/ttyUSB0"

# pcie startech serial card
STANDARD_SERIAL_PORT = "/dev/ttyS4"

# as it appears on physical dockets
areas = mi.docketStartFields

# global constants 
PER_ITEM_MAX = 4
ITEM_MAX = 3
p = Serial(STANDARD_SERIAL_PORT)



#------------------------------------------------------------
# DOCKET HEADER AND META DETAILS
#------------------------------------------------------------

def docket_heading ():
    area = areas[random.randint(0, len(areas)-1)]
    p.set(bold=True, double_height=True, double_width=True)
    red_color()
    p.text("{0}\n".format(area))
    black_color()
    p.set(bold=False, double_height=False, double_width=False)
Exemplo n.º 14
0
from escpos.printer import Serial

p = Serial(devfile='COM5',
           baudrate=9600,
           parity='N',
           stopbits=1,
           timeout=1.00,
           dsrdtr=True)

p.text("\033@")  # Reset
p.text("\033C\100")  # Set sheet eject length
p.text("\0331")  # Select 1/8-inch line spacing
p.text("\033$\000\030")  # Set left margin

p.text("\033a\000")  # Left align
p.text("See back of receipt for your chance\n")
p.text("to win $1000 ID #:7N77MVS1VUY\n")

p.text("\033a\001")  # Center align
p.image("C:\\Users\\Alexander\\Desktop\\download.jpg")
p.text("978-851-6265 Mgr:BETH WATERHOUSE\n")
p.text("333 MAIN ST\n")
p.text("TEWKSBURY MA 01876\n")

p.text("\033a\000")  # Left align
p.text("ST# 02222 OP# 009056 TE# 56 TR# 00079\n")

p.text("PRNCS DIA RING 00128182447 F  52000.00 T\n")
p.text("PRNCS DIA RING 00128182447 F  52000.00 T\n")
p.text("PRNCS DIA RING 00128182447 F  52000.00 T\n")
p.text("PRNCS DIA RING 00128182447 F  52000.00 T\n")
Exemplo n.º 15
0
 def __init__(self, porta_serial):
     self.p = Serial(porta_serial)
     self.p.charcode("MULTILINGUAL")
     self.nome_serial = porta_serial
Exemplo n.º 16
0
for i in range(num_strips):
    area = (0, STRIP_WIDTH * i, img_w, STRIP_WIDTH * (i + 1))
    strips[i] = image.crop(area)
if img_h % STRIP_WIDTH != 0:
    strips[-1] = strips[-1].crop((0, 0, img_w, img_h % STRIP_WIDTH))

# Dump strips into a temporary directory
if not os.path.exists('.temp'):
    os.mkdir('.temp')
for i in range(num_strips):
    strips[i].save(os.path.join('.temp', "strip{0:03}.png".format(i)))

# Do the printing
p = Serial(devfile='COM5',
           baudrate=9600,
           parity='N',
           stopbits=1,
           timeout=1.00,
           dsrdtr=True)

p.text("\033@")  # Reset
p.text("\033C\20")  # Set sheet eject length
p.text("\0331")  # Select 1/8-inch line spacing
p.text("\033$\000\000")  # Set left margin
p.text("\033a\001")  # Center align

for i in range(num_strips):
    p.image(os.path.join('.temp', "strip{0:03}.png".format(i)))

p.text("\033a\000")  # Left align
#p.cut()
Exemplo n.º 17
0
    def run(self):

        simple_printer = Serial(devfile='/dev/cu.BlueToothPrinter-SPPsla',
                                baudrate=9600,
                                bytesize=8,
                                parity='N',
                                stopbits=1,
                                timeout=1.00,
                                dsrdtr=True)

        sticky_printer = Serial(devfile='/dev/cu.BlueToothPrinter-SPPsla-1',
                                baudrate=9600,
                                bytesize=8,
                                parity='N',
                                stopbits=1,
                                timeout=1.00,
                                dsrdtr=True)

        def checkIfGoodColor(color):
            try:
                color = int(color)
                if (type(color) == int and color <= 255 and color >= 0):
                    return True
                else:
                    return False
            except:
                return False

        def ChangeColor(uid, r, g, b):
            User = Query()
            users.update({'color': {"r": r, "g": g, "b": b}}, User.id == uid)

        def ResetActivity(uid):
            User = Query()
            users.update({'activity': 100}, User.id == uid)

        def DeductPrint(uid):
            User = Query()
            prints_left = users.search(User.id == uid)[0]["prints_left"]
            prints_left -= 1
            users.update({'prints_left': prints_left}, User.id == uid)

        def PrintMessage(name, message=None, sticky=False):
            if (not sticky):
                simple_printer.charcode(code='AUTO')
                simple_printer.set(custom_size=True,
                                   width=2,
                                   height=2,
                                   invert=True,
                                   smooth=True)
                simple_printer.text(f"{name}\n")
                simple_printer.set(custom_size=False,
                                   font="b",
                                   width=2,
                                   height=2,
                                   invert=False)
                simple_printer.text(message + "\n\n\n\n\n")
            else:
                sticky_printer.charcode(code='AUTO')
                sticky_printer.set(custom_size=True,
                                   width=2,
                                   height=2,
                                   invert=True,
                                   smooth=True)
                sticky_printer.text(f"{name}\n")
                sticky_printer.set(custom_size=False,
                                   font="b",
                                   width=2,
                                   height=2,
                                   invert=True)
                sticky_printer.text("Welcome to the stream !!!" + "\n\n\n\n\n")

        def CheckOrAddUser(uid, username):
            User = Query()
            found_users = users.search(User.id == uid)

            if (uid == 0):
                return {"new_user": False, "prints_left": 0}

            ResetActivity(uid)

            if (len(found_users) != 0):
                return {
                    "uid": uid,
                    "color": found_users[0]['color'],
                    "new_user": False,
                    "prints_left": found_users[0]['prints_left'],
                    "printed_total": found_users[0]['printed_total']
                }
            else:
                print(f"Creating User | {username}")
                users.insert({
                    'username': username,
                    'id': uid,
                    'printed_total': 0,
                    'prints_left': 5,
                    'color': {
                        "r": 100,
                        "g": 65,
                        "b": 165
                    },
                    'activity': 0,
                })
                return {
                    "uid": uid,
                    "color": {
                        "r": 100,
                        "g": 65,
                        "b": 165
                    },
                    "new_user": True,
                    "prints_left": 2,
                    "printed_total": 0
                }

        def CheckIfAdmin(uid):
            User = Query()
            found_admins = admins.search(User.id == uid)
            if (len(found_admins) != 0):
                return True
            else:
                return False

        def AddToTotal(uid):
            User = Query()
            printed_total = users.search(User.id == uid)[0]["printed_total"]
            printed_total += 1
            users.update({'printed_total': printed_total}, User.id == uid)

        def AddPrintsToUser(username, print_quantity):
            User = Query()
            prints_left = users.search(
                User.username == username)[0]["prints_left"]
            prints_left += int(print_quantity)
            users.update({'prints_left': prints_left},
                         User.username == username)
            print(f"Refill | {username} has {prints_left}")

        class Bot(commands.Bot):
            def __init__(self):
                super().__init__(irc_token=oauthkey.all()[0]["key"],
                                 client_id='chamaloriz',
                                 nick='chamaloriz',
                                 prefix='!',
                                 initial_channels=['chamaloriz'])

            async def event_command_error(self, ctx, error):
                pass

            async def event_ready(self):
                print(f'Ready | {self.nick}')

            async def event_message(self, message):
                status = CheckOrAddUser(message.author.id, message.author.name)
                if (status["new_user"] == True):
                    print(
                        f"NewUser message | {message.author.name} joined the chat"
                    )
                    PrintMessage(message.author.name, sticky=True)
                await self.handle_commands(message)

            @commands.command(name='print')
            async def print(self, ctx):
                message = ctx.message.content[7:]
                user = CheckOrAddUser(ctx.author.id, ctx.author.name)

                if (user["prints_left"] != 0):
                    if (len(message) < 100):
                        print(
                            f"Printing | {len(message)} char message from {ctx.author.name}"
                        )
                        if (message == ""):
                            await ctx.send(
                                f"{ctx.author.name} you need to add a text to print after the command (!print bla bla)"
                            )
                        else:
                            DeductPrint(ctx.author.id)
                            AddToTotal(ctx.author.id)
                            PrintMessage(ctx.author.name, message)
                            # await ctx.send(f"{ctx.author.name} I'll print that ! you have {prints_left} left")
                    else:
                        await ctx.send(
                            f"{ctx.author.name} you can only print 100 chars")
                else:
                    await ctx.send(
                        f"{ctx.author.name} you can't print anymore wait for a refill :p"
                    )

            @commands.command(name='refill')
            async def refill(self, ctx):
                if (CheckIfAdmin(ctx.author.id)):
                    data = ctx.message.content[8:].split(' ')
                    user = data[0]
                    amount = data[1]
                    AddPrintsToUser(user, amount)
                else:
                    print(f"Not Admin {ctx.author.name} : {ctx.author.id}")

            @commands.command(name='color')
            async def changeColor(self, ctx):
                data = ctx.message.content[7:].split(' ')
                r = data[0]
                g = data[1]
                b = data[2]
                if (checkIfGoodColor(r) and checkIfGoodColor(g)
                        and checkIfGoodColor(b)):
                    if (ctx.author.id != 0):
                        print(
                            f"Changing Color | to {r}/{g}/{b} for {ctx.author.name}"
                        )
                        # await ctx.send(f"{ctx.author.name} I'll do that for sure !")
                        ChangeColor(uid=ctx.author.id, r=r, g=g, b=b)
                        color_events.insert({
                            'name':
                            ctx.author.name,
                            'color':
                            data[0] + ' ' + data[1] + ' ' + data[2],
                            'id':
                            (r / (g + b * randint(1, 9)) * randint(1, 1500) /
                             randint(1, 7) * randint(1, 5))
                        })
                else:
                    await ctx.send(
                        f"{ctx.author.name} you can't change to that it should be in this format !color 255 255 255 each color can be from 0 to 255"
                    )

            @commands.command(name='test')
            async def test(self, ctx):
                if (CheckIfAdmin(ctx.author.id)):
                    PrintMessage(ctx.author.name, sticky=True)
                else:
                    print(f"Not Admin {ctx.author.name} : {ctx.author.id}")

            @commands.command(name='github')
            async def github(self, ctx):
                await ctx.send(f"https://github.com/chamaloriz")

            @commands.command(name='discord')
            async def discord(self, ctx):
                await ctx.send(f"https://discord.gg/r73MK2s")

            @commands.command(name='help')
            async def help(self, ctx):
                await ctx.send(
                    f"/me {ctx.author.name} you can !print blablabla to show your message on the printer, !color (0-255) (0-255) (0-255) to change the color of your LED, !github, !discord"
                )

        bot = Bot()
        bot.run()
Exemplo n.º 18
0
class printout:
    """Print stuff from Twitter"""
    def __init__(self, printerConf):
        self.p = Serial(devfile=printerConf['dev'],
                        baudrate=[
                            int(printerConf['baudrate'])
                            if 'baudrate' in printerConf else 9600
                        ][0])
        self.p.open()
        self.printerWidth = printerConf['printerWidth']
        self.basedir = dirname(realpath(__file__)) + sep + pardir + sep
        self.printerConf = printerConf

    def imBox(self, width, height):
        """Create a white rectangle"""
        img = Image.new("1", (width, height))
        draw = ImageDraw.Draw(img)
        bgColor = 255
        draw.rectangle((0, 0) + img.size, fill=bgColor)
        return img

    def imText(self,
               text,
               align="left",
               textSize=None,
               rotate=None,
               bgColor=255,
               fontColor=0,
               scale=None,
               leading=0.25,
               txtWidth=None):
        """Render an image using a truetype font. Text may be be a list of string
        objects (one object per line). If a line is too wide the function will try to line wrap.
        Arg. 'leading' is the interline spacing in as a proportion of the height of a line.
        Arg. 'scale' is the proportion of the width of the paper."""
        if not textSize:
            textSize = int(self.printerConf['textSize'])
        if not txtWidth:
            txtWidth = self.printerConf['printerWidth']
        font = ImageFont.truetype(self.printerConf['fontFile'], textSize)

        def splitList(txtWidth, txtList, font, newlineSplitOnly=False):
            """Each str/unicode in txtList equals one line when printet. Split at newlines and furthermore split if a line is too wide."""
            # First of search for newlines and split the list if a newline is found
            withoutNewlines = []
            for txt in txtList:
                withoutNewlines.extend(txt.split("\n"))
            txtList = withoutNewlines
            if newlineSplitOnly:
                return txtList

            txtListWrapped = []
            for txt in txtList:
                # If the whole line is too wide, remove words until we are good
                if font.getsize(txt)[0] > txtWidth:
                    txtLen = len(txt)
                    for i in range(txtLen)[::-1]:
                        if font.getsize(txt[:i + 1])[0] <= txtWidth:
                            whitespaceEtc = [" ", "\t", "-"]
                            if txt[i] in whitespaceEtc:
                                txtSplit = [txt[:i + 1].rstrip(), txt[i + 1:]]
                                if font.getsize(txtSplit[1])[0] > txtWidth:
                                    txtSplit = splitList(
                                        txtWidth, txtSplit, font)
                                    break
                                else:
                                    break
                            # If there are no whitespaces etc. then split the word
                            elif not any(w in txt[:i + 1]
                                         for w in whitespaceEtc):
                                if font.getsize(txt[:i + 1] +
                                                "-")[0] <= txtWidth:
                                    txtSplit = [
                                        txt[:i + 1].rstrip() + "-", txt[i + 1:]
                                    ]
                                    if font.getsize(txtSplit[1])[0] > txtWidth:
                                        txtSplit = splitList(
                                            txtWidth, txtSplit, font)
                                        break
                                    else:
                                        break
                            else:
                                continue
                else:
                    txtSplit = [txt]
                txtListWrapped.extend(txtSplit)
            return txtListWrapped

        # If txtList is a simple string make it a list
        if type(text) is list:
            txtList = text
        else:
            txtList = [text]
        # Spacing between lines as a proportion of the width of a danish letter for the current text size.
        leadingDots = int(font.getsize(u"Å")[0] * leading)
        if rotate in [90, 270]:
            # Don't wrap lines based on width when turned 90 or 270 degrees
            txtList = splitList(txtWidth, txtList, font, newlineSplitOnly=True)
        else:
            # Do wordwrapping etc.
            txtList = splitList(txtWidth, txtList, font)

        # Determine the size of the resulting text image
        size = [0, 0]
        lineHeight = font.getsize("a")[1]
        size = [0, (leadingDots + lineHeight) * len(txtList) + leadingDots]
        # Find the width
        if rotate is 180:
            # Avoid right alignment of rotated text, if a line is less wide than the paper / printerConf['printerWidth']
            size[0] = self.printerConf['printerWidth']
        else:
            for txt in txtList:
                maxWidth = font.getsize(txt)[0]
                if maxWidth > size[0]:
                    size[0] = maxWidth
        # Create the actual image containing the text
        img = Image.new("1", size)
        draw = ImageDraw.Draw(img)
        draw.rectangle((0, 0) + img.size, fill=bgColor)
        pointer = [0, 0]
        # For each line..
        for txt in txtList:
            txtPxWidth = font.getsize(txt)[0]
            if align == "left":
                pointer[0] = 0
            elif align == "right":
                pointer[0] = size[0] - txtPxWidth
            elif align == "center":
                pointer[0] = (size[0] - txtPxWidth) / 2
            draw.text(pointer, txt, font=font, fill=fontColor)
            pointer[1] += lineHeight + leadingDots

        if rotate:
            angles = [0, 90, 180, 270]
            if rotate in angles:
                img = img.rotate(rotate, expand=True)
            else:
                raise ValueError("rotate must be part of %s if set " %
                                 str(angles))
        if rotate in [90, 270]:
            if img.size[0] > self.printerConf['printerWidth'] and not scale:
                raise Exception(
                    "The textSize is too large to print. Use either a smaller textSize or the scale parameter"
                )
        else:
            if img.size[0] > self.printerConf['printerWidth']:
                raise Exception(
                    "Could not print the text. One or more lines are too wide. Did you choose a very large font?"
                )

        if align is not "left":
            imgOld = img
            img = Image.new("1", (txtWidth, imgOld.size[1]))
            draw = ImageDraw.Draw(img)
            draw.rectangle((0, 0) + img.size, fill=bgColor)
            pointer = [0, 0]
            if align is "center":
                i = 2
            else:
                i = 1
            img.paste(imgOld, ((txtWidth - imgOld.size[0]) / i, 0))
        return img

    def printLine(self,
                  pxWidth=False,
                  width=1.0,
                  pxThickness=4,
                  pxHeading=10,
                  pxTrailing=10):
        """Prints a horisontal line.
        If width is set then pxWidth is ignored. width higher than 1.0 is ignored."""
        # calculate dimensions
        if not pxWidth:
            pxWidth = int(self.printerConf['printerWidth'] * width)
        pxHeight = pxHeading + pxThickness + pxTrailing
        img = Image.new("1", (self.printerConf['printerWidth'], pxHeight))
        draw = ImageDraw.Draw(img)
        draw.rectangle((0, 0, self.printerConf['printerWidth'], pxHeight),
                       fill=255)
        draw.rectangle(
            ((self.printerConf['printerWidth'] - pxWidth) / 2, pxHeading,
             (self.printerConf['printerWidth'] - pxWidth) / 2 + pxWidth,
             pxHeading + pxThickness),
            fill=0)
        return img

    def combinePILObjects(self,
                          imgArray,
                          doPrint=True,
                          multiCol=False,
                          ignoreRotate=False):
        """Combine objects and print them"""
        if multiCol:
            # Multiple columns object (e.g. printing wearther forecast). imgArray is then an array of arrays.
            imArray = [
                self.combinePILObjects(i, doPrint=False, ignoreRotate=True)
                for i in imgArray
            ]
            # Determine height pre multicol
            orgMaxHeight = 0
            for im in imArray:
                h = im[0].size[1]
                if h > orgMaxHeight:
                    orgMaxHeight = h
            numCols = len(imArray)
            imgMaster = self.imBox(self.printerConf['printerWidth'],
                                   orgMaxHeight / numCols)
            # Paste the columns together
            offset = 0
            numCols = len(imArray)
            colWidth = self.printerConf['printerWidth'] / numCols
            for i in imArray:
                imgMaster.paste(
                    i[0].resize([colWidth,
                                 int(i[0].size[1] * 1. / numCols)]),
                    (offset, 0))
                offset += colWidth
        else:
            # Calculate height
            height = 0
            imgTooWide = False
            for i in range(len(imgArray)):
                img = imgArray[i]
                # If an image is too large
                if img.size[0] > self.printerConf['printerWidth']:
                    # resize image
                    imgArray[i] = img.resize([
                        self.printerConf['printerWidth'],
                        int(img.size[1] *
                            float(self.printerConf['printerWidth']) /
                            img.size[0])
                    ])
                height += imgArray[i].size[1]
            # Create
            imgMaster = self.imBox(self.printerConf['printerWidth'], height)
            offset = 0
            for img in imgArray:
                imgMaster.paste(img, (0, offset))
                offset += img.size[1]
            if self.printerConf['rotate'] and not ignoreRotate:
                imgMaster = imgMaster.rotate(180)

        height = imgMaster.size[1]
        bytes_io = BytesIO()
        imgMaster.save(bytes_io, format="PNG")
        bytes_io.seek(0)
        imgData = bytes_io.read()
        if doPrint:
            bytes_io.seek(0)
            self.p.image(bytes_io, impl=self.printerConf['printType'])
        # return: PIL-object, height (int), PNG-file
        return (imgMaster, height, imgData)

    def qrIcon(self, url, size=120):
        iconHeight = size
        qr = qrcode.QRCode(
            version=1,
            error_correction=qrcode.constants.ERROR_CORRECT_M,
            box_size=10,
            border=4,
        )
        qr.add_data(url)
        qr.make(fit=True)
        img = qr.make_image()
        return img.resize((iconHeight, iconHeight))

    def commonPrint(self, conn, srcType):
        try:
            dbPrinter = conn.cursor()
            dbPrinter.execute(
                """SELECT printout.id, printout.jdoc 
                FROM printout INNER JOIN srcType 
                ON srcType.id = printout.srcType 
                WHERE srcType.shortName = %s AND printed = 0
                ORDER BY printout.id ASC LIMIT 1""", (srcType, ))
            row = dbPrinter.fetchone()
            # if there is something unprinted waiting for us for the given srcType
            if row is not None:
                data = json.loads(row[1])
                printFunc = getattr(self, srcType.lower())
                printData = printFunc(data)
                # Hmm. one could argue that if printing something fails,
                # then the message should not be marked as printed in the db..
                dbPrinter.execute(
                    """UPDATE printout SET height = %s, 
                    printed = 1, printedImg = _binary %s, printedImgRotated = %s, 
                    printedImgMimeType = %s WHERE id=%s""",
                    (str(printData[0]), printData[1], str(
                        printData[2]), printData[3], str(row[0])))
            dbPrinter.close()
        except Exception, e:
            print(e)
            try:
                print(
                    "The id for the failed message in the printout table: %i" %
                    row[0])
            except:
                pass
        else:
Exemplo n.º 19
0
def main():
    """Starting point"""
    # Printer object
    global p
    p = Serial(devfile='/dev/receipt_printer',
               baudrate=115200,
               bytesize=8,
               parity='N',
               stopbits=1,
               timeout=1.00,
               dsrdtr=True)

    # Printer settings
    p.set(align='center')
    # Print started message
    p.text("Bragi started!")
    p.cut()
    # Load saves dict
    global data
    try:
        with open("saves.json") as save_file:
            data = json.load(save_file)
    except FileNotFoundError:
        logging.info("saves.json file not found. Creating the file.")
        data = {}
        data['total_prints'] = 0
        data['text_prints'] = 0
        data['image_prints'] = 0
        data['contact_prints'] = 0
        data['poll_prints'] = 0
        data['location_prints'] = 0
        data['users'] = []
        data['last_user_id'] = 0
        try:
            with open("admin_id.txt") as admin_file:
                admin_id = admin_file.read().strip()
        except FileNotFoundError:
            logging.error(
                "No admin_id file found. Add your user id in a file called admin_id.txt in the same directory as the bot."
            )
            return
        data['admin_id'] = int(admin_id)
        with open('saves.json', 'w') as save_file:
            json.dump(data, save_file)
    # Start the bot
    TOKEN = None
    try:
        with open("token.txt") as f:
            TOKEN = f.read().strip()
    except FileNotFoundError:
        logging.error(
            "No token file found. Add your token in a file called token.txt in the same directory as the bot."
        )
        return
    updater = Updater(TOKEN)
    dispatcher = updater.dispatcher
    # Handle commands
    dispatcher.add_handler(CommandHandler("start", start))
    dispatcher.add_handler(CommandHandler("help", help_command))
    dispatcher.add_handler(CommandHandler("stats", stats_command))
    dispatcher.add_handler(CommandHandler("listusers", listusers_command))
    dispatcher.add_handler(
        CommandHandler("givepermission", givepermission_command))
    dispatcher.add_handler(
        CommandHandler("removepermission", removepermission_command))
    dispatcher.add_handler(CommandHandler("anonymous", anonymous_command))
    # Handle all the message types! I might be able to OR some lines, but this also works
    dispatcher.add_handler(
        MessageHandler(Filters.text & ~Filters.command, print_text))
    dispatcher.add_handler(MessageHandler(Filters.photo, print_photo))
    dispatcher.add_handler(MessageHandler(Filters.document.image, print_photo))
    dispatcher.add_handler(MessageHandler(Filters.audio, print_audio))
    dispatcher.add_handler(MessageHandler(Filters.voice, print_audio))
    dispatcher.add_handler(MessageHandler(Filters.contact, print_contact))
    dispatcher.add_handler(
        MessageHandler(
            Filters.document & ~Filters.document.image
            & ~Filters.document.video, print_document))
    dispatcher.add_handler(MessageHandler(Filters.location, print_location))
    dispatcher.add_handler(MessageHandler(Filters.poll, print_poll))
    dispatcher.add_handler(MessageHandler(Filters.sticker, print_photo))
    dispatcher.add_handler(MessageHandler(Filters.video, print_video))
    dispatcher.add_handler(MessageHandler(Filters.document.video, print_video))

    # Start polling
    updater.start_polling()
    updater.idle()
Exemplo n.º 20
0
        if sys.argv[i].startswith('lines'):
            a = sys.argv[i].split('=')
            linesperpage = int(a[1])
            print 'Lines per page', linesperpage
else:
    print 'Usage: thermalrule.py printer=true/false rule=[0-255] lines=80 interface=tcp/serial'
    exit()

if printer:
    if interface == 'tcp':
        print 'Using TCP interface', host, tcpport
        Epson = Network(host=host, port=tcpport, timeout=60)
        time.sleep(2)  # wait for network
    else:
        print 'Using serial interface', devfile, baud
        Epson = Serial(devfile=port, baudrate=baud, dsrdtr=True)
    ret = '\r\n'
else:
    ret = '\n'

Epson.image('rulemart.gif', impl='bitImageColumn')
Epson.set(font='a')
Epson.text('Rule  : ' + str(rulenum) + '\n')
Epson.text('Lines : ' + str(linesperpage) + '\n')
Epson.text(datetime.datetime.now().strftime('Date  : %Y/%m/%d %H:%M:%S\n'))
output('\x1b\x21\x01', lf=False)  # font 'b', 56 chars wide
output('\x1b\x33\x20', lf=False)  # line spacing
output(ret * 3, lf=False)
rule30(rule=rulenum)
output(ret * 3, lf=False)
Epson.barcode(code=datetime.datetime.now().strftime("%Y%m%d%H%M%S"),