Пример #1
0
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()
Пример #2
0
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)
Пример #3
0
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)
Пример #4
0
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()
Пример #5
0
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()

Пример #7
0
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)
    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()