Example #1
0
    def sleep(self):
        self.send_command(0x02)  # POWER_OFF
        self.ReadBusy()
        self.send_command(0x07)  # DEEP_SLEEP
        self.send_data(0xA5)  # check code

        epdconfig.module_exit()
Example #2
0
def ctrl_c_handler(signal, frame):
    print("Crtl-C Pressed. Exiting!")
    epdconfig.module_init()
    epdconfig.module_exit()
    exit(0)

    signal.signal(signal.SIGINT, ctrl_c_handler)
    def sleep(self):
        self.send_command(0x10)
        #deep sleep
        self.send_data(0x01)

        epdconfig.delay_ms(2000)
        epdconfig.module_exit()
Example #4
0
    def sleep(self):
        self.send_command(0X02)  # power off
        self.ReadBusy()
        self.send_command(0X07)  # deep sleep
        self.send_data(0xA5)

        epdconfig.module_exit()
Example #5
0
    def exit(self):
        self.send_command(0X50)
        self.send_data(0xf7)
        self.send_command(0X02)
        self.send_command(0X07)
        self.send_data(0xA5)

        epdconfig.module_exit()
    def EPD_Sleep(self):
        self.M1S1M2S2_SendCommand(0X02)
        time.sleep(0.3)

        self.M1S1M2S2_SendCommand(0X07)
        self.M1S1M2S2_SendData(0xA5)
        time.sleep(0.3)
        print("module_exit")
        epdconfig.module_exit()
Example #7
0
    def sleep(self):
        self.send_command(0x10)  # DEEP_SLEEP_MODE
        self.send_data(0x01)

        epdconfig.delay_ms(2000)
        epdconfig.module_exit()


### END OF FILE ###
Example #8
0
    def sleep(self):
        # self.send_command(0x22) #POWER OFF
        # self.send_data(0xC3)
        # self.send_command(0x20)

        self.send_command(0x10)  #enter deep sleep
        self.send_data(0x03)
        epdconfig.delay_ms(2000)
        epdconfig.module_exit()
Example #9
0
    def sleep(self):
        self.send_command(0X50)
        self.send_data(0xf7)
        self.send_command(0X02)
        self.ReadBusy()
        self.send_command(0x07)  # DEEP_SLEEP
        self.send_data(0xA5)  # check code

        epdconfig.delay_ms(2000)
        epdconfig.module_exit()
Example #10
0
def displayUser(Usernames):

    try:
        print("epd7in5bc Demo")

        epd = epd7in5bc.EPD()
        print("init and Clear")
        epd.init()
        epd.Clear()
        time.sleep(1)

        # Drawing on the image
        print("Drawing")
        font36 = ImageFont.truetype('../lib/Font.ttc', 36)
        font24 = ImageFont.truetype('../lib/Font.ttc', 24)
        font18 = ImageFont.truetype('../lib/Font.ttc', 18)
        # Drawing on the Horizontal image
        print("1.Drawing on the Horizontal image...")
        HBlackimage = Image.new('1', (epd.width, epd.height), 255)  # 298*126
        HRYimage = Image.new('1', (epd.width, epd.height),
                             255)  # 298*126  ryimage: red or yellow image
        drawblack = ImageDraw.Draw(HBlackimage)
        drawry = ImageDraw.Draw(HRYimage)

        # Standard box sections
        uSection = 10
        uSectionTime = 60

        numUsers = 0
        for userOut in usernames:
            place = uSection + (numUsers * 10)
            userOutPrint = userOut[1] + ' ' + userOut[
                2] + ' Phone: ' + userOut[3]
            #TODO: find out how many in list, add logic for if user is still out
            userTimePrint = userOut[4]
            drawblack.text((place, 0), str(userTimePrint), font=font24, fill=0)
            drawry.text((place, uSectionTime),
                        str(userOutPrint),
                        font=font24,
                        fill=0)

        epd.display(epd.getbuffer(HBlackimage), epd.getbuffer(HRYimage))
        time.sleep(2)

        print("Goto Sleep...")
        epd.sleep()

    except IOError as e:
        print(e)

    except KeyboardInterrupt:
        print("ctrl + c:")
        epdconfig.module_exit()
        exit()
    pass
Example #11
0
def main():
    y = json.dumps(top_headlines)
    x = json.loads(y)
    source_name = x['articles'][0]['source']['name']
    source_string = "Source: " + source_name
    epd = epd2in13_V2.EPD()
    while True:
        try:
            print("Clearing EPD")
            epd.init(epd.FULL_UPDATE)
            epd.Clear(0xFF)
            HBlackimage = Image.new(
                '1', (epd2in13_V2.EPD_HEIGHT, epd2in13_V2.EPD_WIDTH), 255)

            print("Drawing information to EPD")
            drawblack = ImageDraw.Draw(HBlackimage)
            font20 = ImageFont.truetype('fonts/arial.ttf', 20)
            font10 = ImageFont.truetype('fonts/arial.ttf', 10)

            n_image = Image.new('1', (epd.height, epd.width), 255)
            n_image_draw = ImageDraw.Draw(image)

            epd.init(epd.FULL_UPDATE)
            epd.displayPartBaseImage(epd.getbuffer(n_image))
            epd.init(epd.PART_UPDATE)

            n_image_draw.text((0, 10), source_string, font=font10, fill=0)

            #Begin displaying top 5 headlines

            articles = top_headlines['articles']
            results = []
            for ar in articles:
                results.append(ar['title'])
            for i in range(0, 5):
                n_image_draw.text((0, (35 + (i * 15))),
                                  (str(i + 1) + "." + results[i]),
                                  font=font10,
                                  fill=0)
            #Displays current time
            while (True):
                n_image_draw.rectangle((180, 0, 250, 30), fill=255)
                n_image_draw.text((180, 0),
                                  time.strftime('%H:%M'),
                                  font=font20,
                                  fill=0)
                epd.displayPartial(epd.getbuffer(n_image))

        except IOError as e:
            print('traceback.format_exec():\n%s', traceback.format_exc())
            epdconfig.module_init()
            epdconfig.module_exit()
            exit()
        time.sleep(60)
Example #12
0
 def sleep(self):
     logging.info('enter sleep')
     self.send_command(0X50)  # Vcom and data interval setting
     self.send_data(0xf7)
     logging.debug('power off')
     self.send_command(0X02)  # power off
     logging.debug('enter deep sleep')
     self.send_command(0X07)  # deep sleep
     self.send_data(0xA5)  #deep sleep
     epdconfig.delay_ms(2000)
     epdconfig.module_exit()
Example #13
0
    def sleep(self):
        self.send_command(0x22) #POWER OFF
        self.send_data(0xC3)
        self.send_command(0x20)

        self.send_command(0x10) #enter deep sleep
        self.send_data(0x01)
        epdconfig.delay_ms(100)

        epdconfig.module_exit()

### END OF FILE ###
Example #14
0
    def sleep(self):
        self.send_command(0x50)  # VCOM_AND_DATA_INTERVAL_SETTING
        self.send_data(0x17)
        self.send_command(0x82)  # to solve Vcom drop
        self.send_data(0x00)
        self.send_command(0x01)  # power setting
        self.send_data(0x02)  # gate switch to external
        self.send_data(0x00)
        self.send_data(0x00)
        self.send_data(0x00)
        self.ReadBusy()

        self.send_command(0x02)  # power off

        epdconfig.module_exit()
def ctrl_c_handler(signal, frame):
    print('Goodbye!')
    # XXX : TODO
    #
    # To preserve the life of the ePaper display, it is best not to keep it powered up -
    # instead putting it to sleep when done displaying, or cutting off power to it altogether.
    #
    # epdconfig.module_exit() shuts off power to the module and calls GPIO.cleanup()
    # The latest epd library chooses to shut off power (call module_exit) even when calling epd.sleep()
    # epd.sleep() calls epdconfig.module_exit(), which in turns calls cleanup().
    # We can therefore end up in a situation calling GPIO.cleanup twice
    #
    # Need to cleanup Waveshare epd code to call GPIO.cleanup() only once
    # for now, calling epdconfig.module_init() to set up GPIO before calling module_exit to make sure
    # power to the ePaper display is cut off on exit
    # I have also modified epdconfig.py to initialize SPI handle in module_init() (vs. at the global scope)
    # because slepe/module_exit closes the SPI handle, which wasn't getting initialized in module_init
    epdconfig.module_init()
    epdconfig.module_exit()
    exit(0)
Example #16
0
 def Dev_exit(self):
     epdconfig.module_exit()
def main():
    epd = epd2in13b.EPD()
    while True:

        # Get Weather data from OWM
        obs = owm.weather_at_id(city_id)
        location = obs.get_location().get_name()
        weather = obs.get_weather()
        reftime = weather.get_reference_time()
        description = weather.get_detailed_status()
        temperature = weather.get_temperature(unit='celsius')
        humidity = weather.get_humidity()
        pressure = weather.get_pressure()
        clouds = weather.get_clouds()
        wind = weather.get_wind()
        rain = weather.get_rain()
        sunrise = weather.get_sunrise_time()
        sunset = weather.get_sunset_time()

        print("location: " + location)
        print("weather: " + str(weather))
        print("description: " + description)
        print("temperature: " + str(temperature))
        print("humidity: " + str(humidity))
        print("pressure: " + str(pressure))
        print("clouds: " + str(clouds))
        print("wind: " + str(wind))
        print("rain: " + str(rain))
        print("sunrise: " + time.strftime('%H:%M', time.localtime(sunrise)))
        print("sunset: " + time.strftime('%H:%M', time.localtime(sunset)))

        # Display Weather Information on e-Paper Display
        try:
            print("Clear...")
            epd.init()
            epd.Clear()

            # Drawing on the Horizontal image
            HBlackimage = Image.new(
                '1', (epd2in13b.EPD_HEIGHT, epd2in13b.EPD_WIDTH),
                255)  # 298*126
            HRedimage = Image.new('1',
                                  (epd2in13b.EPD_HEIGHT, epd2in13b.EPD_WIDTH),
                                  255)  # 298*126

            print("Drawing")
            drawblack = ImageDraw.Draw(HBlackimage)
            drawred = ImageDraw.Draw(HRedimage)
            font24 = ImageFont.truetype(
                '/home/pi/ProtoStax_Weather_Station_Demo/fonts/arial.ttf', 20)
            font16 = ImageFont.truetype(
                '/home/pi/ProtoStax_Weather_Station_Demo/fonts/fonts/arial.ttf',
                12)
            font20 = ImageFont.truetype(
                '/home/pi/ProtoStax_Weather_Station_Demo/fonts/fonts/arial.ttf',
                16)
            fontweather = ImageFont.truetype(
                '/home/pi/ProtoStax_Weather_Station_Demo/fonts/fonts/meteocons-webfont.ttf',
                24)
            fontweatherbig = ImageFont.truetype(
                '/home/pi/ProtoStax_Weather_Station_Demo/fonts/fonts/meteocons-webfont.ttf',
                48)

            w1, h1 = font24.getsize(location)
            w2, h2 = font20.getsize(description)
            w3, h3 = fontweatherbig.getsize(
                weather_icon_dict[weather.get_weather_code()])

            drawblack.text(
                (10, 0),
                location + time.strftime(' - %d %b', time.localtime(reftime)),
                font=font24,
                fill=0)
            drawblack.text((10, 25), description, font=font20, fill=0)
            drawred.text((212 - w3 - 10, 0),
                         weather_icon_dict[weather.get_weather_code()],
                         font=fontweatherbig,
                         fill=0)
            #drawblack.text((10, 45), "Observed at: " , font = font16, fill = 0)

            tempstr = str("{0}{1}C".format(int(round(temperature['temp'])),
                                           u'\u00b0'))
            print(tempstr)
            w4, h4 = font24.getsize(tempstr)
            drawblack.text((20, 55), tempstr, font=font24, fill=0)
            drawred.text((20 + w4, 55), "'", font=fontweather, fill=0)
            drawblack.text((120, 55),
                           str("{0}{1} | {2}{3}".format(
                               int(round(temperature['temp_min'])), u'\u00b0',
                               int(round(temperature['temp_max'])),
                               u'\u00b0')),
                           font=font24,
                           fill=0)

            #drawblack.text((10, 60), str("{} hPA".format(int(round(pressure['press'])))), font = font20, fill = 0)
            #drawblack.text((120, 60), str("{}% RH".format(int(round(humidity)))), font = font20, fill = 0)

            drawred.text((5, 78), "A", font=fontweather, fill=0)
            drawred.text((110, 78), "J", font=fontweather, fill=0)
            drawblack.text((30, 83),
                           time.strftime('%I:%M %p', time.localtime(sunrise)),
                           font=font20,
                           fill=0)
            drawblack.text((135, 83),
                           time.strftime('%I:%M %p', time.localtime(sunset)),
                           font=font20,
                           fill=0)

            epd.display(epd.getbuffer(HBlackimage.rotate(180)),
                        epd.getbuffer(HRedimage.rotate(180)))
            time.sleep(2)

            epd.sleep()

        except IOError as e:
            print('traceback.format_exc():\n%s', traceback.format_exc())
            epdconfig.module_init()
            epdconfig.module_exit()
            exit()

        # Sleep for 10 minutes - loop will continue after 10 minutes
        time.sleep(600)  # Wake up every 10 minutes to update weather display
Example #18
0
 def sleep(self):
     self.send_command(0x10) # DEEP_SLEEP_MODE
     self.send_data(0x01)
     
     epdconfig.module_exit()
    time_image = Image.new('1', (epd.width, epd.height), 255)
    time_draw = ImageDraw.Draw(time_image)
    num = 0
    while (True):
        time_draw.rectangle((10, 10, 120, 50), fill=255)
        time_draw.text((10, 10),
                       time.strftime('%H:%M:%S'),
                       font=font24,
                       fill=0)
        newimage = time_image.crop([10, 10, 120, 50])
        time_image.paste(newimage, (10, 10))
        epd.DisplayPartial(epd.getbuffer(time_image))
        num = num + 1
        if (num == 10):
            break

    print("Clear...")
    epd.Clear(0xFF)

    print("Goto Sleep...")
    epd.sleep()

except IOError as e:
    print(e)

except KeyboardInterrupt:
    print("ctrl + c:")
    epdconfig.module_exit()
    exit()
def main():
    global pics
    # Let's get all the images in the pics/ directory and store them in the pics array
    # XXX : TODO - move this out to a separate function, and handle changes in
    # directory - new files getting added and existing ones getting deleted
    print("Getting list of files (images) to display")
    basepath = 'pics/'
    for entry in os.listdir(basepath):
        if os.path.isfile(os.path.join(basepath, entry)):
            print(entry)
            pics.append(basepath + entry)

    # We'll start with the first image in the array, if it exists
    if (len(pics) > 0):
        pic_index = 0
    else:
        print(
            "No files! Nothing to display! We'll just show the default images")

    # Let's initialize the ePaper Display
    epd = epd2in7b.EPD()
    print("Clear...")
    epd.init()
    epd.Clear()

    # red.bmp and black.bmp are the default images, in case
    # the pics/ directory has no images
    # These images just have a message that tells the user to populate
    # the pics/ directory
    # Let's think about usability! :-)
    HBlackimage = Image.open(os.path.join('black.bmp'))
    HRedimage = Image.open(os.path.join('red.bmp'))

    # We'll start looping over the images to display, endlessly,
    # until stopped by Ctrl C
    while True:
        # Display photos and images on e-Paper Display
        try:
            epd.init()
            print("Getting image to display...")
            # If pictures exist in the pics array, we use those
            # otherwise, we've already defaulted to the red.bmp and black.bmp
            # images earlier
            if (len(pics) > 0):
                # let's get the scaled, color mapped and dithered
                # red and black images to display on the ePaper display
                # for the current picture index
                (HRedimage, HBlackimage) = getImagesToDisplay(pics[pic_index])

            print("Rendering display...")
            if (HRedimage != None and HBlackimage != None):
                epd.display(epd.getbuffer(HBlackimage),
                            epd.getbuffer(HRedimage))
                time.sleep(2)

            epd.sleep()

        except Except as e:
            print('traceback.format_exc():\n%s', traceback.format_exc())
            epdconfig.module_init()
            epdconfig.module_exit()
            exit()

        # Let's get the next picture in the array.
        # We'll cycle over when we hit the end of the array
        if (len(pics) > 0):
            pic_index = (pic_index + 1) % len(pics)

        # Sleep for a configured time before waking up to get and display the
        # next image
        time.sleep(SLEEP_TIME)
Example #21
0
def main():

    try:

        try:
            logging.info("Initializing PiSugar2...")
            ps = PiSugar2()
            logging.info("Getting battery level...")
            battery_percentage = ps.get_battery_percentage()
            logging.info("Battery: " + str(int(battery_percentage.value)) +
                         " %")
        except IOError as e:
            logging.info(e)
            battery_percentage = "N/A"
            ps = False

        logging.info("Initiating EPD...")
        epd = EPD()
        epd.init(epd.FULL_UPDATE)

        logging.info("Clearing display...")
        epd.Clear(0xFF)

        logging.info("Starting...")
        img = Image.new("1", (epd.height, epd.width), 255)

        logging.info("Loading font...")
        font_path_location = "/home/pi/projects/crypto-watcher/OpenSans-Regular.ttf"
        font = ImageFont.truetype(font_path_location, 20)
        font_small = ImageFont.truetype(font_path_location, 16)
        font_tiny = ImageFont.truetype(font_path_location, 12)

        timezone = pytz.timezone("Europe/Lisbon")

        while True:

            draw = ImageDraw.Draw(img)
            draw.rectangle((0, 0, epd.height, epd.width), fill=0)

            #BTC
            logging.info("Fetching BTC...")
            price, diff, ohlc = fetch_crypto_data("btcusdt")

            draw.text((8, 5),
                      text="BTC {}$".format(price_to_str(price)),
                      font=font,
                      fill=1)

            diff_symbol = ""
            if diff > 0:
                diff_symbol = "+"
            if diff < 0:
                diff_symbol = "-"

            draw.text((8, 30),
                      text="{}{}$".format(diff_symbol, price_to_str(diff)),
                      font=font_small,
                      fill=1)

            render_ohlc_data(18, ohlc, draw)

            #ETH
            logging.info("Fetching ETH...")
            price, diff, ohlc = fetch_crypto_data("ethusdt")

            draw.text((130, 5),
                      text="ETH {}$".format(price_to_str(price)),
                      font=font,
                      fill=1)

            diff_symbol = ""
            if diff > 0:
                diff_symbol = "+"
            if diff < 0:
                diff_symbol = "-"

            draw.text((130, 30),
                      text="{}{}$".format(diff_symbol, price_to_str(diff)),
                      font=font_small,
                      fill=1)

            render_ohlc_data(138, ohlc, draw)

            #Last update time and battery percentage
            draw.text((6, 106),
                      text=datetime.datetime.now(timezone).strftime(
                          "%Y-%m-%d %H:%M:%S"),
                      font=font_tiny,
                      fill=1)
            if ps:
                draw.text((130, 106),
                          text="Battery: " +
                          str(int(battery_percentage.value)) + " %",
                          font=font_tiny,
                          fill=1)

            #Send image to display
            logging.info("Sending image to display...")
            epd.display(epd.getbuffer(img))

            if RUN_ONCE:
                logging.info("Ran once, exiting...")
                exit()
            else:
                logging.info("Sleeping for " +
                             str(SLEEP_TIME_BETWEEN_REFRESHES) + " seconds...")
                time.sleep(SLEEP_TIME_BETWEEN_REFRESHES)

    except IOError as e:
        logging.info(e)

    except KeyboardInterrupt:
        logging.info("ctrl + c:")
        epdconfig.module_exit()
        exit()
Example #22
0
def show_weather(epd):
    # Get Weather data from OWM
    obs = owm.weather_at_id(city_id)
    location = obs.get_location().get_name()
    weather = obs.get_weather()
    reftime = weather.get_reference_time()
    description = weather.get_detailed_status()
    temperature = weather.get_temperature(unit='celsius')
    humidity = weather.get_humidity()
    pressure = weather.get_pressure()
    clouds = weather.get_clouds()
    wind = weather.get_wind()
    rain = weather.get_rain()
    sunrise = weather.get_sunrise_time()
    sunset = weather.get_sunset_time()

    # Debug
    # print("location: " + location)
    # print("weather: " + str(weather))
    # print("description: " + description)
    # print("temperature: " + str(temperature))
    # print("humidity: " + str(humidity))
    # print("pressure: " + str(pressure))
    # print("clouds: " + str(clouds))
    # print("wind: " + str(wind))
    # print("rain: " + str(rain))
    # print("sunrise: " + time.strftime( '%H:%M', time.localtime(sunrise)))
    # print("sunset: " + time.strftime( '%H:%M', time.localtime(sunset)))

    try:
        # Drawing on the Horizontal image
        HBlackimage = Image.new('1', (epd2in7b.EPD_HEIGHT, epd2in7b.EPD_WIDTH),
                                255)  # 298*126
        HRedimage = Image.new('1', (epd2in7b.EPD_HEIGHT, epd2in7b.EPD_WIDTH),
                              255)  # 298*126

        drawblack = ImageDraw.Draw(HBlackimage)
        drawred = ImageDraw.Draw(HRedimage)
        font24 = ImageFont.truetype('fonts/arial.ttf', 24)
        font16 = ImageFont.truetype('fonts/arial.ttf', 16)
        font20 = ImageFont.truetype('fonts/arial.ttf', 20)
        fontweather = ImageFont.truetype('fonts/meteocons-webfont.ttf', 30)
        fontweatherbig = ImageFont.truetype('fonts/meteocons-webfont.ttf', 60)
        w1, h1 = font24.getsize(location)
        w2, h2 = font20.getsize(description)
        w3, h3 = fontweatherbig.getsize(
            weather_icon_dict[weather.get_weather_code()])

        drawblack.text((10, 0), location, font=font24, fill=0)
        drawblack.text((10 + (w1 / 2 - w2 / 2), 25),
                       "     " + description,
                       font=font20,
                       fill=0)
        drawred.text((264 - w3 - 10, 0),
                     weather_icon_dict[weather.get_weather_code()],
                     font=fontweatherbig,
                     fill=0)
        drawblack.text((10, 45),
                       "Observed at: " +
                       time.strftime('%I:%M %p', time.localtime(reftime)),
                       font=font16,
                       fill=0)
        tempstr = str("{0}{1}C".format(int(round(temperature['temp'])),
                                       u'\u00b0'))

        w4, h4 = font24.getsize(tempstr)
        drawblack.text((10, 70), tempstr, font=font24, fill=0)
        drawred.text((10 + w4, 70), "'", font=fontweather, fill=0)
        drawblack.text(
            (150, 70),
            str("{0}{1} | {2}{3}".format(int(round(temperature['temp_min'])),
                                         u'\u00b0',
                                         int(round(temperature['temp_max'])),
                                         u'\u00b0')),
            font=font24,
            fill=0)
        drawblack.text((10, 100),
                       str("{} hPA".format(int(round(pressure['press'])))),
                       font=font20,
                       fill=0)
        drawblack.text((150, 100),
                       str("{}% RH".format(int(round(humidity)))),
                       font=font20,
                       fill=0)
        drawred.text((20, 120), "A", font=fontweather, fill=0)
        drawred.text((160, 120), "J", font=fontweather, fill=0)
        drawblack.text((10, 150),
                       time.strftime('%I:%M %p', time.localtime(sunrise)),
                       font=font20,
                       fill=0)
        drawblack.text((150, 150),
                       time.strftime('%I:%M %p', time.localtime(sunset)),
                       font=font20,
                       fill=0)

        epd.display(epd.getbuffer(HBlackimage), epd.getbuffer(HRedimage))

        time.sleep(2)
        epd.sleep()

    except IOError as e:
        print('traceback.format_exc():\n%s', traceback.format_exc())
        epdconfig.module_init()
        epdconfig.module_exit()
        exit()
Example #23
0
def main():

    try:
        logging.info("Running for: " + str(len(sys.argv) - 1) +
                     " cryptocurrencies")
        try:
            logging.info("Initializing PiSugar2...")
            ps = PiSugar2()
            logging.info("Getting battery level...")
            battery_percentage = ps.get_battery_percentage()
            logging.info("Battery: " + str(int(battery_percentage.value)) +
                         " %")
            logging.info("Syncing RTC...")
            ps.set_pi_from_rtc()
        except:
            logging.info(e)
            ps = False

        logging.info("Initiating EPD...")
        epd = EPD()
        epd.init(epd.FULL_UPDATE)
        logging.info("Clearing display...")
        epd.Clear(0xFF)

        logging.info("Starting...")
        img = Image.new("1", (epd.height, epd.width), 255)

        logging.info("Loading font...")
        font_dir_path = os.path.dirname(__file__)
        font_file_name = "OpenSans-Regular.ttf"
        font_absolut_path = os.path.join(font_dir_path, font_file_name)
        logging.info("font path: " + font_absolut_path)
        font = ImageFont.truetype(font_absolut_path, 20)
        font_small = ImageFont.truetype(font_absolut_path, 16)
        font_tiny = ImageFont.truetype(font_absolut_path, 12)

        timezone = pytz.timezone("Europe/Lisbon")

        positive_filling = get_color(1)
        negative_filling = get_color(0)

        while True:

            # Iterate the cryptos provided
            for i in range(1, len(sys.argv)):

                crypto_name = sys.argv[i].upper()
                logging.info("Fetching " + crypto_name + "...")
                try:
                    price, diff, ohlc = fetch_crypto_data(crypto_name + "USDT")
                except:
                    logging.error("Error fetching " + crypto_name + " data...")
                    price = 0
                    diff = 0
                    ohlc = None

                diff_symbol = ""
                if diff > 0:
                    diff_symbol = "+"

                old_price = price - diff
                diff_percentage = "%.1f" % (((price -
                                              (old_price)) / old_price) * 100)

                # Odds on the left, evens on the right
                if (i % 2):
                    # Left side of the display
                    draw = ImageDraw.Draw(img)
                    draw.rectangle((0, 0, epd.height, epd.width),
                                   fill=negative_filling)

                    # Last update time
                    draw.text((6, 106),
                              text=datetime.datetime.now(timezone).strftime(
                                  "%Y-%m-%d %H:%M:%S"),
                              font=font_tiny,
                              fill=positive_filling)

                    # Battery percentage
                    if ps != False:
                        # new PiSugar model uses battery_power_plugged & battery_allow_charging to detect real charging status
                        battery_display_text = "Battery: " + \
                            str(int(battery_percentage.value)) + " %"
                        if ps.get_battery_led_amount().value == 2:
                            if ps.get_battery_power_plugged(
                            ).value and ps.get_battery_allow_charging().value:
                                logging.info("Charging...")
                                battery_display_text = battery_display_text + " CHG"
                        draw.text((130, 106),
                                  text=battery_display_text,
                                  font=font_tiny,
                                  fill=positive_filling)
                    logging.info("Left crypto...")
                    draw.text((8, 5),
                              text="{crypto_name} {value}$".format(
                                  crypto_name=crypto_name,
                                  value=price_to_str(price)),
                              font=font,
                              fill=positive_filling)
                    draw.text(
                        (8, 30),
                        text=
                        "{diff_symbol}{diff_value}$ {diff_symbol}{diff_percentage}%"
                        .format(diff_symbol=diff_symbol,
                                diff_value=price_to_str(diff),
                                diff_percentage=diff_percentage),
                        font=font_small,
                        fill=positive_filling)
                    render_ohlc_data(18, ohlc, draw, font_small)
                else:
                    # Right side of the display
                    logging.info("Right crypto...")
                    draw.text((130, 5),
                              "{crypto_name} {value}$".format(
                                  crypto_name=crypto_name,
                                  value=price_to_str(price)),
                              font=font,
                              fill=positive_filling)
                    draw.text(
                        (130, 30),
                        text=
                        "{diff_symbol}{diff_value}$ {diff_symbol}{diff_percentage}%"
                        .format(diff_symbol=diff_symbol,
                                diff_value=price_to_str(diff),
                                diff_percentage=diff_percentage),
                        font=font_small,
                        fill=positive_filling)
                    render_ohlc_data(138, ohlc, draw, font_small)
                    if (i == len(sys.argv) - 1):
                        # if its the last crypto of the list the script will send the image
                        # to the display and sleep, out of the loop, no need to do it here
                        break
                    else:
                        # Send image to display and wait SLEEP_TIME_BETWEEN_REFRESHES seconds before continue iterating
                        logging.info("Sending image to display...")
                        epd.init(epd.PART_UPDATE)
                        epd.displayPartial(epd.getbuffer(img))
                        logging.info("Sleeping for " +
                                     str(SLEEP_TIME_BETWEEN_REFRESHES) +
                                     " seconds...")
                        time.sleep(SLEEP_TIME_BETWEEN_REFRESHES)

            # Send image to display
            logging.info("Sending image to display...")
            epd.init(epd.PART_UPDATE)
            epd.displayPartial(epd.getbuffer(img))

            if RUN_ONCE:
                logging.info("Ran once, exiting...")
                exit()
            else:
                logging.info("Sleeping for " +
                             str(SLEEP_TIME_BETWEEN_REFRESHES) + " seconds...")
                time.sleep(SLEEP_TIME_BETWEEN_REFRESHES)

    except IOError as e:
        logging.info(e)

    except KeyboardInterrupt:
        logging.info("Detected ctrl + c:")
        try:
            epdconfig.module_exit()
        except RuntimeError as re:
            logging.error("Error exiting display module:")
            logging.error(re)
        exit()
