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()
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 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)
class Screen: 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) def update_header(self, text): self.text.UpdateText("title", text, font_path=sans_font) def update_body(self, text): self.text.UpdateText("body", text, font_path=bold_sans_font) def update_footer(self, text): self.text.UpdateText("footer", text, font_path=bold_sans_font) def write(self): self.text.WriteAll() def clear(self): self.text.Clear()
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()
# If called as "display.py partial", only the changed portions of the screen will be updated. # It's recommended to update the screen with a full refresh every few minutes: # https://github.com/PiSupply/PaPiRus#full-and-partial-updates if sys.argv[1] == 'partial': text.partialUpdates = True outdoor_temperature_formatted = outdoor.json()['temperature'] + '\u00B0' indoor_temperature_formatted = indoor.json()['temperature'] + '\u00B0' outdoor_humidity_formatted = str(outdoor.json()['humidity']) + '%' indoor_humidity_formatted = str(indoor.json()['humidity']) + '%' timestamp = arrow.get(int(outdoor.json()['timestamp']) / 1000).to( os.environ['TIMEZONE']).format('HH:mm') text.AddText(timestamp, 160, -2, size=16, fontPath=bold_font) text.AddText('Outdoor', 0, -2, size=12, fontPath=bold_font) text.AddText(outdoor_temperature_formatted, 0, 3, size=48, fontPath=standard_font) text.AddText(outdoor_humidity_formatted, 130, 14, size=36, fontPath=standard_font) text.AddText('Indoor', 0, 47, size=12, fontPath=bold_font) text.AddText(indoor_temperature_formatted,
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 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")
TWEETNUM = 50 #creates empty list for twitter IDs list = [] #retreives tweet data from API then adds the id strings (a unique id number) to the list search_results = twitter.search(q=keywords, count=TWEETNUM) for tweet in search_results["statuses"]: try: list.append(tweet["id_str"]) print list except TwythonError as e: print e print 'now my code continues' text.AddText("now my code continues", 0, 0, Id="Start") #this section tweets by randomly selecting id strings from the list, cleaning them update #(for somwe reason they are added to the list with some extra character) and retweets them #then removes them from the list countdown = TWEETNUM while (countdown <> 0): print 'The count is:', countdown try: toTweet = list[random.randint(0, len(list)) - 1] list.remove(toTweet) toTweet[2:19] print toTweet text.AddText("count", 0, 40, Id="Second") text.UpdateText("Second", "tweeting %s of %d" % (countdown, TWEETNUM))
# 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)
# disconnect from server db.close() ########################################################################################## # eINC DISPLAY # Calling PapirusTextPos this way will mean nothing is written to the screen be default text = PapirusTextPos(False) # Clear all text from the screen # This does a full update so is a little slower than just removing the text. text.clear() # Write text to the screen at selected point, with an Id # Nothing will show on the screen text.AddText("Order id: ", 10, 10, Id="OrderId") text.AddText("Owner: ", 10, 30, Id="Owner") text.AddText("Type: ", 10, 50, Id="Type") text.AddText("Ammount: ", 10, 70, Id="Ammount") # Now display lines on the scrren text.WriteAll() ########################################################################################## # Command line # (will be removed or commented out later) os.system('clear') print print ' GPS reading'
out_humidity = latest_data['Outdoor']['Humidity'] if datetime.datetime.now().hour > 15: forecast_day = 1 forecast_title = "Tomorrow" else: forecast_day = 0 forecast_title = "Today" forecast_details = forecast.get_forecast() forecast_details_list = forecast_details.get_weathers() forecast_high = '{: 6.1f}'.format( forecast_details_list[forecast_day].get_temperature( unit='celsius')['max']) forecast_text = forecast_details_list[forecast_day].get_status() screen.AddText('Outdoor', 5, 3, 20, Id='OutTitle', font_path=font) screen.AddText(out_temp + u"\u00b0", 5, 10, 70, Id="OutTemp", font_path=font) # screen.AddText(trend_symbol, 170, 30, 50, font_path=arrow_font) screen.AddText('Humidity ' + str(out_humidity) + '%', 5, 86, 12, Id='Humidity', font_path=font) screen.AddText('Bedroom', 5, 103, 15, Id='InTitle', font_path=font) screen.AddText(bedroom_temp + u"\u00b0",
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()
user = os.getuid() if user != 0: print("Please run script as root") sys.exit() # Check EPD_SIZE is defined EPD_SIZE = 0.0 if os.path.exists('/etc/default/epd-fuse'): exec(open('/etc/default/epd-fuse').read()) if EPD_SIZE == 0.0: print("Please select your screen size by running 'papirus-config'.") sys.exit() # Let's define the lines we're gonna use. False in text holds updates to the screen until WriteAll() is called text = PapirusTextPos(False, rotation=0) text.AddText("", 0, 0, 20, Id="1") text.AddText("", 0, 20, 20, Id="2") text.AddText("", 0, 40, 20, Id="3") text.AddText("", 0, 60, 20, Id="4") text.AddText("", 0, 80, 20, Id="5") def exit_gracefully(signum, frame): # let's restore the original signal handlers signal.signal(signal.SIGTERM, original_sigterm) signal.signal(signal.SIGINT, original_sigint) signal.signal(signal.SIGHUP, original_sighup) # clean up gracefully here. bail when done. #text.Clear() one = 'shutdown at'
class papirus_cont(object): 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 set_new_datetime(self): self.now_time = datetime.now() self.papi.UpdateText("date-time", (self.now_time.strftime('%m-%d %H:%M'))) def set_temp(self, temp): self.papi.UpdateText("temp", "{0:.3f}".format(temp) + "[deg]") def set_hum(self, hum): self.papi.UpdateText("hum", "{0:.3f}".format(hum) + "[%]") def set_press(self, press): self.papi.UpdateText("press", "{0:.1f}".format(press) + "[hpa]") def set_ipaddress(self): self.ip = "0.0.0.0" try: #socket.AF_INET:IVv4のアドレス, socket.SOCK_DGRAM:UDPネットワークの #IPv6の場合はAF_INET→IF_INET6 self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) #タイムアウトを10秒 self.s.settimeout(10) #ipアドレス8.8.8.8:80に接続します。 # 8.8.8.8はgoogle Public DNSPCのIP。 # 外のアドレスなら何でもいいです。 self.s.connect(("8.8.8.8", 80)) #今の接続のソケット名を取得します。 self.ip = self.s.getsockname()[0] #IPアドレス表示 #print(self.ip) except socket.error: #ネットワークがエラーだったり無かったら self.ip = 'No Internet' #print('No Internet') #print(type(self.ip)) self.papi.UpdateText("ip", self.ip) def get_network_state(self): return self.ip def update(self): self.papi.WriteAll()
if '' == FONT_FILE: raise 'no font file found' GPIO.setmode(GPIO.BCM) GPIO.setup(button1, GPIO.IN) GPIO.setup(button2, GPIO.IN) GPIO.setup(button3, GPIO.IN) GPIO.setup(button4, GPIO.IN) menu = 0 size1 = 11 size2 = 17 dir_path = os.path.dirname(os.path.realpath(__file__)) int_ip = get_lan_ip() myip = ipgetter.myip() screen = PapirusTextPos(False) screen.AddText("Starting Appliance", 20, 70, size2, FONT_FILE) screen.WriteAll() ext_ip = 'External: ' + myip int_ip = 'Internal: ' + int_ip speed_test_log = dir_path + '/speedtest.txt' screen.Clear() graph_code = dir_path + '/ImageDemo.py temp.png' speed_test_code = dir_path + '/speedtest.sh' show_menu() try: while True: #Primary Menu Options if (menu == 0 and GPIO.input(button1) == False): speed_test() menu = 1 if (menu == 0 and GPIO.input(button2) == False):
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) text.WriteAll() #Display first tweet status, name = home_timeline(sys.argv[1] if len(sys.argv) > 1 else 0) twitter_name = "@" + name text.AddText(twitter_name, 0, 0, Id="start") text.AddText(status, 0, 20, Id="tweet") text.WriteAll() while True: if (GPIO.input(SW1) == False) and (GPIO.input(SW2) == False): write_text(papirus, "Exiting ...", SIZE) sleep(0.2) papirus.clear() sys.exit() if GPIO.input(SW4) == False and tweet_index < 19: tweet_index = tweet_index + 1 next_tweet() if GPIO.input(SW3) == False and tweet_index > 0: tweet_index = tweet_index - 1
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) GPIO.add_event_detect(switch, GPIO.FALLING, callback=buttonPressed)
cur = conn.cursor() # Create a GPS module instance. gps = adafruit_gps.GPS(uart, debug=False) # https://cdn-shop.adafruit.com/datasheets/PMTK_A11.pdf # Turn on the basic GGA and RMC info gps.send_command(b"PMTK314,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0") # Set update rate to once a second (1hz) gps.send_command(b"PMTK220,1000") # Main loop last_print = time.monotonic() text.AddText("Initializing", Id="1") text.AddText("", 0, 20, Id="2") text.AddText("", 0, 40, Id="3") text.AddText("", 0, 60, Id="4") text.WriteAll() waiting = True while True: gps.update() # Every 10 seconds print out current location details if there's a fix. current = time.monotonic() if (current - last_print >= 10.0): last_print = current if not gps.has_fix: # Try again if we don't have a fix yet. print("Waiting for fix...") if waiting is False:
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 " if console_display: print(disp_text) text.AddText(disp_text, 0, vert_spacing * 4, font_size, Id="VPN") disp_text = text_time if console_display: print(disp_text) text.AddText(disp_text, 0, vert_spacing * 5, font_size, Id="date")
AIRNOWAPIKEY = "" LAT = "37.7749" LONG = "-122.4194" #set starting text position YPOS = 0 XPOS = 0 #get the current AQI data aqiurl = "http://www.airnowapi.org/aq/observation/latLong/current/?format=application/json&latitude=" + LAT + "&longitude=" + LONG + "&distance=25&API_KEY=" + AIRNOWAPIKEY #uncomment to print URL to stdout (troubleshooting/debugging) #print (aqiurl) response = urllib.urlopen(aqiurl) data = json.loads(response.read()) #Add text "AQI" at top of display #text.AddText('AQI',30,0,10,Id='title') for item in data: #uncomment print to stdout #print("{}:{}:{}\n".format(item['ParameterName'],item['AQI'],item['Category']['Name'])) #send to papirus text.AddText((item['ParameterName'] + ' ' + str(item['AQI']) + ' ' + item['Category']['Name']), XPOS, YPOS, fontsize, Id=item['ParameterName']) YPOS = YPOS + fontsize * 2 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()
#!/usr/bin/env python from papirus import PapirusTextPos import mock kSymbol = '01. symbol' kPrice = '05. price' kChangePercent = '10. change percent' quote, ignore = mock.get_global_quote_mock() symbol = quote[kSymbol] price = quote[kPrice] changePercent = quote[kChangePercent] line = "{:4.4s} {:^4.4s} {:4.4s}".format(symbol, str(price), str(changePercent)) print(line) # Same as calling "PapirusTextPos(True [,rotation = rot])" text = PapirusTextPos(False, 0) text.Clear() text.AddText(line, 0, 0, 24, Id="Start1") text.AddText("ATRS 3.03 +2.4", 0, 24, 24, Id="Start2") text.AddText("NVDA _145 +.27", 0, 48, 24, Id="Start3") text.AddText("__MU 32.5 -0.7", 0, 72, 24, Id="Start4") text.WriteAll()
#creates empty list for twitter IDs list = [] loops = RUNTOT #retreives tweet data from API then adds the id strings (a unique id number) to the list while (loops <> 0): search_results = twitter.search(q=keywords, count=TWEETNUM) for tweet in search_results["statuses"]: try: list.append(tweet["id_str"]) print list except TwythonError as e: print e print 'now my code continues' text.AddText("now my code continues", 0, 0, Id="Start") #this section tweets by randomly selecting id strings from the list, cleaning them update #(for somwe reason they are added to the list with some extra character) and retweets them #then removes them from the list countdown = TWEETNUM while (countdown <> 0): print 'The count is:', countdown try: toTweet = list[random.randint(0, len(list)) - 1] list.remove(toTweet) toTweet[2:19] print toTweet text.AddText("count", 0, 40, Id="Second") text.UpdateText("Second",
class get_text(Resource): def get(self): return jsonify({'data': lines}) class commit_text(Resource): def get(self): for i in range(0, 9): papirus_text.UpdateText(ids[i], lines[i]) papirus_text.WriteAll() return jsonify({'data': lines}) api.add_resource(get_text, "/status") api.add_resource(set_text, '/<index>/<text>') # Dynamic route api.add_resource(clear_text, '/<index>/') api.add_resource(commit_text, '/commit/') # Routes @app.route('/') def index(): return render_template("index.html") if __name__ == '__main__': for i in range(0, 9): papirus_text.AddText(lines[i], 0, i * 14, Id=ids[i], size=12) papirus_text.WriteAll() app.run(host='0.0.0.0', port=5555)
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 screen text = PapirusTextPos(rotation = 0) text.AddText("hello world", 0, 25, Id="Start" ) #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 = ["mountaineering", "solarpv", "biomass", "windpower", "climatechange" "#antarctica", "#fission", "#tate"] filter = " OR ".join(good_words) blacklist = " -".join(naughty_words)
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)
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)