예제 #1
0
def slave():
    nrf = NRF24L01(SPI(2), Pin('Y5'), Pin('Y4'), payload_size=8)

    nrf.open_tx_pipe(pipes[1])
    nrf.open_rx_pipe(1, pipes[0])
    nrf.start_listening()

    print('NRF24L01 slave mode, waiting for packets... (ctrl-C to stop)')

    while True:
        pyb.wfi()
        if nrf.any():
            while nrf.any():
                buf = nrf.recv()
                millis, led_state = struct.unpack('ii', buf)
                print('received:', millis, led_state)
                for i in range(4):
                    if led_state & (1 << i):
                        pyb.LED(i + 1).on()
                    else:
                        pyb.LED(i + 1).off()
                pyb.delay(15)

            nrf.stop_listening()
            try:
                nrf.send(struct.pack('i', millis))
            except OSError:
                pass
            print('sent response')
            nrf.start_listening()
예제 #2
0
    def wait(self, delay):
        t0 = pyb.millis()
        if delay == 0:
            return
        if delay == -1:
            # if delay == -1 the queue got emptied without stopping the loop
            blue_led.on()
            return
        blue_led.off()
        self._led.on()
        ust = pyb.micros()

        # Do possibly useful things in our idle time
        if delay > 6:
            gct0 = pyb.micros()
            gc.collect()  # we have the time, so might as well clean up
            self.max_gc_us = max(pyb.elapsed_micros(gct0), self.max_gc_us)

        while pyb.elapsed_millis(t0) < delay:
            # Measure the idle time
            # Anything interesting at this point will require an interrupt
            # If not some pin or peripheral or user timer, then it will be
            # the 1ms system-tick interrupt, which matches our wait resolution.
            # So we can save power by waiting for interrupt.
            pyb.wfi()

        self.idle_us += pyb.elapsed_micros(ust)
        self._led.off()
예제 #3
0
def log_gps(uart, read_delay=100):
    led = LED(4)
    with open('/sd/gps.nmea', 'a') as f:
        print(file=f)

        try:
            while True:
                led.on()
                while uart.any():
                    line = str(uart.readline(), 'utf-8').rstrip()
                    print(line, file=f)
                    parse(line)
                    led.toggle()

                f.flush()
                led.off()
                wfi()
                #delay(read_delay)
        finally:
            led.off()
            LED(2).off()
            LED(3).off()
            os.sync()

    LED(1).on()
예제 #4
0
def slave():
    nrf = NRF24L01(SPI(2), Pin('Y5'), Pin('Y4'), payload_size=8)

    nrf.open_tx_pipe(pipes[1])
    nrf.open_rx_pipe(1, pipes[0])
    nrf.start_listening()

    print('NRF24L01 slave mode, waiting for packets... (ctrl-C to stop)')

    while True:
        pyb.wfi()
        if nrf.any():
            while nrf.any():
                buf = nrf.recv()
                millis, led_state = struct.unpack('ii', buf)
                print('received:', millis, led_state)
                for i in range(4):
                    if led_state & (1 << i):
                        pyb.LED(i + 1).on()
                    else:
                        pyb.LED(i + 1).off()
                pyb.delay(15)

            nrf.stop_listening()
            try:
                nrf.send(struct.pack('i', millis))
            except OSError:
                pass
            print('sent response')
            nrf.start_listening()
예제 #5
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())
예제 #6
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())
예제 #7
0
 def run(self):
     state = self.initial_state
     while True:
         state = self._update_devices_info(state)
         state = self.controller(state)
         primitives = self.view(state)
         with self.display:
             self._draw(primitives)
         pyb.wfi()
예제 #8
0
파일: engine.py 프로젝트: nvbn/pyboard-play
 def run(self):
     state = self.initial_state
     while True:
         state = self._update_devices_info(state)
         state = self.controller(state)
         primitives = self.view(state)
         with self.display:
             self._draw(primitives)
         pyb.wfi()
