Esempio n. 1
0
def drawLogo(offset=0, max_height=ugfx.height(), center=True):
    global cfg_logo, default_logo
    try:
        info = badge.png_info(cfg_logo)
    except:
        try:
            cfg_logo = default_logo
            info = badge.png_info(cfg_logo)
        except:
            return 0
    width = info[0]
    height = info[1]
    if width > ugfx.width():
        print("Image too large (x)")
        return
    if height > ugfx.height():
        print("Image too large (y)")
    x = int((ugfx.width() - width) / 2)
    if center:
        if max_height - height < 0:
            print("Not enough space for logo", max_height, height)
            return 0
        y = int((max_height - height) / 2) + offset
    else:
        y = offset
    try:
        #badge.png(x,y,cfg_logo)
        ugfx.display_image(x, y, cfg_logo)
        return height
    except BaseException as e:
        sys.print_exception(e)
    return 0
Esempio n. 2
0
    def __init__(self, text="Please Wait...", title=version.dialog_title):
        self.window = ugfx.Container(30, 30,
                                     ugfx.width() - 60,
                                     ugfx.height() - 60)
        self.window.show()
        self.window.text(5, 10, title, ugfx.BLACK)
        self.window.line(0, 30, ugfx.width() - 60, 30, ugfx.BLACK)
        self.label = ugfx.Label(5,
                                40,
                                self.window.width() - 10,
                                ugfx.height() - 40,
                                text=text,
                                parent=self.window)

        # Indicator to show something is going on
        self.indicator = ugfx.Label(ugfx.width() - 100,
                                    0,
                                    20,
                                    20,
                                    text="...",
                                    parent=self.window)
        self.timer = machine.Timer(-1)
        self.timer.init(period=2000,
                        mode=self.timer.PERIODIC,
                        callback=lambda t: self.indicator.visible(
                            not self.indicator.visible()))
Esempio n. 3
0
def draw_name():
    intro_text = "Hi! I'm"
    intro_height = 30
    name_height = 60
    max_name = 8

    ugfx.orientation(90)
    ugfx.set_default_font(ugfx.FONT_TITLE)
    # Process name
    name_setting = name("Set your name in the settings app")
    if len(name_setting) <= max_name:
        ugfx.set_default_font(ugfx.FONT_NAME)
    else:
        ugfx.set_default_font(ugfx.FONT_MEDIUM_BOLD)

    ugfx.Label(0,
               ugfx.height() - name_height - intro_height,
               ugfx.width(),
               intro_height,
               intro_text,
               justification=ugfx.Label.CENTER)
    ugfx.Label(0,
               ugfx.height() - name_height,
               ugfx.width(),
               name_height,
               name_setting,
               justification=ugfx.Label.CENTER)

    ugfx.orientation(270)
Esempio n. 4
0
def run_app(path):
	import buttons
	buttons.init()
	if not buttons.has_interrupt("BTN_MENU"):
		buttons.enable_menu_reset()
	try:
		mod = __import__(path)
		if "main" in dir(mod):
			mod.main()
	except Exception as e:
		import sys
		import uio
		import ugfx
		s = uio.StringIO()
		sys.print_exception(e, s)
		ugfx.clear()
		ugfx.set_default_font(ugfx.FONT_SMALL)
		w=ugfx.Container(0,0,ugfx.width(),ugfx.height())
		ugfx.Label(0,0,ugfx.width(),ugfx.height(),s.getvalue(),parent=w)
		w.show()
		raise(e)
	import stm
	stm.mem8[0x40002850] = 0x9C
	import pyb
	pyb.hard_reset()
Esempio n. 5
0
    def __init__(self, text="Please Wait...", title="SHA2017Badge"):
        self.window = ugfx.Container(30, 30,
                                     ugfx.width() - 60,
                                     ugfx.height() - 60)
        self.window.show()
        self.window.text(5, 10, title, ugfx.BLACK)
        self.window.line(0, 30, ugfx.width() - 60, 30, ugfx.BLACK)
        self.label = ugfx.Label(5,
                                40,
                                self.window.width() - 10,
                                ugfx.height() - 40,
                                text=text,
                                parent=self.window)

        # Indicator to show something is going on
        self.indicator = ugfx.Label(ugfx.width() - 100,
                                    0,
                                    20,
                                    20,
                                    text="...",
                                    parent=self.window)
        self.timer = pyb.Timer(3)
        self.timer.init(freq=3)
        self.timer.callback(
            lambda t: self.indicator.visible(not self.indicator.visible()))
Esempio n. 6
0
def show_shift_detail():
    global shifts
    global shift_list
    shift_list.visible(False)
    ugfx.clear(ugfx.WHITE)
    ugfx.flush()
    i = shift_list.selected_index()
    title = shifts[i]["name"]
    title_height = 20 if ugfx.get_string_width(
        title, "PermanentMarker22") <= ugfx.width() else 60
    title = ugfx.string_box(0, 0, ugfx.width(), title_height, title,
                            "PermanentMarker22", ugfx.BLACK,
                            ugfx.justifyCenter)
    location = ugfx.string(0, title_height + 5,
                           "Location: " + shifts[i]["Name"],
                           "Roboto_Regular18", ugfx.BLACK)
    description = ugfx.string_box(0, title_height + 25, ugfx.width(), 40,
                                  "Description: " + shifts[i]["title"],
                                  "Roboto_Regular12", ugfx.BLACK,
                                  ugfx.justifyLeft)
    time = ugfx.string(
        0,
        ugfx.height() - 20, "Time: " + generate_timedelta_text(
            int(shifts[i]["start"]), int(shifts[i]["end"])),
        "Roboto_Regular18", ugfx.BLACK)
    ugfx.flush()
    ugfx.input_attach(ugfx.BTN_B, lambda pressed: show_shift_list()
                      if pressed else None)
Esempio n. 7
0
def draw_badge():
	style.set_enabled([ugfx.WHITE, ugfx.html_color(0x800080), ugfx.html_color(0x800080), ugfx.html_color(0x800080)])
	style.set_background(ugfx.html_color(0x800080))
	ugfx.clear(ugfx.html_color(0x800080))
	ugfx.set_default_style(style)
	# Logo stuff
	ugfx.display_image(
		int((ugfx.width() - logo_width) / 2),
		int((ugfx.height() - logo_height) / 2),
		logo_path
	)

	# Draw for people to see
	ugfx.orientation(90)
	# Draw introduction
	ugfx.set_default_font(ugfx.FONT_TITLE)
	ugfx.Label(0, ugfx.height() - name_height - intro_height, ugfx.width(), intro_height, intro_text, justification=ugfx.Label.CENTER)
	# Process name
	name_setting = name("Set your name in the settings app")
	if len(name_setting) <= max_name:
		ugfx.set_default_font(ugfx.FONT_NAME)
	else:
		ugfx.set_default_font(ugfx.FONT_MEDIUM_BOLD)
	# Draw name
	ugfx.Label(0, ugfx.height() - name_height, ugfx.width(), name_height, name_setting, justification=ugfx.Label.CENTER)

	# Draw for wearer to see
	ugfx.orientation(270)
	ugfx.set_default_font(ugfx.FONT_SMALL)
	status = ugfx.Label(0, ugfx.height() - status_height, ugfx.width(), status_height, "", justification=ugfx.Label.LEFT)
Esempio n. 8
0
def list_categories():
    global options
    global text
    global categories

    try:
        categories
    except:
        ugfx.input_init()
        draw_msg('Getting categories')
        try:
            f = urequests.get("https://badge.team/eggs/categories/json",
                              timeout=30)
            categories = f.json()
        except:
            draw_msg('Failed!')
            draw_msg('Returning to launcher :(')
            appglue.start_app('launcher', False)

            f.close()
        draw_msg('Done!')
        options = ugfx.List(0, 0, int(ugfx.width() / 2), ugfx.height())
        text = ugfx.Textbox(int(ugfx.width() / 2), 0, int(ugfx.width() / 2),
                            ugfx.height())

    ugfx.input_attach(ugfx.JOY_UP, lambda pushed: ugfx.flush()
                      if pushed else False)
    ugfx.input_attach(ugfx.JOY_DOWN, lambda pushed: ugfx.flush()
                      if pushed else False)
    ugfx.input_attach(ugfx.BTN_A, select_category)
    ugfx.input_attach(
        ugfx.BTN_B, lambda pushed: appglue.start_app("launcher", False)
        if pushed else False)
    ugfx.input_attach(
        ugfx.BTN_START, lambda pushed: appglue.start_app("")
        if pushed else False)

    ugfx.clear(ugfx.WHITE)
    ugfx.flush()

    while options.count() > 0:
        options.remove_item(0)
    for category in categories:
        options.add_item("%s (%d) >" % (category["name"], category["eggs"]))
    options.selected_index(0)

    text.text("Install or update eggs from the hatchery here\n\n\n\n")
    ugfx.string_box(148, 0, 148, 26, "Hatchery", "Roboto_BlackItalic24",
                    ugfx.BLACK, ugfx.justifyCenter)
    ugfx.line(148, 78, 296, 78, ugfx.BLACK)
    ugfx.string_box(148, 78, 148, 18, " A: Open category", "Roboto_Regular12",
                    ugfx.BLACK, ugfx.justifyLeft)
    ugfx.string_box(148, 92, 148, 18, " B: Return to home", "Roboto_Regular12",
                    ugfx.BLACK, ugfx.justifyLeft)
    ugfx.line(148, 110, 296, 110, ugfx.BLACK)
    ugfx.string_box(148, 110, 148, 18, " badge.team", "Roboto_Regular12",
                    ugfx.BLACK, ugfx.justifyLeft)
    ugfx.flush(ugfx.LUT_FULL)
    gc.collect()
Esempio n. 9
0
    def draw_background(self, colour):

        logo = 'apps/emf_hub_mon/emf_hub_mon.gif'

        ugfx.area(0, 0, ugfx.width(), ugfx.height(), colour)
        ugfx.area(0, 0, ugfx.width(), 25, ugfx.GREY)

        ugfx.display_image(10, 30, logo)
def populate_options():
    global options
    if orientation.isLandscape():
        options = ugfx.List(0, 0, int(ugfx.width() / 2), ugfx.height())
    else:
        options = ugfx.List(0, 0, ugfx.width(), int(ugfx.height() - 18 * 4))
    global currentListTitles
    for title in currentListTitles:
        options.add_item(title)
Esempio n. 11
0
def reset():
    global i
    global j
    i = int(ugfx.width() / 2)
    j = int(ugfx.height() / 2)
    ugfx.area(0, 0, ugfx.width(), ugfx.height(), ugfx.BLACK)
    ugfx.area((i - 1) if i > 0 else 0, (j - 1) if j > 0 else 0, 3 if
              (i > 0 and i < (ugfx.width() - 1)) else 2, 3 if
              (j > 0 and j < (ugfx.height() - 1)) else 2, ugfx.GREY)
Esempio n. 12
0
def prompt_option(options, index=0, text = "Please select one of the following:", title=None, select_text="OK", none_text=None):
	"""Shows a dialog prompting for one of multiple options

	If none_text is specified the user can use the B or Menu button to skip the selection
	if title is specified a blue title will be displayed about the text
	"""
	global wait_for_interrupt, button_pushed

	ugfx.set_default_font("Roboto_Regular12")
	window = ugfx.Container(5, 5, ugfx.width() - 10, ugfx.height() - 10)
	window.show()

	list_y = 30
	if title:
		window.text(5, 10, title, ugfxBLACK)
		window.line(0, 25, ugfx.width() - 10, 25, ugfx.BLACK)
		window.text(5, 30, text, ugfx.BLACK)
		list_y = 50
	else:
		window.text(5, 10, text, ugfx.BLACK)

	options_list = ugfx.List(5, list_y, ugfx.width() - 25, 180 - list_y, parent = window)

	for option in options:
		if isinstance(option, dict) and option["title"]:
			options_list.add_item(option["title"])
		else:
			options_list.add_item(str(option))
	options_list.selected_index(index)

	select_text = "A: " + select_text
	if none_text:
		none_text = "B: " + none_text

	button_select = ugfx.Button(5, ugfx.height() - 50, 140 if none_text else ugfx.width() - 25, 30 , select_text, parent=window)
	button_none = ugfx.Button(ugfx.width() - 160, ugfx.height() - 50, 140, 30 , none_text, parent=window) if none_text else None

	try:
		ugfx.input_init()

		wait_for_interrupt = True
		while wait_for_interrupt:
			if button_pushed == "A": return options[options_list.selected_index()]
			if button_pushed == "B": return None
			if button_none and button_pushed == "START": return None
			time.sleep(0.2)

	finally:
		window.hide()
		window.destroy()
		options_list.destroy()
		button_select.destroy()
		if button_none: button_none.destroy()
		ugfx.poll()
Esempio n. 13
0
	def __init__(self, text = "Please Wait...", title="TiLDA"):
		self.window = ugfx.Container(30, 30, ugfx.width() - 60, ugfx.height() - 60)
		self.window.show()
		self.window.text(5, 10, title, TILDA_COLOR)
		self.window.line(0, 30, ugfx.width() - 60, 30, ugfx.BLACK)
		self.label = ugfx.Label(5, 40, self.window.width() - 10, ugfx.height() - 40, text = text, parent=self.window)

		# Indicator to show something is going on
		self.indicator = ugfx.Label(ugfx.width() - 100, 0, 20, 20, text = "...", parent=self.window)
		self.timer = pyb.Timer(3)
		self.timer.init(freq=3)
		self.timer.callback(lambda t: self.indicator.visible(not self.indicator.visible()))
Esempio n. 14
0
def nickname(y=0,
             font=version.font_nickname_large,
             color=ugfx.BLACK,
             lineHeight=15):
    nick = badge.nvs_get_str("owner", "name", 'WELCOME TO HACKERHOTEL')
    lines = lineSplit(nick, ugfx.width(), font)
    for i in range(len(lines)):
        line = lines[len(lines) - i - 1]
        pos_x = int((ugfx.width() - ugfx.get_string_width(line, font)) / 2)
        ugfx.string(pos_x, y + lineHeight * (len(lines) - i - 1), line, font,
                    color)
    return len(lines) * lineHeight
def prompt_option(options, index=0, text = "Please select one of the following:", title=None, select_text="OK", none_text=None):
    """Shows a dialog prompting for one of multiple options

    If none_text is specified the user can use the B or Menu button to skip the selection
    if title is specified a blue title will be displayed about the text
    """
    ugfx.set_default_font(ugfx.FONT_SMALL)
    window = ugfx.Container(5, 5, ugfx.width() - 10, ugfx.height() - 10)
    window.show()

    list_y = 30
    if title:
        window.text(5, 10, title, TILDA_COLOR)
        window.line(0, 25, ugfx.width() - 10, 25, ugfx.BLACK)
        window.text(5, 30, text, ugfx.BLACK)
        list_y = 50
    else:
        window.text(5, 10, text, ugfx.BLACK)

    options_list = ugfx.List(5, list_y, ugfx.width() - 25, 180 - list_y, parent = window)

    for option in options:
        if isinstance(option, dict) and option["title"]:
            options_list.add_item(option["title"])
        else:
            options_list.add_item(str(option))
    options_list.selected_index(index)

    select_text = "A: " + select_text
    if none_text:
        none_text = "B: " + none_text

    button_select = ugfx.Button(5, ugfx.height() - 50, 140 if none_text else ugfx.width() - 25, 30 , select_text, parent=window)
    button_none = ugfx.Button(ugfx.width() - 160, ugfx.height() - 50, 140, 30 , none_text, parent=window) if none_text else None

    try:
        buttons.init()

        while True:
            pyb.wfi()
            ugfx.poll()
            if buttons.is_triggered("BTN_A"): return options[options_list.selected_index()]
            if button_none and buttons.is_triggered("BTN_B"): return None
            if button_none and buttons.is_triggered("BTN_MENU"): return None

    finally:
        window.hide()
        window.destroy()
        options_list.destroy()
        button_select.destroy()
        if button_none: button_none.destroy()
        ugfx.poll()
Esempio n. 16
0
def prompt_option(options, index=0, text = "Please select one of the following:", title=None, select_text="OK", none_text=None):
	"""Shows a dialog prompting for one of multiple options

	If none_text is specified the user can use the B or Menu button to skip the selection
	if title is specified a blue title will be displayed about the text
	"""
	ugfx.set_default_font(ugfx.FONT_SMALL)
	window = ugfx.Container(5, 5, ugfx.width() - 10, ugfx.height() - 10)
	window.show()

	list_y = 30
	if title:
		window.text(5, 10, title, TILDA_COLOR)
		window.line(0, 25, ugfx.width() - 10, 25, ugfx.BLACK)
		window.text(5, 30, text, ugfx.BLACK)
		list_y = 50
	else:
		window.text(5, 10, text, ugfx.BLACK)

	options_list = ugfx.List(5, list_y, ugfx.width() - 25, 180 - list_y, parent = window)

	for option in options:
		if isinstance(option, dict) and option["title"]:
			options_list.add_item(option["title"])
		else:
			options_list.add_item(str(option))
	options_list.selected_index(index)

	select_text = "A: " + select_text
	if none_text:
		none_text = "B: " + none_text

	button_select = ugfx.Button(5, ugfx.height() - 50, 140 if none_text else ugfx.width() - 25, 30 , select_text, parent=window)
	button_none = ugfx.Button(ugfx.width() - 160, ugfx.height() - 50, 140, 30 , none_text, parent=window) if none_text else None

	try:
		buttons.init()

		while True:
			pyb.wfi()
			ugfx.poll()
			if buttons.is_triggered("BTN_A"): return options[options_list.selected_index()]
			if button_none and buttons.is_triggered("BTN_B"): return None
			if button_none and buttons.is_triggered("BTN_MENU"): return None

	finally:
		window.hide()
		window.destroy()
		options_list.destroy()
		button_select.destroy()
		if button_none: button_none.destroy()
		ugfx.poll()
Esempio n. 17
0
 def __init__(self, text="Please Wait...", title="TiLDA"):
     self.window = ugfx.Container(30, 30,
                                  ugfx.width() - 60,
                                  ugfx.height() - 60)
     self.window.show()
     self.window.text(5, 10, title, TILDA_COLOR)
     self.window.line(0, 30, ugfx.width() - 60, 30, ugfx.BLACK)
     self.label = ugfx.Label(5,
                             40,
                             self.window.width() - 10,
                             ugfx.height() - 40,
                             text=text,
                             parent=self.window)
Esempio n. 18
0
def doScroll():
    global yPos, maxHeight, logo

    # Blank previous logo location
    ugfx.area(0, yPos, ugfx.width(), yPos + logo_height, 0)

    # Move up and wrap
    yPos -= 20
    if (yPos <= -logo_height):
        yPos = maxHeight

    # Draw logo
    ugfx.display_image(int((ugfx.width() - logo_width) / 2), int(yPos), logo)
Esempio n. 19
0
def loading_screen():
    logo = 'lobstervision/lobsterpictures.gif'
    ugfx.area(0, 0, ugfx.width(), ugfx.height(), 0xFFFF)
    ugfx.display_image(0, 50, logo)
    ugfx.set_default_font(ugfx.FONT_SMALL)
    ugfx.text(15, 305, "lobstervision.tv/emf2018", ugfx.GREY)
    display_loading()
    def __init__(self):
        # initialize ugfx
        ugfx.init()
        ugfx.clear(ugfx.WHITE)

        # Buttons
        ugfx.input_init()
        self.init_buttons()

        # Container
        width = ugfx.width()
        height = ugfx.height()
        ind_height = 46
        container_height = height - ind_height

        self.indicator = ugfx.Container(0,
                                        0,
                                        width,
                                        ind_height,
                                        style=styles.ibm_st)
        self.container = ugfx.Container(0,
                                        ind_height,
                                        width,
                                        container_height,
                                        style=styles.ibm_st)

        self.graph_basepos = container_height - 5

        # Sensor
        SCL = Pin(26)  # SCL
        SDA = Pin(25)  # SDA
        self.sensor = MPU6050(I2C(scl=SCL, sda=SDA))

        # Buzzer
        self.buzzer = Buzzer()
Esempio n. 21
0
def draw_screen():
    loc_data = get_data("https://freegeoip.app/json/")
    lat = str(loc_data["latitude"])
    lon = str(loc_data["longitude"])
    city = loc_data["city"]
    country = loc_data["country_name"]
    iss_data = get_data("http://api.open-notify.org/iss-pass.json?lat=" + lat + "&lon=" + lon)
    risetime = iss_data['response'][0]['risetime']
    datetime = iss_data['request']['datetime']
    countdown = datetime
    LED(LED.GREEN).off()
    while countdown < risetime:
        ugfx.clear(ugfx.BLACK)
        ugfx.text(5, 5, "When does the ISS next pass?", ugfx.WHITE)
        ugfx.line(5, 20, ugfx.width(), 20, ugfx.GREY)
        ugfx.text(5, 35, "Location: " + city + ", " + country, ugfx.WHITE)
        ugfx.text(5, 50, "Latitude: " + lat, ugfx.WHITE)
        ugfx.text(5, 65, "Longitude: " + lon, ugfx.WHITE)
        ugfx.text(5, 80, "Rise time: " + str(get_time(risetime)), ugfx.WHITE)
        ugfx.text(5, 95, "Duration: " + str(get_seconds(iss_data['response'][0]['duration'])), ugfx.WHITE)
        countdown +=1
        ugfx.text(5, 110, "Countdown: " + str(get_wait(risetime, countdown)), ugfx.WHITE)
        utime.sleep(1)
    else:
        LED(LED.GREEN).on()
        LED(LED.RED).on()
        utime.sleep(1)
        LED(LED.GREEN).off()
        LED(LED.RED).off()
        draw_screen()
Esempio n. 22
0
def show_names():
    global names
    c = False
    for n in range(0, len(names)):
        color = ugfx.BLACK
        if (c):
            c = False
        else:
            c = True
            color = ugfx.WHITE
        fill_screen_with_crap(color)
        x = int.from_bytes(uos.urandom(1), 1)
        y = round(int.from_bytes(uos.urandom(1), 1) / 2)
        w = ugfx.get_string_width(names[n], "PermanentMarker22")
        if (x + w > ugfx.width()):
            x = x + w
        if (y > ugfx.height() - 22):
            y = ugfx.height() - 22
        if (x == 0):
            x = 1
        if (y == 0):
            y = 1
        print("NAME AT " + str(x) + ", " + str(y))
        draw_name(x, y, names[n])
        time.sleep(1)
Esempio n. 23
0
def loading_screen():
    logo = 'praise_horse_worship_melon/loading.gif'
    ugfx.area(0,0,ugfx.width(),ugfx.height(),0xFFFF)
    ugfx.display_image(2,2,logo)
    ugfx.set_default_font(ugfx.FONT_SMALL)
    ugfx.text(60, 145, "Praise Horse (A)", ugfx.GREY)
    ugfx.text(55, 305, "Worship Melon (B)", ugfx.GREY)
Esempio n. 24
0
def draw_screen():

    ugfx.clear(ugfx.BLACK)
    ugfx.text(60, 5, "what's on tap?", ugfx.RED)
    ugfx.line(5, 20, ugfx.width(), 20, ugfx.GREY)
    for idx, beer in enumerate(bar['location']):
        ugfx.text(5, 22 + idx * 15, beer['description'], ugfx.WHITE)
Esempio n. 25
0
def viewmsg():
	msgid = db.get('msgseq')
	msg = inbox.get(msgid)
	if msg == None:
		ugfx.set_default_font(ugfx.FONT_SMALL)	
		ugfx.area(0,0,ugfx.width(),ugfx.height(),0x0000)
		ugfx.text(40,100,"NO MESSAGES",ugfx.BLUE)
		pyb.delay(1000)
		return
	else:
		data = json.loads(msg)
		printmsg(data['sender'], data['payload'], data['ts'])
	while True:
		if buttons.is_triggered("JOY_UP"):
			print(msgid)
			msgid -= 1
			msg = inbox.get(msgid)
			if msg != None:
				data = json.loads(msg)
				printmsg(data['sender'], data['payload'], data['ts'])
			else:
				msgid += 1
		if buttons.is_triggered("JOY_DOWN"):
			print(msgid)
			msgid += 1
			msg = inbox.get(msgid)
			if msg != None:
				data = json.loads(msg)
				printmsg(data['sender'], data['payload'], data['ts'])
			else:
				msgid -= 1
		if buttons.is_triggered("BTN_B"):
			display()
			return
Esempio n. 26
0
def lineSplit(message, width=ugfx.width(), font=version.font_default):
    words = message.split(" ")
    lines = []
    line = ""
    for word in words:
        wordLength = 0
        for c in word:
            wordLength += ugfx.get_char_width(ord(c), font)
        lineLength = 0
        for c in line:
            lineLength += ugfx.get_char_width(ord(c), font)
        if wordLength > width:
            lines.append(line)
            lines.append(word)
            line = ""
        elif lineLength + wordLength < width:
            if (line == ""):
                line = word
            else:
                line += " " + word
        else:
            lines.append(line)
            line = word
    if len(line) > 0:
        lines.append(line)
    return lines
