Exemplo n.º 1
0
def assign(v, p, in_ep, out_ep):
    try:
        printer = getp.Usb(v, p, 0, in_ep, out_ep)
        printer.text("\n")
        return printer
    except:
        return None
Exemplo n.º 2
0
def get_printer():
    if not have_printer_imports:
        raise PrintError("Printer libraries are not installed")

    if current_app.config.get('ESCPOS_PRINTER_MODE') == 'usb':
        return printer.Usb(*current_app.config['ESCPOS_PRINTER_ID'])
    else:
        raise PrintError("Invalid printer mode")
Exemplo n.º 3
0
def print_list():
    printstring = ''
    for item in dummy_list:
        if not item['done']:
            printstring += '{}\n'.format(item['description'], item['done'])

    printbot = printer.Usb(0x0416, 0x5011)
    printbot.text(printstring if printstring else
                  "I'm sorry human, there's nothing in the list")
    printbot.cut()

    return printstring if printstring else "List empty"
Exemplo n.º 4
0
def main():
    pr = printer.Usb(0x0416, 0x5011)
    while True:
        time.sleep(5)
        dir = glob.glob("/tmp/*.printy")
        if dir:
            print(dir[0])
            file = open(dir[0], mode="r", encoding='utf-8-sig')
            line = file.read()
            pr._raw(line.encode('cp437'))
            pr.text("\n\n\n\n")
            file.close
            os.remove(dir[0])
Exemplo n.º 5
0
def print_custom():
    if not request.json or not 'message' in request.json:
        abort(
            400, 'Shit - no message in the request payload: {}'.format(
                request.json))

    message = request.json['message']

    printbot = printer.Usb(0x0416, 0x5011)
    printbot.text(message if message else
                  "I'm sorry human. I cannot understand that message.")
    printbot.cut()

    return message
Exemplo n.º 6
0
def get_printer(dummy=False):

    if dummy:
        return ep.Dummy()

    db = get_db()
    c = db.cursor()
    c.execute("select conf_value from printer_conf where conf_key='usb_major';")
    major = int(c.fetchone()[0], 16)

    c.execute("select conf_value from printer_conf where conf_key='usb_minor';")
    minor = int(c.fetchone()[0], 16)

    c.close()
    p = ep.Usb(major, minor)
    return p
Exemplo n.º 7
0
def printTicket(uid='123', meal='Lunch'):
    from escpos import printer

    p = printer.Usb(0x1fc9, 0x0064, 4, 0x81, 0x03)  #NGX printer

    #chineese printer  p=printer.Usb(0x0456,0x0808,4,0x81,0x03)

    p.set(align=u'center', font=u'b', width=4, height=4)

    p.text("     RSD MESS\n")
    p.set()
    p.text("******************************************\n")

    p.text(meal)
    p.text('\n')
    p.set()
    p.text('UID :' + uid + '\n******************************************\n\n')
Exemplo n.º 8
0
 def print_payslip(payslip, payslip_info):
     try:
         """ Seiko Epson Corp. Receipt Printer M129 Definitions (EPSON TM-T88IV) """
         # Epson = printer.Usb(0x04b8,0x0202)
         # Epson = printer.Usb(0x0416,0x5011,4,0x81,0x03)
         # Epson = printer.Serial(dev='/dev/rfcomm0', baudrate=9600, bytesize=8, timeout=1)
         # max line: Epson.text("012345678901234567890123456789012345678901\n")
         Epson = printer.Usb(0x04b8, 0x0202)
         # Print image
         Epson.text("\n\n")
         Epson.image("logo.gif")
         # Print Header
         Epson.text("\n\n")
         Epson.set(align='center')
         Epson.text("Milliondog - the cosy company\n")
         Epson.text(time.strftime('%X %x %Z') + "\n")
         # Print text
         Epson.set(align='left')
         Epson.text("\n\n")
         Epson.text("Pos  Beschreibung                Betrag   \n")
         Epson.text("                                          \n")
         total = decimal.Decimal(0.00)
         for counter, payslip_line in enumerate(payslip):
             pos_left = str(counter) + "  " + payslip_line[
                 'code'] + " " + payslip_line['name']
             pos_right = payslip_line['price'] + " " + payslip_info[
                 'currency'] + "\n"
             Epson.text(pos_left + pos_right.rjust(42 - len(pos_left)))
             total = total + decimal.Decimal(payslip_line['price'])
         Epson.text("                                          \n")
         Epson.text("------------------------------------------\n")
         payslip_total = str(total) + " " + payslip_info['currency'] + "\n"
         Epson.text("Total :   " + payslip_total.rjust(42 - 10))
         # Print text
         Epson.text("\n\n")
         Epson.set(font='b', align='center')
         Epson.text("Powered by Semilimes\n")
         # Cut paper
         Epson.text("\n\n")
         Epson.cut()
     except AttributeError:
         print 'AttributeError: printer is probably not connected!'