예제 #9
0
def tmp_wfi():
    sw = Switch()
    sw.callback(f)
    global i
    while True:
        if (i == 1):
            read_tmp()
            i = 0
        else:
            pyb.wfi()
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()
예제 #11
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()
예제 #12
0
파일: api_repl.py 프로젝트: tung6363/uble
 def repl_transmit(*args, **kwargs):
     data = bytearray(20)
     data_mv = memoryview(data)
     blank = b'\x00' * 20
     while True:
         tx_len = len(buffer_tx)
         if tx_len:
             for i in range(min(20, tx_len)):
                 data_mv[i] = buffer_tx.popleft()
             repl_peripheral.write_uuid(repl_tx_characteristic_uuid,
                                        data_mv[:tx_len])
             data_mv[:] = blank
         pyb.wfi()
예제 #13
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
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
예제 #15
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
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()
예제 #17
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()
예제 #18
0
def play_wav(filename, chunksize=3096, freq=44100):
    dac = DAC(1)
    delay_ms = int(chunksize / (freq / 1000000))
    micros = pyb.Timer(2, prescaler=83, period=0x3fffffff)
    start = time.time()
    with open(filename, "rb") as wav:
        chunk = wav.read(chunksize)
        buf = bytearray(chunk)
        while chunk:
            micros.counter(0)
            dac.write_timed(buf, freq, mode=DAC.NORMAL)
            chunk = wav.read(chunksize)
            buf = bytearray(chunk)
            while micros.counter() < delay_ms:
                pyb.wfi()

    dac = DAC(1)
    print (time.time() - start)
예제 #19
0
def is_triggered(button, interval=30):
    """Use this function if you want buttons as a trigger for something in a loop

	It blocks for a while before returning a True and ignores trailing edge highs
	for a certain time to filter out bounce on both edges
	"""
    global _tilda_bounce
    if is_pressed(button):
        if button in _tilda_bounce:
            if pyb.millis() > _tilda_bounce[button]:
                del _tilda_bounce[button]
            else:
                return False  # The button might have bounced back to high

        # Wait for a while to avoid bounces to low
        pyb.delay(interval)

        # Wait until button is released again
        while is_pressed(button):
            pyb.wfi()

        _tilda_bounce[button] = pyb.millis() + interval
        return True
예제 #20
0
def is_triggered(button, interval = 30):
	"""Use this function if you want buttons as a trigger for something in a loop

	It blocks for a while before returning a True and ignores trailing edge highs
	for a certain time to filter out bounce on both edges
	"""
	global _tilda_bounce
	if is_pressed(button):
		if button in _tilda_bounce:
			if pyb.millis() > _tilda_bounce[button]:
				del _tilda_bounce[button]
			else:
				return False # The button might have bounced back to high

		# Wait for a while to avoid bounces to low
		pyb.delay(interval)

		# Wait until button is released again
		while is_pressed(button):
			pyb.wfi()

		_tilda_bounce[button] = pyb.millis() + interval
		return True
