You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

373 lines
13 KiB
Python

This file contains invisible Unicode characters!

This file contains invisible Unicode characters that may be processed differently from what appears below. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to reveal hidden characters.

# bureau
import configparser
import functools
import inspect
import json
import logging
import os.path
import subprocess
import tempfile
import textwrap
import threading
import time
import lmdb
import PIL
import zmq
from escpos import printer
from mako.template import Template
def update_commands(cls):
""" this is some internal magic to keep track of our commands """
for name, method in cls.__dict__.items():
print("name %s method %s" % (name, method))
if hasattr(method, "command"):
comstr = method.command
cls.commands[comstr] = method
return cls
def add_command(comstr, name=""):
""" decorator for making a method into a command """
def decorator(func):
""" the decorator itself """
@functools.wraps(func)
def func_wrap(*args, **kwargs):
""" this is to avoid roaching the namespace """
return func(*args, **kwargs)
func_wrap.command = comstr
func_wrap.name = name
return func_wrap
return decorator
def add_api(apistr, name=""):
""" decorator for making a method into a public bureau api method"""
def decorator(func):
""" the decorator itself """
@functools.wraps(func)
def func_wrap(*args, **kwargs):
""" this is to avoid roaching the namespace """
return func(*args, **kwargs)
func_wrap.api = apistr
func_wrap.name = name
return func_wrap
return decorator
class Bureau(object):
""" Bureau is a base class that implements standard methods for
inter-bureau communication, IO, registration and some convenient stuff
for printing. """
name = "TEST"
prefix = "00"
version = 0
default_config = {"smallprinter": "/dev/usb/lp0"}
def __init__(self):
""" set up ZeroMQ connections and register commands"""
self.commands = {}
self.api = {}
modpath = os.path.dirname(__file__)
xvfb = "xvfb-run"
slimerjs = os.path.join(modpath, "..", "lib", "slimerjs", "slimerjs")
renderer = os.path.join(modpath, "..", "slimerjs", "rasterize.js")
self.slimerjs = os.path.abspath(slimerjs)
self.html2pdf = xvfb + " " + self.slimerjs + " " + \
os.path.abspath(renderer) + " "
mypath = inspect.getfile(self.__class__)
self.mdir = os.path.dirname(mypath)
basepath = os.path.expanduser("~/.screenless")
if not os.path.exists(basepath):
os.mkdir(basepath)
os.chdir(basepath)
# setup log file
# TODO: make log level globally and bureau-specific via config
# TODO: custom handler to print errors to small printer
logfile = os.path.join(basepath, self.prefix + ".log")
logging.basicConfig(filename=logfile, level=logging.DEBUG)
self.log = logging.getLogger(self.prefix)
self.config = configparser.ConfigParser()
self.load_config()
# setup a dir to store files and data
self.datadir = os.path.join(basepath, self.prefix)
if not os.path.exists(self.datadir):
os.mkdir(self.datadir)
# set up a basic key-value store with LMDB - max 10 sub-dbs
# if a bureau needs more then just import lmdb and roll your own
dbfile = os.path.join(self.datadir, self.prefix + ".lmdb")
self.dbenv = lmdb.open(dbfile, max_dbs=10)
self.context = zmq.Context()
self._recv = self.context.socket(zmq.REP)
self._recv.bind("ipc://" + self.prefix + ".ipc")
self.log.debug("bureau " + self.name + " waiting for messages")
self.log.debug("commands: ")
self.log.debug(str(self.commands))
def load_config(self):
"""
load (or reload) config data from file
"""
cfgfile = self.prefix + ".ini"
if os.path.exists(cfgfile):
self.config.read(cfgfile)
else:
self.config["DEFAULT"] = self.default_config
self.config["bureau"] = self.default_config
with open(cfgfile, "w") as configfile:
self.config.write(configfile)
def send(self, recipient, message, data=None):
"""
send commands or API calls to another bureau.
recipient: the 2-character bureau ID
message: a text based message as used in many commands
data: an optional dict, used in API calls
returns either empty string, text or a json object
"""
# clean up for sloppy offices
message = message.strip()
if not message.endswith("."):
message += "."
if data:
message += json.dumps(data)
sender = self.context.socket(zmq.REQ)
sender.connect("ipc://" + recipient + ".ipc")
sender.send_string(message)
events = sender.poll(timeout=10000)
if events is not 0:
resp = sender.recv_string()
if len(resp) == 0:
return None
elif resp[0] == "0":
if len(resp) == 1:
return None
else:
return json.loads(resp[1:])
else:
# TODO: this may need some better error handling
return resp
else:
self.log.warning("message" + message +
" sent... timed out after 10 seconds.")
return None
def _publish_methods(self):
"""
this internal method registers all public commands and bureau API
methods. Inhuman Resources module can then display menus and docs.
"""
# register bureau with Inhuman Resources
bureau_detail = {"name": self.name, "prefix": self.prefix,
"desc": self.__doc__}
# slight hack to avoid messy self-reference and chicken-egg waiting
if self.prefix == "IR":
method = getattr(self, "add_bureau")
method(bureau_detail)
else:
self.send("IR", "addbureau", bureau_detail)
# find and store all published methods
for member in dir(self):
method = getattr(self, member)
# ignore anything that is not a method with command or api details
if not (callable(method) and (hasattr(method, "command") or
hasattr(method, "api"))):
continue
if hasattr(method, "command"):
self.commands[method.command] = method
cmd_detail = {"cmdname": method.name,
"prefix": self.prefix,
"cmd": method.command,
"desc": method.__doc__}
if self.prefix == "IR":
method = getattr(self, "add_cmd")
method(cmd_detail)
else:
self.send("IR", "addcommand", cmd_detail)
elif hasattr(method, "api"):
self.api[method.api] = method
api_detail = {"apiname": method.name,
"prefix": self.prefix,
"api": method.api,
"desc": method.__doc__}
if self.prefix == "IR":
method = getattr(self, "add_api_method")
method(api_detail)
else:
self.send("IR", "addapi", api_detail)
self.log.debug("registered:")
self.log.debug(str(self.commands))
self.log.debug(str(self.api))
def print_full(self, template, **kwargs):
"""print a full page (A4) document """
# TODO: look up the printer LPR name / allow multiple printers/non-default
# lpname = kwargs.get("printer", "default")
htmlfile, htmlpath = tempfile.mkstemp(".html")
htmlfile = os.fdopen(htmlfile, "w")
# run template with kwargs
templfile = os.path.join(self.mdir, template)
self.log.debug("printing with template: %s", templfile)
templ = Template(filename=templfile)
htmlfile.write(templ.render_unicode(**kwargs))
htmlfile.close()
#.encode('utf-8',
# 'replace'))
# texfile, texfilepath = tempfile.mkstemp(".tex")
# texfile.write(templ.render_unicode(
# **kwargs).encode('utf-8', 'replace'))
# texdir = os.path.dirname(texfilepath)
# subprocess.call("cd " + texdir + "; xelatex " + texfilepath)
# TODO: make paper size a config variable
pdfpath = tempfile.mkstemp(".pdf")[1]
self.log.debug("rendering with: " + self.html2pdf + htmlpath + " " + pdfpath)
subprocess.call(self.html2pdf + htmlpath + " " + pdfpath +
" A4 1920px", shell=True)
subprocess.call("lpr " + pdfpath, shell=True)
# TODO: make this asynchronous
def print_small(self, text, printer="/dev/usb/lp0"):
"""
print on Thermal Line printer.
"""
# TODO: look up device and width in config
# TODO: refactor this to use escpos library
lp = open(printer, "w")
text = textwrap.fill(text, width=32)
text += "\r\n" * 5
# text += ".d0"
lp.write(text)
lp.close()
def print_small_image(self, img):
"""
print an image on the mini thermal printer.
"""
# TODO: make printer id/width configured and easy
prn = printer.Usb(0x416, 0x5011)
im = PIL.Image.open(img)
# NOTE: might be worth tring to push up brightness
im = PIL.ImageOps.equalize(im) # stretch histogram for nicer dither
im.thumbnail((384, 384), PIL.Image.ANTIALIAS) # resize to fit printer
prn.image(im, impl="bitImageColumn") # not using this impl crashes ??
@add_command("test")
def test(self, data=None):
"""
Standard test command.
"""
# stupid test to see if modules work
print(("hi! testing. " + self.name + " bureau seems to work!"))
return "seems to work."
def run_io(self):
"""process hardware or timed input
This method can be ignored for most Bureaus.
It should be overloaded for any services that need to independently
generate messages as this is just a placeholder.
It is run in a separate thread and should handle any input or
timed events. Messages are then sent to other Bureaus via the
self.send connection to the OfficeManager. Don't forget to
to consier thread safety issues when accessing data!
"""
pass
def run(self):
"""
main loop for processing messages
This runs all relelvant event processing loops.
"""
# start the hardware input handler
io_handler = threading.Thread(target=self.run_io)
io_handler.start()
# register commands and api methods
self._publish_methods()
while True:
try:
msg = self._recv.recv_string(flags=zmq.NOBLOCK)
except zmq.ZMQError:
time.sleep(0.05) # don't waste CPU
continue
try:
self.log.debug("got message:" + msg)
dot = msg.find(".")
ref = msg[:dot]
if (dot < len(msg) - 1) and (dot > 0):
self.log.debug("msg length: %d", len(msg))
self.log.debug("dot at %d", dot)
# TODO: maybe trim off the trailing "." for convenience
data = msg[dot + 1:]
# data = str(data) # force to be a string
else:
data = None
self.log.debug("data: " + str(data))
except IndexError as err:
self.log.warning("invalid message: %s", err)
continue
self.log.debug("got method: " + ref)
if (ref in self.commands) or (ref in self.api):
# catch TypeErrors for case of bogus params
try:
if ref in self.api:
if data:
data = json.loads(data)
ret = json.dumps(self.api[ref](data))
else:
ret = json.dumps(self.api[ref]())
else:
if data:
ret = self.commands[ref](data)
else:
ret = self.commands[ref]()
if ret is None:
ret = ""
ret = "0" + ret
self._recv.send_string(ret)
#except TypeError as err:
# print(err)
# print("invalid data for command '{}': {}".format(ref, data))
# self._recv.send_unicode("Error. Invalid or missing data.")
except KeyError as err:
self.log.warning(str(err))
self.log.warning("You are calling a command as an API or vice-versa.")
self._recv.send_unicode(
"Error. Command called as API or API as command.")
else:
self.log.warning("error! Command/API %s not found", ref)
self._recv.send_unicode("Error! Command/API not found.")
def main():
buro = Bureau()
buro.run()
if __name__ == "__main__":
main()