Exemplo n.º 9
0
def setup_printer(maincfg, debugcfg, logging):
    # Connects to the printer (unless test mode is enabled, in which case starts a dummy instance)
    if debugcfg['TestMode'] == "1":
        logging.warning(
            'Headlights is in test mode. Nothing will actually be printed - you\'ll just see the output to the printer on the screen.'
        )
        p = printer.Dummy()
        logging.debug("Initialized dummy printer")
    else:
        try:
            p = printer.Usb(int(maincfg['Vendor'], 16),
                            int(maincfg['Product'], 16))
        except (usb.core.NoBackendError,
                escpos.exceptions.USBNotFoundError) as e:
            logging.debug(e)
            handlers.criterr(
                "Could not initialize printer. Check a printer matching the vendor and product in the config file is actually connected, and relaunch Headlights."
            )
        logging.debug("Initialized USB printer")
    return p
Exemplo n.º 10
0
def assign(vendor_id, product_id, in_ep=None, out_ep=None):
    ''' Assign a new printer session and attach it.

    Parameters
    __________
        vendor_id: int
        product_id: int
        in_ep: int
        out_ep: int

    Returns
    -------
        ESCPOS Printer instance.
    '''
    args = [vendor_id, product_id, 0]

    if in_ep and out_ep:
        args += [in_ep, out_ep]

    printer = getp.Usb(*args)
    printer.text("\n")

    return printer
Exemplo n.º 11
0
def printLine(record, flag, deltatime=0):
    p = printer.Usb(0x6868, 0x0200, 0, in_ep=0x81, out_ep=0x02)
    p.set(align='left')
    p._raw(record[1])  #time
    p._raw('\n')
    p._raw(record[3].encode('gbk'))  #username
    p._raw('\n')
    if flag == 0:
        p._raw(('用' + str(deltatime) + '天读完: ').encode('gbk'))
        p._raw('\n')
    if flag == 1:
        p._raw('正在读: '.encode('gbk'))
    p._raw(record[5].encode('gbk'))  #bookname
    p._raw('\n')
    p._raw(('作者: ' + record[7]).encode('gbk'))  #author
    p._raw('\n')
    p._raw(('推荐来源: ' + record[8]).encode('gbk'))  #referral
    p._raw('\n')
    p._raw('\n')
    p._raw('. . . . . . . . . . . . . .')
    p._raw('\n')
    p._raw('\n')
    p._raw('\n')
Exemplo n.º 12
0
    def __init__(self):
        """Setup printer configuration

        """
        from proxypos.proxypos import config
        # Init printer
        ptype = config.get('printer.type').lower()
        settings = config.get('printer.settings')
        if ptype == 'usb':
            self.printer = printer.Usb(settings['idVendor'],
                                       settings['idProduct'])
        elif ptype == 'serial':
            self.printer = printer.Serial(settings['devfile'])
        elif ptype == 'network':
            self.printer = printer.Network(settings['host'])
        # Assign other default values
        self.printer.pxWidth = settings['pxWidth']
        # Set default widht with normal value
        self.printer.width = self.printer.widthA = settings['WidthA']
        self.printer.widthB = settings['WidthB']
        # Set correct table character
        if 'charSet' in settings:
            self.printer.text(settings['charSet'])
Exemplo n.º 13
0
    def printreceipt(self):
        """Print endpoint."""
        query = cherrypy.request.json

        vehicle = query.get("vehicle", "")
        v_str = self._get_vehicle_str(vehicle)
        plate = query.get("plate", "")
        helmets = query.get("helmets", 0)
        checkin = query.get("checkin", "")
        ci_str = self._format_date(checkin)
        complete = query.get("complete", False)
        fee = int(query.get("fee", 0))

        base_fee = int(query.get("base_fee", 0))
        additional_fee = int(query.get("additional_fee", 0))
        additional_hours = int(query.get("additional_hours", 0))
        total_additional_fee = int(query.get("total_additional_fee", 0))
        helmets_fee = int(query.get("helmets_fee", 0))

        p = printer.Usb(0x4b43, 0x3538, 0, 0x82, 0x02)
        p.set(align='center')

        p.text("\n")
        p.text("Parqueadero Alquim\n")
        p.text("NIT 31.945.821-9\n")
        p.text("Carrera 5 con Calle 16\n")
        p.text("Cali, Colombia\n\n")

        p.set(align='center', width=2, height=2)
        p.text(v_str + " " + plate + "\n")
        p.set(align='center', width=1, height=1)

        if helmets > 0:
            p.text("Cascos: " + str(helmets) + "\n")

        p.text("\nIngreso: " + ci_str + "\n")

        if complete:
            checkout = query.get("checkout", "")
            co_str = self._format_date(checkout)
            p.text("Salida:  " + co_str + "\n\n")

            p.set(align='left')
            p.text("Base: \t\t$" + str(base_fee) + "\n")
            p.text("Hora adicional (" + str(additional_hours) + "): \t\t$" +
                   str(total_additional_fee) + "\n")

            if helmets > 0:
                p.text("Accesorios: \t\t$" + str(helmets_fee) + "\n")

            p.text("\n")
            p.set(align='center', width=2, height=2)
            p.text("$" + str(fee))
            p.set(align='center', width=1, height=1)
        else:
            p.text("\n")
            p.set(align='left')
            p.text("Base: \t\t$" + str(base_fee) + "\n")
            p.text("Hora adicional: \t\t$" + str(additional_fee) + "\n")

            if helmets > 0:
                p.text("Accesorios (c/u): \t\t$" + str(helmets_fee) + "\n")

            p.text("\n")
            p.qr(plate, size=8)
            p.text("\n\n")
            p._raw(self.contract_message)

        p.cut()
        return "Ok"
Exemplo n.º 14
0
 def get_printer(self):
     """Create printer instance from configuration"""
     try:
         return printer.Usb(config.ID_VENDOR, config.ID_PRODUCT, 0, config.IN_EP, config.OUT_EP)
     except exceptions.Error:
         return None
Exemplo n.º 15
0
                Printer._raw(jptext(name + "\n\n\n"))
                Printer.image("/tmp/icon_resize.png", False, True,
                              'bitImageColumn')
                Printer.set(align="center", text_type="normal", height=1)
                Printer.text("\n\n\n\n")
                GPIO.output(17, 1)
        except KeyError:
            pass

    def on_error(self, status_code):
        print >> sys.stderr, 'Encountered error with status code:', status_code
        return True  # Don't kill the stream

    def on_timeout(self):
        print >> sys.stderr, 'Timeout...'
        return True  # Don't kill the stream


Printer = printer.Usb(0x08a6, 0x0041)

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)
#me = api.me()

stream = tweepy.streaming.Stream(auth, CustomStreamListener())
try:
    stream.userstream()
except (KeyboardInterrupt):
    print("exit.")
Exemplo n.º 16
0
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
from escpos import printer
from PIL import Image, ImageFont, ImageOps, ImageDraw
   
   

Epson = printer.Usb(0x0fe6,0x811e,0,0x82,0x02)
Epson.set(align='center')
font = ImageFont.truetype('/home/pi/queing-machine/Loma.ttf', 24)

Epson.image('/home/pi/queing-machine/logo.jpg', impl="bitImageRaster",fragment_height=1)
Epson.text("\n\n")
image = Image.new('RGB', (380, 320))
draw = ImageDraw.Draw(image)
# draw the text at the left edge of the box
draw.text((40, 0), "Hello World!", font=font)
image = ImageOps.invert(image)   # invert image to black on white
Epson.image(image,impl="bitImageRaster")      # output image to printer
Epson.text("\n\n\n")
Exemplo n.º 17
0
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""

from __future__ import absolute_import

__author__ = "Stephan Sokolow (deitarion/SSokolow)"
__license__ = "MIT"

import re

from escpos import printer
epson = printer.Usb(0x0416, 0x5011)
# TODO: Un-hardcode this

def _print_text_file(path):
    """Print the given text file"""
    epson.set(align='left')
    with open(path, 'rU') as fobj:
        for line in fobj:
            epson.text(line)

def _print_image_file(path):
    """Print the given image file."""
    epson.fullimage(path, histeq=False, width=384)

def print_files(args):
    """The 'print' subcommand"""
Exemplo n.º 18
0
 def __init__(self, vendorId, productId, profile, timeout=1000, width=43):
   threading.Thread.__init__(self)
   self.profile = profile
   self.width = width
   self.printer = printer.Usb(vendorId, productId, profile=profile, timeout=timeout)
   self.stop_flag = threading.Event()
Exemplo n.º 19
0
import json, os, random, datetime
from printer import Receipt
from escpos import printer

eps = printer.Usb(0x4b8, 0x0e03)
curdir = os.path.dirname(os.path.abspath(__file__))
jsnf = os.path.join(curdir, 'items.json')
jsn = open(jsnf)
items = json.load(jsn)
receipt = Receipt()
rno = str(random.randint(10000, 1000000))
opts = {
    'cname': 'MANGO & PEAR ENTERPRISE LTD DEALERS IN FRUITS',
    'clogo': 'uploads/clogo.png',
    'cinfo': '0243337978 / 0245836125',
    'cloc': 'KNUST, KUMASI',
    'rname': 'Sales Receipt',
    'rno': rno,
    'customer': 'YOU A YOU',
    'cashier': 'ME AM ME',
    'currency': 'GH CEDIS',
    'rdate': datetime.datetime.today().ctime(),
}
receipt.print_header(opts)
receipt.print_items(items)
receipt.print_message('THANKS FOR YOUR PATRONAGE')
receipt.print_vat('Amount is VAT INCLUSIVE')
receipt.print_me('Programmed by : SBKSoftwares Inc. : 0553339728')
# eps.text(receipt._receipt)
# eps.cut()
receipts_dir = os.path.join(curdir, 'receipts')
Exemplo n.º 20
0
#!/usr/bin/python
# -*- coding: UTF-8 -*-
from escpos import printer
#from escpos.printer import Usb