예제 #21
0
파일: main.py 프로젝트: Kimbsy/EMF_20016
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()
예제 #22
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()
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()
예제 #24
0
def main():

    # create objects
    accel = pyb.Accel()
    blue = pyb.LED(4)
    switch = pyb.Switch()
    cam = pyb.Servo(2)
    pyb.delay(10)
    baro = BMP180('X')
    pyb.delay(10)
    imu = MPU9150('X', 1)
    rcv = Reciever()

    # settings
    baro.oversample_sett = 3
    #servo.calibration(860, 2160, 1500)

    # test i2c
    if len(baro._bmp_i2c.scan()) != 4:
        pyb.LED(2).on()
        print('sensors failed')
    else:
        print('sensors ready')

    # create dir
    if 'log' not in os.listdir('/sd/'):
        os.mkdir('/sd/log')
        print('created log dir')
    else:
        print('log dir already there')

    config = open('/sd/log/config.txt', 'w')
    config.write('AC1, AC2, AC3, AC4, AC5, AC6, B1, B2, MB, MC, MD, oversample_sett, accel_range, gyro_range\n')
    con = baro.compvaldump() + [imu.accel_range(), imu.gyro_range()]
    config.write('{},{},{},{},{},{},{},{},{},{},{},{},{},{}'.format(*con))
    config.close()
    print('wrote config file')

    # loop
    while True:

        # wait for interrupt
        pyb.wfi()

        # start if switch is pressed
        if (rcv.ch[1][0] < -45) or switch():                            # switch(): rcv.ch[1][0] < -45
            pyb.delay(300)                      # delay avoids detection of multiple presses
            blue.on()                           # blue LED indicates file open
            pyb.LED(3).off()
            filename = '/sd/log/log'+str(len(os.listdir('log'))+1)+'.bin'
            print('opening '+filename)
            log = open(filename, 'wb')
            i = 0
            trigger = b'\x00'
            cam.angle(90)
            pyb.delay(100)
            cam.angle(0)
            gc.collect()
            t0 = pyb.millis()/1000
            # until switch is pressed again
            while (rcv.ch[1][0] < 45) and (not switch()):                      #not switch(): rcv.ch[1][0] < 45

                t_start_ms = pyb.millis()
                next(baro.gauge())
                log.write(b''.join([struct.pack('I', t_start_ms),
                                    bytes(accel.filtered_xyz()),
                                    imu.get_accel_raw(),
                                    imu.get_gyro_raw(),
                                    baro.UT_raw,
                                    baro.MSB_raw,
                                    baro.LSB_raw,
                                    baro.XLSB_raw,
                                    trigger]))
                i = i+1
                if i%100 == 0:
                    trigger = para(baro.altitude)
                    dt = t_start_ms/1000-t0
                    sys.stdout.write('writing '+
                                     filename+
                                     ' %d lines, %d s, %d Hz \r'
                                     % (i, dt, i/dt))
                    pyb.LED(1).toggle()

            # end after switch is pressed again
            log.close()                         # close file
            blue.off()                          # blue LED indicates file closed
            print('\nclosed '+filename)
            cam.angle(90)
            pyb.delay(100)
            cam.angle(0)
            pyb.delay(300)                      # delay avoids detection of multiple presses
예제 #25
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()
예제 #26
0
        last_ping = now
        try:
            mqtt.ping()
        except OSError:
            print("got an oserror, connecting again")
            connect(mqtt)
        # mqtt.publish(channel, b"hello world")


next_tick = 0
if res == 0:
    last_ping = pyb.millis()
    mqtt.subscribe(channel)
    mqtt.publish(channel, b"hello world")
    while True:
        pyb.wfi()  # Wait For Input -- only waits 1ms
        ugfx.poll()

        now = pyb.millis()
        if (next_tick <= now):
            next_tick = now + TICK_EVERY_MS
            on_tick(now)

# mqtt.disconnect()

# while True:
# pyb.wfi()
# if buttons.is_triggered("BTN_MENU") or buttons.is_triggered("BTN_A") or buttons.is_triggered("BTN_B") or buttons.is_triggered("JOY_CENTER"):
# break;

# ugfx.clear()
예제 #27
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()
예제 #28
0
#hardware platform: pyboard V1.1

import pyb
from pyb import LED

led = LED(1)
led.off()

pyb.freq(168000000)  #set CPU frequency in hertz.
a = 0


def blink():
    global a
    if a > 8400 and a < 16800:
        led.toggle()
    elif a >= 16800:
        a = 0
    a += 1


while True:
    blink()
    pyb.wfi(
    )  #pyb.wfi() is used to reduce power consumption while waiting for an event such as an interrupt.
