Exemplo n.º 1
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()
Exemplo n.º 2
0
def drawui():
    ugfx.init()
    buttons.init()
    ugfx.clear(ugfx.html_color(0x87F717))

    ugfx.set_default_font(ugfx.FONT_MEDIUM)

    ugfx.fill_circle(50,50, 20, ugfx.WHITE)
    ugfx.fill_circle(50, 100, 20, ugfx.WHITE)

    ugfx.text(45, 45, "A", ugfx.RED)
    ugfx.text(45, 95, "B", ugfx.RED)

    ugfx.text(95, 45, "Flash the lights", ugfx.WHITE)
    ugfx.text(95, 95, "Disco Inferno", ugfx.WHITE)

    ugfx.fill_polygon(270,50, [ [0,0], [40,0], [40, 175], [0, 175] ], ugfx.RED)#  , [230, 100], [230, 60]
    ugfx.fill_polygon(270,50, [ [0,0], [-20,10], [-20, 50], [0, 40] ], ugfx.RED)#  , [230, 100], [230, 60]

    ugfx.area(283, 61, 14, 10, ugfx.WHITE)
    ugfx.area(283, 79, 14, 10, ugfx.WHITE)
    ugfx.area(283, 97, 14, 10, ugfx.WHITE)
    ugfx.area(283, 115, 14, 10, ugfx.WHITE)
    ugfx.area(283, 133, 14, 10, ugfx.WHITE)
    ugfx.area(283, 151, 14, 10, ugfx.WHITE)
    ugfx.area(283, 169, 14, 10, ugfx.WHITE)
    ugfx.area(283, 187, 14, 10, ugfx.WHITE)
Exemplo n.º 3
0
def wait_for_exit():
	global chk_upload
	buttons.init()
	while True:
		pyb.wfi()
		if buttons.is_triggered("BTN_B"):
			break;

	database_set("stats_upload", chk_upload.checked())
Exemplo n.º 4
0
def wait_for_exit():
    global chk_upload
    buttons.init()
    while True:
        pyb.wfi()
        if buttons.is_triggered("BTN_B"):
            break

    database_set("stats_upload", chk_upload.checked())
Exemplo n.º 5
0
 def __init__(self):
     ugfx.init()
     if ugfx.backlight() == 0:
         ugfx.power_mode(ugfx.POWER_ON)
     ugfx.backlight(70)
     self.rm = chuckie.render.RenderManager()
     self.raster = raster.RasterTile()
     self._tick = time.ticks_ms()
     self._delta = 0
     buttons.init()
Exemplo n.º 6
0
def parse_buttons(cmd):
    if cmd[1] == "init":
        buttons.init()
    elif cmd[1] == "loop":
        set_loop_cb("buttons", buttons.loop, int(cmd[2]))
    elif cmd[1] == "cb":
        buttons.register_on_state_change_callback(lambda name, state: print(
            "[CLI]: buttons %s -> %s" % (name, state)))
    else:
        print("[CLI]: \"%s\" not implemented" % (" ".join(cmd)))
def init():
    print("[RUNNER]: init")
    buttons.init()
    buttons.action()
    leds.init()
    phy_interface.init()
    sensors.init()
    power_counter.init()
    mqtt.init()
    cli.init()
    things.init()
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()
Exemplo n.º 9
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()
Exemplo n.º 10
0
def init():
    global logger

    my_filter = NoRunningFilter()
    logging.getLogger("apscheduler.scheduler").addFilter(my_filter)
    logging.getLogger("apscheduler.executors.default").addFilter(my_filter)

    logging.basicConfig(
        filename='/home/pi/share/pr/hahoau/headless/logging.log',
        level=logging.INFO,
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    logger = logging.getLogger(__name__)
    logger.info('Start')
    buttons.init()
    sunscreens.init()
Exemplo n.º 11
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
Exemplo n.º 12
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
Exemplo n.º 13
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
Exemplo n.º 14
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()
Exemplo n.º 15
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()
Exemplo n.º 16
0
def init():
    RPi.GPIO.cleanup()
    buttons.init()
    lcd.init()

    lcd_refresh()

    buttons.set_up_btn_callback(next_button)
    buttons.set_down_btn_callback(prev_button)
    buttons.set_enter_btn_callback(call_button)

    linphone.init('/home/mateusz/.linphonerc')

    def linphone_atexit():
        linphone.unregister()
        linphone.exit()

    atexit.register(linphone_atexit)
Exemplo n.º 17
0
def setup():
    print ("starting Poolpi...")

    log.init()

    log.log(log.ALWAYS, "***********************************")
    log.log(log.ALWAYS, "Starting PoolPi " + VERSION + "  " + DATE)
    log.log(log.ALWAYS, "***********************************")
    cfg.VERSION = VERSION

    # init pijuice to monitor power status
    if (power.init() == ERROR):
        gv.piJuicePresent = False;

    # init equipment control
    if (equipment.init() == ERROR):
        return ERROR

    # init serial and lcd
    if (lcd.init() == ERROR):
        return ERROR

    lcd.setCursor(1,1)
    lcd.printLineCenter(VERSION)
    lcd.setCursor(2,1)
    lcd.printLineCenter(DATE)

    # init buttons
    buttons.init()

    # init event timer
    timer.init()

    # init redis
    redispy.init()

    # start temp sensor thread
    ow.init()
    if (ow.start() == ERROR):
        return ERROR

    log.log(log.ALWAYS, "setup() complete")
    return NOERROR
Exemplo n.º 18
0
def main():
    print("emf_hub_mon: Starting emf_hub_mon")

    # Init GFX and Buttons
    ugfx.init()
    buttons.init()

    # Config
    config = database.Database(filename='apps/emf_hub_mon/emf_hub_mon.json')

    # Status bar service
    status_service = status_bar(config)

    # LED service
    led_service = led(config)

    # Display service
    mon_service = mon_display(config, status_service, led_service)

    # Display welcome screen on first boot
    if config.get('first_boot'):
        mon_service.welcome()

    # MQTT service
    mqtt_service = mqtt_handler(config, mon_service)

    # Initialise the monitor display
    mon_service.init()

    while True:
        # Handle MQTT operations
        mqtt_service.handle()

        # Handle Display operations
        mon_service.update()

        # Give the CPU a break
        pyb.delay(200)

    # clean up some stuff, not sure if this is required but w/e
    ugfx.clear()
    led_service.off()
def run_app(path):
	import buttons
	import ugfx
	import sys

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

	if not buttons.has_interrupt("BTN_MENU"):
		buttons.enable_menu_reset()

	try:
		# Make libraries shipped by the app importable
		app_path = '/flash/' + '/'.join(path.split('/')[:-1])
		sys.path.append(app_path)

		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()
Exemplo n.º 20
0
def home_main():
	global orientation, next_tick, tick

	ugfx.area(0,0,320,240,sty_tb.background())

	ugfx.set_default_font(ugfx.FONT_MEDIUM)
	win_bv = ugfx.Container(0,0,80,25, style=sty_tb)
	win_wifi = ugfx.Container(82,0,60,25, style=sty_tb)
	win_name = ugfx.Container(0,25,320,240-25-60, style=dialogs.default_style_badge)
	win_text = ugfx.Container(0,240-60,320,60, style=sty_tb)

	windows = [win_bv, win_wifi, win_text]

	obj_name = apps.home.draw_name.draw(0,25,win_name)

	buttons.init()

	gc.collect()
	ugfx.set_default_font(ugfx.FONT_MEDIUM_BOLD)
	hook_feeback = ugfx.List(0, 0, win_text.width(), win_text.height(), parent=win_text)

	win_bv.show()
	win_text.show()
	win_wifi.show()

	min_ctr = 28

	# Create external hooks so other apps can run code in the context of
	# the home screen.
	# To do so an app needs to have an external.py with a tick() function.
	# The tick period will default to 60 sec, unless you define something
	# else via a "period" variable in the module context (use milliseconds)
	# If you set a variable "needs_wifi" in the module context tick() will
	# only be called if wifi is available
	# If you set a variable "needs_icon" in the module context tick() will
	# be called with a reference to a 25x25 pixel ugfx container that you
	# can modify
	external_hooks = []
	icon_x = 150
	for path in get_external_hook_paths():
		try:
			module = __import__(path)
			if not hasattr(module, "tick"):
				raise Exception("%s must have a tick function" % path)

			hook = {
				"name": path[5:-9],
				"tick": module.tick,
				"needs_wifi": hasattr(module, "needs_wifi"),
				"period": module.period if hasattr(module, "period") else 60 * 1000,
				"next_tick_at": 0
			}

			if hasattr(module, "needs_icon"):
				hook["icon"] = ugfx.Container(icon_x, 0, 25, 25)
				icon_x += 27

			external_hooks.append(hook)
		except Exception as e: # Since we dont know what exception we're looking for, we cant do much
			print ("%s while parsing background task %s.  This task will not run! " % (type(e).__name__, path[5:-9]))
			sys.print_exception(e)
			continue # If the module fails to load or dies during the setup, skip it

	backlight_adjust()

	inactivity = 0
	last_rssi = 0

	## start connecting to wifi in the background
	wifi_timeout = 30 #seconds
	wifi_reconnect_timeout = 0
	try:
		wifi.connect(wait = False)
	except OSError:
		print("Creating default wifi settings file")
		wifi.create_default_config()

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

		if (next_tick <= pyb.millis()):
			tick = True
			next_tick = pyb.millis() + 1000

		#if wifi still needs poking
		if (wifi_timeout > 0):
			if wifi.nic().is_connected():
				wifi_timeout = -1
				#wifi is connected, but if becomes disconnected, reconnect after 5 sec
				wifi_reconnect_timeout = 5
			else:
				wifi.nic().update()


		if tick:
			tick = False

			ledg.on()

			if (wifi_timeout > 0):
				wifi_timeout -= 1;

			# change screen orientation
			ival = imu.get_acceleration()
			if ival['y'] < -0.5:
				if orientation != 0:
					ugfx.orientation(0)
			elif ival['y'] > 0.5:
				if orientation != 180:
					ugfx.orientation(180)
			if orientation != ugfx.orientation():
				inactivity = 0
				ugfx.area(0,0,320,240,sty_tb.background())
				orientation = ugfx.orientation()
				for w in windows:
					w.hide(); w.show()
				apps.home.draw_name.draw(0,25,win_name)


			#if wifi timeout has occured and wifi isnt connected in time
			if (wifi_timeout == 0) and not (wifi.nic().is_connected()):
				print("Giving up on Wifi connect")
				wifi_timeout = -1
				wifi.nic().disconnect()  #give up
				wifi_reconnect_timeout = 30 #try again in 30sec

			wifi_connect = wifi.nic().is_connected()

			#if not connected, see if we should try again
			if not wifi_connect:
				if wifi_reconnect_timeout>0:
					wifi_reconnect_timeout -= 1
					if wifi_reconnect_timeout == 0:
						wifi_timeout = 60 #seconds
						wifi.connect(wait = False)

			ledg.on()

			# display the wifi logo
			rssi = wifi.nic().get_rssi()
			if rssi == 0:
				rssi = last_rssi
			else:
				last_rssi = rssi


			draw_wifi(sty_tb.background(),rssi, wifi_connect,wifi_timeout>0,win_wifi)

			battery_percent = onboard.get_battery_percentage()
			draw_battery(sty_tb.background(),battery_percent,win_bv)

			inactivity += 1

			# turn off after some period
			# takes longer to turn off in the 'used' position
			if ugfx.orientation() == 180:
				inactivity_limit = 120
			else:
				inactivity_limit = 30
			if battery_percent > 120:  #if charger plugged in
				if ugfx.backlight() == 0:
					ugfx.power_mode(ugfx.POWER_ON)
				ugfx.backlight(100)
			elif inactivity > inactivity_limit:
				low_power()
			else:
				backlight_adjust()

			ledg.off()

		for hook in external_hooks:
			try:
				if hook["needs_wifi"] and not wifi.nic().is_connected():
					continue;

				if hook["next_tick_at"] < pyb.millis():
					text = None
					if "icon" in hook:
						text = hook["tick"](hook["icon"])
					else:
						text = hook["tick"]()
					hook["next_tick_at"] = pyb.millis() + hook["period"]
					if text:
						if hook_feeback.count() > 10:
							hook_feeback.remove_item(0)
						hook_feeback.add_item(text)
						if hook_feeback.selected_index() >= (hook_feeback.count()-2):
							hook_feeback.selected_index(hook_feeback.count()-1)
			except Exception as e:  # if anything in the hook fails to work, we need to skip it
				print ("%s in %s background task. Not running again until next reboot! " % (type(e).__name__, hook['name']))
				sys.print_exception(e)
				external_hooks.remove(hook)
				continue

		if buttons.is_pressed("BTN_MENU"):
			pyb.delay(20)
			break
		if buttons.is_pressed("BTN_A"):
			inactivity = 0
			tick = True
		if buttons.is_pressed("BTN_B"):
			inactivity = 0
			tick = True


	for hook in external_hooks:
		if "icon" in hook:
			hook["icon"].destroy()
	for w in windows:
		w.destroy()
	apps.home.draw_name.draw_destroy(obj_name)
	win_name.destroy()
	hook_feeback.destroy()
	if ugfx.backlight() == 0:
		ugfx.power_mode(ugfx.POWER_ON)
	ugfx.backlight(100)
	ugfx.orientation(180)

	#if we havnt connected yet then give up since the periodic function wont be poked
	if wifi_timeout >= 0: # not (wifi.nic().is_connected()):
		wifi.nic().disconnect()
Exemplo n.º 21
0
	ugfx.power_mode(ugfx.POWER_OFF)


ugfx.init()
imu=IMU()
neo = pyb.Neopix(pyb.Pin("PB13"))
neo.display(0x04040404)
ledg = pyb.LED(2)
ival = imu.get_acceleration()
if ival['y'] < 0:
	ugfx.orientation(0)
else:
	ugfx.orientation(180)


buttons.init()
if not onboard.is_splash_hidden():
	splashes = ["splash1.bmp"]
	for s in splashes:
		ugfx.display_image(0,0,s)
		delay = 2000
		while delay:
			delay -= 1
			if buttons.is_triggered("BTN_MENU"):
				break;
			if buttons.is_triggered("BTN_A"):
				break;
			if buttons.is_triggered("BTN_B"):
				break;
			if buttons.is_triggered("JOY_CENTER"):
				break;
Exemplo n.º 22
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()
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", "changename", "alistair~selectwifi", "snake"]
	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 = "Installed Apps" 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_menu = ugfx.Label(230,5,100,20,"Menu",parent=win_help)

	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)

	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 'Installed Apps'
		""", 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_menu.destroy()
		win_header.destroy()
		win_quick.destroy()
		win_help.destroy()
		title.destroy()
Exemplo n.º 24
0
def home_main():
    global orientation, next_tick, tick

    ugfx.area(0, 0, 320, 240, sty_tb.background())

    ugfx.set_default_font(ugfx.FONT_MEDIUM)
    win_bv = ugfx.Container(0, 0, 80, 25, style=sty_tb)
    win_wifi = ugfx.Container(82, 0, 60, 25, style=sty_tb)
    win_name = ugfx.Container(0,
                              25,
                              320,
                              240 - 25 - 60,
                              style=dialogs.default_style_badge)
    win_text = ugfx.Container(0, 240 - 60, 320, 60, style=sty_tb)

    windows = [win_bv, win_wifi, win_text]

    obj_name = apps.home.draw_name.draw(0, 25, win_name)

    buttons.init()

    gc.collect()
    ugfx.set_default_font(ugfx.FONT_MEDIUM_BOLD)
    hook_feeback = ugfx.List(0,
                             0,
                             win_text.width(),
                             win_text.height(),
                             parent=win_text)

    win_bv.show()
    win_text.show()
    win_wifi.show()

    min_ctr = 28

    # Create external hooks so other apps can run code in the context of
    # the home screen.
    # To do so an app needs to have an external.py with a tick() function.
    # The tick period will default to 60 sec, unless you define something
    # else via a "period" variable in the module context (use milliseconds)
    # If you set a variable "needs_wifi" in the module context tick() will
    # only be called if wifi is available
    # If you set a variable "needs_wifi" in the module context tick() will
    # be called with a reference to a 25x25 pixel ugfx container that you
    # can modify
    external_hooks = []
    icon_x = 150
    for path in get_external_hook_paths():
        try:
            module = __import__(path)
            if not hasattr(module, "tick"):
                raise Exception("%s must have a tick function" % path)

            hook = {
                "name": path[5:-9],
                "tick": module.tick,
                "needs_wifi": hasattr(module, "needs_wifi"),
                "period":
                module.period if hasattr(module, "period") else 60 * 1000,
                "next_tick_at": 0
            }

            if hasattr(module, "needs_icon"):
                hook["icon"] = ugfx.Container(icon_x, 0, 25, 25)
                icon_x += 27

            external_hooks.append(hook)
        except Exception as e:  # Since we dont know what exception we're looking for, we cant do much
            print(
                "%s while parsing background task %s.  This task will not run! "
                % (type(e).__name__, path[5:-9]))
            sys.print_exception(e)
            continue  # If the module fails to load or dies during the setup, skip it

    backlight_adjust()

    inactivity = 0
    last_rssi = 0

    ## start connecting to wifi in the background
    wifi_timeout = 30  #seconds
    wifi_reconnect_timeout = 0
    try:
        wifi.connect(wait=False)
    except OSError:
        print("Creating default wifi settings file")
        wifi.create_default_config()

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

        if (next_tick <= pyb.millis()):
            tick = True
            next_tick = pyb.millis() + 1000

        #if wifi still needs poking
        if (wifi_timeout > 0):
            if wifi.nic().is_connected():
                wifi_timeout = -1
                #wifi is connected, but if becomes disconnected, reconnect after 5 sec
                wifi_reconnect_timeout = 5
            else:
                wifi.nic().update()

        if tick:
            tick = False

            ledg.on()

            if (wifi_timeout > 0):
                wifi_timeout -= 1

            # change screen orientation
            ival = imu.get_acceleration()
            if ival['y'] < -0.5:
                if orientation != 0:
                    ugfx.orientation(0)
            elif ival['y'] > 0.5:
                if orientation != 180:
                    ugfx.orientation(180)
            if orientation != ugfx.orientation():
                inactivity = 0
                ugfx.area(0, 0, 320, 240, sty_tb.background())
                orientation = ugfx.orientation()
                for w in windows:
                    w.hide()
                    w.show()
                apps.home.draw_name.draw(0, 25, win_name)

            #if wifi timeout has occured and wifi isnt connected in time
            if (wifi_timeout == 0) and not (wifi.nic().is_connected()):
                print("Giving up on Wifi connect")
                wifi_timeout = -1
                wifi.nic().disconnect()  #give up
                wifi_reconnect_timeout = 30  #try again in 30sec

            wifi_connect = wifi.nic().is_connected()

            #if not connected, see if we should try again
            if not wifi_connect:
                if wifi_reconnect_timeout > 0:
                    wifi_reconnect_timeout -= 1
                    if wifi_reconnect_timeout == 0:
                        wifi_timeout = 60  #seconds
                        wifi.connect(wait=False)

            ledg.on()

            # display the wifi logo
            rssi = wifi.nic().get_rssi()
            if rssi == 0:
                rssi = last_rssi
            else:
                last_rssi = rssi

            draw_wifi(sty_tb.background(), rssi, wifi_connect,
                      wifi_timeout > 0, win_wifi)

            battery_percent = onboard.get_battery_percentage()
            draw_battery(sty_tb.background(), battery_percent, win_bv)

            inactivity += 1

            # turn off after some period
            # takes longer to turn off in the 'used' position
            if ugfx.orientation() == 180:
                inactivity_limit = 120
            else:
                inactivity_limit = 30
            if battery_percent > 120:  #if charger plugged in
                if ugfx.backlight() == 0:
                    ugfx.power_mode(ugfx.POWER_ON)
                ugfx.backlight(100)
            elif inactivity > inactivity_limit:
                low_power()
            else:
                backlight_adjust()

            ledg.off()

        for hook in external_hooks:
            try:
                if hook["needs_wifi"] and not wifi.nic().is_connected():
                    continue

                if hook["next_tick_at"] < pyb.millis():
                    text = None
                    if "icon" in hook:
                        text = hook["tick"](hook["icon"])
                    else:
                        text = hook["tick"]()
                    hook["next_tick_at"] = pyb.millis() + hook["period"]
                    if text:
                        if hook_feeback.count() > 10:
                            hook_feeback.remove_item(0)
                        hook_feeback.add_item(text)
                        if hook_feeback.selected_index() >= (
                                hook_feeback.count() - 2):
                            hook_feeback.selected_index(hook_feeback.count() -
                                                        1)
            except Exception as e:  # if anything in the hook fails to work, we need to skip it
                print(
                    "%s in %s background task. Not running again until next reboot! "
                    % (type(e).__name__, hook['name']))
                sys.print_exception(e)
                external_hooks.remove(hook)
                continue

        if buttons.is_pressed("BTN_MENU"):
            pyb.delay(20)
            break
        if buttons.is_pressed("BTN_A"):
            inactivity = 0
            tick = True
        if buttons.is_pressed("BTN_B"):
            inactivity = 0
            tick = True

    for hook in external_hooks:
        if "icon" in hook:
            hook["icon"].destroy()
    for w in windows:
        w.destroy()
    apps.home.draw_name.draw_destroy(obj_name)
    win_name.destroy()
    hook_feeback.destroy()
    if ugfx.backlight() == 0:
        ugfx.power_mode(ugfx.POWER_ON)
    ugfx.backlight(100)
    ugfx.orientation(180)

    #if we havnt connected yet then give up since the periodic function wont be poked
    if wifi_timeout >= 0:  # not (wifi.nic().is_connected()):
        wifi.nic().disconnect()
def init(color=0xFFFFFF):
    ugfx.init()
    ugfx.clear(ugfx.html_color(color))
    buttons.init()
Exemplo n.º 26
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()
Exemplo n.º 27
0
    def stop(self):
        if self.player:
            self.player.stdin.write('q')
            self.player.kill()
        self.player = None

    def start_stream(self, ip):
        url = 'rtsp://%s:8554/unicast' % ip
        self.player = subprocess.Popen(['omxplayer', url, '--alpha', '200'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)

streamPlayer = StreamPlayer()

#start_stream('localhost')

from buttons import poll, init
init()


import json

class Session(LineReceiver):
    def __init__(self):
        self.buttonLoop = task.LoopingCall(self.poll_buttons)
        self.list = {}

    def poll_buttons(self):
        r = poll()

        if r and len(self.list):
            import random
            #idx = random.randint(0, len(self.list))