# use "system_profiler SPUSBDataType" to check on Mac OSX
#pp = printer.Usb(0x1a86, 0x7584, interface=0, in_ep=2, out_ep=2)
pp = printer.Usb(0x6868, 0x0600, 0, 0x04, 0x03)

# print Chinese
pp.codepage = 'gb2312'
pp.text(u'你好啊')
pp.text('Hello, world!')
pp.control('LF')  # flush
pp.cut('----')
Exemplo n.º 21
0
from escpos import printer
esc = printer.Usb(0x0416, 0x5011, in_ep=0x81, out_ep=0x03)


def pr(*msg):
    print(msg)
    #def foo():
    esc.set(align="center", custom_size=True, width=2, height=2)
    for m in msg:
        esc.block_text("{}\n".format(m), font="b", columns=16)
        esc.ln()
    esc.print_and_feed(2)


LBL = """
Soup Dec 2022
Foo

Bar
""".strip().split('\n')

print(LBL)

if __name__ == '__main__':
    pr(LBL)
#    pr('Chili', 'Sep 2022')
Exemplo n.º 22
0
    def post(self):
        data = create_request_parser([_id_arg]).parse_args()
        order = OrderModel.find_by_id(data['id'])
        if not order:
            return get_not_found_error('order')
        try:
            from escpos import printer
            from datetime import datetime

            p = printer.Usb(0x0483, 0x5743, 0, 0x81, 0x03)
            # header
            p.set(align="center", text_type="B", width=2)
            p.text("Di Sultano Shop\n\n")
            p.set(align="center")
            p.text("Borj.Tyr\n")
            p.text("Tel : 71516540\n")
            p.text(datetime.utcnow().strftime('%d/%b/%Y  %H:%M') + "\n")
            p.set(align="left", text_type="B")
            p.text(f"{'Take away':<9s}{order.customer_name:>39s}")
            p.text("\n")
            # table
            p.set(align="left")
            dash = '-' * 48
            p.text(dash)
            p.text('{:<25s}{:>3s}{:>10s}{:>10s}'.format(
                "Item", "Qty", "Price", "Tot"))
            p.text(dash)
            total_price = 0
            for detail in order.details:
                itemName = detail.product.name
                name = "sdf"
                if len(itemName) > 25:
                    itemName = '{:.<25}'.format(itemName[:22])
                quantity = detail.quantity
                price = "{:,.0f}".format(detail.detail_price)
                tot = "{:,.0f}".format(detail.quantity * detail.detail_price)
                total_price += detail.quantity * detail.detail_price
                p.text('{:<25s}{:>3d}{:>10s}{:>10s}'.format(
                    itemName, quantity, price, tot))

            p.text("\n")
            p.text("-" * 48)
            p.text("\n")

            #  footer
            p.set(align="right", text_type="B")
            p.text("Total Invoice :  {:,} L.L\n".format(total_price))
            p.set(text_type="A")
            p.text('\n')
            p.set(align="left")
            p.text("Served by : Darine Mustafa.\n")
            p.text("Thank you for choosing disultano.\n\n")
            p.set(width=2, align="center")
            p.text("Challenge Test.\n\n")
            p.set(text_type="A")
            p.set(align="right")
            p.text("Owner: Jalal hicham.\n")
            p.cut()
        except Exception as e:
            return get_internal_server_error()

        return {'message': "order printed"}
Exemplo n.º 23
0
from flask import Flask, jsonify
import pymysql
import datetime
from escpos import printer

# Initialising the printer
# Printer Configurations
p = printer.Usb(0x0456, 0x0808, 4, 0x81, 0x03)

app = Flask(__name__)

tasks = {'login': False}
time = {'start': '', 'end': ''}


# Apis
@app.route('/login', methods=['POST'])
def login():
    tasks = {'login': True}
    print(tasks)
    time['start'] = datetime.datetime.today().replace(microsecond=0)
    print(time)
    return jsonify({'task': tasks}), 201


@app.route('/logout', methods=['POST'])
def logout():
    tasks = {'login': False}
    print(tasks)
    time['end'] = datetime.datetime.today().replace(microsecond=0)
    x = datetime.datetime.now()