Ejemplo n.º 1
0
def displayInky(output):
    from PIL import Image, ImageFont, ImageDraw
    from inky import InkyPHAT

    inky_display = InkyPHAT("red")
    inky_display.set_border(inky_display.RED)

    img = Image.new("P", (inky_display.WIDTH, inky_display.HEIGHT))
    draw = ImageDraw.Draw(img)

    headerSize = 12
    headerFont = ImageFont.truetype(
        "/usr/share/fonts/truetype/liberation2/LiberationSans-Bold.ttf",
        headerSize)
    messageFont = ImageFont.truetype(
        "/usr/share/fonts/truetype/liberation2/LiberationMono-Regular.ttf",
        int(75 / (output['bodyLines'])))

    x = 0
    y = 0
    draw.text((x, y), output['header'] + ' - ' + output['subHeader'],
              inky_display.RED, headerFont)
    draw.text((x, y + headerSize), output['body'], inky_display.BLACK,
              messageFont)
    inky_display.set_image(img)
    inky_display.show()
Ejemplo n.º 2
0
class InkyDriver:
    def __init__(self):
        self.inky = InkyPHAT('yellow')

    def create_new_image(self, countries_cases):
        current_height = 0
        # inky_display.set_rotation(180)
        self.inky.set_border(self.inky.RED)

        # Create a new canvas to draw on
        img = Image.new("P", (self.inky.WIDTH, self.inky.HEIGHT))
        draw = ImageDraw.Draw(img)

        # Load the fonts
        font = ImageFont.truetype(HankenGroteskBold, 20)

        # Calculate the positioning and draw the text
        for countryCases in countries_cases:
            text = str(countryCases[0]) + ": " + str(countryCases[1])
            width, height = font.getsize(text)
            center = int((self.inky.WIDTH - width) / 2)
            draw.text((center, current_height),
                      text,
                      self.inky.BLACK,
                      font=font)
            current_height += height

        # Display the completed picture
        self.inky.set_image(img)
        self.inky.show()
Ejemplo n.º 3
0
Archivo: hype.py Proyecto: suttree/hype
def hype(word):
	print(word)

	# Set up the correct display and scaling factors
	inky_display = InkyPHAT('black')
	inky_display.set_border(inky_display.BLACK)
	# inky_display.set_rotation(180)

	w = inky_display.WIDTH
	h = inky_display.HEIGHT

	# Create a new canvas to draw on
	img = Image.new("P", (inky_display.WIDTH, inky_display.HEIGHT))
	draw = ImageDraw.Draw(img)

	# Load the fonts
	font_size = 88
	from fonts.ttf import AmaticSC, FredokaOne

	#font = ImageFont.truetype(SourceSansProSemibold, font_size)
	font = ImageFont.truetype(AmaticSC, font_size)
	#font = ImageFont.truetype(FredokaOne, font_size)

	padding = 20 
	max_width = w - padding
	max_height = h - padding

	below_max_length = False
	while not below_max_length:
			p_w, p_h = font.getsize(word)  # Width and height of quote
			#p_h = p_h * (word.count("\n") + 1)   # Multiply through by number of lines

			if p_h < max_height and p_w < max_width:
					below_max_length = True              # The quote fits! Break out of the loop.

			else:
					font_size = font_size - 2
					#font = ImageFont.truetype(SourceSansProSemibold, font_size)
					font = ImageFont.truetype(AmaticSC, font_size)
					#font = ImageFont.truetype(FredokaOne, font_size)

					continue

	# x- and y-coordinates for the top left of the quote
	#word_x = (w - max_width) / 2
	#word_x = (max_width - p_w) / 2
	#word_y = (max_height - p_h) / 2
	word_x = (w - max_width) / 2
	#word_y = ((h - max_height) + (max_height - p_h - font.getsize("ABCD ")[1])) / 2
	word_y = (h - p_h) / 2

	draw.multiline_text((word_x, word_y), word, fill=inky_display.BLACK, font=font, align="left")
	draw.line((169, 58, 169, 58), 2)

	# Display the completed canvas on Inky wHAT
	inky_display.set_image(img)
	inky_display.show()
Ejemplo n.º 4
0
    def draw_to_display():
        # Set up properties of eInk display
        inky_display = InkyPHAT("red")
        inky_display.set_border(inky_display.BLACK)

        # Load previously generated image
        img = draw_semester_display()

        # Display generated semester progress image
        inky_display.set_image(img)
        inky_display.show()
Ejemplo n.º 5
0
def run():

    inky_display = InkyPHAT(COLOR)

    # inky_display.set_rotation(180)
    inky_display.set_border(InkyPHAT.RED)

    img = Image.new("P", (InkyPHAT.WIDTH, InkyPHAT.HEIGHT))
    palletize(img)
    image_draw = ImageDraw.Draw(img)

    if DEBUG:
        # Draw vertical line
        for y in xrange(InkyPHAT.HEIGHT):
            img.putpixel((InkyPHAT.WIDTH / 2, y), inky_display.RED)
            img.putpixel((InkyPHAT.WIDTH / 4, y), inky_display.RED)

        # Draw horizontal line
        for x in xrange(InkyPHAT.WIDTH):
            img.putpixel((x, InkyPHAT.HEIGHT / 2), inky_display.RED)

    weather = Weather(location_coords)

    if weather.is_same_as_temp_data():
        if DEBUG:
            print("Not updating the display since the forecast is the same as last time")
        weather.save_temp_forecast(only_if_no_such_file=True)
        return
    else:
        if DEBUG:
            print("Updating display since the forecast has changed since the last render")
        weather.save_temp_forecast()

    draw_text(image_draw, 2, "UV",                        "l")
    draw_text(image_draw, 2, weather.uv_index,            "r",
              color=InkyPHAT.RED if weather.is_uv_warning() else InkyPHAT.BLACK)
    draw_text(image_draw, 1, get_high_temp_copy(weather), "c")
    draw_text(image_draw, 4, get_low_temp_copy(weather),  "c")

    if weather.precipitation_is_likely():
        precip_chance_str = str(int(round(weather.current_precip_probability * 100))) + "%"
        draw_text(image_draw, 3, get_sky_icon(weather), "l", is_icon=True)
        draw_text(image_draw, 3, precip_chance_str,     "r", is_icon=False)
    else:
        draw_text(image_draw, 3, get_sky_icon(weather), "c", is_icon=True)

    inky_display.set_image(img)
    inky_display.show()

    if DEBUG:
        print(weather.eink_data_string())
Ejemplo n.º 6
0
def initialiseDisplay():
    """

    Basic setup of display

    Inputs: None
    Return Values: None
    Global Objects Created: inkyDisplay (instance of inkyPHAT)

    """
    global inkyDisplay
    inkyDisplay = InkyPHAT(deviceColour)
    # I think we do this here.
    inkyDisplay.set_border(inkyDisplay.WHITE)
    inkyDisplay.set_border(inkyDisplay.BLACK)
Ejemplo n.º 7
0
def draw_display_message(text: str):
    # Set up properties of eInk display
    inky_display = InkyPHAT("red")
    inky_display.set_border(inky_display.BLACK)

    hanked_medium = ImageFont.truetype(HankenGroteskMedium, 20)

    img = Image.new("P", size=(InkyPHAT.WIDTH, InkyPHAT.HEIGHT))
    draw = ImageDraw.Draw(img)

    text_w, text_h = hanked_medium.getsize(text)
    text_x = (InkyPHAT.WIDTH - text_w) // 2
    text_y = (InkyPHAT.HEIGHT - text_h) // 2
    draw.text((text_x, text_y), text, InkyPHAT.BLACK, font=hanked_medium)

    inky_display.set_image(img)
    inky_display.show()
Ejemplo n.º 8
0
def refreshDisplay(intervall, priority, scheduler):

    logging.info("Refresh Display - start")

    lastValue = readLastValue()
    avgMonth = readAvgFromDays(31)
    avgYear = readAvgFromDays(365)

    inkyDisplay = InkyPHAT(colour)
    inkyDisplay.set_border(inkyDisplay.BLACK)

    # Load our background image
    img = Image.open("/var/local/cellarsense/cellarsense-background.png")
    draw = ImageDraw.Draw(img)

    mainHeaderFont = ImageFont.truetype("FreeMonoBold.ttf", 20)
    mainFont = ImageFont.truetype("FreeMono.ttf", 20)
    medianFont = ImageFont.truetype("FreeMono.ttf", 15)

    lastValuePrint = "{:4.1f}°C {:4.1f}%".format(lastValue["temperature"],
                                                 lastValue["humidity"])
    avgMonthPrint = "øm {:4.1f}°C {:4.1f}%".format(avgMonth["temperature"],
                                                   avgMonth["humidity"])
    avgYearPrint = "øa {:4.1f}°C {:4.1f}%".format(avgYear["temperature"],
                                                  avgYear["humidity"])

    logging.debug("Refresh Display - %s", lastValuePrint)
    logging.debug("Refresh Display - %s", avgMonthPrint)
    logging.debug("Refresh Display - %s", avgYearPrint)

    draw.text((5, 5),
              "CellarSense",
              fill=inkyDisplay.BLACK,
              font=mainHeaderFont)
    draw.text((20, 35), lastValuePrint, fill=inkyDisplay.BLACK, font=mainFont)
    draw.text((10, 70), avgMonthPrint, fill=inkyDisplay.BLACK, font=medianFont)
    draw.text((10, 85), avgYearPrint, fill=inkyDisplay.BLACK, font=medianFont)

    inkyDisplay.set_image(img)
    inkyDisplay.show()

    logging.info("Refresh Display - done")

    # reschedule
    scheduler.enter(intervall, priority, refreshDisplay,
                    (intervall, priority, scheduler))
Ejemplo n.º 9
0
def print_text(text):
    """Displays text in Inky pHAT display.

    Args:
        text: String that is displayed on the Inky pHAT
    """
    inky_display = InkyPHAT("black")
    inky_display.set_border(inky_display.WHITE)
    img = Image.new("P", (inky_display.WIDTH, inky_display.HEIGHT))
    draw = ImageDraw.Draw(img)
    font = ImageFont.truetype(FredokaOne, 30)
    message = text
    width, height = font.getsize(message)
    x_axis = (inky_display.WIDTH / 2) - (width / 2)
    y_axis = (inky_display.HEIGHT / 2) - (height / 2)
    draw.text((x_axis, y_axis), message, inky_display.BLACK, font)
    inky_display.set_image(img)
    inky_display.show()
Ejemplo n.º 10
0
def main():
    inky_display = InkyPHAT("black")
    inky_display.set_border(inky_display.WHITE)

    config = importconfig()

    if config['showtime'] == "True":
        showtime = True
    else:
        showtime = False


#Need to work out the config mode
    if len(config["stops"]) > 1:
        multistops(config, showtime, inky_display)
    else:
        stops = config["stops"][0]
        singlestop(stops, showtime, inky_display)
Ejemplo n.º 11
0
def my_draw(message):
  inky_display = InkyPHAT("black")
  inky_display.set_border(inky_display.WHITE)

  img = Image.new("P", (inky_display.WIDTH, inky_display.HEIGHT))
  draw = ImageDraw.Draw(img)

  font = ImageFont.truetype(FredokaOne, 30)

  w, h = font.getsize(message)
  #x = (inky_display.WIDTH / 2) - (w / 2)
  #y = (inky_display.HEIGHT / 2) - (h / 2)
  x = 1
  y = 1
      
  draw.text((x, y), message, inky_display.BLACK, font)
  inky_display.set_image(img)
  inky_display.show()
Ejemplo n.º 12
0
def presentOnInkyScreen(image):
    logging.info("Loading View onto Inky Phat.")
    from inky import InkyPHAT

    #Test invert image.
    image = image.convert('L')
    image = ImageOps.invert(image)
    image = image.convert('1')

    # Set up the display
    inky_display = InkyPHAT("black")
    #inky_display.set_border(inky_display.BLACK)
    inky_display.v_flip = True
    inky_display.h_flip = True

    # Display
    inky_display.set_border("black")
    inky_display.set_image(image)
    inky_display.show()
    logging.info("View Sent to Device Successfully")
Ejemplo n.º 13
0
class Clock():
    def __init__(self, rotation=180):
        self.inky_display = InkyPHAT("red")
        self.inky_display.set_border(self.inky_display.BLACK)
        self.WIDTH = self.inky_display.WIDTH
        self.HEIGHT = self.inky_display.HEIGHT
        self.WHITE = self.inky_display.WHITE
        self.RED = self.inky_display.RED
        self.BLACK = self.inky_display.BLACK
        self.rotation = 180

    def create_image(self, currenttime, currentdate, temp, tempmax, tempmin):
        img = Image.open("./images/backdrop.png")
        draw = ImageDraw.Draw(img)

        #Adding the time and date
        font = ImageFont.truetype(FredokaOne, 28)
        draw.text((6, 15), currentdate, self.RED, font=font)

        font = ImageFont.truetype(FredokaOne, 40)
        draw.text((int(self.WIDTH / 2), 5), currenttime, self.BLACK, font=font)

        #adding max temp
        font = ImageFont.truetype(FredokaOne, 20)
        draw.text((22, 70), temp, self.RED, font=font)
        draw.text((92, 70), tempmin, self.RED, font=font)
        draw.text((160, 70), tempmax, self.RED, font=font)

        self.display_img(img)

    def display_img(self, img):
        img = img.rotate(self.rotation)
        self.inky_display.set_image(img)
        self.inky_display.show()

    def test_image(self):
        img = Image.open("./images/TagTest-212x104.png")
        self.display_img(img)
Ejemplo n.º 14
0
                    type=str,
                    required=True,
                    choices=["red", "black", "yellow"],
                    help="ePaper display colour")
args = parser.parse_args()

colour = args.colour

# Set up the correct display and scaling factors

if args.type == "phat":
    inky_display = InkyPHAT(colour)
elif args.type == "what":
    inky_display = InkyWHAT(colour)

inky_display.set_border(inky_display.BLACK)

# Pick the correct logo image to show depending on display type/colour

if args.type == "phat":
    if colour == 'black':
        img = Image.open(
            os.path.join(PATH, "phat/resources/InkypHAT-212x104-bw.png"))
    else:
        img = Image.open(
            os.path.join(PATH, "phat/resources/InkypHAT-212x104.png"))
elif args.type == "what":
    if colour == 'black':
        img = Image.open(
            os.path.join(PATH, "what/resources/InkywHAT-400x300-bw.png"))
    else:
Ejemplo n.º 15
0
class PzWeather():
    def __init__(self):
        self.debug = False
        self.display = None
        self.current = None
        self.last = None
        self.last_load = None
        self.bg = None
        self.noaa = None
        self.darksky = None
        self.btn_down = False

        if args.debug is 'true' or args.debug is 'True':
            self.debug = True

        if pzwglobals.RUN_ON_RASPBERRY_PI:
            self.display = InkyPHAT("yellow")
            self.display.set_border(WHITE)

        self.screens = {
            'current_weather':
            CurrentWeather('current_weather',
                           debug=self.debug,
                           display=self.display),
            'forecast_days':
            ForecastDays('forecast_days',
                         debug=self.debug,
                         display=self.display)
        }

    def change_screen(self, screen_name):
        logger.debug('PzWeather::change_screen \t' + screen_name)
        self.make_current_screen(self.screens[screen_name])

    def make_current_screen(self, screen):
        logger.debug('PzWeather::make_current_screen \t' + screen.name)
        if self.current:
            self.last = self.current
        self.current = screen
        self.render_current_screen()

    def render_current_screen(self):
        if self.current is not None:
            self.current.render(bg=self.bg.copy(),
                                darksky=self.darksky,
                                noaa=self.noaa,
                                icon=args.icon)

    # do time check to update data
    def check_time(self):
        now = datetime.now()
        tdiff = now - self.last_load
        if (tdiff >= timedelta(minutes=10)):
            self.load_data()
            self.render_current_screen()

    def load_data(self):
        logger.debug('PzWeather::load_data')
        self.bg = SatelliteImage(args.dither, args.threshold,
                                 debug=self.debug).image
        self.noaa = NoaaForecast(debug=self.debug).forecast
        self.darksky = DarkSkyWeather(debug=self.debug).weather

        logger.debug(self.noaa)
        logger.debug(self.darksky)

        self.last_load = datetime.now()

    def toggle_screens(self):
        logger.debug('PzWeather::toggle_screens')
        if self.current and self.current.name == 'current_weather':
            self.change_screen('forecast_days')
            return
        self.change_screen('current_weather')

    def button_toggle(self):
        self.btn_down = not self.btn_down

        logger.info('PzWeather::button_toggle {}'.format(self.btn_down))

        if self.btn_down:
            pass
        else:
            self.toggle_screens()

    # helper to exit program in case we need special rpi consideration in future
    def kill(self):
        if pzwglobals.RUN_ON_RASPBERRY_PI:
            sys.exit(0)
        else:
            sys.exit(0)
Ejemplo n.º 16
0
                    action="store_true",
                    default=False,
                    help="Clear the ePaper display and exit.")

args = parser.parse_args()

if args.do_clear:
    print("clearing the display ...")
    with open(args.config, 'rt') as fp:
        config = yaml.safe_load(fp)
        cleardisplay = config['ui']['display']['type']
        if cleardisplay in ('inkyphat', 'inky'):
            print("inky display")
            from inky import InkyPHAT
            epd = InkyPHAT(config['ui']['display']['color'])
            epd.set_border(InkyPHAT.BLACK)
            self._render_cb = self._inky_render
        elif cleardisplay in ('papirus', 'papi'):
            print("papirus display")
            from pwnagotchi.ui.papirus.epd import EPD
            os.environ['EPD_SIZE'] = '2.0'
            epd = EPD()
            epd.clear()
        elif cleardisplay in ('waveshare_1', 'ws_1', 'waveshare1', 'ws1'):
            print("waveshare v1 display")
            from pwnagotchi.ui.waveshare.v1.epd2in13 import EPD
            epd = EPD()
            epd.init(epd.lut_full_update)
            epd.Clear(0xFF)
        elif cleardisplay in ('waveshare_2', 'ws_2', 'waveshare2', 'ws2'):
            print("waveshare v2 display")
def main():

    # yyyy-mm-dd hh:mm:ss
    currenttime = strftime("%Y-%m-%d %H:%M:%S", gmtime())

    # Write text with weather values to the canvas
    inkydatetime = strftime("%d/%m %H:%M")

    # IoT Host Name
    host = os.uname()[1]

    # - start timing
    starttime = datetime.datetime.now().strftime('%m/%d/%Y %H:%M:%S')
    start = time.time()

    # Ip address
    ipaddress = minifiutil.IP_address()

    parser = argparse.ArgumentParser()
    parser.add_argument('--price',
                        help='price to be recognized.',
                        required=True)
    args = parser.parse_args()

    # end of processing
    end = time.time()

    # Output JSON
    row = {}
    uuid2 = '{0}_{1}'.format(strftime("%Y%m%d%H%M%S", gmtime()), uuid.uuid4())
    cpuTemp = int(float(minifiutil.getCPUtemperature()))
    usage = psutil.disk_usage("/")

    # Format Fields
    row['host'] = os.uname()[1]
    row['cputemp'] = str(round(cpuTemp, 2))
    row['ipaddress'] = str(ipaddress)
    row['endtime'] = '{0:.2f}'.format(end)
    row['runtime'] = '{0:.2f}'.format(end - start)
    row['systemtime'] = datetime.datetime.now().strftime('%m/%d/%Y %H:%M:%S')
    row['starttime'] = str(starttime)
    row['diskfree'] = "{:.1f}".format(float(usage.free) / 1024 / 1024)
    row['memory'] = str(psutil.virtual_memory().percent)
    row['uuid'] = str(uuid2)
    row['price'] = str(args.price)

    # Output JSON
    json_string = json.dumps(row)
    print(json_string)

    # Set up the display
    inky_display = InkyPHAT("red")
    inky_display.set_border(inky_display.BLACK)

    # Create a new canvas to draw on
    # 212x104
    img = Image.new("P", (inky_display.WIDTH, inky_display.HEIGHT))
    draw = ImageDraw.Draw(img)

    # Load the FredokaOne font
    font = ImageFont.truetype(FredokaOne, 22)

    # draw data
    draw.text((0, 0),
              "{}".format('Cloudera Mug'),
              inky_display.BLACK,
              font=font)
    draw.text((0, 32),
              "Price: $ {}".format(args.price),
              inky_display.RED,
              font=font)

    # Display the data on Inky pHAT
    inky_display.set_image(img)
    inky_display.show()
##########################################################
###  Draw images on the inky display
##########################################################

from inky import InkyPHAT
inky_display = InkyPHAT(inky_color)

# Use BLACK or RED depending on positive or negative change_percent
if '-' in change_percent:
    text_color = inky_display.RED
    plus_sign = "" # number already has minus sign (-)
else:
    text_color = inky_display.BLACK
    plus_sign = "+" # Add plus sign (+) to positive number

inky_display.set_border(text_color)
change_percent = plus_sign + change_percent + "%"


from PIL import Image, ImageFont, ImageDraw
img = Image.new("P", (inky_display.WIDTH, inky_display.HEIGHT))
draw = ImageDraw.Draw(img)

from fonts.ttf import FredokaOne


def draw_price():
    font = ImageFont.truetype(FredokaOne, 36)
    message = price
    w, h = font.getsize(message)
    x = (inky_display.WIDTH / 2) - (w / 2)
Ejemplo n.º 19
0
class InkyDevice():

    def __init__(self):
        self.display = InkyPHAT("black")
        self.display.set_border(self.display.WHITE)
        self.font = ImageFont.truetype('resources/Eden_Mills_Bold.ttf', 12)
        self.lock = threading.Lock()

        self.startup()

    def startup(self):
        print('writing startup image...')
        with self.lock:
            img = Image.open("resources/k8s-bw.png")
            draw = ImageDraw.Draw(img)
            self.display.set_image(img)
            self.display.show()

    def shutdown(self):
        print('writing shutdown image...')
        with self.lock:
            img = Image.open("resources/8-bit-dino.png")
            draw = ImageDraw.Draw(img)

            font = ImageFont.truetype('resources/Eden_Mills_Bold.ttf', 28)
            
            message = "offline    "
            message_width, message_height = self.get_text_size(message, font)
            x, y = Location.CenterRight.place(message, font, message_width, message_height, self.display.WIDTH, self.display.HEIGHT)
            draw.text((x, y), message, self.display.BLACK, font)

            self.display.set_image(img)
            self.display.show()

    def get_text_size(self, message, font):
        # render the text in another text buffer to get the dimensions
        message_width, message_height = 0,0
        for line in message.split("\n"):
            partial_width, partial_height = font.getsize(line)
            message_width = max(message_width, partial_width)
            approx_line_spacing = 1.2
            message_height += int(partial_height*approx_line_spacing)

        return message_width, message_height

    def write(self, render_result):
        with self.lock:
            img = Image.new("P", (self.display.WIDTH, self.display.HEIGHT))
            draw = ImageDraw.Draw(img)

            for location, message in render_result.items():

                # render the text in another text buffer to get the dimensions
                message_width, message_height = self.get_text_size(message, self.font)

                # find the placement of the text buffer and overlay onto the screen buffer
                x, y = location.place(message, self.font, message_width, message_height, self.display.WIDTH, self.display.HEIGHT)
                draw.text((x, y), message, self.display.BLACK, self.font)

            # flush the screen buffer to the device
            self.display.set_image(img)
            self.display.show()
