def main_display(): from EPD import EPD epd = EPD() #epd.clear() previous_messages = [] while True: try: messages = json.loads(urllib2.urlopen("http://fjas.no:8181/messages").read()) except: #urllib2.URLError: print "Got problems, sleeping 13s" time.sleep(13) continue #messages = [ { 'x': 25, 'y': 70, 'text':'hei på deg', 'fontsize': 22 } ] if not listsDifferent(messages, previous_messages): print "No change, sleeping 1.3s" time.sleep(1.300) continue previous_messages = messages print "Got new message, updating screen" image = getImage(epd.size, messages) epd.display(image) epd.update()
def main(): """main program - draw and display a test image""" now = datetime.today() epd = EPD() print('panel = {p:s} {w:d} x {h:d} version={v:s} COG={g:d} FILM={f:d}'.format(p=epd.panel, w=epd.width, h=epd.height, v=epd.version, g=epd.cog, f=epd.film)) epd.clear() # initially set all white background image = Image.new('1', epd.size, WHITE) # prepare for drawing draw = ImageDraw.Draw(image) width, height = image.size font = ImageFont.truetype(FONT_FILE, FONT_SIZE) ethaddr = get_ip_address('eth0') draw.rectangle((0, 0, width, height), fill=WHITE, outline=WHITE) draw.text((0, 0), '{c:s}'.format(c=ethaddr), fill=BLACK, font=font) draw.text((5, 20), '{h:02d}:{m:02d}:{s:02d}'.format(h=now.hour, m=now.minute, s=now.second), fill=BLACK, font=font) # display image on the panel epd.display(image) epd.partial_update()
def main(): """main program - display list of images""" epd = EPD() epd.clear() print( "panel = {p:s} {w:d} x {h:d} version={v:s} COG={g:d} FILM={f:d}".format( p=epd.panel, w=epd.width, h=epd.height, v=epd.version, g=epd.cog, f=epd.film ) ) while True: for cam in cams: fp = urllib2.urlopen(cam) file_name = cStringIO.StringIO(fp.read()) image = Image.open(file_name) image = ImageOps.grayscale(image) rs = image.resize((epd.width, epd.height)) bw = rs.convert("1", dither=Image.FLOYDSTEINBERG) epd.display(bw) epd.update() time.sleep(5) # delay in seconds
def render(self): fin = self.img.rotate(90) # fin.save("halibut.png", 'png') epd = EPD() epd.clear() epd.display(fin) epd.update()
def send_to_display(canvas): try: epd = EPD() epd.display(canvas) epd.update() except IOError: print("EPD not supported") canvas.show()
def main(): """main program - draw and display a test image""" conf = get_config() apikey = conf["weather"]["apikey"] urlbase = conf["weather"]["urlbase"] epd = EPD() print('panel = {p:s} {w:d} x {h:d} version={v:s} COG={g:d} FILM={f:d}'.format(p=epd.panel, w=epd.width, h=epd.height, v=epd.version, g=epd.cog, f=epd.film)) epd.clear() # initially set all white background image = Image.new('1', epd.size, WHITE) # prepare for drawing draw = ImageDraw.Draw(image) width, height = image.size font = ImageFont.truetype(FONT_FILE, FONT_SIZE) wfont = ImageFont.truetype(FONT_FILE, FONT_SIZE/2) counter = get_ip_address('eth0') cities = conf["weather"]["cities"] while True: for city in cities: weather = get_weather(city, urlbase, apikey) temp = u"%d°C" % (weather["main"]["temp"] - 273.15) fp = urllib2.urlopen(weather["iconlink"]) f = cStringIO.StringIO(fp.read()) pic = Image.open(f) pic = ImageOps.grayscale(pic) rs = pic.resize((epd.width/2, epd.height/2)) bw = rs now = datetime.today() draw.rectangle((0, 0, width, height), fill=WHITE, outline=WHITE) draw.text((0, 150), '{c:s}'.format(c=counter), fill=BLACK, font=wfont) draw.text((0, 160), '{h:02d}:{m:02d}:{s:02d}'.format(h=now.hour, m=now.minute, s=now.second), fill=BLACK, font=wfont) draw.text((0, 0), weather["name"], fill=BLACK, font=font) draw.text((0, 20), temp, fill=BLACK, font=font) draw.text((0, 50), weather["weather"][0]["description"], fill=BLACK, font=font) image.paste(bw, (epd.width - epd.width/2, epd.height - epd.height/2)) # display image on the panel epd.display(image) epd.partial_update() time.sleep(10)
def demo(now): epd = EPD('/dev/epd') #print('panel = {p:s} {w:d} x {h:d} version={v:s} COG={g:d}'.format(p=epd.panel, w=epd.width, h=epd.height, v=epd.version, g=epd.cog)) #epd.clear() #font = ImageFont.truetype("freesansbold.ttf", 12) font = ImageFont.truetype('/usr/share/fonts/truetype/ttf-dejavu/DejaVuSansMono-Bold.ttf', 56) image = Image.new('1', epd.size, WHITE) draw = ImageDraw.Draw(image) draw.text((30, 30), '%s' % now.strftime('%H:%M'), fill=BLACK, font=font) epd.display(image) epd.update()
def main(): """main program - draw and display a test image""" epd = EPD() print('panel = {p:s} {w:d} x {h:d} version={v:s} COG={g:d} FILM={f:d}'.format(p=epd.panel, w=epd.width, h=epd.height, v=epd.version, g=epd.cog, f=epd.film)) epd.clear() # initially set all white background image = Image.new('1', epd.size, WHITE) # prepare for drawing draw = ImageDraw.Draw(image) width, height = image.size font = ImageFont.truetype(FONT_FILE, FONT_SIZE) wfont = ImageFont.truetype(FONT_FILE, FONT_SIZE/2) counter = get_ip_address('eth0') lmin = datetime.today().minute conf = get_config() while True: for rss_url in conf["RSS"]: feed = feedparser.parse(rss_url) for item in feed["items"]: now = datetime.today() draw.rectangle((0, 0, width, height), fill=WHITE, outline=WHITE) draw.text((0, 150), '{c:s}'.format(c=counter), fill=BLACK, font=wfont) draw.text((0, 160), '{h:02d}:{m:02d}:{s:02d}'.format(h=now.hour, m=now.minute, s=now.second), fill=BLACK, font=wfont) ttl = strip_tags(item["title"]) ttl.strip() sum = strip_tags(item["summary"]) sum.strip() y = -20 for line in textwrap.wrap(ttl, 20): y += 20 if y < 150: draw.text((0, y), line, fill=BLACK, font=font) y += 10 for line in textwrap.wrap(sum, 40): y += 10 if y < 150: draw.text((0, y), line, fill=BLACK, font=wfont) # display image on the panel epd.display(image) epd.partial_update() time.sleep(30)
def main(argv): """main program - display image""" # print('panel = {p:s} {w:d} x {h:d} version={v:s} COG={g:d} FILM={f:d}'.format(p=epd.panel, w=epd.width, h=epd.height, v=epd.version, g=epd.cog, f=epd.film)) # open image and convert to grayscale image = Image.open(sys.argv[1]) image = ImageOps.grayscale(image) # convert to 8-bit format bw = image.convert("1", dither=Image.FLOYDSTEINBERG) # display the image epd = EPD() epd.display(bw) epd.update()
def main(): # initialize EPD epd = EPD() epd.clear() # initially set all white background image = Image.new('1', epd.size, WHITE) # prepare for drawing draw = ImageDraw.Draw(image) width, height = image.size # load font font = ImageFont.truetype(FONT_FILE, FONT_SIZE) # initialize image draw.rectangle((0, 0, width, height), fill=WHITE, outline=WHITE) # read data files output_in = subprocess.check_output(["cat", FILE_TEMPERATURE_INSIDE]) output_out = subprocess.check_output(["cat", FILE_TEMPERATURE_OUTSIDE]) # insert image inside in_image = Image.open(FILE_IMAGE_INSIDE) resized_image = in_image.resize((70,70)) bw_rs_image = resized_image.convert("1", dither=Image.FLOYDSTEINBERG) offset = 0, 0 image.paste(bw_rs_image, offset) # insert image outside out_image = Image.open(FILE_IMAGE_OUTSIDE) resized_image = out_image.resize((70,70)) bw_rs_image = resized_image.convert("1", dither=Image.FLOYDSTEINBERG) offset = 0, (height/2) image.paste(bw_rs_image, offset) # Draw data to image # Add degree by adding "+ chr(176) + "C"" draw.text((75, 0), str(output_in), fill=BLACK, font=font) draw.text((75, height/2), str(output_out), fill=BLACK, font=font) # Draw image at screen epd.display(image) epd.partial_update()
def display_file(file_name): epd = EPD() epd.clear() print('panel = {p:s} {w:d} x {h:d} version={v:s}'.format(p=epd.panel, w=epd.width, h=epd.height, v=epd.version)) # Open image and convert to black and white image = PImage.open(file_name) image = PImageOps.grayscale(image) # Cropping the image as too large to display on panel. # Note: the height and width are backwards on purpose as I am forcing it to portrait and rotate the image a bit further down # (I couldn't get xhtml2pdf to recognise the flag in the html style sheet, but could be the version of the lib...) cropped = image.crop((0, 0, epd.height, epd.width)) bw = cropped.convert("1", dither=PImage.FLOYDSTEINBERG) bw = bw.rotate(90) epd.display(bw) epd.update()
def main(): """main program - draw and display a test image""" conf = get_config() tickerlist = conf["symbols"] epd = EPD() print('panel = {p:s} {w:d} x {h:d} version={v:s} COG={g:d} FILM={f:d}'.format(p=epd.panel, w=epd.width, h=epd.height, v=epd.version, g=epd.cog, f=epd.film)) epd.clear() # initially set all white background image = Image.new('1', epd.size, WHITE) # prepare for drawing draw = ImageDraw.Draw(image) width, height = image.size font = ImageFont.truetype(FONT_FILE, FONT_SIZE) wfont = ImageFont.truetype(FONT_FILE, FONT_SIZE/2) ip = get_ip_address('eth0') while True: now = datetime.today() draw.rectangle((0, 0, width, height), fill=WHITE, outline=WHITE) draw.text((0, 160), '%04d-%02d-%02d %02d:%02d:%02d' % (now.year, now.month, now.day, now.hour, now.minute, now.second), fill=BLACK, font=wfont) draw.text((0, 150), '{c:s}'.format(c=ip), fill=BLACK, font=wfont) y = -20 for symbol in tickerlist[:7]: y += 20 draw.text((0, y), get_quote(symbol), fill=BLACK, font=font) # display image on the panel epd.display(image) epd.partial_update() tickerlist.insert(0,tickerlist.pop()) time.sleep(10)
x_end = origin[0] + length * math.sin(radians) y_end = origin[1] - length * math.cos(radians) draw.line([(origin[0], origin[1]), (x_end, y_end)], fill = BLACK, width = width) epd = EPD() print('panel = {p:s} {w:d} x {h:d} version={v:s} COG={g:d} FILM={f:d}'.format(p=epd.panel, w=epd.width, h=epd.height, v=epd.version, g=epd.cog, f=epd.film)) epd.clear() # initially set all white background image = Image.new('1', epd.size, WHITE) width, height = image.size # prepare for drawing draw = ImageDraw.Draw(image) font = ImageFont.truetype("LiberationSerif-Regular.ttf", 36) while True: draw.rectangle((0, 0, width, height), fill=WHITE, outline=WHITE) draw.ellipse((origin[0] -55, origin[1] -55, origin[0] +55, origin[1] +55), fill=WHITE, outline=BLACK) t = time.localtime() h, m, s = t[3:6] hh = h + m /60 draw.text((0,0), '{:02d}.{:02d}.{:02d} '.format(h, m, s), font=font) polar_line(2 * math.pi * s/60, 50, 1) polar_line(2 * math.pi * m/60, 50, 2) polar_line(2 * math.pi * (h + m/60)/12, 30, 4) epd.display(image) epd.partial_update()
# s is size of single block, l is level of code 1 = simple, m is border in blocks (relative to s) # send assembled system command os.system(QRname) #load image for processing into correct size imgName = "qrcode.png" im = Image.open(imgName) #put together system command to pad picture with white pixels and put it on the right end of the image convertname = "convert " + imgName + " -background white -gravity east -extent 264x176 "+ imgName #send assembled system command os.system(convertname) #add text label of usercmd to image for human readabilty convertlabel = "convert " + imgName + " -rotate -90 -gravity South -pointsize 20 -font 'FreeMono-Bold' -annotate +0+2 \""+ usercmd + "\"" " -rotate 90 " + imgName os.system(convertlabel) #reopen image after padding (need exact size for epyper) im = Image.open(imgName) im = ImageOps.grayscale(im) #clear epd epd.clear() #display it! epd.display(im) epd.update() # set oldcmd to the usercmd so it's ready for next loop test oldcmd = usercmd
class PiBus: options = None scheduler = None currentJSON = None logger = None session = None fontTiny = None fontMedium = None fontLarge = None fontHuge = None panel = None partialCount = None lastFetchTime = None renderSuspended = None def __init__(self, options, scheduler): self.options = options self.scheduler = scheduler self.logger = logging.getLogger("PiBus") self.session = requests.Session() if options.debug: self.logger.setLevel(logging.DEBUG) self.logger.debug("Command line options: %s" % self.options) if not self.options.busStopID or not self.options.busLine: self.logger.error("You must provide both bus stop and bus route") sys.exit(1) self.partialCount = 0 self.renderSuspended = False self.fontTiny = ImageFont.truetype("font.ttf", size=10) self.fontMedium = ImageFont.truetype("font.ttf", size=20) self.fontLarge = ImageFont.truetype("font.ttf", size=75) self.fontHuge = ImageFont.truetype("font.ttf", size=150) try: self.panel = EPD() self.logger.debug("Panel: {w:d}x{h:d}".format(w=self.panel.width, h=self.panel.height)) except Exception as e: self.panel = None self.logger.warn("No panel found: %s" % e) self.scheduler.add_job(self.updateBusInfo, trigger='interval', seconds=30, next_run_time=datetime.datetime.now(), max_instances=1) self.scheduler.add_job(self.renderBusInfo, trigger='interval', seconds=10, next_run_time=datetime.datetime.now(), max_instances=1) def prettifyJSON(self, jsonText): """Neatly format JSON to make it human readable""" return json.dumps(jsonText, sort_keys=True, indent=4, separators=(',', ': ')) def fetchBusJSON(self, baseURL, stopID): """Fetch the JSON for a bus stop""" try: url = "%s/StopPoint/%s/arrivals" % (baseURL, stopID) self.logger.debug("Fetching: %s" % url) result = self.session.get(url, timeout=20) except Exception as e: self.logger.error("fetchBusJSON error. Stop %s: %s" % (stopID, e)) return None jsonResult = result.json() self.logger.debug("Raw JSON: %s" % self.prettifyJSON(jsonResult)) return jsonResult def updateBusInfo(self): """Update the bus information""" rawJSON = self.fetchBusJSON(self.options.baseURL, self.options.busStopID) if not rawJSON: self.currentJSON = None self.lastFetchTime = -1 return False self.currentJSON = [] for busItem in rawJSON: if busItem[u'lineName'].lower() == \ self.options.busLine.lower(): self.currentJSON.append(busItem) self.lastFetchTime = time.strftime("%H:%M:%S %d/%m/%Y", time.localtime()) return True def getTimes(self): """Fetch the number of minutes until each bus is due""" if not self.currentJSON: return None times = [] now = datetime.datetime.now(datetime.timezone.utc) for bus in self.currentJSON: due = iso8601.parse_date(bus["expectedArrival"]) dueDiff = due - now minutesDue = divmod(dueDiff.total_seconds(), 60)[0] times.append("%02d" % max(minutesDue, 0)) times.sort() if len(times) == 0: times.append("--") if len(times) == 1: times.append("--") if len(times) == 2: times.append("--") return times def renderBusInfo(self): """Render the available bus information to the e-Ink display""" # the first argument means we get a 1 bit depth image = PIL.Image.new('1', self.panel.size, WHITE) draw = ImageDraw.Draw(image) # Draw a box on the screen draw.line(((0, 0), (self.panel.width, 0)), fill=BLACK, width=1) draw.line(((0, 0), (0, self.panel.height)), fill=BLACK, width=1) draw.line(((self.panel.width - 1, 0), (self.panel.width - 1, self.panel.height)), fill=BLACK, width=1) draw.line(((0, self.panel.height - 1), (self.panel.width - 1, self.panel.height - 1)), fill=BLACK, width=1) times = self.getTimes() if not times and not self.renderSuspended: draw.text((0, 0), "No data available", font=self.fontMedium, fill=BLACK) draw.text((0, 25), time.strftime("%H:%M:%S %d/%m/%Y", time.localtime()), font=self.fontMedium, fill=BLACK) self.panel.display(image) self.panel.update() self.renderSuspended = True elif not times: self.logger.debug("Skipping, rendering is suspended") else: self.renderSuspended = False # Divide up the box draw.line(((self.panel.width * 0.66, 0), (self.panel.width * 0.66, self.panel.height)), fill=BLACK, width=1) draw.line(((self.panel.width * 0.66, self.panel.height * 0.5), (self.panel.width, self.panel.height * 0.5)), fill=BLACK, width=1) # Render the times draw.text((-3, 20), times[0], font=self.fontHuge, fill=BLACK) draw.text((174, 10), times[1], font=self.fontLarge, fill=BLACK) draw.text((174, 100), times[2], font=self.fontLarge, fill=BLACK) # Render the bus route draw.text((1, 0), self.options.busLine, font=self.fontTiny, fill=BLACK) # Render the time of last successful data fetch draw.text((1, self.panel.height - 10), "Fetched: %s" % self.lastFetchTime, font=self.fontTiny, fill=BLACK) self.panel.display(image) if self.partialCount >= 10: self.panel.update() self.partialCount = 0 else: self.panel.partial_update() self.partialCount += 1 def dummyShowBusInfo(self): """blah""" times = self.getTimes() print("") if not times: print("No time information is available") return if len(times) == 0: print("Times info is empty") return for aTime in times: print("Bus due in %d minutes" % aTime)
import sys from PIL import Image from PIL import ImageDraw from EPD import EPD import commands WHITE = 1 BLACK = 0 epd = EPD() epd.clear() # initially set all white background image = Image.new('1', epd.size, WHITE) # prepare for drawing draw = ImageDraw.Draw(image) # stuff output = commands.getoutput('hostname -I') # text draw.text((30, 30), output, fill=BLACK) epd.display(image) epd.update()