Example #24
0
 def deinit():
     epdconfig.module_exit()
Example #25
0
def main():
    y = json.dumps(top_headlines)
    x = json.loads(y)
    yy = json.dumps(top_headlines_2)
    xx = json.loads(yy)
    source_name = x['articles'][0]['source']['name']
    source_name_2 = xx['articles'][0]['source']['name']
    source_string = "Sources: " + source_name
    source_string_2 = "Sources: " + source_name_2
    epd = epd2in13_V2.EPD()
    while True:
        try:
            print("Clear...")
            epd.init(
                epd.FULL_UPDATE
            )  #Initiates the E-Paper Display; Also wakes up from deep sleep
            epd.Clear(0xFF)  #Sets the screen to white
            HBlackimage = Image.new(
                '1', (epd2in13_V2.EPD_HEIGHT, epd2in13_V2.EPD_WIDTH), 255)

            print("Drawing...")
            drawblack = ImageDraw.Draw(HBlackimage)
            font20 = ImageFont.truetype('fonts/arial.ttf', 20)
            font12 = ImageFont.truetype(
                'fonts/arial.ttf',
                10)  #Note changed to 10 just for testing purposes!

            ######Test for updating time, but static headlines
            time_image = Image.new('1', (epd.height, epd.width), 255)
            time_draw = ImageDraw.Draw(time_image)

            epd.init(epd.FULL_UPDATE)
            epd.displayPartBaseImage(epd.getbuffer(time_image))
            epd.init(epd.PART_UPDATE)

            time_draw.text((0, 10), source_string, font=font12, fill=0)
            time_draw.text((0, 25), source_string_2, font=font12, fill=0)

            #Begin displaying the top 3 headlines from each language

            articles_de = top_headlines['articles']
            results_de = []
            for ar in articles_de:
                results_de.append(ar['title'])
            for i_d in range(0, 3):
                time_draw.text((0, (35 + (i_d * 15))),
                               (str(i_d + 1) + "." + results_de[i_d]),
                               font=font12,
                               fill=0)

            articles = top_headlines_2['articles']
            results = []
            for art in articles:
                results.append(art['title'])
            for i in range(0, 3):
                time_draw.text((0, (80 + (i * 15))),
                               str(i + 3) + "." + results[i],
                               font=font12,
                               fill=0)

            while (True):
                time_draw.rectangle((180, 0, 250, 30), fill=255)
                time_draw.text((180, 0),
                               time.strftime('%H:%M'),
                               font=font20,
                               fill=0)
                epd.displayPartial(epd.getbuffer(time_image))

        except IOError as e:
            print('traceback.format_exec():\n%s', traceback.format_exc())
            epdconfig.module_init()
            epdconfig.module_exit()
            exit()
        time.sleep(60)
Example #26
0
def ctrl_c_handler(signal, frame):
    print('Control-C Pressed - Exiting!')
    epdconfig.module_init()
    epdconfig.module_exit()
    exit(0)
Example #27
0
def ctrl_c_handler(signal, frame):
    # print('Goodbye!')
    epdconfig.module_init()
    epdconfig.module_exit()
    exit(0)