def startupdisplay(argv): papirus = Papirus(rotation=int(argv[0]) if len(sys.argv) > 1 else 0) image = PIL.Image.new('1', papirus.size, WHITE) draw = ImageDraw.Draw(image) draw.text((20, 10), 'Welcome to the', fill=BLACK, font=font1) draw.text((10, 20), 'LightningATM', fill=BLACK, font=font) draw.text((7, 75), '- please insert coins -', fill=BLACK, font=font2) papirus.display(image) papirus.update()
class PapirusDisplay: def __init__(self): self.papirus = Papirus(rotation=180) self.papirus.clear() self.first_draw = True def update(self, im): self.papirus.display(im) if self.first_draw: self.papirus.update() self.first_draw = False else: self.papirus.partial_update()
def main(): """Main function""" global g_image try: # *** PaPiRus ePaper / eInk Screen HAT for Raspberry Pi - 2.7" *** from papirus import Papirus papirus = Papirus(rotation=0) g_image = Image.new('1', papirus.size, WHITE) draw_image() g_image.save(image_filename) papirus.display(g_image) papirus.update() return except: logging.debug("Papirus failed.", exc_info=1) try: # *** Waveshare 2.7inch e-Paper HAT *** libdir = os.path.realpath( os.getenv('HOME') + '/e-Paper/RaspberryPi_JetsonNano/python/lib') if os.path.exists(libdir): sys.path.append(libdir) else: libdir = os.path.realpath( os.getenv('HOME') + '/e-Paper/RaspberryPi&JetsonNano/python/lib') if os.path.exists(libdir): sys.path.append(libdir) from waveshare_epd import epd2in7 epd = epd2in7.EPD() epd.init() g_image = Image.new('1', (epd.height, epd.width), 255) draw_image() g_image.save(image_filename) epd.display(epd.getbuffer(g_image)) epd.sleep() return except: logging.debug("Waveshare failed.", exc_info=1) # *** no known screen: just save the bmp logging.debug("No known screen.") g_image = Image.new('1', (264, 176), WHITE) draw_image() g_image.save(image_filename)
class PapirusText(): def __init__(self): self.papirus = Papirus() def write(self, text, size=20, font_path='/usr/share/fonts/truetype/freefont/FreeMono.ttf'): # initially set all white background image = Image.new('1', self.papirus.size, WHITE) # prepare for drawing draw = ImageDraw.Draw(image) font = ImageFont.truetype(font_path, size) # Calculate the max number of char to fit on line line_size = (self.papirus.width / (size * 0.65)) current_line = 0 # unicode by default text_lines = [u""] # Compute each line for word in text.split(): # If there is space on line add the word to it if (len(text_lines[current_line]) + len(word)) < line_size: text_lines[current_line] += " " + word else: # No space left on line so move to next one text_lines.append("") current_line += 1 text_lines[current_line] += " " + word current_line = 0 for l in text_lines: current_line += 1 draw.text((0, ((size * current_line) - size)), l, font=font, fill=BLACK) self.papirus.display(image) self.papirus.update()
class PapirusText(object): def __init__(self, rotation=0): self.papirus = Papirus(rotation=rotation) def write(self, text, size=20, fontPath='/usr/share/fonts/truetype/freefont/FreeMono.ttf', maxLines=100): # initially set all white background image = Image.new('1', self.papirus.size, WHITE) # prepare for drawing draw = ImageDraw.Draw(image) font = ImageFont.truetype(fontPath, size) # Calculate the max number of char to fit on line lineSize = (self.papirus.width / (size*0.65)) currentLine = 0 # unicode by default textLines = [u""] # Compute each line for word in text.split(): # Always add first word (even when it is too long) if len(textLines[currentLine]) == 0: textLines[currentLine] += word elif (draw.textsize(textLines[currentLine] + " " + word, font=font)[0]) < self.papirus.width: textLines[currentLine] += " " + word else: # No space left on line so move to next one textLines.append(u"") if currentLine < maxLines: currentLine += 1 textLines[currentLine] += word currentLine = 0 for l in textLines: draw.text( (0, size*currentLine) , l, font=font, fill=BLACK) currentLine += 1 self.papirus.display(image) self.papirus.update()
class PapirusImage(): def __init__(self, rotation=0): self.papirus = Papirus(rotation=rotation) def write(self, image): image = Image.open(image) image = ImageOps.grayscale(image) # crop to the middle w, h = image.size x = w / 2 - self.papirus.width / 2 y = h / 2 - self.papirus.height / 2 rs = image if w != self.papirus.width or h != self.papirus.height: rs = image.resize((self.papirus.width, self.papirus.height)) bw = rs.convert("1", dither=Image.FLOYDSTEINBERG) self.papirus.display(bw) self.papirus.update()
class PapirusText(): def __init__(self): self.papirus = Papirus() def write(self, text, size = 20): WHITE = 1 BLACK = 0 # initially set all white background image = Image.new('1', Papirus().size, WHITE) # prepare for drawing draw = ImageDraw.Draw(image) font = ImageFont.truetype('/usr/share/fonts/truetype/freefont/FreeMono.ttf', size) # Calculate the max number of char to fit on line line_size = (Papirus().width / (size*0.65)) current_line = 0 text_lines = [""] # Compute each line for word in text.split(): # If there is space on line add the word to it if (len(text_lines[current_line]) + len(word)) < line_size: text_lines[current_line] += " " + word else: # No space left on line so move to next one text_lines.append("") current_line += 1 text_lines[current_line] += " " + word current_line = 0 for l in text_lines: current_line += 1 draw.text( (0, ((size*current_line)-size)) , l, font=font, fill=BLACK) self.papirus.display(image) self.papirus.update()
class PapirusImage(): def __init__(self): self.papirus = Papirus() def write(self, image): image = Image.open(image) image = ImageOps.grayscale(image) # crop to the middle w,h = image.size x = w / 2 - self.papirus.width / 2 y = h / 2 - self.papirus.height / 2 rs = image if w != self.papirus.width or h != self.papirus.height: rs = image.resize((self.papirus.width, self.papirus.height)) bw = rs.convert("1", dither=Image.FLOYDSTEINBERG) self.papirus.display(bw) self.papirus.update()
def update_startup_screen(): font1 = ImageFont.truetype( os.path.expanduser("~/LightningATM/resources/fonts/FreeMono.ttf"), 18) font = ImageFont.truetype( os.path.expanduser("~/LightningATM/resources/fonts/Sawasdee-Bold.ttf"), 30) font2 = ImageFont.truetype( os.path.expanduser("~/LightningATM/resources/fonts/FreeMono.ttf"), 14) papirus = Papirus(rotation=int(argv[0]) if len(sys.argv) > 1 else 0) image = Image.new("1", papirus.size, WHITE) draw = ImageDraw.Draw(image) draw.text((20, 10), "Welcome to the", fill=BLACK, font=font1) draw.text((10, 20), "LightningATM", fill=BLACK, font=font) draw.text((7, 75), "- please insert coins -", fill=BLACK, font=font2) papirus.display(image) papirus.update()
class PapirusImage(object): def __init__(self, rotation=0): self.papirus = Papirus(rotation=rotation) def write(self, imagefile): fileimg = Image.open(imagefile) w, h = fileimg.size rsimg = fileimg if w > self.papirus.width or h > self.papirus.height: rsimg.thumbnail(self.papirus.size) xpadding = (self.papirus.width - rsimg.size[0]) // 2 ypadding = (self.papirus.height - rsimg.size[1]) // 2 image = Image.new('1', self.papirus.size, WHITE) image.paste(rsimg, (xpadding, ypadding)) self.papirus.display(image) self.papirus.update()
class PapirusPlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.ProgressPlugin): def on_after_startup(self): self._logger.info("Hello World!") self.papirus = Papirus() self.font = ImageFont.truetype('/usr/share/fonts/truetype/freefont/FreeMono.ttf', 14) self.papirus.clear() self.last_update = datetime.now() def on_print_progress(self, storage, path, progress): pass def on_slicing_progress(self, slicer, source_location, source_path, dest_location, dest_path, progress): if progress == 0 or progress == 100 or (datetime.now() - self.last_update).total_seconds() > 3: width, height = self.papirus.size self.last_update = datetime.now() image = Image.new('1', (width, height), 1) draw = ImageDraw.Draw(image) #Draw progress start_x = width / 10 end_x = width - start_x start_y = height / 2 end_y = start_y + 20 draw.rectangle((start_x, start_y, end_x, end_y), 1, 0) fillWidth = (end_x - start_x) * progress / 100 try: self._logger.info("On slicing progress : ({}, {}, {}, {}, {})".format(start_x, end_x, start_y, end_y, fillWidth)) except: self._logger.info("Error writing log") draw.rectangle((start_x, start_y, start_x + fillWidth, end_y), 0, 0) # Draw text draw.text((0, 0), dest_path, font=self.font, fill=0) del draw self.papirus.display(image) self.papirus.update()
class PapirusDisplay(Display): _WHITE = (255, 255, 255) _IMAGE_SUFFIX = "-papirus.bmp" def __init__(self): self._screen = Papirus() self._image = PapirusImage() self._text = PapirusText() def draw(self, notification): self._screen.update() if isinstance(notification, TextNotification): self._text.write(notification.get_text()) elif isinstance(notification, ImageNotification): image_path = notification.get_image_path() converted_image_path = image_path + self._IMAGE_SUFFIX if not os.path.exists(converted_image_path): convert_bmp(image_path, converted_image_path) self._image.write(converted_image_path) @staticmethod def get_supported_notifications(): return [TextNotification, ImageNotification] @staticmethod def get_id(): return "papirus" def __str__(self): return "Papirus display" @staticmethod def get_config_factory(): return PapirusConfig()
class PapirusDisplay(Display.Display): def __init__(self, config, logFilename): self.my_papirus = Papirus(rotation=180) self.WHITE = 1 self.BLACK = 0 super().__init__(config, logFilename) while True: time.sleep(self.fullUpdateInterval*60) self.fullUpdate = True def getWidth(self): return self.my_papirus.width def getHeight(self): return self.my_papirus.height def display(self, image): self.my_papirus.display(image[0]) if self.fullUpdate: self.my_papirus.update() self.fullUpdate = False else: self.my_papirus.partial_update()
from textbitmaps import bitmaps from papirus import Papirus from PIL import Image import time import datetime import predictions SCREEN = Papirus() SCREEN.update() def display(s, full=False): img, _ = bitmaps.display_text_prop(s, display_size=(200, 96), char_size=2) img.save("tmp.bmp") file = Image.open("tmp.bmp") SCREEN.display(file) if full: SCREEN.update() else: SCREEN.partial_update() i = 0 while True: try: current_predictions = predictions.request_predictions() i += 1 now = datetime.datetime.now().strftime('%-I:%M:%S %p') buffer = '\n'.join(( ' {}'.format(now),
class PapirusTextPos(object): def __init__(self, autoUpdate=True, rotation=0): # Set up the PaPirus and dictionary for text self.papirus = Papirus(rotation=rotation) self.allText = dict() self.image = Image.new('1', self.papirus.size, WHITE) self.autoUpdate = autoUpdate self.partialUpdates = False def AddText(self, text, x=0, y=0, size=20, Id=None, invert=False, fontPath='/usr/share/fonts/truetype/freefont/FreeMono.ttf', maxLines=100): # Create a new Id if none is supplied if Id == None: Id = str(uuid.uuid4()) # If the Id doesn't exist, add it to the dictionary if Id not in self.allText: self.allText[Id] = DispText(text, x, y, size, invert) # add the text to the image self.addToImageText(Id, fontPath, maxLines) #Automatically show? if self.autoUpdate: self.WriteAll() def UpdateText(self, Id, newText, fontPath='/usr/share/fonts/truetype/freefont/FreeMono.ttf', maxLines=100): # If the ID supplied is in the dictionary, update the text # Currently ONLY the text is update if Id in self.allText: self.allText[Id].text = newText # Remove from the old text from the image (that doesn't use the actual text) self.removeImageText(Id) # Add the new text to the image self.addToImageText(Id, fontPath, maxLines) #Automatically show? if self.autoUpdate: self.WriteAll() def RemoveText(self, Id): # If the ID supplied is in the dictionary, remove it. if Id in self.allText: self.removeImageText(Id) del self.allText[Id] #Automatically show? if self.autoUpdate: self.WriteAll() def removeImageText(self, Id): # prepare for drawing draw = ImageDraw.Draw(self.image) # Draw over the top of the text with a rectangle to cover it draw.rectangle([ self.allText[Id].x, self.allText[Id].y, self.allText[Id].endx, self.allText[Id].endy ], fill="white") def addToImageText( self, Id, fontPath='/usr/share/fonts/truetype/freefont/FreeMono.ttf', maxLines=100): # Break the text item back in to parts size = self.allText[Id].size x = self.allText[Id].x y = self.allText[Id].y fontColor = BLACK backgroundColor = WHITE if self.allText[Id].invert: fontColor = WHITE backgroundColor = BLACK # prepare for drawing draw = ImageDraw.Draw(self.image) # Grab the font to use, fixed at the moment font = ImageFont.truetype(fontPath, size) # Calculate the max number of char to fit on line # Taking in to account the X starting position lineWidth = self.papirus.width - x # Starting vars currentLine = 0 # Unicode by default textLines = [u""] # Split the text by \n first toProcess = self.allText[Id].text.splitlines() # Go through the lines and add them for line in toProcess: # Add in a line to add the words to textLines.append(u"") currentLine += 1 # Compute each line for word in line.split(): # Always add first word (even it is too long) if len(textLines[currentLine]) == 0: textLines[currentLine] += word elif (draw.textsize(textLines[currentLine] + " " + word, font=font)[0]) < lineWidth: textLines[currentLine] += " " + word else: # No space left on line so move to next one textLines.append(u"") if currentLine < maxLines: currentLine += 1 textLines[currentLine] += word # Remove the first empty line if len(textLines) > 1: del textLines[0] # Go through all the lines as needed, drawing them on to the image # Reset the ending position of the text self.allText[Id].endy = y self.allText[Id].endx = x # Start at the beginning, calc all the end locations currentLine = 0 for l in textLines: # Find out the size of the line to be drawn textSize = draw.textsize(l, font=font) # Adjust the x end point if needed if textSize[0] + x > self.allText[Id].endx: self.allText[Id].endx = textSize[0] + x # Add on the y end point self.allText[Id].endy += size # If next line does not fit, quit currentLine += 1 if self.allText[Id].endy > (self.papirus.height - size - 3): del textLines[currentLine:] break # Little adjustment to make sure the text gets covered self.allText[Id].endy += 3 # If the text is wanted inverted, put a rectangle down first if self.allText[Id].invert: draw.rectangle([ self.allText[Id].x, self.allText[Id].y, self.allText[Id].endx, self.allText[Id].endy ], fill=backgroundColor) # Start at the beginning, add all the lines to the image currentLine = 0 for l in textLines: # Draw the text to the image yline = y + size * currentLine draw.text((x, yline), l, font=font, fill=fontColor) currentLine += 1 def WriteAll(self, partialUpdate=False): # Push the image to the PaPiRus device, and update only what's needed # (unless asked to do a full update) self.papirus.display(self.image) if partialUpdate or self.partialUpdates: self.papirus.partial_update() else: self.papirus.update() def Clear(self): # Clear the image, clear the text items, do a full update to the screen self.image = Image.new('1', self.papirus.size, WHITE) self.allText = dict() self.papirus.clear()
class PapirusTextPos(): def __init__(self, autoUpdate=True): # Set up the PaPirus and dictionary for text self.papirus = Papirus() self.allText = dict() self.image = Image.new('1', self.papirus.size, WHITE) self.autoUpdate = autoUpdate def AddText(self, text, x=0, y=0, size=20, Id=None, font_path='/usr/share/fonts/truetype/freefont/FreeMono.ttf'): # Create a new Id if none is supplied if Id == None: Id = str(uuid.uuid4()) # If the Id doesn't exist, add it to the dictionary if Id not in self.allText: self.allText[Id] = DispText(text.decode('string_escape'), x, y, size) # add the text to the image self.addToImageText(Id, font_path) #Automatically show? if self.autoUpdate: self.WriteAll() def UpdateText( self, Id, newText, font_path='/usr/share/fonts/truetype/freefont/FreeMono.ttf'): # If the ID supplied is in the dictionary, update the text # Currently ONLY the text is update if Id in self.allText: self.allText[Id].text = newText # Remove from the old text from the image (that doesn't use the actual text) self.removeImageText(Id) # Add the new text to the image self.addToImageText(Id, font_path) #Automatically show? if self.autoUpdate: self.WriteAll() def RemoveText(self, Id): # If the ID supplied is in the dictionary, remove it. if Id in self.allText: self.removeImageText(Id) del self.allText[Id] #Automatically show? if self.autoUpdate: self.WriteAll() def removeImageText(self, Id): # prepare for drawing draw = ImageDraw.Draw(self.image) # Draw over the top of the text with a rectangle to cover it draw.rectangle([ self.allText[Id].x, self.allText[Id].y, self.allText[Id].endx, self.allText[Id].endy ], fill="white") def addToImageText( self, Id, font_path='/usr/share/fonts/truetype/freefont/FreeMono.ttf'): # Break the text item back in to parts size = self.allText[Id].size x = self.allText[Id].x y = self.allText[Id].y # prepare for drawing draw = ImageDraw.Draw(self.image) # Grab the font to use, fixed at the moment font = ImageFont.truetype(font_path, size) # Calculate the max number of char to fit on line # Taking in to account the X starting position line_size = ((self.papirus.width - x) / (size * 0.65)) # Starting vars current_line = 0 text_lines = [] # Split the text by \n first toProcess = self.allText[Id].text.splitlines() # Go through the lines and add them for line in toProcess: # Add in a line to add the words to text_lines.append("") # Compute each line for word in line.split(): # If there is space on line add the word to it if (len(text_lines[current_line]) + len(word)) < line_size: text_lines[current_line] += " " + word else: # No space left on line so move to next one text_lines.append("") current_line += 1 text_lines[current_line] += " " + word # Move the pointer to next line current_line += 1 # Go through all the lines as needed, drawing them on to the image # Reset the ending position of the text self.allText[Id].endy = y self.allText[Id].endx = x # Start at the beginning current_line = 0 for l in text_lines: current_line += 1 # Find out the size of the line to be drawn textSize = draw.textsize(l, font=font) # Adjust the x end point if needed if textSize[0] + x > self.allText[Id].endx: self.allText[Id].endx = textSize[0] + x # Add on the y end point self.allText[Id].endy += textSize[1] # Draw the text to the image draw.text((x, ((size * current_line) - size) + y), l, font=font, fill=BLACK) # Little adjustment to make sure the text gets covered self.allText[Id].endy += 3 def WriteAll(self): # Push the image to the PaPiRus device, and update only what's needed self.papirus.display(self.image) self.papirus.update() def Clear(self): # Clear the image, clear the text items, do a full update to the screen self.image = Image.new('1', self.papirus.size, WHITE) self.allText = dict() self.papirus.display(self.image) self.papirus.update()
exec(open('/etc/default/epd-fuse').read()) image = Image.new('1', PAPIRUS.size, BLACK) qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=2, border=2, ) qr.add_data( 'lnurl1dp68gurn8ghj7ctsdyhxc6t8dp6xu6twvuhxw6txw3ej7mrww4exctesxdnxyerrvvmk2e3svdjkye3hxuenyvtyx3jr2erzxcmrxvfj893xvd3cxu6xgdrxv56n2e3jvdnqs3t6l7' .upper()) img = qr.make_image() print(type(img)) print(img.size) img = img.resize((96, 96), resample=0) print(img.size) draw = ImageDraw.Draw(image) draw.bitmap((0, 0), img, fill=WHITE) draw.text((110, 25), 'Scan to', fill=WHITE, font=createfont('freemonob', 16)) draw.text((110, 45), 'receive', fill=WHITE, font=createfont('freemonob', 16)) PAPIRUS.display(image) PAPIRUS.update()
from papirus import Papirus from papirus import PapirusImage from papirus import PapirusText screen = Papirus() image = PapirusImage() text = PapirusText() screen.update() image.write('/home/pi/papirus/epapertrump.bmp') #text.write("hello")
papirus.display(image) papirus.partial_update() sleep(.5) path = apath + "face7.bmp" image = Image.open(path) papirus.display(image) papirus.partial_update() sleep(.5) if (GPIO.input(16) == False) or (GPIO.input(20) == False) or ( GPIO.input(21) == False) or (GPIO.input(26) == False): sleeping = False lastinput = datetime.datetime.now() path = apath + "face7.bmp" image = Image.open(path) papirus.display(image) papirus.update() sleep(.30) path = apath + "face6.bmp" image = Image.open(path) papirus.display(image) papirus.partial_update() sleep(.20) path = apath + "face0.bmp" image = Image.open(path) papirus.display(image) papirus.partial_update() else: blink = random.randint(1, 500000) if facevis and blink == 49: path = apath + "face6.bmp" image = Image.open(path)
class HomeHub(): def __init__(self): #button setup self.SW1 = 21 self.SW2 = 16 self.SW3 = 20 self.SW4 = 19 GPIO.setmode(GPIO.BCM) GPIO.setup(self.SW1, GPIO.IN) GPIO.setup(self.SW2, GPIO.IN) GPIO.setup(self.SW3, GPIO.IN) GPIO.setup(self.SW4, GPIO.IN) #config file self.Config = ConfigParser.ConfigParser() self.Config.read('./config.ini') rotation = int(self.Config.get('PAPIRUS', 'rotation')) fontPath = self.Config.get('PAPIRUS', 'fontPath') self.fontSize = int(self.Config.get('PAPIRUS', 'fontSize')) backgroundPath = self.Config.get('PAPIRUS', 'backgroundPath') self.defaultDisplayOption = self.Config.get('HOMEHUB', 'defaultDisplayOption') self.url = self.Config.get('HOMEHUB', 'url') self.currentLightGroup = 0 self.ResetLightGroups(True) #papirus setup self.initX = 15 self.initY = 40 self.papirusDisplay = Papirus(rotation=rotation) self.papirusDisplay.clear() #papirus screen setup rsimg = Image.open(backgroundPath) self.image = Image.new('1', self.papirusDisplay.size, 1) self.image.paste(rsimg, (0, 0)) self.draw = ImageDraw.Draw(self.image) self.font = ImageFont.truetype(fontPath, self.fontSize) self.CreateTextObject(self.lightGroups[self.currentLightGroup]) self.ButtonRead() def ResetLightGroups(self, init): print 'resetLightGroup' self.jsonLightGroups = self.QueryLightList(self.url) self.lightGroups = self.JsonLightToLightGroupNames( self.jsonLightGroups, self.defaultDisplayOption, init) print 'powerTest:' + str(self.jsonLightGroups[self.lightGroups[ self.currentLightGroup]][0]['power']) #initial homehub query to retrieve light list def QueryLightList(self, url): print 'QueryLightList' queryParams = { self.Config.get('HOMEHUB', 'queryValue'): self.Config.get('HOMEHUB', 'paramValue') } page = requests.get(url, queryParams) #light group setup return json.loads(page.text) def JsonLightToLightGroupNames(self, jsonObject, default, init): lightGroups = [] print 'jsonToNames' for key in jsonObject: lightGroups.append(key) if key == default and init: self.currentLightGroup = len(lightGroups) - 1 return lightGroups def CreateTextObject(self, textToDisplay): self.draw.text((self.initX, self.initY), textToDisplay, font=self.font, fill=0) self.papirusDisplay.display(self.image) self.papirusDisplay.update() self.TextCleanupForFutureDelete(textToDisplay) def TextCleanupForFutureDelete(self, textToDisplay): #calculate some text values for when we want to clear this object textSize = self.draw.textsize(textToDisplay, font=self.font) self.endX = self.initX + textSize[0] self.endY = self.initY + self.fontSize def ClearExistingTextNoUpdate(self): self.draw.rectangle([self.initX, self.initY, self.endX, self.endY], fill='white') def UpdateText(self, textToDisplay): self.ClearExistingTextNoUpdate() self.draw.text((self.initX, self.initY), textToDisplay, font=self.font, fill=0) self.papirusDisplay.display(self.image) self.papirusDisplay.partial_update() def ButtonRead(self): while True: if GPIO.input(self.SW1) == False and GPIO.input(self.SW2) == False: sleep(0.2) self.papirusDisplay.clear() break if GPIO.input(self.SW1) == False: self.currentLightGroup -= 1 if self.currentLightGroup < 0: self.currentLightGroup = len(self.lightGroups) - 1 self.UpdateText(self.lightGroups[self.currentLightGroup]) sleep(0.1) if GPIO.input(self.SW2) == False: self.currentLightGroup += 1 if self.currentLightGroup >= len(self.lightGroups): self.currentLightGroup = 0 self.UpdateText(self.lightGroups[self.currentLightGroup]) sleep(0.1) if GPIO.input(self.SW3) == False: sleep(0.1) if GPIO.input(self.SW4) == False: currentLightStatus = self.jsonLightGroups[self.lightGroups[ self.currentLightGroup]][0]['power'] newLightStatus = 'true' if currentLightStatus: newLightStatus = 'false' print 'lightStatus:' + newLightStatus updateParams = { self.Config.get('HOMEHUB', 'queryValue'): self.Config.get('HOMEHUB', 'updateParamValue'), self.Config.get('HOMEHUB', 'updateGroupQueryValue'): self.lightGroups[self.currentLightGroup], self.Config.get('HOMEHUB', 'updateStatusQueryValue'): newLightStatus } toggle = requests.get(self.url, updateParams, timeout=5) sleep(0.1) self.ResetLightGroups(False) sleep(0.1) sleep(0.1)
else: logging.debug("Error reading weather data from.") messages.append(u"WEATHER ERROR") # Get next #13 bus departure time bus16_no, bus16_time = bus_times.get_next_bus_time(stop_number=51034) # Get next #33 bus westbound departure time bus33_no, bus33_time = bus_times.get_next_bus_time(stop_number=61128) messages.append("Buses: %s @ %s, %s @ %s" % (bus16_no, bus16_time, bus33_no, bus33_time)) text = u"\n".join(messages) if text != previous_text: im, char_count = bitmaps.display_text_prop(text, char_set="unicode", char_size=1) # Note: np.asarray(im) does not # currently work due to a bug in PIL im.putdata([p ^ 255 for p in im.getdata()]) display.display(im) display.update() logging.info("Display updated.") previous_text = text time.sleep(refresh_rate)
class PapirusTextPos(object): def __init__(self, autoUpdate = True, rotation = 0): # Set up the PaPirus and dictionary for text self.papirus = Papirus(rotation = rotation) self.allText = dict() self.image = Image.new('1', self.papirus.size, WHITE) self.autoUpdate = autoUpdate self.partial_updates = False def AddText(self, text, x=0, y=0, size = 20, Id = None, invert=False, font_path='/usr/share/fonts/truetype/freefont/FreeMono.ttf'): # Create a new Id if none is supplied if Id == None: Id = str(uuid.uuid4()) # If the Id doesn't exist, add it to the dictionary if Id not in self.allText: self.allText[Id] = DispText(text, x, y, size, invert) # add the text to the image self.addToImageText(Id, font_path) #Automatically show? if self.autoUpdate: self.WriteAll() def UpdateText(self, Id, newText, font_path='/usr/share/fonts/truetype/freefont/FreeMono.ttf'): # If the ID supplied is in the dictionary, update the text # Currently ONLY the text is update if Id in self.allText: self.allText[Id].text = newText # Remove from the old text from the image (that doesn't use the actual text) self.removeImageText(Id) # Add the new text to the image self.addToImageText(Id, font_path) #Automatically show? if self.autoUpdate: self.WriteAll() def RemoveText(self, Id): # If the ID supplied is in the dictionary, remove it. if Id in self.allText: self.removeImageText(Id) del self.allText[Id] #Automatically show? if self.autoUpdate: self.WriteAll() def removeImageText(self, Id): # prepare for drawing draw = ImageDraw.Draw(self.image) # Draw over the top of the text with a rectangle to cover it draw.rectangle([self.allText[Id].x, self.allText[Id].y, self.allText[Id].endx, self.allText[Id].endy], fill="white") def addToImageText(self, Id, font_path='/usr/share/fonts/truetype/freefont/FreeMono.ttf'): # Break the text item back in to parts size = self.allText[Id].size x = self.allText[Id].x y = self.allText[Id].y font_col = BLACK back_col = WHITE if self.allText[Id].invert: font_col = WHITE back_col = BLACK # prepare for drawing draw = ImageDraw.Draw(self.image) # Grab the font to use, fixed at the moment font = ImageFont.truetype(font_path, size) # Calculate the max number of char to fit on line # Taking in to account the X starting position line_size = ((self.papirus.width - x) / (size*0.65)) # Starting vars current_line = 0 # unicode by default text_lines = [u""] # Split the text by \n first toProcess = self.allText[Id].text.splitlines() # Go through the lines and add them for line in toProcess: # Add in a line to add the words to text_lines.append("") # Compute each line for word in line.split(): # If there is space on line add the word to it if (len(text_lines[current_line]) + len(word)) < line_size: # Only add a space if there`s something on the line if len(text_lines[current_line]) > 0: text_lines[current_line] += " " text_lines[current_line] += word else: # No space left on line so move to next one text_lines.append("") current_line += 1 text_lines[current_line] += " " + word # Move the pointer to next line current_line +=1 # Go through all the lines as needed, drawing them on to the image # Reset the ending position of the text self.allText[Id].endy = y self.allText[Id].endx = x # Start at the beginning, calc all the end locations current_line = 0 for l in text_lines: current_line += 1 # Find out the size of the line to be drawn textSize = draw.textsize(l, font=font) # Adjust the x end point if needed if textSize[0]+x > self.allText[Id].endx: self.allText[Id].endx = textSize[0] + x # Add on the y end point self.allText[Id].endy += textSize[1] # Little adjustment to make sure the text gets covered self.allText[Id].endy += 3 # If the text is wanted inverted, put a rectangle down first if self.allText[Id].invert: draw.rectangle([self.allText[Id].x, self.allText[Id].y, self.allText[Id].endx, self.allText[Id].endy], fill=back_col) # Start at the beginning, add all the lines to the image current_line = 0 for l in text_lines: current_line += 1 # Draw the text to the image draw.text( (x, ((size*current_line)-size) + y) , l, font=font, fill=font_col) def WriteAll(self, partial_update=False): # Push the image to the PaPiRus device, and update only what's needed # (unless asked to do a full update) self.papirus.display(self.image) if partial_update or self.partial_updates: self.papirus.partial_update() else: self.papirus.update() def Clear(self): # Clear the image, clear the text items, do a full update to the screen self.image = Image.new('1', self.papirus.size, WHITE) self.allText = dict() self.papirus.clear()