2020-08-31 23:36:47 +02:00
|
|
|
#! /usr/bin/env python
|
|
|
|
|
|
|
|
# python imports
|
2020-09-09 11:48:51 +02:00
|
|
|
import argparse
|
2020-08-31 23:36:47 +02:00
|
|
|
import logging
|
2020-09-09 17:09:38 +02:00
|
|
|
import math
|
2020-08-31 23:36:47 +02:00
|
|
|
import datetime
|
2020-09-09 17:09:38 +02:00
|
|
|
import os
|
2020-09-01 19:25:27 +02:00
|
|
|
import os.path
|
2021-08-11 12:48:42 +02:00
|
|
|
import sys
|
2020-08-31 23:36:47 +02:00
|
|
|
|
|
|
|
# 3rd party imports
|
2021-08-11 21:08:27 +02:00
|
|
|
from escpos.printer import Usb, File
|
2020-09-01 23:35:24 +02:00
|
|
|
import feedparser
|
2021-08-11 01:37:47 +02:00
|
|
|
import ignition
|
2020-09-09 17:09:38 +02:00
|
|
|
from PIL import Image
|
2020-09-01 23:35:24 +02:00
|
|
|
import re
|
|
|
|
import requests
|
2020-08-31 23:36:47 +02:00
|
|
|
|
2021-08-11 16:33:04 +02:00
|
|
|
from config import load_config, CONFIG_PATH
|
2020-08-31 23:36:47 +02:00
|
|
|
|
|
|
|
|
|
|
|
# Enable logging
|
|
|
|
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
|
|
|
level=logging.INFO)
|
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2021-08-11 16:33:04 +02:00
|
|
|
config = {}
|
|
|
|
|
2021-08-11 21:08:27 +02:00
|
|
|
genqr = False
|
|
|
|
|
2020-08-31 23:36:47 +02:00
|
|
|
|
|
|
|
def initialize():
|
|
|
|
"""
|
|
|
|
Initializes the printer and returns a printer object to
|
|
|
|
generate the print
|
|
|
|
"""
|
2021-08-11 16:33:04 +02:00
|
|
|
global config
|
|
|
|
config = load_config()
|
|
|
|
if not config:
|
2021-08-11 12:48:42 +02:00
|
|
|
print(f"Config file created, check {CONFIG_PATH}")
|
|
|
|
|
|
|
|
if os.path.exists(config.get("PRINTER_FILE")):
|
|
|
|
return File(config.get("PRINTER_FILE"))
|
|
|
|
|
2020-08-31 23:36:47 +02:00
|
|
|
printer_id = config.get("PRINTER_USB_ID")
|
|
|
|
|
|
|
|
if not printer_id:
|
|
|
|
logger.error("Please configure your printer")
|
|
|
|
|
|
|
|
prid1, prid2 = printer_id.split(":")
|
|
|
|
|
|
|
|
printer_interface = config.get("PRINTER_INTERFACE") or 0
|
|
|
|
printer_endpoint = config.get("PRINTER_ENDPOINT") or 0x01
|
|
|
|
|
2021-08-11 12:48:42 +02:00
|
|
|
return Usb(prid1, prid2, printer_interface, printer_endpoint)
|
2020-08-31 23:36:47 +02:00
|
|
|
|
|
|
|
|
|
|
|
def reset_defaults(printer):
|
|
|
|
"""
|
|
|
|
Reset the printer to the defaults
|
|
|
|
"""
|
2020-09-01 19:25:27 +02:00
|
|
|
printer.set(align='left', font='a', width=1, text_type="normal",
|
2020-08-31 23:36:47 +02:00
|
|
|
height=1, density=9, invert=False, smooth=False, flip=False)
|
|
|
|
|
|
|
|
|
2021-08-11 12:48:42 +02:00
|
|
|
def print_weather(printer, city=None):
|
2020-08-31 23:36:47 +02:00
|
|
|
reset_defaults(printer)
|
|
|
|
appkey = config.get("OWM")
|
|
|
|
if not appkey:
|
|
|
|
logger.error("Open Weather key not set!")
|
|
|
|
return
|
|
|
|
|
2021-08-11 12:48:42 +02:00
|
|
|
if not city:
|
|
|
|
city = config.get("CITY")
|
2020-08-31 23:36:47 +02:00
|
|
|
|
|
|
|
if not city:
|
|
|
|
logger.error("No city set")
|
|
|
|
|
|
|
|
params = {"q": city, "APPID": appkey, "units": "metric"}
|
|
|
|
|
|
|
|
weatherdata = requests.get('http://api.openweathermap.org/data/2.5/weather', params=params)
|
|
|
|
|
|
|
|
if "weather" in weatherdata.json():
|
|
|
|
weather = weatherdata.json()
|
|
|
|
today = datetime.datetime.now()
|
|
|
|
current_day = today.strftime("%a, %d %b, %Y")
|
|
|
|
|
|
|
|
printer.set(align="center",
|
2020-09-01 19:25:27 +02:00
|
|
|
font="a",
|
|
|
|
text_type="b")
|
2020-08-31 23:36:47 +02:00
|
|
|
printer.text(f"{current_day}\n\n{city}\n")
|
|
|
|
|
|
|
|
reset_defaults(printer)
|
|
|
|
printer.set(align="center", font="b")
|
|
|
|
|
|
|
|
description = weather['weather'][0]['description']
|
2020-09-01 19:25:27 +02:00
|
|
|
printer.text(f"{description}\n\n")
|
2020-08-31 23:36:47 +02:00
|
|
|
icon_code = weather['weather'][0]['icon']
|
2020-09-01 19:25:27 +02:00
|
|
|
|
2021-12-07 08:50:41 +01:00
|
|
|
dir_path = os.path.dirname(os.path.realpath(__file__)) # Get this file's current directory
|
|
|
|
|
|
|
|
if not os.path.exists(os.path.join(dir_path, "icons/weather")):
|
|
|
|
dir_path = "/usr/share/smallprint/icons/weather"
|
|
|
|
|
|
|
|
else:
|
|
|
|
dir_path = os.path.join(dir_path, "icons/weather")
|
|
|
|
|
|
|
|
if not os.path.exists(os.path.join(dir_path, f"{icon_code}.png")):
|
|
|
|
icon_path = os.path.join(dir_path, "any.png")
|
2020-09-01 19:25:27 +02:00
|
|
|
|
|
|
|
else:
|
2021-12-07 08:50:41 +01:00
|
|
|
icon_path = os.path.join(dir_path, f"{icon_code}.png")
|
2020-09-01 19:25:27 +02:00
|
|
|
|
2020-09-01 23:35:24 +02:00
|
|
|
# TODO: The image impl should be an option
|
2020-09-01 19:25:27 +02:00
|
|
|
printer.image(icon_path,
|
|
|
|
impl="bitImageColumn")
|
|
|
|
printer.text("\n")
|
2020-08-31 23:36:47 +02:00
|
|
|
# TODO: Print a nice icon based on the codes here: https://openweathermap.org/weather-conditions
|
|
|
|
temperature = weather['main']['temp']
|
|
|
|
humidity = weather['main']['humidity']
|
|
|
|
wind = weather['wind']['speed']
|
|
|
|
|
|
|
|
printer.text(f"Temperature: {temperature}C\n")
|
|
|
|
printer.text(f"Humidity: {humidity}%\n")
|
|
|
|
printer.text(f"Wind: {wind}km\\h\n")
|
|
|
|
|
|
|
|
else:
|
|
|
|
logger.error("No weather info available")
|
|
|
|
|
|
|
|
|
2021-08-11 01:37:47 +02:00
|
|
|
def print_gemini(printer, link):
|
|
|
|
"""
|
|
|
|
Given a Gemini link, it prints the file to the printer
|
|
|
|
and tries to do some interpretation if it is gemtext
|
|
|
|
"""
|
|
|
|
response = ignition.request(link)
|
|
|
|
|
|
|
|
if not response.success():
|
|
|
|
logger.error(f"Received error {response.status}")
|
|
|
|
return
|
|
|
|
|
|
|
|
reset_defaults(printer)
|
|
|
|
if response.meta == "text/gemini":
|
|
|
|
for raw_line in str(response.data()).split("\n"):
|
|
|
|
line = raw_line.rstrip()
|
|
|
|
if len(line) == 0:
|
|
|
|
printer.text("\n")
|
|
|
|
continue
|
|
|
|
|
|
|
|
if line.startswith("# "):
|
|
|
|
printer.set(align="left",
|
|
|
|
text_type="BU",
|
|
|
|
width=2, height=2,
|
|
|
|
smooth=True)
|
|
|
|
printer.text(line[2:])
|
|
|
|
|
|
|
|
elif line.startswith("## "):
|
|
|
|
printer.set(align="left",
|
|
|
|
text_type="BU",
|
|
|
|
width=1, height=1,
|
|
|
|
smooth=True)
|
|
|
|
printer.text(line[3:])
|
|
|
|
|
|
|
|
elif line.startswith("### "):
|
|
|
|
printer.set(align="left",
|
|
|
|
font="a",
|
|
|
|
text_type="U",
|
|
|
|
width=1, height=1,
|
|
|
|
smooth=True)
|
|
|
|
printer.text(line[4:])
|
|
|
|
|
|
|
|
elif line.startswith("#### "):
|
|
|
|
printer.set(align="left",
|
|
|
|
font="b",
|
|
|
|
text_type="U",
|
|
|
|
width=1, height=1,
|
|
|
|
smooth=True)
|
|
|
|
printer.text(line[5:])
|
|
|
|
|
|
|
|
elif line.startswith("=>"):
|
|
|
|
reset_defaults(printer)
|
2021-08-11 21:08:27 +02:00
|
|
|
if generate_qr:
|
|
|
|
printer.set(align="left",
|
|
|
|
font="b")
|
|
|
|
printer.text(line[3:])
|
|
|
|
reset_defaults(printer)
|
|
|
|
lnk = _process_link(link, line[3:])
|
|
|
|
printer.text("\n")
|
|
|
|
printer.qr(lnk, size=6)
|
|
|
|
|
|
|
|
else:
|
|
|
|
printer.set(align="left",
|
|
|
|
font="b",
|
|
|
|
text_type="U")
|
|
|
|
printer.text(line)
|
|
|
|
printer.text("\n")
|
2021-08-11 01:37:47 +02:00
|
|
|
|
|
|
|
else:
|
|
|
|
printer.set(align="left",
|
|
|
|
font="b")
|
|
|
|
printer.text(line)
|
|
|
|
|
|
|
|
printer.text("\n")
|
|
|
|
|
|
|
|
else:
|
|
|
|
printer.text(response.data())
|
|
|
|
|
|
|
|
|
|
|
|
def _process_link(orig_link, link_text):
|
|
|
|
"""
|
|
|
|
Extracts the link from the text, and completes it if
|
|
|
|
necessary
|
|
|
|
"""
|
|
|
|
uri = link_text.split()[0]
|
|
|
|
|
|
|
|
if "://" in link_text:
|
|
|
|
return uri
|
|
|
|
|
|
|
|
if link_text.startswith("/"):
|
|
|
|
return orig_link + link_text
|
|
|
|
|
|
|
|
else:
|
|
|
|
return orig_link + "/" + link_text
|
|
|
|
|
|
|
|
|
|
|
|
def print_rss(printer, link, news=3):
|
2020-09-01 23:35:24 +02:00
|
|
|
"""
|
|
|
|
Given an RSS link and a printer, prints the news from it
|
|
|
|
"""
|
|
|
|
reset_defaults(printer)
|
|
|
|
feed = feedparser.parse(link)
|
2021-12-07 08:50:41 +01:00
|
|
|
title = feed["channel"].get("title", link)[:16]
|
2020-09-01 23:35:24 +02:00
|
|
|
|
|
|
|
printer.set(align="center",
|
|
|
|
text_type="BU",
|
|
|
|
width=2, height=2,
|
|
|
|
smooth=True)
|
|
|
|
|
|
|
|
printer.text(f"{title}\n\n")
|
|
|
|
reset_defaults(printer)
|
|
|
|
items = feed["items"][:news]
|
|
|
|
for item in items:
|
|
|
|
_print_rss_item(item)
|
|
|
|
|
|
|
|
|
|
|
|
def _print_rss_item(item):
|
|
|
|
title = item["title"]
|
|
|
|
date = item["published"]
|
|
|
|
text = clear_html(item["summary"])
|
2021-12-07 08:50:41 +01:00
|
|
|
if len(text) > 255:
|
|
|
|
# Limit the text output in certain "summaries"
|
|
|
|
text = text[:252] + "...\n"
|
2020-09-01 23:35:24 +02:00
|
|
|
link = item["link"]
|
|
|
|
|
2021-12-07 08:50:41 +01:00
|
|
|
printer.set(align="center",
|
2020-09-01 23:35:24 +02:00
|
|
|
text_type="BU",
|
|
|
|
smooth=True)
|
|
|
|
printer.text(f"{title}\n")
|
|
|
|
reset_defaults(printer)
|
2021-12-07 08:50:41 +01:00
|
|
|
printer.set(align="left",
|
2020-09-01 23:35:24 +02:00
|
|
|
font="b")
|
|
|
|
printer.text(f"{date}\n\n")
|
|
|
|
printer.text(text)
|
|
|
|
printer.text("\n")
|
2021-08-11 21:08:27 +02:00
|
|
|
|
|
|
|
if generate_qr:
|
|
|
|
printer.qr(link, size=6)
|
|
|
|
printer.text("\n")
|
2020-09-01 23:35:24 +02:00
|
|
|
|
|
|
|
|
2020-09-09 11:48:51 +02:00
|
|
|
def print_text(printer, text):
|
|
|
|
"""
|
|
|
|
Prints a text in the smallest form possible
|
|
|
|
"""
|
|
|
|
reset_defaults(printer)
|
|
|
|
# Set the font to a small one and align to
|
|
|
|
# the left
|
|
|
|
printer.set(align="left",
|
|
|
|
text_type="NORMAL",
|
|
|
|
font="b",
|
|
|
|
smooth=True)
|
|
|
|
printer.text("\n")
|
2021-08-11 12:48:42 +02:00
|
|
|
if text.strip() == "-":
|
|
|
|
# Load stdin data
|
|
|
|
for line in sys.stdin:
|
|
|
|
printer.text(line)
|
|
|
|
|
2020-09-09 11:48:51 +02:00
|
|
|
printer.text(text)
|
|
|
|
|
|
|
|
|
|
|
|
def print_file(printer, file):
|
|
|
|
"""
|
|
|
|
Prints a file
|
|
|
|
"""
|
|
|
|
reset_defaults(printer)
|
|
|
|
# Set the font to a small one and align to
|
|
|
|
# the left
|
|
|
|
printer.set(align="left",
|
|
|
|
text_type="NORMAL",
|
|
|
|
font="b",
|
|
|
|
smooth=True)
|
|
|
|
|
|
|
|
printer.text("\n")
|
|
|
|
|
|
|
|
for line in file:
|
|
|
|
printer.text(line)
|
|
|
|
|
|
|
|
file.close()
|
|
|
|
|
|
|
|
|
2020-09-09 17:09:38 +02:00
|
|
|
def print_image(printer, image):
|
|
|
|
"""
|
|
|
|
Prints an image
|
|
|
|
"""
|
|
|
|
# Load the image to adjust it
|
|
|
|
im = Image.open(image)
|
|
|
|
|
|
|
|
ratio = float(im.size[0]) / float(im.size[1])
|
|
|
|
|
|
|
|
if im.size[0] > im.size[1]:
|
|
|
|
# The image needs to be rotated
|
|
|
|
width = math.floor(384 * ratio)
|
|
|
|
im = im.resize((width, 384))
|
|
|
|
im = im.transpose(Image.ROTATE_90)
|
|
|
|
|
|
|
|
else:
|
2020-09-09 20:57:00 +02:00
|
|
|
height = math.floor(384.0 / ratio)
|
2020-09-09 17:09:38 +02:00
|
|
|
im = im.resize((384, height))
|
|
|
|
|
|
|
|
im.save("temp.png")
|
|
|
|
printer.hw("INIT")
|
|
|
|
printer.image("temp.png")
|
|
|
|
os.remove("temp.png")
|
|
|
|
|
2020-09-09 11:48:51 +02:00
|
|
|
|
2021-12-07 08:50:41 +01:00
|
|
|
def printing_script(printer):
|
|
|
|
"""
|
|
|
|
Gets the configuration and parses its script
|
|
|
|
"""
|
|
|
|
script = config.get("SCRIPT")
|
|
|
|
|
|
|
|
if not script:
|
|
|
|
logger.error("No script in config file")
|
|
|
|
return
|
|
|
|
|
|
|
|
for command in script:
|
|
|
|
key = list(command)[0]
|
|
|
|
value = command[key]
|
|
|
|
if key == 'WEATHER':
|
|
|
|
print_weather(printer, city=value)
|
|
|
|
|
|
|
|
if key == 'RSS':
|
|
|
|
print_rss(printer, value)
|
|
|
|
|
|
|
|
if key == 'GEMINI':
|
|
|
|
print_gemini(printer, value)
|
|
|
|
|
|
|
|
if key == 'FILE':
|
|
|
|
print_file(printer, value)
|
|
|
|
|
|
|
|
if key == 'IMAGE':
|
|
|
|
print_image(printer, value)
|
|
|
|
|
|
|
|
if key == 'TEXT':
|
|
|
|
print_text(printer, value)
|
|
|
|
|
|
|
|
printer.set(align="center",
|
|
|
|
text_type="NORMAL",
|
|
|
|
font="b",
|
|
|
|
smooth=True)
|
|
|
|
printer.text("-----\n")
|
|
|
|
|
|
|
|
|
2020-09-01 23:35:24 +02:00
|
|
|
def clear_html(text):
|
|
|
|
cleanr = re.compile('<.*?>|&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-f]{1,6});')
|
|
|
|
cleantext = re.sub(cleanr, '', text)
|
|
|
|
return cleantext
|
|
|
|
|
|
|
|
|
2020-09-09 11:48:51 +02:00
|
|
|
def create_parser():
|
|
|
|
"""
|
|
|
|
Create an argpaser for command line interaction
|
|
|
|
"""
|
|
|
|
parser = argparse.ArgumentParser()
|
|
|
|
|
2021-08-11 21:08:27 +02:00
|
|
|
parser.add_argument("--weather", default=False, help="Prints the weather in the given city")
|
|
|
|
parser.add_argument("--news", default=False, help="Loads a RSS or ATOM feed and prints it out")
|
|
|
|
parser.add_argument("--gemini", default=False, help="Loads a Gemini url and prints it out")
|
|
|
|
parser.add_argument("--text", nargs=1, default=None, help="Print the given text, use '-' to read from stdin")
|
|
|
|
parser.add_argument("--file", default=None, type=open, help="Loads a file and sends it to the printer (as text)")
|
|
|
|
parser.add_argument("--image", nargs=1, default=None, help="Print an image")
|
|
|
|
parser.add_argument("--genqr", action="store_true", help="Activates the generation of QR codes for links in news and gemini")
|
2020-09-09 11:48:51 +02:00
|
|
|
|
|
|
|
return parser
|
|
|
|
|
|
|
|
|
2020-08-31 23:36:47 +02:00
|
|
|
if __name__ == "__main__":
|
|
|
|
printer = initialize()
|
2020-09-09 11:48:51 +02:00
|
|
|
|
|
|
|
parser = create_parser()
|
|
|
|
args = parser.parse_args()
|
|
|
|
|
2021-08-11 21:08:27 +02:00
|
|
|
generate_qr = args.genqr
|
|
|
|
|
2021-12-07 08:50:41 +01:00
|
|
|
ops_called = 0
|
|
|
|
|
2020-09-09 11:48:51 +02:00
|
|
|
if args.text:
|
2021-12-07 08:50:41 +01:00
|
|
|
ops_called += 1
|
2020-09-09 17:09:38 +02:00
|
|
|
print_text(printer, args.text[0])
|
2020-09-09 11:48:51 +02:00
|
|
|
printer.text("\n\n")
|
|
|
|
|
|
|
|
if args.file:
|
2021-12-07 08:50:41 +01:00
|
|
|
ops_called += 1
|
2020-09-09 11:48:51 +02:00
|
|
|
print_file(printer, args.file)
|
|
|
|
printer.text("\n\n")
|
|
|
|
|
|
|
|
if args.weather:
|
2021-12-07 08:50:41 +01:00
|
|
|
ops_called += 1
|
|
|
|
print_weather(printer, args.weather)
|
2020-09-09 11:48:51 +02:00
|
|
|
printer.text("\n\n")
|
|
|
|
|
2021-08-11 01:37:47 +02:00
|
|
|
if args.gemini:
|
2021-12-07 08:50:41 +01:00
|
|
|
ops_called += 1
|
2021-08-11 01:37:47 +02:00
|
|
|
print_gemini(printer, args.gemini)
|
2021-08-11 21:08:27 +02:00
|
|
|
printer.text("\n\n")
|
2021-08-11 01:37:47 +02:00
|
|
|
|
2020-09-09 11:48:51 +02:00
|
|
|
if args.news:
|
2021-12-07 08:50:41 +01:00
|
|
|
ops_called += 1
|
2021-08-11 01:37:47 +02:00
|
|
|
print_rss(printer, args.news)
|
2020-09-09 17:09:38 +02:00
|
|
|
|
|
|
|
if args.image:
|
2021-12-07 08:50:41 +01:00
|
|
|
ops_called += 1
|
2020-09-09 17:09:38 +02:00
|
|
|
print_image(printer, args.image[0])
|
|
|
|
printer.text("\n\n")
|
2021-12-07 08:50:41 +01:00
|
|
|
|
|
|
|
# In case we get called (almost) empty
|
|
|
|
if ops_called == 0:
|
|
|
|
# Try to parse a config script
|
|
|
|
printing_script(printer)
|
|
|
|
printer.text("\n\n")
|