예제 #29
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()
예제 #30
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
예제 #31
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()
예제 #32
0
def main():

    # Set up the switch to read 0 when not triggered, 1 when triggered
    # Wiring:
    # - Connect one side of switch to the 'X1' pin
    # - Connect the other side of the switch to ground
    brake_switch = machine.Pin('X1', machine.Pin.IN, machine.Pin.PULL_UP)

    # Output effect of switch to the red LED matrix
    from lights import matrix
    brake_lights = matrix.MainGrid()
    brake_lights.off()

    # Options
    sleeptime = 20  #milliseconds; 20 = 50 times/second

    # infinite loop allows data logging while the system is on
    while True:

        # wait for interrupt
        # this reduces power consumption while waiting for switch press
        pyb.wfi()

        # start if switch is pressed
        if switch():

            blue.on()  #Acknowledge button press
            pyb.delay(200)  # delay avoids detection of multiple presses

            #Calibrate - assume no motion for 2 seconds after button is pressed
            blue.off(
            )  #indicate that calibration is occuring - data not yet logging
            orange.on()
            pitch, roll = calc_tilt_angles()

            #Create the log file
            filename = make_filename('/sd/log', '.csv')
            log = open(filename,
                       'w')  # open file on SD (SD: '/sd/', flash: '/flash/)
            orange.off()
            blue.on()  #indicate data logging is starting
            log.write(
                "pitch_degrees:{},roll_degrees:{},Time,X,Y,Z,Brake\n".format(
                    pitch, roll))

            #Initialize some loop utility variables
            brake_lights.off()  #make sure this matches previous_braking
            previous_braking = 0
            last_save_t = pyb.millis()  #initialize to now

            # until switch is pressed again
            while not switch():

                #Get the data and log it
                t = pyb.millis()  # get time
                #x, y, z = accel.filtered_xyz()              # get acceleration data
                x = accel.x()
                y = accel.y()
                z = accel.z()
                braking = brake_switch.value()  # is brake switch triggered?
                log.write('{},{},{},{},{},{},{}\n'.format(
                    '', '', t, x, y, z, braking))  # write data to file

                #Toggle the lights if needed
                if previous_braking != braking:
                    try:
                        brake_lights.toggle()
                    except Exception as e:
                        #Needed because the I2C connection sometimes has timeout errors.
                        # It's more important to continue logging, and let the lights
                        # toggle on the next switch press instead.
                        pass

                #autosave the data in case of crash during long write function
                if t > (last_save_t + 1000):
                    last_save_t = t
                    log.close()
                    log = open(filename, 'a')

                #Wrap up stuff in the loop
                previous_braking = braking
                sleep_ms(sleeptime)

            # end after switch is pressed again
            log.close()  # close file
            blue.off()  # blue LED indicates file closed
            pyb.delay(200)  # delay avoids detection of multiple presses
예제 #33
0
def main():
    print('Traffic lights running ...')

    class Events:
        RED_TIMEOUT = 1
        AMBER_TIMEOUT = 2
        GREEN_TIMEOUT = 3
        ERROR = 4
        START = 5

    start = State(
        ident='start'
    )  # Special start state to allow for initialization before operation.

    timer0 = 10

    class FlashingRed(State):  # Special fault state that should never exit.
        def __init__(self):
            super().__init__(ident='error')
            self.timer = Timer(timer0 + 4)
            self.led = LED(1)

            # noinspection PyUnusedLocal
            def toggle_with_arg(
                not_used
            ):  # Toggle func that accepts an arg, because ``schedule`` *needs* an arg.
                self.led.toggle()

            self.led_tog_ref = toggle_with_arg  # Store the function reference locally to avoid allocation in interrupt.

        def __enter__(self):
            self.timer.init(
                freq=2, callback=lambda _: schedule(self.led_tog_ref, None))
            return self

        def __exit__(self, exc_type, exc_val, exc_tb):
            self.led.off()
            self.timer.deinit()

    flashing_red = FlashingRed()

    traffic_lights = Machine(initial_state=start)  # The traffic light machine.
    traffic_lights.actions[
        Events.RED_TIMEOUT] = flashing_red.action  # Catch anything unexpected.
    traffic_lights.actions[Events.AMBER_TIMEOUT] = flashing_red.action
    traffic_lights.actions[Events.GREEN_TIMEOUT] = flashing_red.action
    traffic_lights.actions[Events.ERROR] = flashing_red.action
    traffic_lights.actions[Events.START] = flashing_red.action

    tl_fire_ref = traffic_lights.fire  # Store the function reference locally to avoid allocation in interrupt.
    error = Switch()
    error.callback(lambda: schedule(tl_fire_ref, Events.ERROR))

    class LEDState(
            State
    ):  # Output is determined by ``__enter__`` and ``__exit__`` (common in embedded machines).
        def __init__(self, led_num, time_on, event):
            super().__init__(ident=led_num)  # Use the LED num as the ident.
            self.led = LED(self.ident)  # The LED to use.
            self.timer = Timer(timer0 + self.ident)  # The timer to use.
            self.timeout = time_on  # Time to wait before firing event.
            self.event = event  # Event to fire at end of time_on.

        def __enter__(self):
            self.led.on()
            self.timer.init(
                freq=1 / self.timeout,
                callback=lambda _: schedule(tl_fire_ref, self.event))
            return self

        def __exit__(self, exc_type, exc_value, traceback):
            self.led.off()
            self.timer.deinit()
            return False

    red = LEDState(led_num=1, time_on=3, event=Events.RED_TIMEOUT)
    green = LEDState(led_num=2, time_on=3, event=Events.GREEN_TIMEOUT)
    amber = LEDState(led_num=3, time_on=0.5, event=Events.AMBER_TIMEOUT)

    red.actions[Events.RED_TIMEOUT] = green.action
    green.actions[Events.GREEN_TIMEOUT] = amber.action
    amber.actions[Events.AMBER_TIMEOUT] = red.action
    start.actions[Events.START] = red.action

    with traffic_lights:
        _ = traffic_lights.fire(
            event=Events.START
        )  # Start the machine once all the setup is complete.
        while True:  # Keep running timers (and other peripherals), but otherwise do nothing.
            wfi()
