def main(): p = argparse.ArgumentParser() p.add_argument('--posX', '-x', type=int, default=0, help="X position of the start of the text") p.add_argument('--posY', '-y', type=int, default=0, help="Y position of the start of the text") p.add_argument('--fsize', '-s',type=int , default=12, help="Font size to use for the text") p.add_argument('--rotation', '-r',type=int , default=0, help="Rotation one of 0, 90, 180, 270") p.add_argument('--invert', '-i', type=bool, default=False, help="Invert the display of the text") args = p.parse_args() args.content = "at some point I will figure out why this is a required variable but until then I'll just nail it up like this" with open('trains.xml') as fd: doc = xmltodict.parse(fd.read(), xml_attribs=True) iterCount = 0 numDisplayed = 0 if args.content: for iterCount in range(30): dest = doc['ActueleVertrekTijden']['VertrekkendeTrein'][iterCount]['EindBestemming'] time = doc['ActueleVertrekTijden']['VertrekkendeTrein'][iterCount]['VertrekTijd'] plat = doc['ActueleVertrekTijden']['VertrekkendeTrein'][iterCount]['VertrekSpoor']['#text'] spc = " " print(dest + spc + time[11:16] + spc + plat) if (dest == "Enkhuizen" and numDisplayed <= 1) or (dest == "Breda" and numDisplayed <= 1): if dest == "Den Helder": dest = "HDR" elif dest == "Schagen": dest = "SGN" if numDisplayed == 0: # Xpos = 0 # Ypos = 0 disp = dest + spc + time[11:16] + spc + "Spoor " + plat elif numDisplayed == 1: # Xpos = 25 # Ypos = 25 disp2 = dest + spc + time[11:16] + spc + "Spoor " + plat numDisplayed += 1 dest = str(dest) # text = PapirusTextPos(False, rotation=args.rotation) #text = PapirusTextPos(rotation=args.rotation) # text.partial_update() # text.AddText(disp, args.posX, args.posY, args.fsize, invert=args.invert) text = PapirusTextPos(False, rotation=args.rotation) text.AddText("Vertrek van de treinen\n\n", 10, 0, 13, Id="Header") text.AddText(disp, 0, 20, 18, Id="opt1") try: disp2 except NameError: disp2_exists = False else: disp2_exists = True if disp2_exists == True: text.AddText(disp2, 0, 40, 18, Id="opt2") if numDisplayed == 0: text = PapirusTextPos(False, rotation=args.rotation) text.AddText("Vertrek van de treinen\n\n", 10, 0, 13, Id="Header") text.AddText("Apparently there are no trains.", 0, 35, 18, Id="errtxt") text.WriteAll()
class Item_List(): items = [] text = PapirusTextPos(False) items_per_screen = 0 selected = 0 bottom_window = 2 def __init__(self, items, items_per_screen=3): self.items = items self.items_per_screen = items_per_screen self.draw_text() def draw_text(self): if self.selected > bottom_window: self.bottom_window += 1 elif self.selected < bottom_window - 2: self.bottom_window -= 1 def redraw_text(self, oldID, newID): self.text.UpdateText(oldID, self.items[oldID]) self.text.UpdateText(newID, u"\u003E"+self.items[newID]) self.text.WriteAll() def select_up(self): old = self.selected if self.selected > 0: self.selected = self.selected - 1 self.redraw_text(old, self.selected) def select_down(self): old = self.selected if self.selected < len(self.items): self.selected = self.selected + 1 self.redraw_text(old, self.selected)
def main(): p = argparse.ArgumentParser() p.add_argument('--posX', '-x', type=int, default=0, help="X position of the start of the text") p.add_argument('--posY', '-y', type=int, default=0, help="Y position of the start of the text") p.add_argument('--fsize', '-s', type=int, default=20, help="Font size to use for the text") p.add_argument('--rotation', '-r', type=int, default=0, help="Rotation one of 0, 90, 180, 270") p.add_argument('--invert', '-i', type=bool, default=False, help="Invert the display of the text") args = p.parse_args() args.content = "at some point I will figure out why this is a required variable but until then I'll just nail it up like this" with open('trains.xml') as fd: doc = xmltodict.parse(fd.read(), xml_attribs=True) iterCount = 0 numDisplayed = 0 if args.content: for iterCount in range(30): dest = doc['ActueleVertrekTijden']['VertrekkendeTrein'][ iterCount]['EindBestemming'] time = doc['ActueleVertrekTijden']['VertrekkendeTrein'][ iterCount]['VertrekTijd'] plat = doc['ActueleVertrekTijden']['VertrekkendeTrein'][ iterCount]['VertrekSpoor']['#text'] if (dest == u"Den Helder" and numDisplayed <= 1) or (dest == u"Schagen" and numDisplayed <= 1): numDisplayed += 1 disp = dest + " || " + time[ 11:16] + " || " + "Platform " + plat dest = str(dest) text = PapirusTextPos(rotation=args.rotation) text.AddText(disp, args.posX, args.posY, args.fsize, invert=args.invert)
def handle(self): page = PapirusTextPos(False) line = self.rfile.readline() while line != b'': log("line: " + repr(line)) op = json.loads(line.decode('utf-8')) #import pdb; pdb.set_trace() self.invokeop(page, op) line = self.rfile.readline() log("finished with connection")
def main(): p = argparse.ArgumentParser() # p.add_argument('--posX', '-x', type=int, default=0, help="X position of the start of the text") # p.add_argument('--posY', '-y', type=int, default=0, help="Y position of the start of the text") p.add_argument('--fsize', '-s', type=int, default=11, help="Font size to use for the text") p.add_argument('--rotation', '-r', type=int, default=0, help="Rotation one of 0, 90, 180, 270") p.add_argument('--invert', '-i', type=bool, default=False, help="Invert the display of the text") args = p.parse_args() args.content = "just f**k off" with open('trains.xml') as fd: doc = xmltodict.parse(fd.read(), xml_attribs=True) iterCount = 0 numDisplayed = 0 if args.content: for iterCount in range(30): dest = doc['ActueleVertrekTijden']['VertrekkendeTrein'][ iterCount]['EindBestemming'] time = doc['ActueleVertrekTijden']['VertrekkendeTrein'][ iterCount]['VertrekTijd'] plat = doc['ActueleVertrekTijden']['VertrekkendeTrein'][ iterCount]['VertrekSpoor']['#text'] spaces = " || " if (dest == u"Den Helder" and numDisplayed <= 1) or (dest == u"Schagen" and numDisplayed <= 1): numDisplayed += 1 ## print dest, " || ", time[11:16], " || ", "Platform ", plat disp = dest + " || " + time[ 11:16] + " || " + "Platform " + plat text = PapirusTextPos(rotation=args.rotation) text.AddText(disp, args.posX, args.posY, args.fsize, invert=args.invert)
def __init__(self): self.papi = PapirusTextPos(False) self.papi.Clear() self.papi.AddText("DATE:", 0, 0, Id="datetext") self.papi.AddText("00-00 00:00", 60, 0, Id="date-time") self.papi.AddText("TEMP:", 0, 20, Id="temptext") self.papi.AddText("00.000", 60, 20, Id="temp") self.papi.AddText("HUME:", 0, 40, Id="humtext") self.papi.AddText("00.000", 60, 40, Id="hum") self.papi.AddText("PRES:", 0, 60, Id="presstxt") self.papi.AddText("0000", 60, 60, Id="press") self.papi.AddText("Initializing", 0, 80, Id="ip") self.papi.WriteAll()
def __init__(self, rotation=0): self.text = PapirusTextPos(False, rotation=rotation) self.text.AddText("", x=0, y=5, size=36, Id="title", font_path=sans_font) self.text.AddText("", x=7, y=55, size=16, Id="body", font_path=sans_font) self.text.AddText("", x=7, y=75, size=16, Id="footer", font_path=sans_font)
#Python LED Web Handler import socket from flask import Flask, render_template from flask_jsonpify import jsonify from flask_restful import Api, Resource from papirus import PapirusTextPos rot = 90 papirus_text = PapirusTextPos(False, rotation=rot) ipAddr = socket.gethostname() lines = [ipAddr, "", "", "", "", "", "", "", ""] ids = ["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"] app = Flask(__name__) api = Api(app) class set_text(Resource): def get(self, index, text): print("Index: " + index) print("Text: " + text) offset = int(index) - 1 print("offset: {}".format(offset)) print("Testing: " + lines[0]) lines[offset] = text print("Text: " + lines[offset]) return jsonify({'data': lines}) class clear_text(Resource):
def main(): logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') ch.setFormatter(formatter) logger.addHandler(ch) if os.path.exists(r"/home/mikey/logs/watch.log"): fh = logging.FileHandler(filename=r"/home/mikey/logs/watch.log") fh.setLevel(logging.DEBUG) fh.setFormatter(formatter) logger.addHandler(fh) my_511_token = sys.argv[1] # giving time for device service to startup, which is needed before init of Papirus time.sleep(20) try: global key # Running as root only needed for older Raspbians without /dev/gpiomem if not (os.path.exists('/dev/gpiomem') and os.access('/dev/gpiomem', os.R_OK | os.W_OK)): user = os.getuid() if user != 0: print('Please run script as root') sys.exit() shutdown_button = Button(SW1, pull_up=False) north_transit_button = Button(SW2, pull_up=False) south_transit_button = Button(SW3, pull_up=False) weather_button = Button(SW4, pull_up=False) button5 = Button(SW5, pull_up=False) font_path = "/home/mikey/nasalization-rg.ttf" text_size = 60 text = PapirusTextPos(rotation=0) text.Clear() old_time = datetime.datetime.now().strftime("%H:%M") text.AddText(old_time, size=text_size, fontPath=font_path) logger.info("Entering watch loop") while True: # Define button press action (Note: inverted logic w.r.t. gpiozero) shutdown_button.when_released = setkey north_transit_button.when_released = setkey south_transit_button.when_released = setkey weather_button.when_released = setkey button5.when_released = setkey # check key key = getkey() if key == 'none': new_time = datetime.datetime.now().strftime("%H:%M") if old_time == new_time: time.sleep(1) continue text.Clear() text.AddText(new_time, size=text_size, fontPath=font_path) old_time = new_time time.sleep(.3) elif key == "shutdown": logger.info("shutting down") text.Clear() text.AddText("Bye :)", size=text_size, fontPath=font_path) time.sleep(2) shutdown_path = __file__.split("/")[:-1] shutdown_path = "/".join(shutdown_path) # if started script manually, from the scripts directory, will see blank path to file if shutdown_path == "": shutdown_path = "." subprocess.Popen( ['sudo', '{}/shutdown.sh'.format(shutdown_path)]) sys.exit() elif key == "n_transit": logger.info("getting n_transit") n_transit = get_northbound_arrivals(my_511_token=my_511_token) display_arivals(text, n_transit, logger, font_path) key = 'none' old_time = "fake time" elif key == "s_transit": logger.info("getting s_transit") s_transit = get_southbound_arrivals(my_511_token) display_arivals(text, s_transit, logger, font_path) key = 'none' old_time = "fake time" elif key == "weather": logger.info("getting weather") weather = get_sf_weather() text.Clear() text.AddText(weather, size=15, fontPath=font_path) time.sleep(7) key = 'none' old_time = "fake time" elif key == "button5": logger.info("button 5 pressed") key = 'none' except KeyboardInterrupt as e: logger.exception("keyboard interupt caught", exc_info=e) except Exception as e: logger.info("exception occured") logger.exception("Exception occured", exc_info=e)
#!/usr/bin/env python3 from netifaces import interfaces, ifaddresses, AF_INET from papirus import PapirusTextPos from datetime import datetime import subprocess import socket import re import time console_display = False inv = False text = PapirusTextPos(False, 0) text.Clear() text.autoUpdate = False text.partialUpdates = True font_size = 15 vert_spacing = font_size + 1 cur_time = datetime.now() text_time = cur_time.strftime('%Y/%m/%d %I:%M:%S') disp_text = "web - http://secure.pi" if console_display: print(disp_text) text.AddText(disp_text, 0, vert_spacing * 0, font_size, Id="web") disp_text = "wifi- " if console_display: print(disp_text) text.AddText(disp_text, 0, vert_spacing * 1, font_size, Id="wifi") disp_text = "wlan- " if console_display: print(disp_text) text.AddText(disp_text, 0, vert_spacing * 2, font_size, Id="wlan0") disp_text = "wan - " if console_display: print(disp_text) text.AddText(disp_text, 0, vert_spacing * 3, font_size, Id="Pub") disp_text = "VPN is "
from twython import Twython, TwythonError import time import random from random import randint from random import choice from time import sleep from papirus import Papirus from papirus import PapirusText from papirus import PapirusTextPos #configure papirus text = PapirusTextPos(rotation=0) screen = Papirus(rotation=0) #Authorise APP_KEY = 'hwtNGXTnCAjeUOgRveksZdESX' APP_SECRET = '1YrUz3JLLD86AtwPorc4PVh1MZBUptrOnLEIeL4SWjjh1zMtma' OAUTH_TOKEN = '20427648-Xx2mqMa0ANvyVheg8xagsrgh6sm3LtEuKUxuSylfR' OAUTH_TOKEN_SECRET = 'KYoMPhcvq7iMOf0i9Y8p2TwDnyLbcCrPB78SNd9jRf51v' #Prepare your twitter, you will need it for everything twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) #The above should just be a single line, without the break #keywords for search query q naughty_words = [ " -RT", "MAGA", "Brexit", "Trump", "xxx", "p**n", "gay", "tory", "labour", "conservative", "brexit", "russia" ] good_words = ["solarpv", "arduino", "ceramics", "raspberrypi"] filter = " OR ".join(good_words)
#!/usr/bin/env python from papirus import PapirusTextPos papi = PapirusTextPos() papi.AddText("00-00 00:00", 0, 0, Id="date-time") papi.AddText("00.000", 0, 20, Id="temp") #papi.Add papi.UpdateText("Start", "New Text")
GPIO.setup(SW3, GPIO.IN) GPIO.setup(SW4, GPIO.IN) # Populate your twitter API details below, replacing # CONSUMER_KEY_HERE etc with your details from Twitter consumer_key = '*******************' consumer_secret = '*******************' access_token_key = '********************' access_token_secret = '*******************' api = twitter.Api(consumer_key=consumer_key, consumer_secret=consumer_secret, access_token_key=access_token_key, access_token_secret=access_token_secret) tweet_index = 0 text = PapirusTextPos(False, rotation=0) statuses = api.GetHomeTimeline(count=20) def home_timeline(Home): name = statuses[tweet_index].user.screen_name status = statuses[tweet_index].text return status, name def next_tweet(): status, name = home_timeline(sys.argv[1] if len(sys.argv) > 1 else 0) twitter_name = "@" + name text.UpdateText("start", twitter_name) text.UpdateText("tweet", status)
import datetime from datetime import date, timedelta from darksky import forecast import textwrap # set lat/long for location LOCATION = 37.5396,127.0097 #put your longitude and latittude here in decimal degrees UNITS = 'auto' #specify the units you want your results in here, see the Dark Sky API docs page for details # set Darksky API Key APIKEY= 'xxxxx' # put your Dark Sky API key here. Get one at https://darksky.net/dev # For PaPiRus screen = Papirus() text = PapirusTextPos(True) # tempFont = ImageFont.truetype('fonts/Aller_Bd.ttf', 22) # dayFont = ImageFont.truetype('fonts/Roboto-Black.ttf', 18) # dateFont = ImageFont.truetype('fonts/Roboto-Bold.ttf', 14) # font = ImageFont.truetype('fonts/ElecSign.ttf', 10) # smallFont = ImageFont.truetype('fonts/ElecSign.ttf', 8) # smallestFont = ImageFont.truetype('fonts/ElecSign.ttf', 7) def display(): with forecast (APIKEY, *LOCATION, units=UNITS) as location: # today currentTemp = location['currently']['temperature'] upcoming_conditions = location['currently']['summary'] relativeHumidity = location['currently']['humidity'] daily_conditions = location['daily']['data'][0]['summary']
def main(): p = argparse.ArgumentParser() p.add_argument('--posX', '-x', type=int, default=0, help="X position of the start of the text") p.add_argument('--posY', '-y', type=int, default=0, help="Y position of the start of the text") p.add_argument('--fsize', '-s', type=int, default=12, help="Font size to use for the text") p.add_argument('--rotation', '-r', type=int, default=0, help="Rotation one of 0, 90, 180, 270") p.add_argument('--invert', '-i', type=bool, default=False, help="Invert the display of the text") args = p.parse_args() args.content = "at some point I will figure out why this is a required variable but until then I'll just nail it up like this" with open('oldtrains.xml') as fd: doc = xmltodict.parse(fd.read(), xml_attribs=True) iterCount = 0 numDisplayed = 0 if args.content: for iterCount in range(30): text = PapirusTextPos(False, rotation=args.rotation) text.AddText("Vertrek van de treinen\n\n", 10, 0, 13, Id="Header") dest = doc['ActueleVertrekTijden']['VertrekkendeTrein'][ iterCount]['EindBestemming'] time = doc['ActueleVertrekTijden']['VertrekkendeTrein'][ iterCount]['VertrekTijd'] plat = doc['ActueleVertrekTijden']['VertrekkendeTrein'][ iterCount]['VertrekSpoor']['#text'] spc = " " print(dest + spc + time[11:16] + spc + plat) if (dest == "Den Helder" and numDisplayed <= 1) or (dest == "Schagen" and numDisplayed <= 1): if dest == "Den Helder": dest = "HLD" print("YUP, " + dest + "!") elif dest == "Schagen": dest = "SGN" print(dest + ", YEEHA!") if numDisplayed == 0: print("numDisplayed == 0") disp = dest + spc + time[11:16] + spc + "Spoor " + plat elif numDisplayed == 1: print("numDisplayed == 1") disp2 = dest + spc + time[11:16] + spc + "Spoor " + plat elif numDisplayed == 2: disp3 = dest + spc + time[11:16] + spc + "Spoor " + plat print("incrementing numDisplayed from ") print(numDisplayed) print(" to ") numDisplayed += 1 print(numDisplayed) print("adding 1st dest to screen buffer") text.AddText(disp, 0, 25, 18, Id="opt1") try: disp2 except NameError: disp2_exists = False else: disp2_exists = True if disp2_exists == True: print("adding 2nd dest to screen buffer") text.AddText(disp2, 0, 50, 18, Id="opt2") try: disp3 except NameError: disp3_exists = False else: disp3_exists = True if disp3_exists == True: text.AddText(disp3, 0, 75, 18, Id="opt3") if numDisplayed == 0: text.AddText("Apparently there are no trains.", 0, 35, 18, Id="errtxt") print("writing buffer to screen") text.WriteAll()
humid_in = str(inside['Humidity']) humid_out = str(outside['Humidity']) # Put together strings inside = house_icon + temp_in + degree_icon + arrow(temp_in_trend) outside = sun_icon + temp_out + degree_icon + arrow(temp_out_trend) meter = pressure + "Hg" + arrow(pressure_trend) inside_more = co2 + " ppm" + "\n" + noise + " db" outside_more = min_temp + degree_icon + "lo" + "\n" + max_temp + degree_icon + "hi" meter_more = humid_in + "% in" + "\n" + humid_out + "% out" font_path = "../FiraMono-Regular.ttf" # Write to the screen text = PapirusTextPos(0) text.AddText(inside, 0, -3, largefont, Id="inside", fontPath=font_path) text.AddText(outside, 0, 30, largefont, Id="outside", fontPath=font_path) text.AddText(meter, 0, 63, largefont, Id="meter", fontPath=font_path) text.AddText(inside_more, 135, 0, smallfont, Id="inside_more", fontPath=font_path) text.AddText(outside_more, 135, 33, smallfont, Id="outside_more",
def handle_data(self, data): # Take the contents of the first <pre> section. if not self.is_pre: return if self.pre_data is None: self.pre_data = data elif data.rstrip(): print("Warn: found multiple non-empty <pre> sections") def error(self, message): print("Parsing error: {}".format(message)) exit(1) if __name__ == "__main__": try: main() except Exception as e: # Display abnormal errors, but not SystemExit or KeyboardInterrupt. # TODO: how to get config from here? text = PapirusTextPos(autoUpdate=False, rotation=180) text.AddText("Error {} {}: {}".format( datetime.datetime.now().strftime("%Y-%m-%d %I:%M %p"), type(e).__name__, e, )) text.WriteAll(partialUpdate=True) raise
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # SPDX-License-Identifier: MIT import pihole as ph from papirus import PapirusTextPos import configparser # set up text writer text = PapirusTextPos(autoUpdate=False) fontPath = '/usr/share/fonts/opentype/b612/B612-Regular.otf' # authenticate with the given password config = configparser.ConfigParser() config.read('secrets.ini') pihole = ph.PiHole('localhost') pihole.authenticate(config['pihole']['password']) # get top 5 sites pihole.refresh() pihole.refreshTop(5) # display counts ads = pihole.top_ads msg = [] for host in ads.keys(): msg.append(f'{ads[host]:4d} {host}') text.AddText('\n'.join(msg),size=10,fontPath=fontPath) text.WriteAll()
def main(): p = argparse.ArgumentParser() p.add_argument('--posX', '-x', type=int, default=0, help="X position of the start of the text") p.add_argument('--posY', '-y', type=int, default=0, help="Y position of the start of the text") p.add_argument('--fsize', '-s', type=int, default=12, help="Font size to use for the text") p.add_argument('--rotation', '-r', type=int, default=0, help="Rotation one of 0, 90, 180, 270") p.add_argument('--invert', '-i', type=bool, default=False, help="Invert the display of the text") args = p.parse_args() args.content = " " with open('/tmp/trains.xml') as fd: doc = xmltodict.parse(fd.read(), xml_attribs=True) iterCount = 0 numDisplayed = 0 ## CONFIGURABLE ITEM ## Depending on the time of day, and the size of your station, there will ## be a varying number of results returned in the 'trains.xml' file. If ## range(VALUE) exceeds the number of results contained in the file, the ## script will die. I realize that this sucks, and I will work on fixing ## it. For now, set the range(VALUE) to something that works for you. ## 30 seems to be safe for Amsterdam Centraal most of the time. #for iterCount in range(0, len(doc), not_fucked_up=True, dont_always_return_1=True): if args.content: for iterCount in range(30): ## I'm only grabbing the end station, departure time, and ## departure platform at start station to display. ## There are more things you can retrieve-- paw through trains.xml ## +read xmltodict docs to understand how to retrieve them. ## I found this page useful: ## http://omz-software.com/pythonista/docs/ios/xmltodict.html dest = doc['ActueleVertrekTijden']['VertrekkendeTrein'][ iterCount]['EindBestemming'] time = doc['ActueleVertrekTijden']['VertrekkendeTrein'][ iterCount]['VertrekTijd'] plat = doc['ActueleVertrekTijden']['VertrekkendeTrein'][ iterCount]['VertrekSpoor']['#text'] spc = " " print(dest + spc + time[11:16] + spc + plat) ## print each row on CLI ## CONFIGURABLE ITEM ## Currently the script outputs the next four trains matching your ## destination. Reduce the max value on both below checks of ## numDisplayed to get fewer results. if (dest == destStation1 and numDisplayed <= 3) or (dest == destStation2 and numDisplayed <= 3): ## Shortening names to 3-letter codes to fit screen. ## I *may* automate and elegantize this later. if dest == "Schagen": dest = "SGN" print("!! HIT") ## flagging matches on CLI for debug elif dest == "Den Helder": dest = "HLD" print("!! HIT") ## flagging matches on CLI for debug ## save each extracted row to its own variable because ## I can't quite grasp how to do this better. if numDisplayed == 0: ## chars [11:16] is where the time lives. ## the raw var contains e.g. ## 2017-07-01T21:07:00+0200 disp = dest + spc + time[11:16] + spc + "Spoor " + plat elif numDisplayed == 1: disp2 = dest + spc + time[11:16] + spc + "Spoor " + plat elif numDisplayed == 2: disp3 = dest + spc + time[11:16] + spc + "Spoor " + plat elif numDisplayed == 3: disp4 = dest + spc + time[11:16] + spc + "Spoor " + plat numDisplayed += 1 # dest = str(dest) #initialize screen buffer var "text" without displaying anything text = PapirusTextPos(False, rotation=args.rotation) #Append the first bit of text to the screen buffer, top centered. #X position 12, Y position 0, font size 13, Id="Header" #text.AddText("Text", Xpos, Xpos, fontSize, Id="freeformElementID") text.AddText("Vertrek van de treinen", 12, 0, 13, Id="Header") text.AddText(disp, 0, 19, 18, Id="opt1") ## The next three stanzas are merely an attempt to gracefully ## handle fewer than the maximum allowed number of results. ## The results, if they exist, are presented roughly centered ## in a stack starting from the top, as you can see from the ## increasing Y values in text.AddText. try: disp2 except NameError: disp2_exists = False else: disp2_exists = True if disp2_exists == True: text.AddText(disp2, 0, 39, 18, Id="opt2") try: disp3 except NameError: disp3_exists = False else: disp3_exists = True if disp3_exists == True: text.AddText(disp3, 0, 59, 18, Id="opt3") try: disp4 except NameError: disp4_exists = False else: disp4_exists = True if disp4_exists == True: text.AddText(disp3, 0, 79, 18, Id="opt4") ## Exception handling. If we got all the way here and there was ## nothing to display, print something on the screen and the CLI ## to alert the user. if numDisplayed == 0: print( "\nNo hits for configured stations. Assuming disruption. Exception handler goes here." ) text = PapirusTextPos(False, rotation=args.rotation) text.AddText("Vertrek van de treinen\n\n", 10, 0, 13, Id="Header") ## this is the small Choo-Choo #404 from above, appearing ## shortly on your PaPiRus :) text.AddText(train6, 87, 15, 13, Id="train6") text.AddText(train7, 28, 27, 13, Id="train7") text.AddText(train8, 20, 40, 13, Id="train8") text.AddText(train9, 15, 53, 13, Id="train9") # text.AddText("Apparently there", 15, 35, 18, Id="errtxt1") # text.AddText("are no trains.", 25, 55, 18, Id="errtxt2") text.AddText("Apparently there are no trains", 8, 80, 10, Id="errtxt") ## And here's another Choo-Choo #404 to keep your terminal company print(train1) print(train2) print(train3) print(train4) print(train5 + "\n") ## Finally, the grand finale! Up until now, every text.AddText() ## operation was merely adding data to the buffer for the screen, ## not actually displaying it. text.WriteAll() dumps everything ## to the screen all at once, as befits an ePaper display. We ## only have to call this once per run of the entire script, # which is why it's at the end. d3rp. text.WriteAll()
fonaLock.release() lasttxt = result papi.UpdateText("result", result) #papi.WriteAll() #papi.write(result) papi.papirus.display(papi.image) papi.papirus.partial_update() fonaLock = threading.Lock() #start serial connection to fona fona = Serial('/dev/ttyUSB0', timeout=1) lasttxt = "" #papi = PapirusTextPos(False) #connect to papirus screen papi = PapirusTextPos(False) papi.AddText("", 0, 25, Id="result") papi.AddText("", 0, 75, Id="bat") papi.AddText("", 125, 75, Id="weather") papi.AddText("", 50, 75, Id="time") #menu options papi.AddText("Last", 20, 0, Id="SW5", size=12) papi.AddText("Wthr", 60, 0, Id="SW4", size=12) papi.AddText("SW3", 90, 0, Id="SW3", size=12) papi.AddText("Away", 120, 0, Id="SW2", size=12) papi.AddText("Here", 160, 0, Id="SW1", size=12) #setup switches on pins GPIO.setmode(GPIO.BCM) for switch in SW: GPIO.setup(switch, GPIO.IN)
# Note: As of today, the hat needed for the PaPirus is not compatible with # the GrovePi+ hat. Both work independently. You may choose to use either # one depending on your project. Further compatibility may come... #!/usr/bin/env python from papirus import PapirusTextPos import sys text = PapirusTextPos() text.AddText( sys.argv[1], Id="Top", font_path='/home/pi/processing/sketchbook/fonts/NeueHaasUnicaPro-Bold.ttf') #print sys.argv[1] # instantiate writer text = PapirusTextPos() #Write text (see README.MD of repo for more examples) #AddText(*text, x, y, id, font_path, size)# #text.AddText("your text", Id="Top", font_path='/home/pi/processing/sketchbook/fonts/NeueHaasUnicaPro-Light.ttf') #text.AddText(sys.argv[1], Id="Top", font_path='/home/pi/processing/sketchbook/fonts/NeueHaasUnicaPro-Bold.ttf') #text.AddText("your text", 15, 15, Id="Start", font_path='/home/pi/processing/sketchbook/fonts/NeueHaasUnicaPro-Bold.ttf', size=36)
elif dest == "Schagen": dest = "SGN" print("!! HIT") if numDisplayed == 0: disp = dest + spc + time[11:16] + spc + "Spoor " + plat elif numDisplayed == 1: disp2 = dest + spc + time[11:16] + spc + "Spoor " + plat numDisplayed += 1 # dest = str(dest) text = PapirusTextPos(False, rotation=args.rotation) text.AddText("Vertrek van de treinen\n\n", 10, 0, 13, Id="Header") text.AddText(disp, 0, 20, 18, Id="opt1") try: disp2 except NameError: disp2_exists = False else: disp2_exists = True if disp2_exists == True: text.AddText(disp2, 0, 40, 18, Id="opt2") if numDisplayed == 0: print("\nNo hits for configured stations. Assuming storing. Exception handler goes here.") text = PapirusTextPos(False, rotation=args.rotation) text.AddText("Vertrek van de treinen\n\n", 10, 0, 13, Id="Header") text.AddText("Apparently there are no trains.", 0, 35, 18, Id="errtxt") text.WriteAll() if __name__ == '__main__': main()
print 'Unable to parse OWM config file' exit(1) while True: try: netatmo_authorization = lnetatmo.ClientAuth() owm = pyowm.OWM(owm_key) break except: print 'Unable to connect to services, waiting 30 seconds and retrying' time.sleep(30) while True: now = time.strftime("%Y-%m-%d %H:%M") screen = PapirusTextPos(False) try: weatherData = lnetatmo.WeatherStationData(netatmo_authorization) latest_data = weatherData.lastData() forecast = owm.daily_forecast(owm_location, limit=2) except: print 'Unable to update data, skipping' pass data_time = datetime.datetime.fromtimestamp( latest_data['Outdoor']['When']).strftime('%Y-%m-%d %H:%M') out_temp = '{: 6.1f}'.format(latest_data['Outdoor']['Temperature']) bedroom_temp = '{: 6.1f}'.format(latest_data['Bedroom']['Temperature']) out_humidity = latest_data['Outdoor']['Humidity']
def main(): p = argparse.ArgumentParser() p.add_argument('--posX', '-x', type=int, default=0, help="X position of the start of the text") p.add_argument('--posY', '-y', type=int, default=0, help="Y position of the start of the text") p.add_argument('--fsize', '-s', type=int, default=12, help="Font size to use for the text") p.add_argument('--rotation', '-r', type=int, default=0, help="Rotation one of 0, 90, 180, 270") p.add_argument('--invert', '-i', type=bool, default=False, help="Invert the display of the text") args = p.parse_args() args.content = "at some point I will figure out why this is a required variable but until then I'll just nail it up like this" with open('/tmp/trains.xml') as fd: doc = xmltodict.parse(fd.read(), xml_attribs=True) iterCount = 0 numDisplayed = 0 if args.content: for iterCount in range(30): dest = doc['ActueleVertrekTijden']['VertrekkendeTrein'][ iterCount]['EindBestemming'] time = doc['ActueleVertrekTijden']['VertrekkendeTrein'][ iterCount]['VertrekTijd'] plat = doc['ActueleVertrekTijden']['VertrekkendeTrein'][ iterCount]['VertrekSpoor']['#text'] spc = " " print(dest + spc + time[11:16] + spc + plat) if (dest == "qeq" and numDisplayed <= 3) or (dest == "wew " and numDisplayed <= 3): if dest == "Wormerveer": dest = "WRM" print("!! HIT") elif dest == "Rotterdam Centraal": dest = "RDC" print("!! HIT") if numDisplayed == 0: disp = dest + spc + time[11:16] + spc + "Spoor " + plat elif numDisplayed == 1: disp2 = dest + spc + time[11:16] + spc + "Spoor " + plat elif numDisplayed == 2: disp3 = dest + spc + time[11:16] + spc + "Spoor " + plat elif numDisplayed == 3: disp4 = dest + spc + time[11:16] + spc + "Spoor " + plat numDisplayed += 1 # dest = str(dest) text = PapirusTextPos(False, rotation=args.rotation) text.AddText("Vertrek van de treinen\n\n", 12, 0, 13, Id="Header") text.AddText(disp, 0, 19, 18, Id="opt1") try: disp2 except NameError: disp2_exists = False else: disp2_exists = True if disp2_exists == True: text.AddText(disp2, 0, 39, 18, Id="opt2") try: disp3 except NameError: disp3_exists = False else: disp3_exists = True if disp3_exists == True: text.AddText(disp3, 0, 59, 18, Id="opt3") try: disp4 except NameError: disp4_exists = False else: disp4_exists = True if disp4_exists == True: text.AddText(disp3, 0, 79, 18, Id="opt4") if numDisplayed == 0: print( "\nNo hits for configured stations. Assuming storing. Exception handler goes here." ) text = PapirusTextPos(False, rotation=args.rotation) text.AddText("Vertrek van de treinen\n\n", 10, 0, 13, Id="Header") text.AddText(train6, 11, 10, 13, Id="train6") text.AddText(train7, 1, 25, 13, Id="train7") text.AddText(train8, 0, 40, 13, Id="train8") text.AddText(train9, 0, 55, 13, Id="train9") # text.AddText("Apparently there", 15, 35, 18, Id="errtxt1") # text.AddText("are no trains.", 25, 55, 18, Id="errtxt2") text.AddText("Apparently there are no trains", 15, 80, 9, Id="errtxt") #assbag git text.WriteAll()
def main(argv): global SIZE GPIO.setmode(GPIO.BCM) GPIO.setup(SW1, GPIO.IN) GPIO.setup(SW2, GPIO.IN) GPIO.setup(SW3, GPIO.IN) GPIO.setup(SW4, GPIO.IN) if SW5 != -1: GPIO.setup(SW5, GPIO.IN) papirus = PapirusTextPos(False, rotation=int(argv[0]) if len(sys.argv) > 1 else 0) cdrom = '' i = 0 files = [] papirus.AddText('USB Gadget ISO Loader\n\nREDRAW CDROM UP DOWN SELECT', 0, 0, Id='browser', size=12) papirus.AddText('Status Unknown', 0, 55, Id='status', size=20) papirus.AddText('', 160, 55, Id='cdrom', size=12) papirus.AddText('Please select a disk.', 0, 80, Id='selected', size=12) papirus.WriteAll() while True: press = False if GPIO.input(SW5) == False: papirus.WriteAll() if GPIO.input(SW4) == False: if not cdrom: cdrom = ' cdrom=y' papirus.UpdateText('cdrom', 'cdrom') else: cdrom = '' papirus.UpdateText('cdrom', '') press = True if GPIO.input(UP) == False: press = True i = i - 1 if GPIO.input(DOWN) == False: press = True i = i + 1 if GPIO.input(SELECT) == False: os.system('rmmod g_mass_storage') status = os.system('modprobe g_mass_storage file="%s" stall=0 %s' % ('/'.join((iso_dir, file)), cdrom)) papirus.UpdateText('selected', file) if cdrom: type = 'CDROM ' else: type = 'DISK ' cdrom = '' papirus.UpdateText('cdrom', '') if (status == 0): papirus.UpdateText('status', type + 'OK') else: papirus.UpdateText('status', type + 'Fail!') papirus.WriteAll(True) if press is False: sleep(0.1) continue try: file = files[i] except IndexError: files = natural_sort(os.listdir(iso_dir)) if (i > 0): i = 0 else: i = -1 if not files: papirus.UpdateText('browser', 'No files found') file = files[i] papirus.UpdateText( 'browser', '%s\n%s\n%s\n%s' % (safe_index(files, i), safe_index(files, i + 1), safe_index(files, i + 2), safe_index(files, i + 3))) papirus.WriteAll(True) sleep(0.1)
def main(): # TODO: load config from somewhere - config.py? Path from environment variable? # TODO: concept of ... pages? tabs? that are loaded in and registered. # TODO: instead of trying to use the tiny buttons on the papirus, is there # like a row of 5 keyboard keys? maybe nice cherry switches. # TODO: Parameterize lat/long in config; this is Ann Arbor, MI. latitude = 42.22 longitude = -83.74 timezone = tzlocal() rotation = 180 text = PapirusTextPos(autoUpdate=False, rotation=rotation) # TODO: Bitmap support requires using PapirusComposite instead of # PapirusTextPos. text.AddText("Today is", 0, 0, size=17, Id="date") text.AddText("Startup...", 93, 20, size=19, Id="startup") text.AddText("\u2600rise:", 0, 35, size=23, Id="sunrise_label") text.AddText("\u2600set:", 0, 57, size=23, Id="sunset_label") text.AddText("", 87, 35, size=23, Id="sunrise") text.AddText("", 87, 57, size=23, Id="sunset") text.AddText("Temp", 0, 80, size=14, Id="temp") text.WriteAll() text.RemoveText("startup") first_display = True while True: today = datetime.date.today() # TODO: Accommodate lack of sunrise/sunset like as far north as # Utqiaġvik - the city formerly known as Barrow, Alaska. # get_sunrise_sunset() returns those as None. sunrise_time, sunset_time = get_sunrise_sunset(latitude, longitude, today, timezone) text.UpdateText("date", "Today is {}".format(today.strftime("%A, %Y-%m-%d"))) text.UpdateText("sunrise", sunrise_time.strftime("%I:%M %p")) text.UpdateText("sunset", sunset_time.strftime("%I:%M %p")) # For testing the longest English day name. #text.UpdateText("date", "Today is {}".format(today.strftime("Wednesday, %Y-%m-%d"))) text.UpdateText( "temp", "Temp {}".format(get_temperature_forecast(latitude, longitude))) # Do a partial update on startup, and a full update each following hour. text.WriteAll(first_display) first_display = False # Wait until the next hour. now = datetime.datetime.now() next_hour = (now + datetime.timedelta(hours=1)).replace(microsecond=0, second=0, minute=0) wait_seconds = (next_hour - now).total_seconds() print("waiting {} seconds until next hour".format(wait_seconds)) time.sleep(wait_seconds)
from PIL import Image, ImageTk import PrintScreen as PS import Services as SV Units = "°K" STOP = False SLEEP = False BearerAUTH = "" conf = configparser.ConfigParser() conf.read("config.cfg") if os.path.exists('/etc/default/epd-fuse'): from papirus import PapirusTextPos TextPAPIRUS = PapirusTextPos(False) TextPAPIRUS.Clear() def Main(): #Fonction Coeur try: if conf["TWITTER"]["TwitterAPI"] != "" and conf["TWITTER"]["twitterapisecret"] != "": global BearerAUTH BearerRAW = os.popen("curl -u '"+ conf["TWITTER"]["TwitterAPI"] + ":" + conf["TWITTER"]["TwitterAPISecret"] + "' --data 'grant_type=client_credentials' 'https://api.twitter.com/oauth2/token'").read() BearerJSON = json.loads(BearerRAW) BearerAUTH = BearerJSON["access_token"] while True: global STOP #global SLEEP #if SLEEP: #GUI ONLY #je dors #while SLEEP: