Пример #1
0
def bouw_afbeelding_met_quote(quote):
    epd = epd2in13_V2.EPD()
    epd.init(epd.FULL_UPDATE)
    epd.Clear(0xFF)

    font17 = ImageFont.truetype(os.path.join(picdir, 'Font.ttc'), 17)

    image = Image.new('1', (epd.height, epd.width), 255)  # Frame eerst poetsen
    draw = ImageDraw.Draw(image)
    logging.debug('Afbeelding maken van de gevonden quote.')

    # Breek zinnen af zodat het past op scherm
    def wrap_by_word(tekst, linebreakLocatie):
        gespletenTekst = tekst.split()
        resultaat = ''
        for i in range(0, len(gespletenTekst), linebreakLocatie):
            resultaat += ' '.join(
                gespletenTekst[i:i + linebreakLocatie]) + '\n'
        return resultaat

    # Centrale quote
    draw.multiline_text((20, 20),
                        wrap_by_word(quote, 4),
                        align="left",
                        font=font17)

    epd.display(epd.getbuffer(image))

    epd.sleep()
Пример #2
0
def printImage(img):
    logging.info("Printing to ePaper Display")
    epd = epd2in13_V2.EPD()
    epd.init(epd.FULL_UPDATE)
    epd.Clear(0xFF)
    image = Image.open(os.path.join(picturesDir, img))
    epd.display(epd.getbuffer(image))
    time.sleep(2)
Пример #3
0
def printPicture(img):
    logging.info("Wallpaper")
    epd = epd2in13_V2.EPD()
    logging.info("init and Clear")
    epd.init(epd.FULL_UPDATE)
    epd.Clear(0xFF)
    logging.info("reading image file...")
    image = Image.open(os.path.join(cameraDir, img))
    epd.display(epd.getbuffer(image))
    time.sleep(2)
    logging.info("Goto Sleep...")
Пример #4
0
def printWallpaper():
    logging.info("Wallpaper")
    epd = epd2in13_V2.EPD()
    logging.info("init and Clear")
    epd.init(epd.FULL_UPDATE)
    epd.Clear(0xFF)
    wallpaper = 'wallpaper-' + str(random.randint(1, 4)) + '.jpg'
    logging.info("reading image file...")
    image = Image.open(os.path.join(wallpaperDir, wallpaper))
    epd.display(epd.getbuffer(image))
    time.sleep(2)
    logging.info("Goto Sleep...")
Пример #5
0
def init_display():
    global epd, font_stats, font_line1, font_line2, time_image, time_draw;
    epd = epd2in13_V2.EPD();
    epd.init(epd.FULL_UPDATE);
    epd.Clear(0xFF);

    font_stats = ImageFont.truetype(os.path.join(picdir, 'Font.ttc'), 15);
    font_line1 = ImageFont.truetype(os.path.join(picdir, 'Font.ttc'), 24);
    font_line2 = ImageFont.truetype(os.path.join(picdir, 'Font.ttc'), 24);
    time_image = Image.new('1', (epd.height, epd.width), 255);
    time_draw = ImageDraw.Draw(time_image);
    
    epd.displayPartBaseImage(epd.getbuffer(time_image));
    epd.init(epd.PART_UPDATE);
Пример #6
0
def beanaproblem(message):
#   A visual cue that the wheels have fallen off
    thebean = Image.open(os.path.join(picdir,'thebean.bmp'))
    epd = epd2in13_V2.EPD()
    epd.init(epd.FULL_UPDATE)
    image = Image.new('L', (epd.height, epd.width), 255)    # 255: clear the image with white
    draw = ImageDraw.Draw(image)
    image.paste(thebean, (60,15))
    draw.text((15,150),message, font=font_date,fill = 0)
    image = ImageOps.mirror(image)
    epd.display(epd.getbuffer(image))
    logging.info("epd2in13_V2 BTC Frame")
#   Reload last good config.yaml
    with open(configfile) as f:
        config = yaml.load(f, Loader=yaml.FullLoader)
Пример #7
0
def printToPaper(text):
    logging.info("print to paper")
    epd = epd2in13_V2.EPD()
    logging.info("init and Clear")
    epd.init(epd.FULL_UPDATE)
    epd.Clear(0xFF)
    # Drawing on the image
    smallText = ImageFont.truetype(
        os.path.join(fontsDir, 'Poppins-SemiBold.ttf'), 18)
    #logging.info("1.Drawing on the image...")
    image = Image.new('1', (epd.height, epd.width),
                      255)  # 255: clear the frame
    draw = ImageDraw.Draw(image)
    draw.text((20, 5), text, font=smallText, fill=0)
    epd.display(epd.getbuffer(image))
    time.sleep(2)
Пример #8
0
 def __init__(self):
     self.__image = Image.new('1', (height, width), 255)
     self.__draw = ImageDraw.Draw(self.__image)
     self.__picdir = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))), 'pic')
     self.__font12 = ImageFont.truetype(os.path.join(self.__picdir, 'Font.ttc'), 12)
     self.__font15 = ImageFont.truetype(os.path.join(self.__picdir, 'Font.ttc'), 15)
     self.__font24 = ImageFont.truetype(os.path.join(self.__picdir, 'Font.ttc'), 24)
     self.__font30 = ImageFont.truetype(os.path.join(self.__picdir, 'Font.ttc'), 30)
     self.__font35 = ImageFont.truetype(os.path.join(self.__picdir, 'Font.ttc'), 35)
     self.__font40 = ImageFont.truetype(os.path.join(self.__picdir, 'Font.ttc'), 40)
     logging.info("init screen")
     self.__epd = epd2in13_V2.EPD()  # 实例化墨水屏对象
     logging.info("set full update")
     self.__epd.init(self.__epd.FULL_UPDATE)  # 设置为全局刷新
     self.drawbackimg()
     self.__epd.displayPartBaseImage(self.__epd.getbuffer(self.__image))  # 绘制背景图片
Пример #9
0
  def __init__(self, logger, weather, dark, datadir):
    self.logger = logger
    self.weather = weather
    self.width = 250
    self.height = 122
    self.enable_epd = os.environ.get('DEBUG') is None
    if self.enable_epd:
      self.epd = epd2in13_V2.EPD()
    self.font_size = [8, 10, 13, 17, 22, 28, 35, 43]
    self.fonts = {
      'japanese': {},
      'emoji': {},
    }
    self.font_file_dirs = [
      os.path.dirname(__file__) + '/fonts',
      '/usr/share/fonts/opentype/noto',
      '/usr/share/fonts/noto',
    ]
    self.font_file_names = {
      'japanese': 'NotoSansCJK-Regular.ttc',
      'emoji': 'NotoEmoji-Regular.ttf'
    }
    self.font_files = {}
    # check
    for (name, filename) in self.font_file_names.items():
      for dir in self.font_file_dirs:
        if os.path.exists(f'{dir}/{filename}'):
          self.font_files[name] = f'{dir}/{filename}'
          break
    missing = list(filter(lambda n: not self.font_files.get(n), self.font_file_names))
    if len(missing) > 0:
      raise Exception('font file not found: %s' % (' '.join([self.font_file_names[m] for m in missing])))
    # initialize fonts
    for s in self.font_size:
      for n, p in self.font_files.items():
        self.fonts[n][s] = ImageFont.truetype(p, s)

    self.imagefile = f'{datadir}/image.png'
    self.draw = None

    if dark:
      self.background_color = 0
      self.foreground_color = 255
    else:
      self.background_color = 255
      self.foreground_color = 0
Пример #10
0
def main(text):
    try:
        epd = epd213.EPD()
        epd.init(epd.FULL_UPDATE)
        epd.Clear(0xFF)

        # Drawing and creating image
        fontt = ImageFont.truetype(os.path.join(picdir, 'Font.ttc'), 24)

        image = Image.new('1', (epd.height, epd.width),
                          255)  # 255: clear the frame
        draw = ImageDraw.Draw(image)

        draw.text((110, 90), text, font=fontt, fill=0)
        epd.display(epd.getbuffer(image))

    except IOError as e:
        logging.info(e)
Пример #11
0
def main():
    try:
        epd = epd2in13_V2.EPD()
        epd.init(epd.FULL_UPDATE)
        epd.Clear(0xFF)

        screen_image = Image.new('1', (SCREEN_WIDTH, SCREEN_HEIGHT), 255)
        screen_draw = ImageDraw.Draw(screen_image)
        epd.displayPartBaseImage(epd.getbuffer(screen_image))
        epd.init(epd.PART_UPDATE)

        while True:
            try:
                prices = fetch_prices()
                form_image(prices, screen_draw)

                screen_image_rotated = screen_image.rotate(180)
                epd.displayPartial(epd.getbuffer(screen_image_rotated))
                # TODO: add a way to switch bewen partial and full update
                # epd.display(epd.getbuffer(screen_image_rotated))

                time.sleep(REFRESH_INTERVAL)
            except HTTPError as e:
                print(e)
                time.sleep(5)

        epd.init(epd.FULL_UPDATE)
        epd.Clear(0xFF)
        epd.sleep()
        epd.Dev_exit()

    except IOError as e:
        print(e)

    except KeyboardInterrupt:
        print("exiting")
        epd2in13_V2.epdconfig.module_exit()
        exit()
Пример #12
0
    def __init__(self, width, height):

        self._width = width
        self._height = height

        self._config = configparser.ConfigParser()
        self._config.read(CONFIG_FILE)
        self._realtime_api = self._config.get('weather', 'realtime_api')
        self._airquality_api = self._config.get('weather', 'airquality_api')
        self._refresh_seconds = int(
            self._config.get('weather', 'refresh_seconds'))
        self._city_code = self._config.get('city', 'code')

        self._spider = WeatherSpider(realtime_api=self._realtime_api,
                                     airquality_api=self._airquality_api)
        self._weather_data = WeatherData(self._city_code)

        self._epd = epd2in13_V2.EPD()

        self._image = Image.new('1', (self._width, self._height), 'white')
        image_draw = ImageDraw.Draw(self._image)
        self._weather_painter = WeatherPainterSmall(image_draw, self._width,
                                                    self._height)
Пример #13
0
def main():
    try:
        lastrun = time.time() - 300
        device = cloud4rpi.connect(CLOUD4RPI_DEVICE_TOKEN)
        epd = epd2in13_V2.EPD()
        epd.init(epd.FULL_UPDATE)
        # epd.Clear(0xFF)
        image = Image.new("1", (epd.height, epd.width), 255)  # 255: clear the frame
        draw = ImageDraw.Draw(image)
        epd.displayPartBaseImage(epd.getbuffer(image))
        epd.init(epd.PART_UPDATE)
        while True:
            status, remitdata = InstaRemRate()
            if status:
                rate_instarem = round(remitdata["destination_amount"]/1000, 2)
                fx_rate = round(remitdata["fx_rate"], 2)
            else:
                rate_instarem = 0
            # Remitly
            status, rate_remitly = RemitlyRate()
            # Xoom
            status, rate_xoom = XoomRate()
            # Ria Rate
            status, rate_ria = RiaRate()
            datetime = time.strftime("%m/%d/%y %H:%M:%S")
            print(f"FX Rate: {fx_rate} Instarem: {rate_instarem} Remitly: {rate_remitly} Xoom: {rate_xoom} Ria: {rate_ria}  Last Updated {datetime}")
            draw.rectangle([(0, 0), (epd.height, 26)], fill=255)
            draw.text((0, 0), f"$1 = {fx_rate}", font=font24, fill=0)
            draw.text((140, 2), time.strftime("%m/%d %H:%M"), font=font20, fill=0)
            draw.line([(0, 30), (epd.height, 30)], fill=0, width=1)
            rate_all = {
                "instarem": rate_instarem,
                "remitly": rate_remitly,
                "xoom": rate_xoom,
                "ria": rate_ria
                }
            rate_sorted = sorted(rate_all.items(), key=lambda x: x[1], reverse=True)
            draw.rectangle([(0, 75), (epd.height, 105)], fill=255)
            ypos_icon = 10
            ypos_rate = 0
            space_icon = 65
            for name, rate in rate_sorted:
                image.paste(get_icon(name), (ypos_icon, 40))
                if rate != 0:
                    draw.text((ypos_rate, 75), str(rate), font=font20, fill=0)
                ypos_icon += space_icon
                ypos_rate += space_icon
            draw.rectangle((0, 104, 249, 121), fill=255, outline=0)
            epd.displayPartial(epd.getbuffer(image))
            currentperf = time.time()
            try:
                diagnostics = {
                "CPU Temp": rpi.cpu_temp,
                "IP Address": rpi.ip_address,
                "Host": rpi.host_name,
                "Operating System": rpi.os_name,
                "Client Version:": cloud4rpi.__version__,
                }
                variables = {
                    "Fx Rate": {
                        "type": "numeric",
                        "value": fx_rate if fx_rate != 0 else ""
                    },
                    "Instarem": {
                        "type": "numeric",
                        "value": rate_instarem if rate_instarem != 0 else ""
                    },
                    "Remitly": {
                        "type": "numeric",
                        "value": rate_remitly if rate_remitly != 0 else ""
                    },
                    "Xoom": {
                        "type": "numeric",
                        "value": rate_xoom if rate_xoom != 0 else ""
                    },
                    "Ria": {
                        "type": "numeric",
                        "value": rate_ria if rate_ria != 0 else ""
                    }
                }
                device.declare(variables)
                device.declare_diag(diagnostics)
                # device.publish_config()
                # time.sleep(1)
                device.publish_diag()
                if currentperf - lastrun > 300:
                    print("Uploading  Data to cloud4rpi")
                    device.publish_data()
                    lastrun = time.time()
            except Exception as e:
                error = cloud4rpi.get_error_message(e)
                cloud4rpi.log.exception("ERROR! %s %s", error, sys.exc_info()[0])
            for i in range(10, 255, 10):
                draw.rectangle((0, 107, i, 118), fill=0)
                epd.displayPartial(epd.getbuffer(image))
                time.sleep(2)
    except KeyboardInterrupt:
        epd2in13_V2.epdconfig.module_exit()
        exit()
Пример #14
0
 def _init_display():
     epd = epd2in13_V2.EPD()
     epd.init(epd.FULL_UPDATE)
     epd.Clear(0xFF)
     epd.init(epd.PART_UPDATE)
     return epd
Пример #15
0
def displaymain():

    try:
        logging.info("epd2in13_V2 Demo")

        epd = epd2in13_V2.EPD()
        logging.info("init and Clear")
        epd.init(epd.FULL_UPDATE)
        epd.Clear(0xFF)

        # Drawing on the image
        font15 = ImageFont.truetype(os.path.join(picdir, 'Font.ttc'), 15)
        font24 = ImageFont.truetype(os.path.join(picdir, 'Font.ttc'), 24)
        font16 = ImageFont.truetype(os.path.join(picdir, 'Font1.otf'), 16)
        font12 = ImageFont.truetype(os.path.join(picdir, 'Font1.otf'), 12)

        time_image = Image.new('1', (epd.height, epd.width), 255)
        time_draw = ImageDraw.Draw(time_image)

        image = Image.new('1', (epd.height, epd.width),
                          255)  # 255: clear the frame
        draw = ImageDraw.Draw(image)

        epd.init(epd.FULL_UPDATE)

        num = 0

        time_draw.text((0, 107),
                       str(num) + 'Bottom font15',
                       font=font12,
                       fill=0)
        draw.text((0, 107), str(num) + 'Bottom font15', font=font12, fill=0)

        epd.displayPartBaseImage(epd.getbuffer(image))

        epd.init(epd.PART_UPDATE)

        # draw.text((0, 107), 'Bottom font15', font = font15, fill = 0)

        currtemttime = 0
        while (True):
            # while(s.recvfrom(1024)[0].decode('gb2312')!='exit'):
            time_draw.rectangle((0, 0, 125, 61), fill=255)
            time_draw.rectangle((126, 62, 250, 122), fill=255)
            time_draw.text((0, 0),
                           str(num) + u'次 time draw',
                           font=font12,
                           fill=0)
            # time_draw.text((10, 13), u'新世紀エヴァンゲリオン', font = font16, fill = 0)
            # time_draw.text((10, 13), recv_msg, font=font16, fill=0)
            # print(recv_msg+' Thread 2')
            # logging.info(recv_msg)
            # time_draw.text((0, 40), '', font = font12, fill = 0)
            time_draw.text((126, 62),
                           time.strftime('%H:%M:%S'),
                           font=font16,
                           fill=0)
            # edp.displayPartial
            # logging.info(str(time.time()))
            draw.rectangle((126, 62, 250, 122), fill=255)
            draw.text((0, 0), str(num) + u'次 draw', font=font12, fill=0)

            epd.displayPartial(epd.getbuffer(time_image))
            print('part1')
            time.sleep(2)

            epd.displayPartial(epd.getbuffer(image))
            print('part2')
            time.sleep(2)

            num = num + 1
            # print(recv_msg)
            if (num == 5):
                break
            # if (recv_msg.endswith('bye')):
            #     break

        logging.info("Clear...")
        epd.init(epd.FULL_UPDATE)
        epd.Clear(0xFF)

        logging.info("Goto Sleep...")
        epd.sleep()
        epd.Dev_exit()

    except IOError as e:
        logging.info(e)

    except KeyboardInterrupt:
        logging.info("ctrl + c:")
        epd2in13_V2.epdconfig.module_exit()
        exit()
Пример #16
0
anyway = False  #for test
font12 = ImageFont.truetype(os.path.join(picdir, 'Font.ttc'), 12)
font15 = ImageFont.truetype(os.path.join(picdir, 'Font.ttc'), 15)
font24 = ImageFont.truetype(os.path.join(picdir, 'Font.ttc'), 24)
font30 = ImageFont.truetype(os.path.join(picdir, 'Font.ttc'), 30)
font35 = ImageFont.truetype(os.path.join(picdir, 'Font.ttc'), 35)
font40 = ImageFont.truetype(os.path.join(picdir, 'Font.ttc'), 40)
logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s:%(name)s:%(levelname)s:%(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S')
#logging.basicConfig(filename="clock.log", level=logging.DEBUG)

try:
    logging.info("show time")
    #初始化屏幕并清屏
    epd = epd2in13_V2.EPD()  #实例化墨水屏对象
    logging.info("init and Clear")
    epd.init(epd.FULL_UPDATE)  #初始化和退出睡眠后调用,full_update全刷性
    #epd.Clear(0xFF)

    # 设置背景图片
    logging.info("show time...")
    time_image = Image.new('1', (epd.height, epd.width), 255)
    time_draw = ImageDraw.Draw(time_image)
    time_draw.line((0, 45, epd.height, 45), fill=0)
    time_draw.line((80, 45, 80, 120), fill=0)
    time_draw.line((162, 45, 162, 120), fill=0)
    time_draw.text((170, 80), u"数据来自", font=font15, fill=0)
    time_draw.text((170, 100), u"彩云科技", font=font15, fill=0)
    logging.info("set background img")
    epd.displayPartBaseImage(epd.getbuffer(time_image))
Пример #17
0
def updateDisplay(config,pricestack,whichcoin,fiat,other):
    """   
    Takes the price data, the desired coin/fiat combo along with the config info for formatting
    if config is re-written following adustment we could avoid passing the last two arguments as
    they will just be the first two items of their string in config 
    """
    days_ago=int(config['ticker']['sparklinedays'])   
    symbolstring=currency.symbol(fiat.upper())
    if fiat=="jpy" or fiat=="cny":
        symbolstring="¥"
    pricenow = pricestack[-1]
    currencythumbnail= 'currency/'+whichcoin+'.bmp'
    tokenfilename = os.path.join(picdir,currencythumbnail)
    sparkbitmap = Image.open(os.path.join(picdir,'spark.bmp'))
    ATHbitmap= Image.open(os.path.join(picdir,'ATH.bmp'))
#   Check for token image, if there isn't one, get on off coingecko, resize it and pop it on a white background
    if os.path.isfile(tokenfilename):
        logging.info("Getting token Image from Image directory")
        tokenimage = Image.open(tokenfilename).convert("RGBA")
    else:
        logging.info("Getting token Image from Coingecko")
        tokenimageurl = "https://api.coingecko.com/api/v3/coins/"+whichcoin+"?tickers=false&market_data=false&community_data=false&developer_data=false&sparkline=false"
        rawimage = requests.get(tokenimageurl).json()
        tokenimage = Image.open(requests.get(rawimage['image']['large'], stream=True).raw).convert("RGBA")
        resize = 100,100
        tokenimage.thumbnail(resize, Image.ANTIALIAS)
        new_image = Image.new("RGBA", (120,120), "WHITE") # Create a white rgba background with a 10 pixel border
        new_image.paste(tokenimage, (10, 10), tokenimage)   
        tokenimage=new_image
        tokenimage.thumbnail((100,100),Image.ANTIALIAS)
        tokenimage.save(tokenfilename)


    pricechange = str("%+d" % round((pricestack[-1]-pricestack[0])/pricestack[-1]*100,2))+"%"
    if pricenow > 1000:
        pricenowstring =format(int(pricenow),",")
    else:
        pricenowstring =str(float('%.5g' % pricenow))

    if config['display']['orientation'] == 0 or config['display']['orientation'] == 180 :
        epd = epd2in13_V2.EPD()
        epd.init(epd.FULL_UPDATE)
        image = Image.new('L', (epd.width, epd.height), 255)    # 255: clear the image with white
        draw = ImageDraw.Draw(image)              
        draw.text((110,80),str(days_ago)+"day :",font =font_date,fill = 0)
        draw.text((110,95),pricechange,font =font_date,fill = 0)
        # Print price to 5 significant figures
        draw.text((15,200),symbolstring+pricenowstring,font =font,fill = 0)
        draw.text((10,10),str(time.strftime("%H:%M %a %d %b %Y")),font =font_date,fill = 0)
        image.paste(tokenimage, (10,25))
        image.paste(sparkbitmap,(10,125))
        if config['display']['orientation'] == 180 :
            image=image.rotate(180, expand=True)


    if config['display']['orientation'] == 90 or config['display']['orientation'] == 270 :
        epd = epd2in13_V2.EPD()
        epd.init(epd.FULL_UPDATE)
        image = Image.new('L', (epd.height, epd.width), 255)    # 255: clear the image with white
        draw = ImageDraw.Draw(image)   
        draw.text((135,85),str(days_ago)+" day : "+pricechange,font =font_date,fill = 0)
#mining
        if config['mining']['enabled'] == True :
            host = 'https://api2.nicehash.com' #host connection
            organisation_id = str(config['mining']['organisation']) #organisation string
            key = str(config['mining']['key']) #public key string
            secret = str(config['mining']['secret']) #secret key string

            private_api = nicehash.private_api(host, organisation_id, key, secret)

            if config['mining']['display'] == "wallet,unpaid" or config['mining']['display'] == "wallet" :
                accounts = private_api.get_accounts() #get accounts json
                accountsdata = str(accounts['total']) #grab totals
                accountslist = accountsdata.split("'") #organize
                wallet = float(accountslist[7]) #isolate total balance
                currencydata = str(accounts['currencies'])
                currencylist = currencydata.split(":")
                rate = float('{:.8}'.format(currencylist[7]))
                total = wallet*rate
                balance = float('{:.2f}'.format(total))
                
                if config['mining']['walletcurrency'] == "btc" :
                    draw.text((100,13),"Wallet: "+str(wallet)+" BTC",font =font_mining2,fill = 0) #draw wallet balance
                if config['mining']['walletcurrency'] == "cad" :
                    draw.text((100,13),"Wallet: $"+str(balance),font =font_mining,fill = 0)
            if config['mining']['display'] == "unpaid,wallet" or config['mining']['display'] == "unpaid" :
                unpaid = private_api.get_unpaid() #get unpaid json

                strdata = str(unpaid['data']) #grab "data" section and convert to string
                listdata = strdata.split(",") #organize

                maybe = float(listdata[2]) #grab total unpaid
                almost = format(float(maybe), '.8f') #convert form scientific to decimal float
                working = decimal.Decimal(almost) #convert from float to decimal
                ok = working * 100000000 #make whole number
                final = int(ok) #convert to integer to drop decimals

                draw.text((100,13),"Unpaid NH: "+str(final)+" Sat",font =font_mining,fill = 0) #draw unpaid mining


#end mining

 #.     uncomment the line below to show volume
 #       draw.text((110,105),"24h vol : " + human_format(other['volume']),font =font_date,fill = 0)
        if config['ticker']['coinname'] == True :
            draw.text((100,100),symbolstring+pricenowstring+"/"+whichcoin,font =fontHorizontal,fill = 0)
        else:
            draw.text((135,100),symbolstring+pricenowstring,font =fontHorizontal,fill = 0)

        if other['ATH']==True:
            image.paste(ATHbitmap,(190,85))
        image.paste(sparkbitmap,(80,25))
        image.paste(tokenimage, (0,10))
 #       draw.text((5,110),"Inretrospect, it was inevitable",font =font_date,fill = 0)
        draw.text((95,1),str(time.strftime("%H:%M %a %d %b %Y")),font =font_date,fill = 0)
        if config['display']['orientation'] == 270 :
            image=image.rotate(180, expand=True)
#       This is a hack to deal with the mirroring that goes on in 4Gray Horizontal
#        image = ImageOps.mirror(image)

#   If the display is inverted, invert the image usinng ImageOps        
    if config['display']['inverted'] == True:
        image = ImageOps.invert(image)
#   Send the image to the screen        
    epd.display(epd.getbuffer(image))
Пример #18
0
def updateDisplay(config,pricestack,whichcoin,fiat,other):
    """   
    Takes the price data, the desired coin/fiat combo along with the config info for formatting
    if config is re-written following adustment we could avoid passing the last two arguments as
    they will just be the first two items of their string in config 
    """
    days_ago=int(config['ticker']['sparklinedays'])   
    symbolstring=currency.symbol(fiat.upper())
    if fiat=="jpy" or fiat=="cny":
        symbolstring="¥"
    pricenow = pricestack[-1]
    currencythumbnail= 'currency/'+whichcoin+'.bmp'
    tokenfilename = os.path.join(picdir,currencythumbnail)
    sparkbitmap = Image.open(os.path.join(picdir,'spark.bmp'))
    ATHbitmap= Image.open(os.path.join(picdir,'ATH.bmp'))
#   Check for token image, if there isn't one, get on off coingecko, resize it and pop it on a white background
    if os.path.isfile(tokenfilename):
        logging.info("Getting token Image from Image directory")
        tokenimage = Image.open(tokenfilename)
    else:
        logging.info("Getting token Image from Coingecko")
        tokenimageurl = "https://api.coingecko.com/api/v3/coins/"+whichcoin+"?tickers=false&market_data=false&community_data=false&developer_data=false&sparkline=false"
        rawimage = requests.get(tokenimageurl).json()
        tokenimage = Image.open(requests.get(rawimage['image']['large'], stream=True).raw)
        resize = 100,100
        tokenimage.thumbnail(resize, Image.ANTIALIAS)
        new_image = Image.new("RGBA", (120,120), "WHITE") # Create a white rgba background with a 10 pixel border
        new_image.paste(tokenimage, (10, 10), tokenimage)   
        tokenimage=new_image
        tokenimage.thumbnail((100,100),Image.ANTIALIAS)
        tokenimage.save(tokenfilename)


    pricechange = str("%+d" % round((pricestack[-1]-pricestack[0])/pricestack[-1]*100,2))+"%"
    if pricenow > 1000:
        pricenowstring =format(int(pricenow),",")
    else:
        pricenowstring =str(float('%.5g' % pricenow))

    if config['display']['orientation'] == 0 or config['display']['orientation'] == 180 :
        epd = epd2in13_V2.EPD()
        epd.init(epd.FULL_UPDATE)
        image = Image.new('L', (epd.width, epd.height), 255)    # 255: clear the image with white
        draw = ImageDraw.Draw(image)              
        draw.text((110,80),str(days_ago)+"day :",font =font_date,fill = 0)
        draw.text((110,95),pricechange,font =font_date,fill = 0)
        # Print price to 5 significant figures
        draw.text((15,200),symbolstring+pricenowstring,font =font,fill = 0)
        draw.text((10,10),str(time.strftime("%H:%M %a %d %b %Y")),font =font_date,fill = 0)
        image.paste(tokenimage, (10,25))
        image.paste(sparkbitmap,(10,125))
        if config['display']['orientation'] == 180 :
            image=image.rotate(180, expand=True)


    if config['display']['orientation'] == 90 or config['display']['orientation'] == 270 :
        epd = epd2in13_V2.EPD()
        epd.init(epd.FULL_UPDATE)
        image = Image.new('L', (epd.height, epd.width), 255)    # 255: clear the image with white
        draw = ImageDraw.Draw(image)   
        draw.text((135,85),str(days_ago)+" day : "+pricechange,font =font_date,fill = 0)

 #.     uncomment the line below to show volume
 #       draw.text((110,105),"24h vol : " + human_format(other['volume']),font =font_date,fill = 0)
        draw.text((135,100),symbolstring+pricenowstring,font =fontHorizontal,fill = 0)
        if other['ATH']==True:
            image.paste(ATHbitmap,(190,85))
        image.paste(sparkbitmap,(80,25))
        image.paste(tokenimage, (0,10))
 #       draw.text((5,110),"In retrospect, it was inevitable",font =font_date,fill = 0)
        draw.text((95,1),str(time.strftime("%H:%M %a %d %b %Y")),font =font_date,fill = 0)
        if config['display']['orientation'] == 270 :
            image=image.rotate(180, expand=True)
#       This is a hack to deal with the mirroring that goes on in 4Gray Horizontal
#        image = ImageOps.mirror(image)

#   If the display is inverted, invert the image usinng ImageOps        
    if config['display']['inverted'] == True:
        image = ImageOps.invert(image)
#   Send the image to the screen        
    epd.display(epd.getbuffer(image))
Пример #19
0
def displaymain():
    # print('displaymain')
    try:
        print('main display')
        logging.info("epd2in13_V2 Demo")

        epd = epd2in13_V2.EPD()
        logging.info("init and Clear")
        epd.init(epd.FULL_UPDATE)
        epd.Clear(0xFF)

        # Drawing on the image
        font15 = ImageFont.truetype(os.path.join(picdir, 'Font.ttc'), 15)
        font24 = ImageFont.truetype(os.path.join(picdir, 'Font.ttc'), 24)
        font16 = ImageFont.truetype(os.path.join(picdir, 'Font1.otf'), 16)
        font8 = ImageFont.truetype(os.path.join(picdir, 'Font1.otf'), 8)
        font12 = ImageFont.truetype(os.path.join(picdir, 'Font1.otf'), 12)
        # logging.info("1.Test TEXT...")
        # image = Image.new('1', (epd.height, epd.width), 255)  # 255: clear the frame
        # draw = ImageDraw.Draw(image)

        # # draw.rectangle([(0,0),(50,50)],outline = 0)
        # # draw.rectangle([(55,0),(100,50)],fill = 0)
        # # draw.line([(0,0),(50,50)], fill = 0,width = 1)
        # # draw.line([(0,50),(50,0)], fill = 0,width = 1)
        # # draw.chord((10, 60, 50, 100), 0, 360, fill = 0)
        # # draw.ellipse((55, 60, 95, 100), outline = 0)
        # # draw.pieslice((55, 60, 95, 100), 90, 180, outline = 0)
        # # draw.pieslice((55, 60, 95, 100), 270, 360, fill = 0)
        # # draw.polygon([(110,0),(110,50),(150,25)],outline = 0)
        # # draw.polygon([(190,0),(190,50),(150,25)],fill = 0)
        # rec_data=s.recvfrom(1024)
        # logging.info(rec_data,rec_data[1],rec_data[0].decode('gb2312'))
        # draw.text((0, 0), 'TOP font15', font = font16, fill = 0)
        # # draw.text((0, 107),rec_data[0].decode('gb2312'), font = font16, fill = 0)
        # # draw.text((120, 60), 'e-Paper demo', font = font16, fill = 0)
        # # draw.text((110, 90), u'微雪电子', font = font16, fill = 0)
        # epd.display(epd.getbuffer(image))
        # time.sleep(2)

        # # read bmp file
        # logging.info("2.read bmp file...")
        # image = Image.open(os.path.join(picdir, '2in13.bmp'))
        # epd.display(epd.getbuffer(image))
        # time.sleep(2)

        # # read bmp file on window
        # logging.info("3.read bmp file on window...")
        # # epd.Clear(0xFF)
        # image1 = Image.new('1', (epd.height, epd.width), 255)  # 255: clear the frame
        # bmp = Image.open(os.path.join(picdir, '100x100.bmp'))
        # image1.paste(bmp, (2,2))
        # epd.display(epd.getbuffer(image1))
        # time.sleep(2)

        logging.info("2.Combine TEXT...")

        time_image = Image.new('1', (epd.height, epd.width), 255)
        time_draw = ImageDraw.Draw(time_image)

        image = Image.new('1', (epd.height, epd.width),
                          255)  # 255: clear the frame
        draw = ImageDraw.Draw(image)

        epd.init(epd.FULL_UPDATE)

        num = 0

        time_draw.text((0, 107), '看不見我', font=font12, fill=0)

        epd.displayPartBaseImage(epd.getbuffer(time_image))

        epd.init(epd.PART_UPDATE)

        # draw.text((0, 107), 'Bottom font15', font = font15, fill = 0)

        currtemttime = 0

        while (True):
            # while(s.recvfrom(1024)[0].decode('gb2312')!='exit'):
            time_draw.rectangle((0, 0, 125, 61), fill=255)
            time_draw.rectangle((126, 62, 250, 122), fill=255)
            time_draw.text((0, 0), str(num) + u'次更新', font=font12, fill=0)
            # time_draw.text((10, 13), u'新世紀エヴァンゲリオン', font = font16, fill = 0)
            time_draw.text((10, 13),
                           wrcon.read_config('main'),
                           font=font12,
                           fill=0)
            # print(recv_msg+' Thread 2')
            # logging.info(recv_msg)
            # time_draw.text((0, 40), '', font = font12, fill = 0)
            time_draw.text((126, 62),
                           'Time: ' + time.strftime('%H:%M:%S'),
                           font=font12,
                           fill=0)
            # edp.displayPartial
            # logging.info(str(time.time()))

            epd.displayPartial(epd.getbuffer(time_image))
            time.sleep(2)
            num = num + 1
            # print(recv_msg)
            # if(num == 5):
            #     break
            if (wrcon.read_config('main').endswith('bye')):
                break

        # # partial update
        # logging.info("4.show time...")
        # 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)
        # num = 0
        # while (True):
        #     time_draw.rectangle((120, 8020, 80), time.strftime('%H:%M:%S'), font = font24, fill = 0)
        #     epd.displayPartial(epd.getbuffer(time_image)), 220, 105), fill = 255)
        #     time_draw.text((1
        #     num = num + 1
        #     if(num == 5):
        #         break

        logging.info("Clear...")
        epd.init(epd.FULL_UPDATE)
        epd.Clear(0xFF)

        logging.info("Goto Sleep...")
        epd.sleep()
        epd.Dev_exit()

    except IOError as e:
        logging.info(e)

    except KeyboardInterrupt:
        logging.info("ctrl + c:")
        epd2in13_V2.epdconfig.module_exit()
        exit()
Пример #20
0
 def __init__(self, *args):
     self.epd = epd2in13_V2.EPD()
     self.epd.init(self.epd.FULL_UPDATE)
     self.buf = []
Пример #21
0
# TODO: Add variable to set certificate check to true or false

# Papirus eInk size is 128 x 96 pixels
WHITE = 1
BLACK = 0
PAPIRUSROT = 0
if "papirus" in conf["atm"]["display"]:
    from papirus import Papirus

    PAPIRUS = Papirus(rotation=PAPIRUSROT)

# Display - Waveshare 2.13 is 250 * 122 pixels
if "waveshare" in conf["atm"]["display"]:
    from waveshare_epd import epd2in13_V2

    WAVESHARE = epd2in13_V2.EPD()

# API URL for coingecko
COINGECKO_URL_BASE = "https://api.coingecko.com/api/v3/"

# Fiat and satoshi variables
FIAT = 0
SATS = 0
SATSFEE = 0
INVOICE = ""

# Set btc and sat price
BTCPRICE = utils.get_btc_price(conf["atm"]["cur"])
SATPRICE = math.floor((1 / (BTCPRICE * 100)) * 100000000)

# Button / Acceptor Pulses
Пример #22
0
    os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'lib')