예제 #34
0
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"
if not all( [ ("ssid" in config) for config in w ] ):
	label.text("Couldn't find a valid wifi.json :(" + wifi_info)
	while True: pyb.wfi()

n = network.CC3100()
visible_ssids = [ ap['ssid'] for ap in n.list_aps() ]
known_ssids = [ ap['ssid'] for ap in w ]

if len(set(known_ssids).intersection(visible_ssids)) < 1:
	label.text("Couldn't find any networks listed in wifi.json :(" + wifi_info)
	while True: pyb.wfi()	

for ap in w:
	if ap["ssid"] in visible_ssids:
		label.text("Connecting to '%s'.\nIf this is incorrect, please check your wifi.json%s" % (ap["ssid"], wifi_info))
		if ("pw" in ap) and ap["pw"]:
			n.connect(ap["ssid"], ap["pw"], timeout=10)
		else:
예제 #35
0
파일: main.py 프로젝트: mescriche/treadmill
from speed import SpeedManager
from slope import SlopeManager

mcu = MCU()  # blink yellow
spd_mngr = SpeedManager()
slp_mngr = SlopeManager()
uboard = Board(spd_mngr, slp_mngr)  #user board

while True:
    #making sure speed and slope leaders go down on red light
    mcu.yellow()
    uboard.start()  # yellow color

    while uboard.isReady() is not True:
        delay(1000)
        wfi()
    else:
        mcu.green()
        uboard.setReady()  #green light and beep: it's safe to get onboard

    # waiting for start/stop button to be pushed
    while uboard.isOn() is not True:
        delay(1000)
        wfi()
    else:
        mcu.blue()
        uboard.setOn()  #blue light and three beeps to state to getting started

    # action is about to start
    spd_mngr.start()
    #walking: control loop
예제 #36
0
def sleep():
    while True:
        pyb.wfi()
예제 #37
0
	OpenMV 
	
	@date: 2018.05.10

'''


# Quick reference for the openmvcam

'''
 1.1 General board control 
'''
import pyb

pyb.repl_uart(pyb.UART(3, 9600, timeout_char=1000)) # duplicate REPL on UART(3)
pyb.wfi() # pause CPU, waiting for interrupt
pyb.stop() # stop CPU, waiting for external interrupt


'''
 1.2 Delay and timing
'''



'''
	图像处理背景知识
'''

# ref: http://book.openmv.cc/
# https://blog.csdn.net/HZ_CloudRiver/article/details/78177307?locationNum=6&fps=1#t1