Skip to content

Instantly share code, notes, and snippets.

@rduplain
Created August 12, 2014 03:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rduplain/02e9beb0a0fcd2fb799a to your computer and use it in GitHub Desktop.
Save rduplain/02e9beb0a0fcd2fb799a to your computer and use it in GitHub Desktop.
Simple project to print text to Epson receipt.
# Print text to serial Epson printer. Escape codes are Epson ESC/POS.
#
# pip install pyserial jeni # Developed on Python 3.4.
import struct
import serial
from jeni import annotate, partial
from jeni import Injector
PORT = '/dev/ttyS0'
BAUDRATE = 19200
XONXOFF = True
LINEWIDTH = 42
ENCODING = 'ascii'
LINESCUT = 8
@annotate
def reset(ser: 'serial'):
return ser.write(b'\x1d@')
@annotate
def feed(linecount, ser: 'serial'):
return ser.write(b'\x1bd' + struct.pack('B', linecount))
@annotate
def cut(ser: 'serial'):
return ser.write(b'\x1dV\x00')
@annotate
def writetext(
text,
ser: 'serial',
reset: partial(reset),
feed: partial(feed),
cut: partial(cut),
encoding=ENCODING,
linescut=LINESCUT):
reset()
ser.write(text.encode(encoding))
feed(linescut)
cut()
def count_lines(text, width=LINEWIDTH):
return sum(_count_lines(text, width=width))
def _count_lines(text, width):
for line in text.splitlines():
if not line:
yield 1
else:
div, mod = divmod(len(line), width)
if div:
yield div
if mod:
yield 1
@Injector.factory('serial')
def serial_factory():
return serial.Serial(port=PORT, baudrate=BAUDRATE, xonxoff=XONXOFF)
if __name__ == '__main__':
import sys
injector = Injector()
injector.apply(writetext, sys.stdin.read())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment