示例#1
0
文件: yawk.py 项目: brunolalb/yawk
    def __init__(self):
        self.cfg_data = dict()
        cfg_file_data = get_config_data(CONFIGFILE)
        self.cfg_data['api'] = cfg_file_data['api_key']
        self.cfg_data['city'] = cfg_file_data['city_id']

        self.fbink_cfg = ffi.new("FBInkConfig *")
        self.fbink_cfg.is_centered = True
        self.fbink_cfg.is_halfway = True
        self.fbink_cfg.is_cleared = True

        self.fbfd = fbink.fbink_open()
        fbink.fbink_init(self.fbfd, self.fbink_cfg)
        state = ffi.new("FBInkState *")
        fbink.fbink_get_state(self.fbink_cfg, state)

        if "linux" in platform:
            self.screen_size = (state.view_width, state.view_height)
        else:
            self.screen_size = (768, 1024)
        self.forecast = None
        self.current = None
        self.ip_address = "1.1.1.1"

        try:
            self.weather = yawkWeather(self.cfg_data)
        except ValueError as e:
            print(e)
            fbink.fbink_close(self.fbfd)
            
        # configuration for the image
        # Boxes positions
        #   current condition
        self.box_CURRENT = {'x': 0, 'y': 0, 'w': int(2 * self.screen_size[0] / 3), 'h': int(self.screen_size[1] / 3)}
        #   today's forecast
        self.box_TODAY = {'x': self.box_CURRENT['w'], 'y': 0, 'w': self.screen_size[0] - self.box_CURRENT['w'], 'h': self.box_CURRENT['h']}
        #   tomorrow
        self.box_TOMORROW = {'x': 0, 'y': self.box_CURRENT['h'], 'w': self.screen_size[0], 'h': int((self.screen_size[1] - self.box_CURRENT['h']) / 3)}
        #   next 3 days
        self.boxes_NEXT_DAYS = [{'x': 0, 'y': self.box_CURRENT['h'] + self.box_TOMORROW['h'], 'w': int(self.screen_size[0] / 3), 'h': self.screen_size[1] - self.box_CURRENT['h'] - self.box_TOMORROW['h']}]
        self.boxes_NEXT_DAYS.append({'x': self.boxes_NEXT_DAYS[0]['w'], 'y': self.boxes_NEXT_DAYS[0]['y'], 'w': self.boxes_NEXT_DAYS[0]['w'], 'h': self.boxes_NEXT_DAYS[0]['h']})
        self.boxes_NEXT_DAYS.append({'x': self.boxes_NEXT_DAYS[1]['x'] + self.boxes_NEXT_DAYS[1]['w'], 'y': self.boxes_NEXT_DAYS[1]['y'], 'w': self.boxes_NEXT_DAYS[1]['w'], 'h': self.boxes_NEXT_DAYS[1]['h']})
        # fonts
        #   used on the weather condition for the next days and ip address
        self.font_tiny = ImageFont.truetype("fonts/Cabin-Regular.ttf", 22)
        #   used on the headers and most stuff on the current conditions
        self.font_small = ImageFont.truetype("fonts/Fabrica.otf", 26)
        #   temperatures (gets scaled according to the box)
        self.font_comfortaa = ImageFont.truetype("fonts/Comfortaa-Regular.ttf", 60)
        #   for the current temperature
        self.font_main_temperature = ImageFont.truetype("fonts/Comfortaa-Regular.ttf", int(self.screen_size[1] / 10))        
        # icons
        self.icon_celsius = Image.open('icons/C.png')
        self.icon_wind = Image.open('icons/w.png')
        self.icon_humidity = Image.open('icons/h.png')
示例#2
0
文件: yawk.py 项目: brunolalb/yawk
    def update(self):
        try:
            self.current = self.weather.get_weather_current()
            self.forecast = self.weather.get_weather_forecast()
        except Exception as e:
            # Something went wrong while getting API Data, try again later.
            print("Failed to get weather data:\r\n" + str(e))
            return
        image = self._create_image()
        print("Drawing image")
        rect = ffi.new("FBInkRect *")
        rect.top = 0
        rect.left = 0
        rect.width = 0
        rect.height = 0
        fbink.fbink_cls(self.fbfd, self.fbink_cfg, rect, 0)

        fbink.fbink_print_image(self.fbfd, image, 0, 0, self.fbink_cfg)
示例#3
0
        with open(filePath, 'wb') as f:
            f.write(response.content)
            return filePath


display_width = 1080
input_query = "Integral from 1 to 3 of x**2"
appid = "JQT35P-425P6G3YT5"
baseURL = "http://api.wolframalpha.com/v1/simple?"
filePath = "result.png"
isKeyboardMode = True
runeStr = ""
upperCase = False

# INITIALIZING DISPLAY
fbink_cfg = ffi.new("FBInkConfig *")
fbfd = FBInk.fbink_open()
FBInk.fbink_init(fbfd, fbink_cfg)
#Get screen infos
state = ffi.new("FBInkState *")
FBInk.fbink_get_state(fbink_cfg, state)
display_width = state.screen_width
screenHeight = state.screen_height
#Clear screen
FBInk.fbink_cls(fbfd, fbink_cfg)

# INITIALIZING TOUCH
touchPath = "/dev/input/event1"
t = KIP.inputObject(touchPath, 1080, 1440)

# INITIALIZING APP
示例#4
0
import sys
import syslog
# Requires a Python snapshot circa 0.15.N-r15585
from _fbink import ffi, lib as fbink

# ------- Logging & user feedback (from the K5 Fonts Hack)

LIBRARIAN_SYNC = "LibrarianSync"

# Setup FBInk to our liking...
FBINK_CFG = ffi.new("FBInkConfig *")
FBINK_CFG.is_quiet = True
FBINK_CFG.is_padded = True
FBINK_CFG.is_centered = True
# FIXME: Switch from padded + centered to rpadded when that hits a snapshot...
#FBINK_CFG.is_rpadded = True
FBINK_CFG.row = -6

# And initialize it
fbink.fbink_init(fbink.FBFD_AUTO, FBINK_CFG)


# Pilfered from KindleUnpack, with minor tweaks ;).
# force string to be utf-8 encoded whether unicode or bytestring
def utf8_str(p, enc=sys.getfilesystemencoding()):
    if isinstance(p, unicode):
        return p.encode('utf-8')
    if enc != 'utf-8':
        return p.decode(enc).encode('utf-8', 'replace')
    return p
示例#5
0
def mpopup(title,
           text,
           buttons,
           filePath="temp_mpopup.png",
           screen_width=default_screenWidth,
           screen_height=default_screenHeight):
    """
	Pauses the app, displays a popup with as many buttons as there are in the array 'button'
	Then restore a screen dump from before the popup appeared
	Then returns the button which was pressed
	"text", "title" and button's "text" may contain eof characters (untested)
	Usage for a yes/no question:
	import utils
	buttons = [{"text":"Yes","valueToReturn":True},{"text":"No","valueToReturn":False}]
	doesUserLikeCheese = utils.mpopup("Cheese","Do you like cheese?",buttons)
	"""
    # Setup the config...
    fbink_cfg = ffi.new("FBInkConfig *")
    # Open the FB...
    fbfd = fbink.fbink_open()
    fbink.fbink_init(fbfd, fbink_cfg)
    # INITIALIZING TOUCH
    t = KIP.inputObject(touchPath, screen_width, screen_height)
    # Init :
    pp_width = int(3 * screen_width / 5)
    pp_height = int(screen_height / 3)
    start_coord_x = int(1 * screen_width / 5)
    start_coord_y = int(1 * screen_width / 3)
    num_btns = len(buttons)
    img = Image.new('L', (pp_width + 1, pp_height + 1), color=white)
    mpopup_img = ImageDraw.Draw(img, 'L')
    # Main rectangle:
    mpopup_img.rectangle([(0, 0), (pp_width, pp_height)],
                         fill=pp_color,
                         outline=pp_outline)
    # Main separation lines:
    mpopup_img.line([0, int(pp_height / 4), pp_width,
                     int(pp_height / 4)], pp_outline)  # Title and text
    mpopup_img.line(
        [0, int(3 * pp_height / 4), pp_width,
         int(3 * pp_height / 4)], pp_outline)  # text and buttons
    # Main texts
    title_w, title_h = mpopup_img.textsize(title, font=small_font_bold)
    mpopup_img.text((int(pp_width / 2 - 0.5 * title_w),
                     int(pp_height / 8 - 0.5 * title_h)),
                    title,
                    font=small_font_bold,
                    fill=black)
    text_w, text_h = mpopup_img.textsize(text, font=small_font)
    mpopup_img.text(
        (int(pp_width / 2 - 0.5 * text_w), int(pp_height / 2 - 0.5 * text_h)),
        text,
        font=small_font,
        fill=black)
    # Separation between buttons and buttons text :
    btns_areas = []
    for i in range(num_btns):
        btn_area = [
            int((i) * pp_width / num_btns),
            int(3 * pp_height / 4),
            int((i + 1) * pp_width / num_btns), pp_height
        ]
        btns_areas.append(btn_area)
        mpopup_img.rectangle(btn_area, fill=white, outline=pp_outline)
        btn_w, btn_h = mpopup_img.textsize(buttons[i]["text"], font=small_font)
        mpopup_img.text((int((btn_area[0] + btn_area[2]) / 2 - 0.5 * btn_w),
                         int(3 * pp_height / 4 + pp_height / 8 - 0.5 * btn_h)),
                        buttons[i]["text"],
                        font=small_font,
                        fill=black)
    # Saving to a file :
    img.save(filePath)
    # Making a copy of the screen
    fbink_dumpcfg = ffi.new("FBInkDump *")
    fbink.fbink_region_dump(fbfd, start_coord_x, start_coord_y,
                            start_coord_x + pp_width + 1,
                            start_coord_y + pp_height + 1, fbink_cfg,
                            fbink_dumpcfg)
    # Displaying image
    fbink.fbink_print_image(fbfd, filePath, start_coord_x, start_coord_y,
                            fbink_cfg)
    # Listening for touch in one of a button's area
    lastTouch = time()
    while True:
        try:
            (x, y, err) = t.getInput()
            if time() - lastTouch > 0.2:
                lastTouch = time()
                relative_x = x - start_coord_x
                relative_y = y - start_coord_y
                for i in range(num_btns):
                    if coordsInArea(relative_x, relative_y, btns_areas[i]):
                        #Closing touch file
                        t.close()
                        #Restoring dump
                        fbink.fbink_restore(fbfd, fbink_cfg, fbink_dumpcfg)
                        fbink.fbink_close(fbfd)
                        #Returning value
                        return buttons[i]["valueToReturn"]
        except:
            print("Bad touch event")
            continue
示例#6
0
def mprompt(title,
            text,
            filePath="temp_mprompt.png",
            screen_width=default_screenWidth,
            screen_height=default_screenHeight):
    """
	Pauses the app, displays a popup with an on-screen-keyboard
	Then restore a screen dump from before the popup appeared
	Then returns the string)
	"""
    # Setup the config...
    fbink_cfg = ffi.new("FBInkConfig *")
    # Open the FB...
    fbfd = fbink.fbink_open()
    fbink.fbink_init(fbfd, fbink_cfg)
    # INITIALIZING TOUCH
    t = KIP.inputObject(touchPath, screen_width, screen_height)
    # INITIALIZING KEYBOARD
    with open(mainFolder + 'sample-keymap-en_us.json') as json_file:
        km = json.load(json_file)
        vk = osk.virtKeyboard(km, screen_width, screen_height)
        # Generate an image of the OSK
        vkPNG = "img/vk.png"
        vk.createIMG(vkPNG)
    # Init :
    pp_width = int(4 * screen_width / 5)
    pp_height = int(screen_height / 3)
    start_coord_x = int(0.5 * screen_width / 5)
    start_coord_y = int(1 * screen_width / 3)
    img = Image.new('L', (pp_width + 1, pp_height + 1), color=white)
    mpopup_img = ImageDraw.Draw(img, 'L')
    # Main rectangle:
    mpopup_img.rectangle([(0, 0), (pp_width, pp_height)],
                         fill=pp_color,
                         outline=pp_outline)
    # Main separation lines:
    mpopup_img.line([0, int(pp_height / 4), pp_width,
                     int(pp_height / 4)], pp_outline)  # Title and text
    mpopup_img.line(
        [0, int(3.2 * pp_height / 4), pp_width,
         int(3.2 * pp_height / 4)], pp_outline)  # text and buttons
    # Main texts
    title_w, title_h = mpopup_img.textsize(title, font=small_font_bold)
    mpopup_img.text((int(pp_width / 2 - 0.5 * title_w),
                     int(pp_height / 8 - 0.5 * title_h)),
                    title,
                    font=small_font_bold,
                    fill=black)
    text_w, text_h = mpopup_img.textsize(text, font=small_font)
    mpopup_img.text(
        (int(pp_width / 2 - 0.5 * text_w), int(pp_height / 2 - 0.5 * text_h)),
        text,
        font=small_font,
        fill=black)
    # Saving to a file :
    img.save(filePath)
    # Making a copy of the screen
    fbink_dumpcfg = ffi.new("FBInkDump *")
    fbink.fbink_region_dump(fbfd, 0, 0, screen_width, screen_height, fbink_cfg,
                            fbink_dumpcfg)
    # Displaying image of the popup
    fbink.fbink_print_image(fbfd,
                            str(filePath).encode('ascii'), start_coord_x,
                            start_coord_y, fbink_cfg)
    # Displaying image of the OSK
    fbink.fbink_print_image(fbfd,
                            str(vkPNG).encode('ascii'),
                            int(vk.StartCoords["X"]), int(vk.StartCoords["Y"]),
                            fbink_cfg)
    # Listening for touch in one of a button's area
    lastTouch = time()
    lastTouchArea = [-3, -3, -2, -2]
    runeStr = ""
    upperCase = False
    # For an easy example, we only print it "manually" at the correct place.
    # You may want to print it using a better font and at a fixed coordinates
    # Should you want it, the text should be printed at the following coordinates:
    # x  =  start_coord_x + int(3.2*pp_height/4) + 10
    # y  =  start_coord_y + 10
    fbink_cfg.row = 32
    fbink_cfg.col = 6
    while True:
        # try:
        (x, y, err) = t.getInput()
        if time() - lastTouch > 0.2 or not coordsInArea(x, y, lastTouchArea):
            # Simple yet effective debounce system
            lastTouchArea = [x - 7, y - 7, x + 7, y + 7]
            k = vk.getPressedKey(x, y)
            if k != None:
                if not k["isKey"]:
                    continue
                if k["keyType"] == osk.KTstandardChar:
                    if upperCase:
                        key = str(k["keyCode"]).upper()
                    else:
                        key = str(k["keyCode"]).lower()
                    runeStr = runeStr + key
                    fbink.fbink_print(fbfd,
                                      str(runeStr).encode('ascii'), fbink_cfg)
                elif k["keyType"] == osk.KTbackspace:
                    if len(runeStr) > 0:
                        # removing last element and drawing and empty space instead
                        runeStr = runeStr[:-1]
                        fbink.fbink_print(
                            fbfd,
                            str(str(runeStr) + " ").encode('ascii'), fbink_cfg)
                elif k["keyType"] == osk.KTcapsLock:
                    if upperCase:
                        upperCase = False
                    else:
                        upperCase = True
                elif k["keyType"] == osk.KTcarriageReturn:
                    #Closing touch file
                    t.close()
                    #Restoring dump
                    fbink.fbink_restore(fbfd, fbink_cfg, fbink_dumpcfg)
                    fbink.fbink_close(fbfd)
                    return runeStr
                else:
                    continue
    # except:
    # 	print("Bad touch event")
    # 	continue
    return True
示例#7
0
#!/usr/bin/env python
import sys
import os
import threading
from time import sleep
# Load the wrapper module, it's linked against FBInk, so the dynamic loader will take care of pulling in the actual FBInk library
from _fbink import ffi, lib as FBInk
# Load Pillow
from PIL import Image, ImageDraw, ImageFont

sys.path.append('/mnt/onboard/.adds/mavireck/Kobo-Input-Python')
import KIP

fbink_cfg = ffi.new("FBInkConfig *")
fbink_dumpcfg = ffi.new("FBInkDump *")
fbfd = FBInk.fbink_open()
FBInk.fbink_init(fbfd, fbink_cfg)
#Get screen infos
state = ffi.new("FBInkState *")
FBInk.fbink_get_state(fbink_cfg, state)
screen_width = state.screen_width
screen_height = state.screen_height
view_width = state.view_width
view_height = state.view_height
h_offset = screen_height - view_height
w_offset = screen_width - view_width
isEmulator = False


def wait(time_seconds):
    sleep(time_seconds)
示例#8
0
# To get a Py3k-like print function
from __future__ import print_function

import sys
# Load the wrapper module, it's linked against FBInk, so the dynamic loader will take care of pulling in the actual FBInk library
from _fbink import ffi, lib as FBInk

# Let's check which FBInk version we're using...
# NOTE: ffi.string() returns a bytes on Python 3, not a str, hence the extra decode
print("Loaded FBInk {}".format(
    ffi.string(FBInk.fbink_version()).decode("ascii")))

# And now we're good to go! Let's print "Hello World" in the center of the screen...
# Setup the config...
fbink_cfg = ffi.new("FBInkConfig *")
fbink_cfg.is_centered = True
fbink_cfg.is_halfway = True
"""
# Open the FB...
fbfd = FBInk.fbink_open()
if fbfd == -1:
	raise SystemExit("Failed to open the framebuffer, aborting . . .")

# Initialize FBInk...
if FBInk.fbink_init(fbfd, fbink_cfg) < 0:
	raise SystemExit("Failed to initialize FBInk, aborting . . .")

# Do stuff!
if FBInk.fbink_print(fbfd, b"Hello World", fbink_cfg) < 0:
	print("Failed to print that string!", file=sys.stderr)