if os.path.exists(libdir):
    sys.path.append(libdir)

import logging
from waveshare_epd import epd2in13_V2
import time
from PIL import Image, ImageDraw, ImageFont
import traceback

logging.basicConfig(level=logging.DEBUG)

try:
    logging.info("epd2in13_V2 Demo")

    epd = epd2in13_V2.EPD()
    logging.info("init and Clear")
    epd.init(epd.FULL_UPDATE)
    epd.Clear(0xFF)

    # Drawing on the image
    font15 = ImageFont.truetype(os.path.join(picdir, 'Font.ttc'), 15)
    font24 = ImageFont.truetype(os.path.join(picdir, 'Font.ttc'), 24)

    logging.info("1.Drawing on the image...")
    image = Image.new('1', (epd.height, epd.width),
                      255)  # 255: clear the frame
    draw = ImageDraw.Draw(image)

    draw.rectangle([(0, 0), (50, 50)], outline=0)
    draw.rectangle([(55, 0), (100, 50)], fill=0)
Пример #23
0
def main():
    #initialize the display
    logging.info("epd2in13_V2 Demo")
    epd = epd2in13_V2.EPD()
    logging.info("init and Clear")
    epd.init(epd.FULL_UPDATE)
    epd.Clear(0xFF)

    logging.info("1.Drawing on the image...")
    image = Image.new('1', (epd.height, epd.width), 255)  # 255: clear the frame
    draw = ImageDraw.Draw(image)

    logging.info("Create all of the text objects")

    artMoji = u'🎤'
    titMoji = u'🎼'
    durMoji = u'⏳'

    clockTx = getClockString()
    logging.info("{}".format(clockTx))

    baseInfo = Track()
    logging.info("A:{}\n\tT:{}".format(baseInfo.Artist, baseInfo.Title))
    (durationTx, remainingTx) = getDurationInfo(baseInfo.Duration, baseInfo.Position)
    logging.info("{}, {}".format(durationTx, remainingTx))

    logging.info("Time to start measuring things.")
    (clW, clH) = draw.textsize(clockTx, clockFont)
    (moW, moH) = draw.textSize(artMoji, mojiFont)
    (arW, arH) = draw.textsize(baseInfo.Artist, infoFont)
    (tiW, tiH) = draw.textsize(baseInfo.Title, infoFont)
    (duW, duH) = draw.textsize(durationTx, lenFont)
    (reW, reH) = draw.textsize(remainingTx, lenFont)


    print("clock: W:{} H:{}".format(clW,clH))
    print("headers: W:{} H:{}".format(moW,moH))
    print("artist: W:{} H:{}".format(arW,arH))
    print("title: W:{} H:{}".format(tiW,tiH))
    print("duration: W:{} H:{}".format(duW,duH))
    print("remaining: W:{} H:{}".format(reW,reH))

    #draw row headers
#    moW,moH = draw.textsize(emoji1Line,emojifont)
#    draw.rectangle([(0,clH),(moW,clH+moH)],outline=0)     # mic
#    draw.rectangle([(0,clH),(moW,clH+2*moH+4)],outline=0)  #note
#    draw.rectangle([(0,clH),(moW,clH+3*moH+8)],outline=0)  #timer

    # # partial update
    logging.info("4.show time...")
    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)
    num = 0
    while (True):
        time_draw.rectangle((120, 80, 220, 105), fill = 255)
        time_draw.text((120, 80), time.strftime('%H:%M:%S'), font = font24, fill = 0)
        epd.displayPartial(epd.getbuffer(time_image))
        num = num + 1
        if(num == 10):
            break

    logging.info("Clear...")
    epd.init(epd.FULL_UPDATE)
    epd.Clear(0xFF)

    logging.info("Goto Sleep...")
    epd.sleep()
    epd.Dev_exit()