Ejemplo n.º 20
0
if args.number:
    cycles = args.number
else:
    cycles = 3

colours = (inky_display.RED, inky_display.BLACK, inky_display.WHITE)
colour_names = (colour, "black", "white")

# Create a new canvas to draw on

img = Image.new("P", (inky_display.WIDTH, inky_display.HEIGHT))

# Loop through the specified number of cycles and completely
# fill the display with each colour in turn.

for i in range(cycles):
    print("Cleaning cycle %i\n" % (i + 1))
    for j, c in enumerate(colours):
        print("- updating with %s" % colour_names[j])
        inky_display.set_border(c)
        for x in range(inky_display.WIDTH):
            for y in range(inky_display.HEIGHT):
                img.putpixel((x, y), c)
        inky_display.set_image(img)
        inky_display.show()
        time.sleep(1)
    print("\n")

print("Cleaning complete!")
Ejemplo n.º 21
0
    import lib.epd2in13_V2  
    display = lib.epd2in13_V2.EPD()
    display.init(display.FULL_UPDATE)
    display.Clear(0xFF)
    # These are the opposite of what InkyPhat uses.
    WIDTH = display.height # yes, Height
    HEIGHT = display.width # yes, width
    img = Image.new('1', (WIDTH, HEIGHT), 255)
    BLACK = "black"
else:
    logging.info("Display type: InkyPHAT")

    from inky import InkyPHAT
    display = InkyPHAT("black")
    display.set_border(display.WHITE)
    WIDTH = display.WIDTH
    HEIGHT = display.HEIGHT
    img = Image.new("P", (display.WIDTH, display.HEIGHT))
    BLACK = display.BLACK

logging.info("Display dimensions: W %s x H %s", WIDTH, HEIGHT)

draw = ImageDraw.Draw(img)

font_size = 37
if "FONT_SIZE" in os.environ:
    font_size = int(os.environ["FONT_SIZE"])

# Use a dashboard defined message if we have one, otherwise load a nice quote
if "INKY_MESSAGE" in os.environ:
Ejemplo n.º 22
0
class draw_words():
    def __init__(self):
        # Start by loading the word list
        with open('longwords.txt', 'r') as f:
            self.word_list = f.read().splitlines()

        self.d = InkyPHAT("red")
        self.d.set_border(self.d.RED)

        self.d.h_flip = True
        self.d.v_flip = True

        self.font = ImageFont.load("font.pil")

    def cls(self):
        img = Image.new("P", (self.d.WIDTH, self.d.HEIGHT))
        draw = ImageDraw.Draw(img)
        draw.rectangle([0, 0, self.d.WIDTH, self.d.HEIGHT], fill=self.d.BLACK)
        self.d.set_image(img)
        self.d.show()

    def draw_list(self, key_code):
        img = Image.new("P", (self.d.WIDTH, self.d.HEIGHT))
        draw = ImageDraw.Draw(img)

        # Start by filling the screen with a black fill...
        draw.rectangle([0, 0, self.d.WIDTH, self.d.HEIGHT], fill=self.d.BLACK)

        int_value = int(key_code, 16)
        bits_list = []
        mask = 0x1FFF

        for i in range(9):
            bits_list.append((int_value >> (13 * i)) & mask)

        bits_list.append(int_value >> 117)

        # Now we have the word list - we need to pad the final block to 13-bits...
        bits_list[9] = bits_list[9] << 2

        words = []
        for block in bits_list:
            words.append(self.word_list[block])

        i = 0
        l_col = True
        for word in words:
            y = (22 * (i + 1)) - 3  #2
            draw.line((0, y, self.d.WIDTH, y), self.d.RED, 2)
            if l_col:
                draw.text((5, (i * 22) - 2), word.upper(), self.d.WHITE,
                          self.font)
            else:
                draw.text((110, (i * 22) - 2), word.upper(), self.d.WHITE,
                          self.font)
                i += 1

            l_col = not (l_col)

        draw.line((0, 0, 0, self.d.HEIGHT), self.d.RED, 2)
        draw.line((self.d.WIDTH / 2, 0, self.d.WIDTH / 2, self.d.HEIGHT),
                  self.d.RED, 2)
        draw.line((self.d.WIDTH - 2, 0, self.d.WIDTH - 2, self.d.HEIGHT),
                  self.d.RED, 2)

        self.d.set_image(img)
        self.d.show()
Ejemplo n.º 23
0
if len(sys.argv) > 1:
    INKY_COLOUR = sys.argv[1]

if INKY_COLOUR not in ['red', 'yellow', 'black']:
    print("Usage: {} <red, yellow, black>".format(sys.argv[0]))
    sys.exit(1)

phat = InkyPHAT(INKY_COLOUR)

white = Image.new('P', (212, 104), phat.WHITE)
black = Image.new('P', (212, 104), phat.BLACK)

while True:
    print("White")
    phat.set_border(phat.WHITE)
    phat.set_image(black)
    phat.show()
    time.sleep(1)

    if INKY_COLOUR == 'red':
        print("Red")
        phat.set_border(phat.RED)
        phat.set_image(white)
        phat.show()
        time.sleep(1)

    if INKY_COLOUR == 'yellow':
        print("Yellow")
        phat.set_border(phat.YELLOW)
        phat.set_image(white)
Ejemplo n.º 24
0
from inky import InkyPHAT
from PIL import Image

# valid colors are red, yellow and black
inky_display = InkyPHAT("black")
inky_display.set_border(InkyPHAT.WHITE)

img = Image.open("/home/pi/src/superporgs/superporgs8.png")
inky_display.set_image(img)
inky_display.show()
Ejemplo n.º 25
0
colour = args.colour

# Set up the correct display and scaling factors

if args.type == "phat":
    inky_display = InkyPHAT(colour)
    scale_size = 1
    padding = 0
elif args.type == "what":
    inky_display = InkyWHAT(colour)
    scale_size = 2.20
    padding = 15

# inky_display.set_rotation(180)
inky_display.set_border(inky_display.RED)

# Create a new canvas to draw on

img = Image.new("P", (inky_display.WIDTH, inky_display.HEIGHT))
draw = ImageDraw.Draw(img)

# Load the fonts

fredoka_font = ImageFont.truetype(FredokaOne, int(30 * scale_size))
hanken_bold_font = ImageFont.truetype(HankenGroteskMedium,
                                      int(14 * scale_size))
hanken_medium_font = ImageFont.truetype(HankenGroteskBold,
                                        int(30 * scale_size))

# Grab the text to be displayed
Ejemplo n.º 26
0
class Inky(DisplayImpl):
    def __init__(self, config):
        super(Inky, self).__init__(config, 'inky')
        self._display = None

    def layout(self):
        fonts.setup(10, 8, 10, 28, 25, 9)
        self._layout['width'] = 212
        self._layout['height'] = 104
        self._layout['face'] = (0, 37)
        self._layout['name'] = (5, 18)
        self._layout['channel'] = (0, 0)
        self._layout['aps'] = (30, 0)
        self._layout['uptime'] = (147, 0)
        self._layout['line1'] = [0, 12, 212, 12]
        self._layout['line2'] = [0, 92, 212, 92]
        self._layout['friend_face'] = (0, 76)
        self._layout['friend_name'] = (40, 78)
        self._layout['shakes'] = (0, 93)
        self._layout['mode'] = (187, 93)
        self._layout['status'] = {
            'pos': (102, 18),
            'font': fonts.status_font(fonts.Small),
            'max': 20
        }
        return self._layout

    def initialize(self):
        logging.info("initializing inky display")

        if self.config['color'] == 'fastAndFurious':
            logging.info("Initializing Inky in 2-color FAST MODE")
            logging.info(
                "THIS MAY BE POTENTIALLY DANGEROUS. NO WARRANTY IS PROVIDED")
            logging.info("USE THIS DISPLAY IN THIS MODE AT YOUR OWN RISK")

            from pwnagotchi.ui.hw.libs.inkyphat.inkyphatfast import InkyPHATFast
            self._display = InkyPHATFast('black')
            self._display.set_border(InkyPHATFast.BLACK)
        elif self.config['color'] == 'auto':
            from inky.auto import auto
            self._display = auto()
            self._display.set_border(self._display.BLACK)
            self._layout['width'] = self._display.WIDTH
            self._layout['height'] = self._display.HEIGHT
        else:
            from inky import InkyPHAT
            self._display = InkyPHAT(self.config['color'])
            self._display.set_border(InkyPHAT.BLACK)

    def render(self, canvas):
        if self.config['color'] == 'black' or self.config[
                'color'] == 'fastAndFurious':
            display_colors = 2
        else:
            display_colors = 3

        img_buffer = canvas.convert('RGB').convert('P',
                                                   palette=1,
                                                   colors=display_colors)
        if self.config['color'] == 'red':
            img_buffer.putpalette([
                255,
                255,
                255,  # index 0 is white
                0,
                0,
                0,  # index 1 is black
                255,
                0,
                0  # index 2 is red
            ])
        elif self.config['color'] == 'yellow':
            img_buffer.putpalette([
                255,
                255,
                255,  # index 0 is white
                0,
                0,
                0,  # index 1 is black
                255,
                255,
                0  # index 2 is yellow
            ])
        else:
            img_buffer.putpalette([
                255,
                255,
                255,  # index 0 is white
                0,
                0,
                0  # index 1 is black
            ])

        self._display.set_image(img_buffer)
        try:
            self._display.show()
        except:
            logging.exception("error while rendering on inky")

    def clear(self):
        self._display.Clear()
Ejemplo n.º 27
0
    dto = datetime.fromisoformat(dt).astimezone(pytz.timezone("Europe/London"))
    return dto.strftime("%A {}, %H:%M".format(date_suffixed(dto.strftime("%d"))))

def format_temperature(t):
    return "{}˚C".format(t)

def format_humidity(h):
    return "{}%".format(h)

def sample_hygrometer(device):
    dt = datetime.now(tz=timezone.utc)
    (t,h) = device.readSensor()
    return (dt.isoformat(timespec='seconds'), t, h)

phat = InkyPHAT("red")
phat.set_border(phat.WHITE)
phat.h_flip = True
phat.v_flip = True

img = Image.new("P", (phat.WIDTH, phat.HEIGHT))
draw = ImageDraw.Draw(img)

smallFont = ImageFont.truetype("04B_03__.ttf", 8)
mediumFont = ImageFont.truetype(FredokaOne, 16)
largeFont = ImageFont.truetype(FredokaOne, 32)

am2320 = AM2320(args.i2c)
(sensor_dt, sensor_t, sensor_h) = sample_hygrometer(am2320)

dt = format_datetime(sensor_dt)
t = format_temperature(sensor_t)
Ejemplo n.º 28
0
from inky import InkyPHAT
from PIL import Image, ImageFont, ImageDraw
from font_fredoka_one import FredokaOne

# get inky display variable
inky_display = InkyPHAT("yellow")

# set inky display border (YELLOW/BLACK/WHITE)
inky_display.set_border(inky_display.YELLOW)

img = Image.new("P", (inky_display.WIDTH, inky_display.HEIGHT))
draw = ImageDraw.Draw(img)

# decide font and size
font = ImageFont.truetype(FredokaOne, 32)

# message to write
message = "Hello, World!"

# get width and height of the message to write
w, h = font.getsize(message)

# The x and y variables will tell the draw.text() function where to place the top left corner of our text
x = (inky_display.WIDTH / 2) - (w / 2)
y = (inky_display.HEIGHT / 2) - (h / 2)

# draw message at a starting point, with decided font and colour
draw.text((x, y), message, inky_display.YELLOW, font)

inky_display.set_image(img)
inky_display.show()
Ejemplo n.º 29
0
# code taken from tutorial at https://learn.pimoroni.com/tutorial/sandyj/getting-started-with-inky-phat
# John Harney, 1.17.2020

from inky import InkyPHAT
from PIL import Image, ImageFont, ImageDraw
from font_fredoka_one import FredokaOne

inky_display = InkyPHAT("yellow")
inky_display.set_border(inky_display.WHITE)

img = Image.new("P", (inky_display.WIDTH, inky_display.HEIGHT))
draw = ImageDraw.Draw(img)

font = ImageFont.truetype(FredokaOne, 22)

message = "Centre College"
w, h = font.getsize(message)
x = (inky_display.WIDTH / 2) - (w / 2)
y = (inky_display.HEIGHT / 2) - (h / 2)

draw.text((x, y), message, inky_display.YELLOW, font)
inky_display.set_image(img)
inky_display.show()
Ejemplo n.º 30
0
def set_inky_display(image):
    inky_display = InkyPHAT(display_colour)
    inky_display.set_image(image)
    inky_border = inky_display.WHITE if border_colour == 'white' else inky_display.BLACK
    inky_display.set_border(inky_border)
    inky_display.show()