Esempio n. 27
0
    def setup_screen(self):
        """ Set up the screen and the labels that display
            values on it. 
        """
        ugfx.init()
        width=ugfx.width()
        height=ugfx.height()
        ugfx.clear(ugfx.html_color(0x800080))
        style = ugfx.Style()
        style.set_enabled([ugfx.WHITE, ugfx.html_color(0x800080), ugfx.html_color(0x800080), ugfx.html_color(0x800080)])
        style.set_background(ugfx.html_color(0x800080))
        ugfx.set_default_style(style)
        ugfx.orientation(90)
        ugfx.set_default_font(ugfx.FONT_TITLE)
        ugfx.Label(0, 0, width, 60,"Air Quality", justification=ugfx.Label.CENTER)
        label_height=45
        self.ppm10_label = ugfx.Label(0, label_height, width, label_height,"PPM 10: starting", justification=ugfx.Label.CENTER)
        self.ppm25_label = ugfx.Label(0, label_height*2, width, label_height,"PPM 2.5: starting", justification=ugfx.Label.CENTER)

        self.temp_label = ugfx.Label(0, label_height*3, width, label_height,"Temp: starting", justification=ugfx.Label.CENTER)
        self.humid_label = ugfx.Label(0, label_height*4, width, label_height,"Humid: starting", justification=ugfx.Label.CENTER)
        self.error_label = ugfx.Label(0, label_height*5, width, label_height,"", justification=ugfx.Label.CENTER)
        self.message_label = ugfx.Label(0, label_height*6, width, label_height,"", justification=ugfx.Label.CENTER)
        self.error_count = 0
        self.error_message = ""
        self.neopix = Neopix()
        self.p10_decode = ((100,0x00ff00),(250,0xffff00),(350,0xff8000),(430,0xff0000),(-1,0xcc6600))
        self.p25_decode = ((60, 0x00ff00),(91, 0xffff00), (121,0xff8000),(251,0xff0000),(-1,0xcc6600))
Esempio n. 28
0
def lineSplit(message, width=None, font=version.font_default):
    words = message.split(" ")
    lines = []
    line = ""

    if width == None:
        width = ugfx.width()

    for word in words:
        wordLength = ugfx.get_string_width(word, font)
        lineLength = ugfx.get_string_width(line, font)
        if wordLength > width:
            lines.append(line)
            lines.append(word)
            line = ""
        elif lineLength + wordLength < width:
            if (line == ""):
                line = word
            else:
                line += " " + word
        else:
            lines.append(line)
            line = word
    if len(line) > 0:
        lines.append(line)
    return lines
Esempio n. 29
0
def msg_nosplit(message, title='Loading...', reset=False):
    global NUM_LINES
    """Show a terminal style loading screen with title

	title can be optionaly set when resetting or first call
	"""
    global messageHistory

    try:
        messageHistory
        if reset:
            raise exception
    except:
        ugfx.clear(ugfx.WHITE)
        ugfx.string(0, 0, title, version.font_header, ugfx.BLACK)
        messageHistory = []

    if len(messageHistory) < NUM_LINES:
        ugfx.string(0, 19 + (len(messageHistory) * 13), message,
                    version.font_default, ugfx.BLACK)
        messageHistory.append(message)
    else:
        messageHistory.pop(0)
        messageHistory.append(message)
        ugfx.area(0, 15, ugfx.width(), ugfx.height() - 15, ugfx.WHITE)
        for i, message in enumerate(messageHistory):
            ugfx.string(0, 19 + (i * 13), message, version.font_default,
                        ugfx.BLACK)

    ugfx.flush(ugfx.LUT_FASTER)
Esempio n. 30
0
def showPage():
    global current_page
    # avoid out of bounds errors
    current_page = max(1, min(current_page, total_pages))
    
    start = (current_page - 1) * APPS_PER_PAGE
    end = start + APPS_PER_PAGE
    apps_on_current_page = all_apps[start:end]

    # Refresh page
    ugfx.clear(ugfx.html_color(EMF_PURPLE))

    # Write current page number and arrows
    ugfx.Label(0, 20, ugfx.width(), 20, "Page {} of {}".format(current_page, total_pages), justification=ugfx.Label.CENTER)

    if current_page > 1:
        ugfx.fill_polygon(10, 16, [[0, 10], [15, 20], [15, 0]], ugfx.WHITE)
        
    if current_page < total_pages:
        ugfx.fill_polygon(ugfx.width() - 30, 16, [[0, 0], [15, 10], [0, 20]], ugfx.WHITE)
    
    # Write app numbers and names
    i = 0
    yOffset = 45
    xOffset = 0
    for a in apps_on_current_page:
        # xOffset = (i % 3) * 8  # offset lines to match the physical layout of the keypad
        ugfx.area(20 + xOffset, yOffset + 2, 20, 20, ugfx.WHITE)
        ugfx.text(23 + xOffset, yOffset + 3, keypadLabels[i] + " ", EMF_PURPLE)

        ugfx.Label(46 + xOffset, yOffset + 3, ugfx.width(), 20, a['title'], justification=ugfx.Label.LEFT)
        yOffset = yOffset + 22
        i = i + 1

    while True:
        for key in keypad:
            keyIndex = keypad.index(key)
            if buttons.is_pressed(key) and (keyIndex < len(apps_on_current_page)):
                apps_on_current_page[keyIndex]['app'].boot()
                break

        if buttons.is_triggered(Buttons.JOY_Right) and (current_page is not total_pages):
            current_page = current_page + 1
            return
        if buttons.is_triggered(Buttons.JOY_Left) and (current_page is not 1):
            current_page = current_page - 1
            return
Esempio n. 31
0
def messageCentered(message, firstLineTitle=True, png=None):
    try:
        font1 = "Roboto_Regular18"
        font2 = "Roboto_Regular12"
        color = ugfx.BLACK
        ugfx.clear(ugfx.WHITE)
        parts = message.split("\n")
        lines = []
        font = font1
        for part in parts:
            if len(part) < 1:
                lines.append("")
            else:
                lines.extend(lineSplit(part, ugfx.width(), font))
            if firstLineTitle:
                font = font2

        offset_y = int(ugfx.height() / 2)  #Half of the screen height
        offset_y -= 9  #Height of the first line divided by 2
        if firstLineTitle:
            offset_y -= 6 * len(lines) - 1  #Height of font1 divided by 2
        else:
            offset_y -= 9 * len(lines) - 1  #Height of font2 divided by 2

        if png != None:
            try:
                img_info = badge.png_info(png)
                offset_y -= int(img_info[1] / 2) + 4
                img_x = int((ugfx.width() - img_info[0]) / 2)
                ugfx.display_image(img_x, offset_y, png)
                offset_y += img_info[1] + 8
            except:
                pass

        lineCentered(offset_y, lines[0], font1, color)
        offset_y += 18

        for i in range(len(lines) - 1):
            if not firstLineTitle:
                lineCentered(offset_y, lines[i + 1], font1, color)
                offset_y += 18
            else:
                lineCentered(offset_y, lines[i + 1], font2, color)
                offset_y += 12
        ugfx.flush()
    except:
        print("!!! Exception in easydraw.messageCentered !!!")
Esempio n. 32
0
def display_logo():
    ugfx.clear(ugfx.BLACK)
    ugfx.string(280, 228, 'v{}'.format(get_version()),
            'IBMPlexSans_Regular12', ugfx.WHITE)
    ugfx.display_image(40, 70, bytearray(open('ibm_logo.gif', 'rb').read()), 2, 300)
    ugfx.string_box(0, 140, ugfx.width(), 50, 'Developer Day 2018',
            'IBMPlexSans_Regular22', ugfx.HTML2COLOR(0x01d7dd), ugfx.justifyCenter)
    gc.collect()
Esempio n. 33
0
    def draw_everything():
# We draw the bird at X, and pipes every X*10 locations.
        ugfx.area(0,0,ugfx.width(), ugfx.height(), back_colour)
        draw_bird(10,y)
        for i in range(0,len(pipe_heights)):
            draw_pipe(10+i*10-x,pipe_heights[i])
        #ugfx.text(30,10, "Bird %d,%d Pipe: %d,%d" % (x,y,pipe_heights[x//10],pipe_heights[x//10]+gap), ugfx.WHITE)
        ugfx.text(30,10, "Score %d" % (score), ugfx.WHITE)
Esempio n. 34
0
def display():
	logo = 'apps/nexmo~messages/nexmo_logo.gif'
	ugfx.area(0,0,ugfx.width(),ugfx.height(),0xFFFF)
	ugfx.set_default_font(ugfx.FONT_MEDIUM_BOLD)	
	ugfx.text(20,20,"My Number is...",ugfx.BLACK)
	ugfx.text(20,130,"Powered By, ",ugfx.GREY)
	ugfx.display_image(15,150,logo)
	ugfx.set_default_font(ugfx.FONT_TITLE)
	ugfx.text(40,75,mynumber+" ",ugfx.BLUE)
def getdata():
	server = 'badge.emf.camp'
	#url = 'http://'+server+':9002/schedule'
	#url = 'http://hackspace-leaderboard-scollins.c9users.io/schedule'
	url = 'http://api.ipify.org/'
	resp = get(url).text
	ugfx.area(0,0,ugfx.width(),ugfx.height(),0x0000)
	while True:
		ugfx.text(30,30,resp,ugfx.WHITE)
	return json.loads(resp)
Esempio n. 36
0
def prompt_text(description, init_text = "", true_text="OK", false_text="Back", width = 300, height = 200, font=ugfx.FONT_MEDIUM_BOLD, style=default_style_badge):
	"""Shows a dialog and keyboard that allows the user to input/change a string

	Returns None if user aborts with button B
	"""

	window = ugfx.Container(int((ugfx.width()-width)/2), int((ugfx.height()-height)/2), width, height, style=style)

	if false_text:
		true_text = "M: " + true_text
		false_text = "B: " + false_text

	if buttons.has_interrupt("BTN_MENU"):
		buttons.disable_interrupt("BTN_MENU")

	ugfx.set_default_font(ugfx.FONT_MEDIUM)
	kb = ugfx.Keyboard(0, int(height/2), width, int(height/2), parent=window)
	edit = ugfx.Textbox(5, int(height/2)-30, int(width*4/5)-10, 25, text = init_text, parent=window)
	ugfx.set_default_font(ugfx.FONT_SMALL)
	button_yes = ugfx.Button(int(width*4/5), int(height/2)-30, int(width*1/5)-3, 25 , true_text, parent=window)
	button_no = ugfx.Button(int(width*4/5), int(height/2)-30-30, int(width/5)-3, 25 , false_text, parent=window) if false_text else None
	ugfx.set_default_font(font)
	label = ugfx.Label(int(width/10), int(height/10), int(width*4/5), int(height*2/5)-60, description, parent=window)

	try:
		buttons.init()

		button_yes.attach_input(ugfx.BTN_MENU,0)
		if button_no: button_no.attach_input(ugfx.BTN_B,0)

		window.show()
		edit.set_focus()
		while True:
			pyb.wfi()
			ugfx.poll()
			#if buttons.is_triggered("BTN_A"): return edit.text()
			if buttons.is_triggered("BTN_B"): return None
			if buttons.is_triggered("BTN_MENU"): return edit.text()

	finally:
		window.hide()
		window.destroy()
		button_yes.destroy()
		if button_no: button_no.destroy()
		label.destroy()
		kb.destroy()
		edit.destroy();
	return
Esempio n. 37
0
def do_circle_of_life():
    ugfx.init()
    buttons.init()
    buttons.disable_menu_reset()

    colour = get_colour()
    grid = Grid(ugfx.width(), ugfx.height(), colour_fore = colour, colour_back = COLOUR_BACK)
    grid.randomise()

    ugfx.clear(COLOUR_BACK)

    hash_count = 0
    hash_last = None
    hash_last_last = None
    while True:
        # display
        hash_val = grid.display_badge()

        # randomise, if needed
        if hash_val == hash_last_last:
            hash_count += 1

            if hash_count == HASH_COUNT_LIMIT:
                colour = get_colour(colour)
                grid.set_colour(colour)
                grid.randomise()
                hash_count = 0

        else:
            hash_count = 0

        hash_last_last = hash_last
        hash_last = hash_val

        # process next generation
        grid.next_generation()
        grid.swap_cell_buffers()

        # buttons
        pyb.wfi()
        if buttons.is_triggered("BTN_A") or buttons.is_triggered("BTN_B"):
            colour = get_colour(colour)
            grid.set_colour(colour)
            grid.randomise()

        if buttons.is_triggered("BTN_MENU"):
            break
Esempio n. 38
0
def printmsg(sender, text, ts):
	ugfx.set_default_font(ugfx.FONT_SMALL)	
	ugfx.area(0,0,ugfx.width(),ugfx.height(),0x0000)
	ugfx.text(10,10,"From: "+sender,ugfx.BLUE)
	timestamp = timestring(ts)
	linelen = 40
	lines = int(math.ceil(len(text)/linelen))
	for l in range(0, lines):
		pixels = l*25+35
		start = l*linelen
		end = l*linelen+linelen
		if end>len(text):
			end = len(text)
		linetext = text[start:end]
		ugfx.text(10,pixels,linetext,0xFFFF)
	ugfx.text(10,200,timestamp,ugfx.GREEN)
	return
Esempio n. 39
0
def prompt_boolean(text, title="TiLDA", true_text="Yes", false_text="No", width = 260, height = 180, font=ugfx.FONT_SMALL, style=None):
	"""A simple one and two-options dialog

	if 'false_text' is set to None only one button is displayed.
	If both 'true_text' and 'false_text' are given a boolean is returned
	"""
	global default_style_dialog
	if style == None:
		style = default_style_dialog
	ugfx.set_default_font(ugfx.FONT_MEDIUM_BOLD)
	window = ugfx.Container((ugfx.width() - width) // 2, (ugfx.height() - height) // 2,  width, height, style=style)
	window.show()
	ugfx.set_default_font(font)
	window.text(5, 10, title, TILDA_COLOR)
	window.line(0, 30, width, 30, ugfx.BLACK)

	if false_text:
		true_text = "A: " + true_text
		false_text = "B: " + false_text

	ugfx.set_default_font(font)
	label = ugfx.Label(5, 30, width - 10, height - 80, text = text, parent=window)
	ugfx.set_default_font(ugfx.FONT_MEDIUM_BOLD)
	button_yes = ugfx.Button(5, height - 40, width // 2 - 15 if false_text else width - 15, 30 , true_text, parent=window)
	button_no = ugfx.Button(width // 2 + 5, height - 40, width // 2 - 15, 30 , false_text, parent=window) if false_text else None

	try:
		buttons.init()

		button_yes.attach_input(ugfx.BTN_A,0)
		if button_no: button_no.attach_input(ugfx.BTN_B,0)

		window.show()

		while True:
			pyb.wfi()
			if buttons.is_triggered("BTN_A"): return True
			if buttons.is_triggered("BTN_B"): return False

	finally:
		window.hide()
		window.destroy()
		button_yes.destroy()
		if button_no: button_no.destroy()
		label.destroy()
Esempio n. 40
0
def showevent(stage, event):
	start = event['start_date']
	end = event['end_date']
	speaker = event['speaker']
	text = event['title']
	ugfx.set_default_font(ugfx.FONT_MEDIUM)	
	ugfx.area(0,0,ugfx.width(),ugfx.height(),0x0000)
	ugfx.text(10,10,stage,ugfx.GREY)
	ugfx.text(10,35,"Start: "+start,ugfx.GREEN)
	ugfx.text(10,60,"End: "+end,ugfx.RED)
	ugfx.text(10,85,"Speaker: "+speaker,ugfx.BLUE)
	linelen = 25
	lines = int(math.ceil(len(text)/linelen))
	for l in range(0, lines):
		pixels = l*25+110
		start = l*linelen
		end = l*linelen+linelen
		if end>len(text):
			end = len(text)
		linetext = text[start:end]
		ugfx.text(10,pixels,linetext,0xFFFF)
	return
Esempio n. 41
0
				sha256.update(buf)
				buf = file.read(128)
			return str(binascii.hexlify(sha256.digest()), "utf8")
	except:
		return "ERR"

def download(url, target, expected_hash):
	while True:
		get(url).raise_for_status().download_to(target)
		if calculate_hash(target) == expected_hash:
			break

ugfx.init()
ugfx.clear(ugfx.WHITE)
ugfx.text(5, 5, "Downloading TiLDA software", ugfx.BLACK)
label = ugfx.Label(5, 30, ugfx.width() - 10, ugfx.height() - 60, "Please wait")
ugfx.Label(5, ugfx.height() - 30, ugfx.width() - 10, 30, "If nothing happens for 2 minutes please press the reset button on the back")

w = {}
try:
	if "wifi.json" in os.listdir():
		with open("wifi.json") as f:
			w = json.loads(f.read())
except ValueError as e:
	print(e)

if type(w) is dict:
	# convert original format json (dict, one network) to new (list, many networks)
	w = [w]

wifi_info = "\nMore information:\nbadge.emfcamp.org/TiLDA_MK3/wifi"
Esempio n. 42
0
def mainscreen():
	ugfx.area(0,0,ugfx.width(),ugfx.height(),0x0000)
	ugfx.set_default_font(ugfx.FONT_MEDIUM_BOLD)	
	ugfx.text(30,30,"EMF Schedule Now & Next ",ugfx.GREY)
	ugfx.text(40,75,"Press [A] to get events ",ugfx.BLUE)
	return
Esempio n. 43
0
            break

        pyb.delay(100)
    return score
    
playing = 1
while playing:
    score = one_round()
    new_high_score = False
    with Database() as db:
        high_score = db.get("improved_snake-high-score", 0)
        if score > high_score:
            db.set("improved_snake-high-score", score)
            new_high_score = True

    ugfx.area(0,0,ugfx.width(),ugfx.height(),0)
    ugfx.text(30, 30, "GAME OVER Score: %d" % (score), 0xFFFF)
    if new_high_score:
        ugfx.text(30, 60, "NEW HIGH SCORE!", 0xFFFF)
    else:
        ugfx.text(30, 60, "High score: %d" % (high_score), 0xFFFF)  
    ugfx.text(30, 90, "Press A to play again", 0xFFFF)
    ugfx.text(30, 120, "Press MENU to quit" , 0xFFFF)
    while True:
        pyb.wfi()
        if buttons.is_triggered("BTN_A"):
            break

        if buttons.is_triggered("BTN_MENU"):
            playing = 0 #pyb.hard_reset()
            break
Esempio n. 44
0
import ugfx
import pyb


keepgoing = 1
tgl_menu = pyb.Pin("BTN_MENU", pyb.Pin.IN)
tgl_menu.init(pyb.Pin.IN, pyb.Pin.PULL_UP)
ugfx.enable_tear()
tear = pyb.Pin("TEAR", pyb.Pin.IN)
wi = ugfx.width()
hi = ugfx.height()
while(keepgoing):
	
	while(tear.value() == 0):
		2+2 
	while(tear.value()):
		2+2 
	ugfx.area(0,0,wi,hi,ugfx.RED)
	pyb.delay(60)
	
	while(tear.value() == 0):
		2+2 
	while(tear.value()):
		2+2 
	ugfx.area(0,0,wi,hi,ugfx.GREEN)
	pyb.delay(60)
	
	while(tear.value() == 0):
		2+2 
	while(tear.value()):
		2+2 
Esempio n. 45
0
import usocket, ujson
from imu import IMU

def cls():
    ugfx.area(0, 0, 320, 240, ugfx.BLACK)
    c.hide()
    c.show()

print("Stats app starting")

# Initialise graphics

print("Init uGFX")

ugfx.init()
ugfx.area(0, 0, ugfx.width(), ugfx.height(), ugfx.BLACK)
ugfx.set_default_font(ugfx.FONT_TITLE)

# Set up all the styles

print("Init Styles")

sty = ugfx.Style()
sty.set_enabled([ugfx.PURPLE, ugfx.BLACK, ugfx.GREEN, ugfx.GREY])
sty.background(ugfx.BLACK)

styUse = ugfx.Style()
styUse.set_enabled([ugfx.PURPLE, ugfx.BLACK, ugfx.GREEN, ugfx.GREY])
styUse.background(ugfx.BLACK)

styLbl = ugfx.Style()
Esempio n. 46
0
def file_loader():
	width = ugfx.width()
	height = ugfx.height()
	buttons.disable_menu_reset()

	# Create visual elements
	win_header = ugfx.Container(0,0,width,30)
	win_files = ugfx.Container(0,33,int(width/2),height-33)
	win_preview = ugfx.Container(int(width/2)+2,33,int(width/2)-2,height-33)
	components = [win_header, win_files, win_preview]
	ugfx.set_default_font(ugfx.FONT_TITLE)
	components.append(ugfx.Label(3,3,width-10,29,"Choose App",parent=win_header))
	ugfx.set_default_font(ugfx.FONT_MEDIUM)
	options = ugfx.List(0,30,win_files.width(),win_files.height()-30,parent=win_files)
	btnl = ugfx.Button(5,3,20,20,"<",parent=win_files)
	btnr = ugfx.Button(win_files.width()-7-20,3,20,20,">",parent=win_files)
	btnr.attach_input(ugfx.JOY_RIGHT,0)
	btnl.attach_input(ugfx.JOY_LEFT,0)
	components.append(options)
	components.append(btnr)
	components.append(btnl)
	ugfx.set_default_font(ugfx.FONT_MEDIUM_BOLD)
	l_cat = ugfx.Label(30,3,100,20,"Built-in",parent=win_files)
	components.append(l_cat)
	components.append(ugfx.Button(10,win_preview.height()-25,20,20,"A",parent=win_preview))
	components.append(ugfx.Label(35,win_preview.height()-25,50,20,"Run",parent=win_preview))
	components.append(ugfx.Button(80,win_preview.height()-25,20,20,"B",parent=win_preview))
	components.append(ugfx.Label(105,win_preview.height()-25,100,20,"Back",parent=win_preview))
	components.append(ugfx.Button(10,win_preview.height()-50,20,20,"M",parent=win_preview))
	components.append(ugfx.Label(35,win_preview.height()-50,100,20,"Pin/Unpin",parent=win_preview))
	ugfx.set_default_font(ugfx.FONT_SMALL)
	author = ugfx.Label(1,win_preview.height()-78,win_preview.width()-3,20,"by: ",parent=win_preview)
	desc = ugfx.Label(3,1,win_preview.width()-10,win_preview.height()-83,"",parent=win_preview,justification=ugfx.Label.LEFTTOP)
	components.append(author)
	components.append(desc)

	app_to_load = None

	pinned = database_get("pinned_apps", [])
	catergories = get_local_app_categories()
	c_ptr = 0

	try:
		win_header.show()
		win_files.show()
		win_preview.show()

		pinned = database_get("pinned_apps", [])
	#	apps = []
		apps_path = []

		if is_dir("apps"):
			for app in os.listdir("apps"):
				path = "apps/" + app
				if is_dir(path) and is_file(path + "/main.py"):
					apps_path.append(path + "/main.py")
		if is_dir("examples"):
			for app in os.listdir("examples"):
				path = "examples/" + app
				if is_file(path) and path.endswith(".py"):
					apps_path.append(path)

		displayed_apps = update_options(options, catergories[c_ptr], pinned)

		index_prev = -1;

		while True:
			pyb.wfi()
			ugfx.poll()

			if index_prev != options.selected_index():
				if options.selected_index() < len(displayed_apps):
					author.text("by: %s" % displayed_apps[options.selected_index()].user)
					desc.text(displayed_apps[options.selected_index()].description)
				index_prev = options.selected_index()

			if buttons.is_triggered("JOY_LEFT"):
				if c_ptr > 0:
					c_ptr -= 1
					btnl.set_focus()
					l_cat.text(catergories[c_ptr])
					displayed_apps = update_options(options, catergories[c_ptr], pinned)
					index_prev = -1

			if buttons.is_triggered("JOY_RIGHT"):
				if c_ptr < len(catergories)-1:
					c_ptr += 1
					btnr.set_focus()
					l_cat.text(catergories[c_ptr])
					displayed_apps = update_options(options, catergories[c_ptr], pinned)
					index_prev = -1

			if buttons.is_triggered("BTN_MENU"):
				app = displayed_apps[options.selected_index()]
				if app.folder_name in pinned:
					pinned.remove(app.folder_name)
				else:
					pinned.append(app.folder_name)
				update_options(options, catergories[c_ptr], pinned)
				database_set("pinned_apps", pinned)

			if buttons.is_triggered("BTN_B"):
				return None

			if buttons.is_triggered("BTN_A"):
				return displayed_apps[options.selected_index()]

	finally:
		for component in components:
			component.destroy()
Esempio n. 47
0
		gc.collect()
		pyb.info()
		print("Loading: %s" % app_to_load)
		mod = __import__(app_to_load.main_path[:-3])
		if "main" in dir(mod):
			mod.main()
	except Exception as e:
		s = uio.StringIO()
		sys.print_exception(e, s)
		u=pyb.USB_VCP()
		if u.isconnected():
			raise(e)
		else:
			ugfx.clear()
			ugfx.set_default_font(ugfx.FONT_SMALL)
			w=ugfx.Container(0,0,ugfx.width(),ugfx.height())
			l=ugfx.Label(0,0,ugfx.width(),ugfx.height(),s.getvalue(),parent=w)
			w.show()
			while True:
				pyb.wfi()
				if (buttons.is_triggered("BTN_B")) or (buttons.is_triggered("BTN_B")) or (buttons.is_triggered("BTN_MENU")):
					break;
			#str=s.getvalue().split("\n")
			#if len(str)>=4:
			#out = "\n".join(str[4:])
			#dialogs.notice(out, width=wi-10, height=hi-10)
	onboard.semihard_reset()

	#deinit ugfx here
	#could hard reset here too
Esempio n. 48
0
def display_name():
	ugfx.area(0,0,ugfx.width(),ugfx.height(),0xFFFF)
	ugfx.set_default_font("D*")
	ugfx.text(40,120,"MATT",ugfx.YELLOW)
	ugfx.circle(160,200,40,ugfx.GREEN)
Esempio n. 49
0
import pyb
import ugfx
import buttons

ugfx.init()
buttons.init()

BALLCOLOR1 =    ugfx.RED
BALLCOLOR2 =    ugfx.YELLOW
WALLCOLOR =     ugfx.GREEN
BACKCOLOR =     ugfx.BLUE
FLOORCOLOR =    ugfx.PURPLE
SHADOWALPHA =   (255-255*0.2)

width = ugfx.width()
height = ugfx.height()

radius=height/5+height%2+1 # The ball radius
ii = 1.0/radius            # radius as easy math
floor=height/5-1           # floor position
spin=0.0                   # current spin angle on the ball
spinspeed=0.1              # current spin speed of the ball
ballx=width/2              # ball x position (relative to the ball center)
bally=height/4             # ball y position (relative to the ball center)
dx=.01*width               # motion in the x axis
dy=0.0                     # motion in the y axis
ballcx = 12*radius/5       # ball x diameter including the shadow
ballcy = 21*radius/10      # ball y diameter including the shadow

# The clipping window for this frame.
Esempio n. 50
0
### Author: Lars Weiler
### Description: progress bar
### Category: fun
### License: THE NERD-WARE LICENSE (Revision 2)
### Appname: progressbar

import pyb
import ugfx

ugfx.init()
h = ugfx.height()
w = ugfx.width()

ugfx.clear(ugfx.BLACK)

lw = 240    # progress bar width
lh = 40     # progress bar height
m = 5       # margin
s = 1       # step

ugfx.box((w//2)-(lw//2), (h//2)-(lh//2), lw, lh, ugfx.WHITE)
for i in range(m, lw-2*m, s):
    # use the 30bit random number, bitshift by 24 bits, which will give 0-65
    # and use this number for the delay in milliseconds
    pyb.delay(pyb.rng()>>24)
    ugfx.area((w//2)-(lw//2-m), (h//2)-(lh//2-m), i, (lh-2*m), ugfx.WHITE)
# wait 500ms and blank the screen
pyb.delay(500)
ugfx.clear(ugfx.BLACK)

Esempio n. 51
0
import pyb
import math
import ugfx

# Example of how a simple animation can be done
# ToDo: This is quite flickery. It would work a lot better with
#       Pixmaps, but I couldn't get them to work :(

ugfx.init()
ugfx.enable_tear()
tear = pyb.Pin("TEAR", pyb.Pin.IN)
ugfx.set_tear_line((int(320/2)+0))
ugfx.area(0,0,ugfx.width(), ugfx.height(), 0)
sec = 0;

def draw_hand(cx, cy, angle, length, thickness, color):
    x = int(math.cos(angle) * length + cx);
    y = int(math.sin(angle) * length + cy);
    ugfx.thickline(cx, cy, x, y, color, thickness, 1)

while True:
    

    # Center
    cx = int(ugfx.width() / 2);
    cy = int(ugfx.height() / 2);


    # Hand: hours
    angel_hour = math.pi * 2 * sec / 60 / 60 / 12 - math.pi / 2    
Esempio n. 52
0
def quick_launch_screen():
	wi = ugfx.width()
	hi = ugfx.height()

	win_header = ugfx.Container(0,0,wi,30)
	win_quick = ugfx.Container(0,33,wi,hi-33-33)
	win_help = ugfx.Container(0,hi-30,wi,30)

	DEFAULT_APPS = ["app_library", "sponsors", "changename"]
	with Database() as db:
		pinned = [App(a) for a in db.get("pinned_apps", DEFAULT_APPS)]
		pinned = [app for app in pinned if app.loadable] # Filter out deleted apps
		pinned = pinned[:7] # Limit to 7
		db.set("pinned_apps", [app.folder_name for app in pinned])

	ugfx.set_default_font(ugfx.FONT_TITLE)
	title = ugfx.Label(3,3,wi-10,45,"EMF Camp 2016",parent=win_header)

	ugfx.set_default_font(ugfx.FONT_MEDIUM_BOLD)

	pinned_buttons = []
	for i in range(0, 8):
		x = i % 2
		y = i // 2
		button_title = "View all" if i == 7 else ""
		if i < len(pinned):
			button_title = pinned[i].title
		pinned_buttons.append(ugfx.Button(35 + 155 * x, 5 + 40 * y, 120, 35, button_title, parent=win_quick))

	btn_ok = ugfx.Button(10,5,20,20,"A",parent=win_help,shape=ugfx.Button.ELLIPSE)
	l_ok = ugfx.Label(40,5,100,20,"Run",parent=win_help)

	btn_back = ugfx.Button(100,5,20,20,"B",parent=win_help,shape=ugfx.Button.ELLIPSE)
	l_back = ugfx.Label(130,5,100,20,"Back",parent=win_help)

	btn_menu = ugfx.Button(200,5,20,20,"M",parent=win_help,shape=ugfx.Button.ROUNDED)
	l_back = ugfx.Label(230,5,100,20,"Menu",parent=win_help)

	sty = dialogs.default_style_badge

	win_header.show()
	win_quick.show()
	win_help.show()

	buttons.init()
	cursor = {"x": 0, "y": 0}
	last_cursor = cursor.copy()
	_draw_cursor(0, 0, ugfx.RED, win_quick)

	app_to_load = "sponsors"

	if not database_get("quicklaunch_firstrun"):
		dialogs.notice("""This screen displays the most commonly used apps.
Apps pinned here can also interact with the name screen.
To view all apps, pin and un-pin, select 'View All'
		""", title="TiLDA - Quick Launch", close_text="Close")
		database_set("quicklaunch_firstrun", True)

	try:
		while True:
			pyb.wfi()

			if buttons.is_triggered("JOY_UP"):
				cursor["y"] = max(0, cursor["y"] - 1)
			if buttons.is_triggered("JOY_DOWN"):
				cursor["y"] = min(3, cursor["y"] + 1)
			if buttons.is_triggered("JOY_RIGHT"):
				cursor["x"] = 1
			if buttons.is_triggered("JOY_LEFT"):
				cursor["x"] = 0

			if cursor["x"] != last_cursor["x"] or cursor["y"] != last_cursor["y"]: # Has the cursor moved?
				_draw_cursor(last_cursor["x"], last_cursor["y"], dialogs.default_style_badge.background(), win_quick)
				_draw_cursor(cursor["x"], cursor["y"], ugfx.RED, win_quick)
				last_cursor = cursor.copy()

			if buttons.is_triggered("BTN_B"):
				return None

			#if buttons.is_triggered("BTN_MENU"):
			#	open unpin dialog
			#	break;

			if buttons.is_triggered("BTN_A"):
				index = cursor["x"] + cursor["y"] * 2
				if index == 7:
					return "file_loader"
				if index < len(pinned):
					return pinned[index]
	finally:
		buttons.disable_all_interrupt()

		win_header.hide()
		win_quick.hide()
		win_help.hide()
		for b in pinned_buttons:
			b.destroy()
		btn_ok.destroy()
		l_ok.destroy()
		btn_back.destroy()
		l_back.destroy()
		btn_menu.destroy()
		l_back.destroy()
		win_header.destroy()
		win_quick.destroy()
		win_help.destroy()
		title.destroy()
Esempio n. 53
0
def one_round():
    grid_size = 8;
    body_colour = ugfx.RED
    back_colour = 0;
    food_colour = ugfx.YELLOW
    wall_colour = ugfx.BLUE
    score = 0;
    edge_x = math.floor(ugfx.width()/grid_size)-2;
    edge_y = math.floor(ugfx.height()/grid_size)-2;

    def disp_square(x,y,colour):
        ugfx.area((x+1)*grid_size, (y+1)*grid_size, grid_size, grid_size, colour)

    def disp_body_straight(x,y,rotation,colour):
        if (rotation == 0):
            ugfx.area((x+1)*grid_size+1, (y+1)*grid_size+1, grid_size-2, grid_size, colour)
        elif (rotation == 90):
            ugfx.area((x+1)*grid_size+1, (y+1)*grid_size+1, grid_size, grid_size-2, colour)
        elif (rotation == 180):
            ugfx.area((x+1)*grid_size+1, (y+1)*grid_size-1, grid_size-2, grid_size, colour)
        else:
            ugfx.area((x+1)*grid_size-1, (y+1)*grid_size+1, grid_size, grid_size-2, colour)

    def disp_eaten_food(x,y,colour):
        ugfx.area((x+1)*grid_size, (y+1)*grid_size, grid_size, grid_size, colour)

    def randn_square():
        return  [pyb.rng()%edge_x, pyb.rng()%edge_y]

    body_x = [12,13,14,15,16]
    body_y = [2,2,2,2,2]

    ugfx.area(0,0,ugfx.width(),ugfx.height(),0)

    ugfx.area(0,0,grid_size*(edge_x+1),grid_size,wall_colour)
    ugfx.area(0,0,grid_size,grid_size*(edge_y+1),wall_colour)
    ugfx.area(grid_size*(edge_x+1),0,grid_size,grid_size*(edge_y+1),wall_colour)
    ugfx.area(0,grid_size*(edge_y+1),grid_size*(edge_x+2),grid_size,wall_colour)

    keepgoing = 1;

    food = [20,20]

    dir_x = 1
    dir_y = 0
    orient = 270

    #for i in range(0,len(body_x)):
    #   disp_body_straight(body_x[i],body_y[i],orient,body_colour)

    while keepgoing:
        disp_square(food[0],food[1],food_colour)
        if buttons.is_pressed("JOY_RIGHT"):
            if orient != 90:
                dir_x = 1;
                dir_y = 0;
                orient = 270
        elif buttons.is_pressed("JOY_LEFT"):
            if orient != 270:
                dir_x = -1;
                dir_y = 0;
                orient = 90
        elif buttons.is_pressed("JOY_DOWN"):
            if orient != 0:
                dir_y = 1;
                dir_x = 0;
                orient = 180
        elif buttons.is_pressed("JOY_UP"):
            if orient != 180:
                dir_y = -1;
                dir_x = 0;
                orient = 0

        body_x.append(body_x[-1]+dir_x)
        body_y.append(body_y[-1]+dir_y)

        for i in range(0,len(body_x)-1):
            if (body_x[i] == body_x[-1]) and (body_y[i] == body_y[-1]):
                keepgoing = 0

        if not((body_x[-1] == food[0]) and (body_y[-1] == food[1])):
            x_del = body_x.pop(0)
            y_del = body_y.pop(0)
            disp_eaten_food(x_del,y_del,back_colour)
        else:
            disp_eaten_food(food[0],food[1],body_colour)
            food = randn_square()
            disp_square(food[0],food[1],food_colour)
            score = score + 1

        disp_body_straight(body_x[-1],body_y[-1],orient,body_colour)


        if ((body_x[-1] >= edge_x) or (body_x[-1] < 0) or (body_y[-1] >= edge_y) or (body_y[-1] < 0)):
            break

        pyb.delay(100)
    return score
Esempio n. 54
0
 def render(self):
     global game_state
     print('render '+game_state)
     ugfx.clear()
     if game_state == 'SEARCH':
         ugfx.set_default_font(ugfx.FONT_MEDIUM_BOLD)
         ugfx.Label(5, 5, ugfx.width(), 20, "Scanning for hackers!...")
         ugfx.set_default_font(ugfx.FONT_NAME)
         ugfx.Label(5, 30, ugfx.width(), 40, self.current_battle.status())
         ugfx.set_default_font(ugfx.FONT_MEDIUM_BOLD)
         ugfx.Label(5, 100, ugfx.width(), 20, "Press (A) to battle, (B) to try to escape")
     elif game_state == 'BATTLE':
         ugfx.set_default_font(ugfx.FONT_NAME)
         ugfx.Label(5, 30, ugfx.width(), 40, self.current_battle.status())
         ugfx.set_default_font(ugfx.FONT_MEDIUM_BOLD)
         ugfx.Label(5, 100, ugfx.width(), 20, "Press (A) to continue, (B) to try to escape")
     elif game_state == 'ATTACK':
         ugfx.set_default_font(ugfx.FONT_NAME)
         ugfx.Label(5, 30, ugfx.width(), 40, self.current_battle.status())
         ugfx.set_default_font(ugfx.FONT_MEDIUM_BOLD)
         ugfx.Label(5, 100, ugfx.width(), 20, "Press (A) to continue, (B) to try to escape")
     elif game_state == 'ESCAPE':
         ugfx.set_default_font(ugfx.FONT_NAME)
         ugfx.Label(5, 30, ugfx.width(), 40, self.current_battle.status())
         ugfx.set_default_font(ugfx.FONT_MEDIUM_BOLD)
         ugfx.Label(5, 100, ugfx.width(), 20, "Press (A) to continue, (B) to try to escape")
     elif game_state == 'WIN':
         ugfx.set_default_font(ugfx.FONT_NAME)
         ugfx.Label(5, 30, ugfx.width(), 40, self.current_battle.status())
         ugfx.set_default_font(ugfx.FONT_MEDIUM_BOLD)
         ugfx.Label(5, 100, ugfx.width(), 20, "Press (A) to continue, (B) to try to escape")
     elif game_state == 'LOSE':
         ugfx.set_default_font(ugfx.FONT_NAME)
         ugfx.Label(5, 30, ugfx.width(), 40, self.current_battle.status())
         ugfx.set_default_font(ugfx.FONT_MEDIUM_BOLD)
         ugfx.Label(5, 100, ugfx.width(), 20, "Press (A) to continue, (B) to try to escape")
     elif game_state == 'INACTIVE':
         ugfx.set_default_font(ugfx.FONT_MEDIUM_BOLD)
         ugfx.Label(5, 5, ugfx.width(), 25, "Hello agent,")
         ugfx.Label(5, 25, ugfx.width(), 25, "Captures: %i" % self.gumshoe.captures)
         ugfx.Label(5, 50, ugfx.width(), 25, "XP: %i" % self.gumshoe.xp)
         ugfx.Label(5, 75, ugfx.width(), 25, "Instructions:")
         ugfx.Label(5, 100, ugfx.width(), 25, "(1) Explore the EMF site")
         ugfx.Label(5, 125, ugfx.width(), 50, "(2) When in position, press A to start a search for nearby hackers...")
         ugfx.Label(5, 175, ugfx.width(), 50, "Beware of confronting more experienced hackers!")
def mainscreen():
	ugfx.area(0,0,ugfx.width(),ugfx.height(),0x0000)
	ugfx.set_default_font(ugfx.FONT_MEDIUM_BOLD)	
	ugfx.text(30,30,"Whats My IP",ugfx.YELLOW)
	ugfx.text(40,75,"Press [A] to continue",ugfx.YELLOW)
	return
Esempio n. 56
0
### Author: EMF Badge team
### Description: Test app for the hook into the home screen
### Category: Example
### License: MIT
### Appname : Home Callback Test

import ugfx, buttons, pyb

ugfx.init()
buttons.init()
ugfx.clear()

ugfx.Label(5, 5, ugfx.width(), ugfx.height(), "Nothing to see here")

while True:
	pyb.wfi()