diff --git a/render.py b/render.py index 3a3b555..2ede679 100644 --- a/render.py +++ b/render.py @@ -1,3 +1,4 @@ +import json import math import os import StringIO @@ -14,6 +15,7 @@ class App(flask.Flask): def __init__(self, *args, **kwargs): super(App, self).__init__(*args, **kwargs) self.last = 0 + self.health = (0, False, "unknown") app = App(__name__) @@ -70,6 +72,31 @@ class Renderer(object): def index(): return flask.render_template('index.html') +def healthcheck(): + last_checked, last_status, last_details = app.health + if time.time() - last_checked < 1: + return last_status, last_details + output = subprocess.check_output(['lpstat', '-p', '-d']) + mark = False + for line in output.split('\n'): + line = line.strip() + if line.startswith('printer DYMO_LabelWriter_450'): + mark = True + continue + if mark: + if line.startswith('Ready to print'): + app.health = (time.time(), True, line) + return True, line + else: + app.health = (time.time(), False, line) + return False, line + mark = False + +@app.route('/health') +def health(): + ok, details = healthcheck() + return json.dumps({'ok': ok, 'details': details}) + @app.route('/stuff/preview//') def stuff_preview(size): text = flask.request.args.get('text') @@ -84,6 +111,8 @@ def stuff_preview(size): DELAY = 5 @app.route('/stuff/print//', methods=['POST']) def stuff_print(size): + if not healthcheck()[0]: + return 'Printer is down.' last = app.last print last, time.time() - last if time.time() - last < DELAY: diff --git a/templates/index.html b/templates/index.html index 8d6291e..fe367c3 100644 --- a/templates/index.html +++ b/templates/index.html @@ -44,6 +44,7 @@ body {

Box 'o Stuff Label For SAMLA boxes with common equipment

@@ -114,6 +115,19 @@ $(document).ready(function() { print(); }); generatePreview(); + var updateStatus = function() { + $.getJSON("/health", function(data) { + if (data.ok) { + $("#systemstatus").attr("class", "label label-success"); + $("#systemstatus").html(data.details); + } else { + $("#systemstatus").attr("class", "label label-danger"); + $("#systemstatus").html(data.details); + } + }); + }; + updateStatus(); + setInterval(updateStatus, 1000); });