Пример #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()
Пример #2
0
def choose_wifi(dialog_title='TiLDA'):
    with dialogs.WaitingMessage(text='Scanning for networks...', title=dialog_title):
        visible_aps = nic().list_aps()
        visible_aps.sort(key=lambda x:x['rssi'], reverse=True)
        visible_ap_names = []
        # We'll get one result for each AP, so filter dupes
        for ap in visible_aps:
            if ap['ssid'] not in visible_ap_names:
                visible_ap_names.append(ap['ssid'])
        visible_aps = None

    ssid = dialogs.prompt_option(
        visible_ap_names,
        text='Choose wifi network',
        title=dialog_title
    )
    key = dialogs.prompt_text("Enter wifi key (blank if none)", width = 310, height = 220)
    if ssid:
        with open("wifi.json", "wt") as file:
            if key:
                conn_details = {"ssid": ssid, "pw": key}
            else:
                conn_details = {"ssid": ssid}

            file.write(json.dumps(conn_details))
        os.sync()
        # We can't connect after scanning for some bizarre reason, so we reset instead
        pyb.hard_reset()
Пример #3
0
def reset_and_run(path):
	import pyb
#	if stm.mem8[0x40002850] == 0:   # this battery backed RAM section is set to 0 when the name screen runs
	with open('main.json', 'w') as f:
		f.write('{"main":"' + path + '"}')
#		stm.mem8[0x40002850] = 2    #set this address to != 0 so this if statement doesnt run next time
	pyb.hard_reset()
def reset_and_run(path):
	import pyb
#	if stm.mem8[0x40002850] == 0:   # this battery backed RAM section is set to 0 when the name screen runs
	with open('main.json', 'w') as f:
		f.write('{"main":"' + path + '"}')
#		stm.mem8[0x40002850] = 2    #set this address to != 0 so this if statement doesnt run next time
	pyb.hard_reset()
def stop_callback(line):
  global start_pressed, stop_int, stop_value, start_pin, stop_pin, pyb, led_pin
  
  #print("stop pressed = "+str(stop_value))
  if stop_pin.value() == 0: # 1 = not pressed
    stop_int.disable()
    led_pin.low()
    pyb.hard_reset() #reset and reboot
    print("stop pressed")
    start_pressed = 0
def stop_callback(line):
    global start_pressed, stop_int, stop_value, start_pin, stop_pin, pyb, led_pin

    #print("stop pressed = "+str(stop_value))
    if stop_pin.value() == 0:  # 1 = not pressed
        stop_int.disable()
        led_pin.low()
        pyb.hard_reset()  #reset and reboot
        print("stop pressed")
        start_pressed = 0
Пример #7
0
def callback(line):
    '''This is a function which runs during interrupts. This should occur when
    the emergecny stop button is pressed down. It waits until the emergency
    stop has been disengaged and initiates a soft restart'''
    print("Emergency Stop pressed...")
    RedLED.high()
    while True:
        if Stop_Pin.value() == 0:
            print("... and released")
            RedLED.low()
            break

    import pyb
    pyb.hard_reset()
Пример #8
0
def choose_wifi(dialog_title='TiLDA'):
    filtered_aps = []
    with dialogs.WaitingMessage(text='Scanning for networks...', title=dialog_title):
        visible_aps = nic().list_aps()
        visible_aps.sort(key=lambda x:x['rssi'], reverse=True)
        # We'll get one result for each AP, so filter dupes
        for ap in visible_aps:
            title = ap['ssid']
            security = get_security_level(ap)
            if security:
                title = title + ' (%s)' % security
            ap = {
                'title': title,
                'ssid': ap['ssid'],
                'security': security,
            }
            if ap['ssid'] not in [ a['ssid'] for a in filtered_aps ]:
                filtered_aps.append(ap)
        del visible_aps

    ap = dialogs.prompt_option(
        filtered_aps,
        text='Choose wifi network',
        title=dialog_title
    )
    if ap:
        key = None
        if ap['security'] != 0:
            # Backward compat
            if ap['security'] == None:
                ap['security'] = 'wifi'

            key = dialogs.prompt_text(
                "Enter %s key" % ap['security'],
                width = 310,
                height = 220
            )
        with open("wifi.json", "wt") as file:
            if key:
                conn_details = {"ssid": ap['ssid'], "pw": key}
            else:
                conn_details = {"ssid": ap['ssid']}

            file.write(json.dumps(conn_details))
        os.sync()
        # We can't connect after scanning for some bizarre reason, so we reset instead
        pyb.hard_reset()
Пример #9
0
def connect(wait=True,
            timeout=10,
            show_wait_message=False,
            prompt_on_fail=True,
            dialog_title='TiLDA'):
    retry_connect = True

    while retry_connect:
        if nic().is_connected():
            return

        details = connection_details()
        if not details:
            if prompt_on_fail:
                choose_wifi(dialog_title=dialog_title)
            else:
                raise OSError("No valid wifi configuration")

        if not wait:
            connect_wifi(details, timeout=None, wait=False)
            return
        else:
            try:
                if show_wait_message:
                    with dialogs.WaitingMessage(
                            text="Connecting to '%s'...\n(%ss timeout)" %
                        (details['ssid'], timeout),
                            title=dialog_title):
                        connect_wifi(details, timeout=timeout, wait=True)
                else:
                    connect_wifi(details, timeout=timeout, wait=True)
            except OSError:
                if prompt_on_fail:
                    retry_connect = dialogs.prompt_boolean(
                        text="Failed to connect to '%s'" % details['ssid'],
                        title=dialog_title,
                        true_text="Try again",
                        false_text="Forget it",
                    )
                    if not retry_connect:
                        os.remove('wifi.json')
                        os.sync()
                        # We would rather let you choose a new network here, but
                        # scanning doesn't work after a connect at the moment
                        pyb.hard_reset()
                else:
                    raise
Пример #10
0
def main():
    """
    The method that controls everything.

    Initialization procedure:
    1: Wait for bytes from PC are specifically 'start'
        1a: Dim the indicator light
    2: Write the array of pins, `pin_strings`, so that the PC knows what it's working with
    """
    # Objects
    usb = VCP()

    # Initial
    while True:
        read = usb.read_timeout(inf)
        if read == 'start':
            usb.write_encode('start')
            break

    # Object manipulation
    indicator_light.intensity(32)  # dim the indicator light
    # Writes
    usb.write_encode(pin_strings)
    # Reads
    timer_frequency = int(usb.verify_read(inf))
    # Post init variables
    pins = tuple(Pin(i) for i in pin_strings)
    adc_pins = tuple(ADC(p) for p in pins)
    adc_arrays = tuple(array('H', [0]) for j in adc_pins)
    timer = Timer(8, freq=timer_frequency)
    # Loop
    while True:
        start_time = millis()
        ADC.read_timed_multi(adc_pins, adc_arrays, timer)

        if usb.read_timeout(1) == 'kill':
            hard_reset()

        write_table = {}
        usb.write_encode('newset\n')
        for i, v in enumerate(adc_arrays):
            usb.write_encode('\'{pin}\': {value}\n'.format(pin=pin_strings[i],
                                                           value=v[0]))
            #write_table[pin_strings[i]] = v[0]
        usb.write_encode('endset\n')

        write_table['duration'] = elapsed_millis(start_time)
Пример #11
0
def choose_wifi(dialog_title='TiLDA'):
    filtered_aps = []
    with dialogs.WaitingMessage(text='Scanning for networks...',
                                title=dialog_title):
        visible_aps = nic().list_aps()
        visible_aps.sort(key=lambda x: x['rssi'], reverse=True)
        # We'll get one result for each AP, so filter dupes
        for ap in visible_aps:
            title = ap['ssid']
            security = get_security_level(ap)
            if security:
                title = title + ' (%s)' % security
            ap = {
                'title': title,
                'ssid': ap['ssid'],
                'security': security,
            }
            if ap['ssid'] not in [a['ssid'] for a in filtered_aps]:
                filtered_aps.append(ap)
        del visible_aps

    ap = dialogs.prompt_option(filtered_aps,
                               text='Choose wifi network',
                               title=dialog_title)
    if ap:
        key = None
        if ap['security'] != 0:
            # Backward compat
            if ap['security'] == None:
                ap['security'] = 'wifi'

            key = dialogs.prompt_text("Enter %s key" % ap['security'],
                                      width=310,
                                      height=220)
        with open("wifi.json", "wt") as file:
            if key:
                conn_details = {"ssid": ap['ssid'], "pw": key}
            else:
                conn_details = {"ssid": ap['ssid']}

            file.write(json.dumps(conn_details))
        os.sync()
        # We can't connect after scanning for some bizarre reason, so we reset instead
        pyb.hard_reset()
Пример #12
0
def connect(wait=True, timeout=10, show_wait_message=False, prompt_on_fail=True, dialog_title='TiLDA'):
    retry_connect = True

    while retry_connect:
        if nic().is_connected():
            return

        details = connection_details()
        if not details:
            if prompt_on_fail:
                choose_wifi(dialog_title=dialog_title)
            else:
                raise OSError("No valid wifi configuration")

        if not wait:
            connect_wifi(details, timeout=None, wait=False)
            return
        else:
            try:
                if show_wait_message:
                    with dialogs.WaitingMessage(text="Connecting to '%s'...\n(%ss timeout)" % (details['ssid'], timeout), title=dialog_title):
                        connect_wifi(details, timeout=timeout, wait=True)
                else:
                    connect_wifi(details, timeout=timeout, wait=True)
            except OSError:
                if prompt_on_fail:
                    retry_connect = dialogs.prompt_boolean(
                        text="Failed to connect to '%s'" % details['ssid'],
                        title=dialog_title,
                        true_text="Try again",
                        false_text="Forget it",
                    )
                    if not retry_connect:
                        os.remove('wifi.json')
                        os.sync()
                        # We would rather let you choose a new network here, but
                        # scanning doesn't work after a connect at the moment
                        pyb.hard_reset()
                else:
                    raise
Пример #13
0
def save_settings(config):
    try:
        if USB_ENABLED and not config["usb"]:
            os.remove("%s/%s" % (storage_root, "USB_ENABLED"))
        if not USB_ENABLED and config["usb"]:
            with open("%s/%s" % (storage_root, "USB_ENABLED"), "w") as f:
                f.write("dummy") # should be hmac instead
        if DEV_ENABLED and not config["developer"]:
            os.remove("%s/%s" % (storage_root, "DEV_ENABLED"))
        if not DEV_ENABLED and config["developer"]:
            with open("%s/%s" % (storage_root, "DEV_ENABLED"), "w") as f:
                f.write("dummy") # should be hmac instead
        time.sleep_ms(100)
        if simulator:
            # meh... kinda doesn't work on unixport
            sys.exit()
        else:
            import pyb
            pyb.hard_reset()
    except Exception as e:
        gui.error("Failed to update settings!\n%r" % e)
    print(config)
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()
Пример #15
0
import pyb

# This code can be run on your pyboard without modifications

pyb.delay(1000)

pyb.udelay(1000000)

pyb.millis()

pyb.micros()

pyb.elapsed_millis(pyb.millis())

pyb.elapsed_micros(pyb.micros())

pyb.hard_reset()

pyb.delay(1000)

pyb.udelay(1000000)

pyb.millis()

pyb.micros()
Пример #16
0
        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
    while uboard.isOn(
    ):  # control loop remain until start/stop button is pushed
        spd_mngr.control()
        slp_mngr.control()
        uboard.running()
    else:  #stop procedure
        mcu.red()
        uboard.stopping()  # red light and three beeps
        spd_mngr.slow_down()  # reduce speed until 2.0 km/h
        slp_mngr.get_down()  # get down slope to horizontal level
        spd_mngr.stop()  # zero speed

    mcu.green()
    uboard.stopped()  # green light and three long beeps
    # getting down from machine
    sleep(30)  # before starting new loop 30 seconds wait

# just in case
mcu.random()
spd_mngr.stop()
hard_reset()

stop_int = pyb.ExtInt(stop_pin, pyb.ExtInt.IRQ_FALLING, pyb.Pin.PULL_UP,
                      stop_callback)

while (1):
    #global pyb
    print("one loop passed-----" + str(start_pressed))
    sleep(1)
    if start_pressed == 1:
        uart.write(cmd_dis_standby +
                   '\r')  # Disable standby from last heating cycle
        led_pin.high()
        #sleep(10) #for test
        uart.write(cmd_prefix + '%05X' % t1_set +
                   '\r')  # Set temperature point 1, i.e. 20C
        sleep(t1_last * 60)  #Keep t1_set for t1_last minutes
        #sleep(2) #for test
        for i in range(t1_set, t2_set + 1, t1_t2_step):  #Increase 1C per loop
            uart.write(cmd_prefix + '%05X' % i +
                       '\r')  # Increase temperature point 1 until t2_set
            sleep((t1_t2_last * 60 / ((t2_set - t1_set) / t1_t2_step)))
            #sleep(1) #for test
        sleep(t2_last * 60)  #Keep t2_set for t2_last minutes
        #sleep(300) #for test
        uart.write(cmd_standby + '\r')  # Shut off heater
        sleep(off_last * 60)  #Keep off state for off_last minutes
        #sleep(2) #for test
        led_pin.low()
        pyb.hard_reset()  # Mission accomplished then reset and reboot
Пример #18
0
    def GUI_Lookup_Table(self, input):
        ''' Decodes GUI commands based on a defined list of commands. Once
        received, an acknowledgement is printed so the GUI knows the
        command was processed.
        @param input - The incoming GUI command to decode and act upon.
        Command Variations:
            "abort (a); axis (x,z,y,p)"
            "enable (e); axis (x,z,y,p)" or "disable (d); axis (x,z,y,p)"
            "move (m); axis (x,z,y,p); steps; direction; init speed; max speed; accel rate"
            "zero (z); axis (x,z,y,p)"
            "microstep (t); axis (x,z,y,p); microsteps per fullstep"
            "reset (r)"
        '''
        command = input.split(";")
        action = command[0]
        axis = command[1]

        if action == "a":
            self.x_enable.put(0)
            self.z_enable.put(0)
            self.y_enable.put(0)
            self.p_enable.put(0)
            print('a')

        # ENABLE MOTOR
        elif action == "e":
            if axis == "x":
                self.x_enable.put(1)
                print('e;x')
            elif axis == "z":
                self.z_enable.put(1)
                print('e;z')
            elif axis == "y":
                self.y_enable.put(1)
                print('e;y')
            elif axis == "p":
                self.p_enable.put(1)
                print('e;p')

        # DISABLE MOTOR
        elif action == "d":
            if axis == "x":
                self.x_enable.put(0)
                print('d;x')
            elif axis == "z":
                self.z_enable.put(0)
                print('d;z')
            elif axis == "y":
                self.y_enable.put(0)
                print('d;y')
            elif axis == "p":
                self.p_enable.put(0)
                print('d;p')

        # MOVE MOTOR
        elif action == "m":
            steps = int(command[2])
            direction = int(command[3])
            init_speed = int(command[4])
            max_speed = int(command[5])
            accel_rate = int(command[6])
            if axis == "x":
                self.X_POSITIONING = True
                self.x_params.put(direction)
                self.x_params.put(init_speed)
                self.x_params.put(max_speed)
                self.x_params.put(accel_rate)
                self.x_params.put(steps)
                print('m;x')
            elif axis == "z":
                self.Z_POSITIONING = True
                self.z_params.put(direction)
                self.z_params.put(init_speed)
                self.z_params.put(max_speed)
                self.z_params.put(accel_rate)
                self.z_params.put(steps)
                print('m;z')
            elif axis == "y":
                self.Y_POSITIONING = True
                self.y_params.put(direction)
                self.y_params.put(init_speed)
                self.y_params.put(max_speed)
                self.y_params.put(accel_rate)
                self.y_params.put(steps)
                print('m;y')
            elif axis == "p":
                self.P_POSITIONING = True
                self.p_params.put(direction)
                self.p_params.put(init_speed)
                self.p_params.put(max_speed)
                self.p_params.put(accel_rate)
                self.p_params.put(steps)
                print('m;p')

        # ZERO
        elif action == "z":
            if axis == "x":
                self.x_zero.put(1)
                print('z;x')
            elif axis == "z":
                self.z_zero.put(1)
                print('z;z')
            elif axis == "y":
                self.y_zero.put(1)
                print('z;y')
            elif axis == "p":
                self.p_zero.put(1)
                print('z;p')

        # SEND TMC COMMAND
        elif action == "t":
            if axis == "x":
                self.set_TMC_microstep(int(command[2]), self.x_csn_pin)
                print('t;x' + ';' + command[2])
            elif axis == "z":
                self.set_TMC_microstep(int(command[2]), self.z_csn_pin)
                print('t;z' + ';' + command[2])
            elif axis == "y":
                self.set_TMC_microstep(int(command[2]), self.y_csn_pin)
                print('t;y' + ';' + command[2])
            elif axis == "p":
                self.set_TMC_microstep(int(command[2]), self.p_csn_pin)
                print('t;p' + ';' + command[2])

        # RESET
        elif action == "r":
            print('Resetting the RTOS')
            pyb.hard_reset()
Пример #19
0
def semihard_reset():
    hide_splash_on_next_boot()
    pyb.hard_reset()
    def GUI_Lookup_Table(self, input):
        ''' Decodes GUI commands based on a defined list of commands.
        @param command The incoming GUI command to decode.
        Command Variations:
            "abort (a); axis (x,z,y,p)"
            "enable (e); axis (x,z,y,p)" or "disable (d); axis (x,z,y,p)"
            "move (m); axis (x,z,y,p); steps; direction; init speed; max speed; accel rate"
        '''
        command = input.split(";")
        action = command[0]
        axis = command[1]

        if action == "a":
            self.x_enable.put(0)
            self.z_enable.put(0)
            self.y_enable.put(0)
            self.p_enable.put(0)
            # shares.print_task.put_bytes(b'a')
            print('a')

        # ENABLE MOTOR
        elif action == "e":
            if axis == "x":
                self.x_enable.put(1)
                print('e;x')
            elif axis == "z":
                self.z_enable.put(1)
                print('e;z')
            elif axis == "y":
                self.y_enable.put(1)
                print('e;y')
            elif axis == "p":
                self.p_enable.put(1)
                print('e;p')
            # shares.print_task.put_bytes(b'e')
            # print('e')

        # DISABLE MOTOR
        elif action == "d":
            if axis == "x":
                self.x_enable.put(0)
                print('d;x')
            elif axis == "z":
                self.z_enable.put(0)
                print('d;z')
            elif axis == "y":
                self.y_enable.put(0)
                print('d;y')
            elif axis == "p":
                self.p_enable.put(0)
                print('d;p')
            # shares.print_task.put_bytes(b'd')
            # print('d')

        # MOVE MOTOR
        elif action == "m":
            steps = int(command[2])
            direction = int(command[3])
            init_speed = int(command[4])
            max_speed = int(command[5])
            accel_rate = int(command[6])
            if axis == "x":
                self.X_POSITIONING = True
                self.x_params.put(direction)
                self.x_params.put(init_speed)
                self.x_params.put(max_speed)
                self.x_params.put(accel_rate)
                self.x_params.put(steps)
                print('m;x')
            elif axis == "z":
                self.Z_POSITIONING = True
                self.z_params.put(direction)
                self.z_params.put(init_speed)
                self.z_params.put(max_speed)
                self.z_params.put(accel_rate)
                self.z_params.put(steps)
                print('m;z')
            elif axis == "y":
                self.Y_POSITIONING = True
                self.y_params.put(direction)
                self.y_params.put(init_speed)
                self.y_params.put(max_speed)
                self.y_params.put(accel_rate)
                self.y_params.put(steps)
                print('m;y')
            elif axis == "p":
                self.P_POSITIONING = True
                # print(type(input).encode('UTF-8'))
                # print(move[2].encode('UTF-8'))
                self.p_params.put(direction)
                self.p_params.put(init_speed)
                self.p_params.put(max_speed)
                self.p_params.put(accel_rate)
                self.p_params.put(steps)
                print('m;p')
            # shares.print_task.put_bytes(b'm')
            # print('m')

        # ZERO
        elif action == "z":
            if axis == "x":
                self.x_zero.put(1)
                print('z;x')
            elif axis == "z":
                self.z_zero.put(1)
                print('z;z')
            elif axis == "y":
                self.y_zero.put(1)
                print('z;y')
            elif axis == "p":
                self.p_zero.put(1)
                print('z;p')
            # shares.print_task.put_bytes(b'z')
            # print('z')

        # SEND TMC COMMAND
        elif action == "t":
            if axis == "x":
                self.set_TMC_microstep(int(command[2]), self.x_csn_pin)
                print('t;x')
            elif axis == "z":
                self.set_TMC_microstep(int(command[2]), self.z_csn_pin)
                print('t;z')
            elif axis == "y":
                self.set_TMC_microstep(int(command[2]), self.y_csn_pin)
                print('t;y')
            elif axis == "p":
                self.set_TMC_microstep(int(command[2]), self.p_csn_pin)
                print('t;p')

        # RESET
        elif action == "r":
            print('Resetting the RTOS')
            pyb.hard_reset()
Пример #21
0
def reset():
    pyb.hard_reset()
Пример #22
0
def main(v_flip = False, h_flip = False):

    global PIR_flag

## The 9 inch board has X19/X20 swapped. For this board, use the alternative code
    if TFT_SIZE == 9:
        adc = pyb.ADC(pyb.Pin.board.X19)  # read battery voltage (large PCB)
    else:
        adc = pyb.ADC(pyb.Pin.board.X20)  # read battery voltage
    vbus = pyb.Pin('USB_VBUS')
    if vbus.value():
        USBSUPPLY = True
    else:
        USBSUPPLY = False

    usb = pyb.USB_VCP()

    batval = adc.read()
    if (TOOLOWBAT < batval < LOWBAT) and USBSUPPLY == False: # low battery, switch off
        while True: # stay there until reset
            pyb.stop()  # go to sleep. Only the PIR Sensor may wake me up
# Battery OK, or suppy by USB, start TFT.
    if TFT_SIZE == 7:
        mytft = tft.TFT("SSD1963", "AT070TN92", tft.PORTRAIT, v_flip, h_flip)
    elif TFT_SIZE == 4:
        mytft = tft.TFT("SSD1963", "LB04301", tft.LANDSCAPE, v_flip, h_flip)
    elif TFT_SIZE == 9:
        mytft = tft.TFT("SSD1963", "AT090TN10", tft.PORTRAIT, False, True)
    mytft.clrSCR()
    width, height = mytft.getScreensize()
    
    if TFT_SIZE == 9:
## The 9 inch board has X19/X20 swapped. For this board, use the alternative code
        extint = pyb.ExtInt(pyb.Pin.board.X20, pyb.ExtInt.IRQ_RISING, pyb.Pin.PULL_NONE, callback) ## large PCB
    else:
        extint = pyb.ExtInt(pyb.Pin.board.X19, pyb.ExtInt.IRQ_RISING, pyb.Pin.PULL_NONE, callback)
    extint.enable()

    total_cnt = 0

    if TFT_SIZE == 4:
        os.chdir("img_272x480")
    else:
        os.chdir("img_480x800")
    files = os.listdir(".")

    start = COUNTER  # reset timer once
    PIR_flag = False

    while True:
        TESTMODE = usb.isconnected()  # On USB, run test mode
        while True:  # get the next file name, but not banner.bmp
            myrng = pyb.rng()
            name = files[myrng % len(files)]
            if name != BANNER_NAME:
                break

        batval = adc.read()
        if TESTMODE:
            print("Battery: ", batval, ", Files: ", len(files), ", File: ", name, ", RNG: ", myrng)

# test for low battery, switch off, or total count reached
        if (TOOLOWBAT < batval < LOWBAT) and USBSUPPLY == False:
            tft_standby(mytft)
            while True: # stay there until reset
                pyb.stop()

        if (total_cnt % BANNER_COUNTER) == 0:
            displayfile(mytft, BANNER_NAME, width, height)
            mytft.setTextPos(0, 0)
            if LOWBAT <= batval < WARNBAT:
                textcolor = (255,255,0)
            elif TOOLOWBAT < batval < LOWBAT:
                textcolor = (255,0,0)
            else: 
                textcolor = (0,255,0)
            mytft.setTextStyle(textcolor, None, 0, font14)
            mytft.printString("{:.3}V - {} - {}".format(((batval * 3.3 * SCALING) / 4096) + OFFSET, batval, total_cnt))
            pyb.delay(BANNER_TIME)

        total_cnt += 1
        displayfile(mytft, name, width, height)
        pyb.delay(PICT_TIME)

        if PIR_flag == False: ## For one picture activity, check inactivity counter
            start -= 1
            if start <= 0 or total_cnt > TOTAL_COUNTER:  # no activity,  long enough
                if TESTMODE == False:
                    tft_standby(mytft) # switch TFT off and ports inactive
                    pyb.delay(200)
                    pyb.stop()  # go to sleep Only PIR Sensor may wake me up
                    pyb.hard_reset() # will do all the re-init
                else:
                    print("Should switch off here for a second")
                    mytft.clrSCR()
                    mytft.setTextStyle((255,255,255), None, 0, font14)
                    mytft.setTextPos(0, 0)
                    pyb.delay(100)
                    batval = adc.read()
                    mytft.printString("{:.3}V - {}".format(((batval * 3.3 * SCALING) / 4096) + OFFSET, total_cnt))
                    mytft.printNewline()
                    mytft.printCR()
                    mytft.printString("Should switch off here for a second")
                    pyb.delay(3000)
                    if total_cnt > TOTAL_COUNTER:
                        total_cnt = 0
                PIR_flag = False
                start = COUNTER  # reset timer
        else: # activity. restart counter
            PIR_flag = False
            start = COUNTER  # reset timer
Пример #23
0
def reboot():
    if simulator:
        sys.exit()
    else:
        pyb.hard_reset()
Пример #24
0
def reboot(kwargs):
    pi.result['code'] = 200
    pi.result['msg'] = 'rebooting'
    # 在重启前将响应信息发送。
    pi.write_task_result()
    hard_reset()
Пример #25
0
def main(v_flip = False, h_flip = False):

    global PIR_flag

## The 9 inch board has X19/X20 swapped. For this board, use the alternative code
    if TFT_SIZE == 9:
        adc = pyb.ADC(pyb.Pin.board.X19)  # read battery voltage (large PCB)
    else:
        adc = pyb.ADC(pyb.Pin.board.X20)  # read battery voltage
    vbus = pyb.Pin('USB_VBUS')
    if vbus.value():
        USBSUPPLY = True
    else:
        USBSUPPLY = False

    usb = pyb.USB_VCP()

    batval = adc.read()
    if (TOOLOWBAT < batval < LOWBAT) and USBSUPPLY == False: # low battery, switch off
        while True: # stay there until reset
            pyb.stop()  # go to sleep. Only the PIR Sensor may wake me up
# Battery OK, or suppy by USB, start TFT.
    if TFT_SIZE == 7:
        mytft = tft.TFT("SSD1963", "AT070TN92", tft.PORTRAIT, v_flip, h_flip)
    elif TFT_SIZE == 4:
        mytft = tft.TFT("SSD1963", "LB04301", tft.LANDSCAPE, v_flip, h_flip)
    elif TFT_SIZE == 9:
        mytft = tft.TFT("SSD1963", "AT090TN10", tft.PORTRAIT, False, True)
    mytft.clrSCR()
    width, height = mytft.getScreensize()
    
    if TFT_SIZE == 9:
## The 9 inch board has X19/X20 swapped. For this board, use the alternative code
        extint = pyb.ExtInt(pyb.Pin.board.X20, pyb.ExtInt.IRQ_RISING, pyb.Pin.PULL_DOWN, callback) ## large PCB
    else:
        extint = pyb.ExtInt(pyb.Pin.board.X19, pyb.ExtInt.IRQ_RISING, pyb.Pin.PULL_NONE, callback)
    extint.enable()

    files, has_banner, shuffle = get_files("/sd/serie", "/sd/zufall")

    start = COUNTER  # reset timer once
    PIR_flag = False

    file_index = 1  # 1: do not start with banner, 0: Start with banner
    while True:
        TESTMODE = usb.isconnected()  # On USB, run test mode
            # on every series start create a random shuffle
        if file_index == 0 and shuffle == True:
            files = list_shuffle(files)
        name = files[file_index]
        file_index = (file_index + 1) % len(files)
## on USB supply assume good battery
        if USBSUPPLY == False:
            batval = adc.read()
        else:
            batval = WARNBAT + 1
        if TESTMODE:
            print("Battery: ", batval, ", Files: ", len(files), ", File: ", name)

## test for low battery, switch off
        if (TOOLOWBAT < batval < LOWBAT) and USBSUPPLY == False:
            tft_standby(mytft)
            while True: # stay there until reset
                pyb.stop()

        if (file_index % BANNER_COUNTER) == 1 and has_banner == True:
            displayfile(mytft, BANNER_NAME, width, height)
            display_batlevel(mytft, batval)
            pyb.delay(BANNER_TIME)

        if displayfile(mytft, name, width, height):
            display_batlevel(mytft, batval)
            pyb.delay(PICT_TIME)

        if PIR_flag == False: ## For one picture activity, check inactivity counter
            start -= 1
            if start <= 0:  # no activity,  long enough
                if TESTMODE == False:
                    tft_standby(mytft) # switch TFT off and ports inactive
                    pyb.delay(200)
                    pyb.stop()  # go to sleep Only PIR Sensor may wake me up
                    pyb.hard_reset() # will do all the re-init
                else:
                    print("Should switch off here for a second")
                    mytft.clrSCR()
                    mytft.setTextStyle((255,255,255), None, 0, font14)
                    mytft.setTextPos(0, 0)
                    pyb.delay(100)
                    batval = adc.read()
                    mytft.printString("{:.3}V - {}".format(((batval * 3.3 * SCALING) / 4096) + OFFSET, file_index))
                    mytft.printNewline()
                    mytft.printCR()
                    mytft.printString("Should switch off here for a second")
                    pyb.delay(3000)
                PIR_flag = False
                start = COUNTER  # reset timer
        else: # activity. restart counter
            PIR_flag = False
            start = COUNTER  # reset timer
Пример #26
0
def restart(data):
    pyb.hard_reset()
Пример #27
0
def semihard_reset():
	hide_splash_on_next_boot()
	pyb.hard_reset()
def main(v_flip = False, h_flip = False):

    global PIR_flag

## The 9 inch board has X19/X20 swapped. For this board, use the alternative code
    if TFT_SIZE == 9:
        adc = pyb.ADC(pyb.Pin.board.X19)  # read battery voltage (large PCB)
    else:
        adc = pyb.ADC(pyb.Pin.board.X20)  # read battery voltage
    vbus = pyb.Pin('USB_VBUS')
    if vbus.value():
        USBSUPPLY = True
    else:
        USBSUPPLY = False

    usb = pyb.USB_VCP()

    batval = adc.read()
    if (TOOLOWBAT < batval < LOWBAT) and USBSUPPLY == False: # low battery, switch off
        while True: # stay there until reset
            pyb.stop()  # go to sleep. Only the PIR Sensor may wake me up
# Battery OK, or suppy by USB, start TFT.
    if TFT_SIZE == 7:
        mytft = tft.TFT("SSD1963", "AT070TN92", tft.PORTRAIT, v_flip, h_flip)
    elif TFT_SIZE == 4:
        mytft = tft.TFT("SSD1963", "LB04301", tft.LANDSCAPE, v_flip, h_flip)
    elif TFT_SIZE == 9:
        mytft = tft.TFT("SSD1963", "AT090TN10", tft.PORTRAIT, False, True)
    mytft.clrSCR()
    width, height = mytft.getScreensize()
    
    if TFT_SIZE == 9:
## The 9 inch board has X19/X20 swapped. For this board, use the alternative code
        extint = pyb.ExtInt(pyb.Pin.board.X20, pyb.ExtInt.IRQ_RISING, pyb.Pin.PULL_DOWN, callback) ## large PCB
    else:
        extint = pyb.ExtInt(pyb.Pin.board.X19, pyb.ExtInt.IRQ_RISING, pyb.Pin.PULL_NONE, callback)
    extint.enable()

    files, has_banner, shuffle = get_files("/sd/serie", "/sd/zufall")

    start = COUNTER  # reset timer once
    PIR_flag = False

    file_index = 0
    while True:
        TESTMODE = usb.isconnected()  # On USB, run test mode
            # on every series start create a random shuffle
        if file_index == 0 and shuffle == True:
            files = list_shuffle(files)
        name = files[file_index]
        file_index = (file_index + 1) % len(files)
## on USB supply assume good battery
        if USBSUPPLY == False:
            batval = adc.read()
        else:
            batval = WARNBAT + 1
        if TESTMODE:
            print("Battery: ", batval, ", Files: ", len(files), ", File: ", name)

## test for low battery, switch off
        if (TOOLOWBAT < batval < LOWBAT) and USBSUPPLY == False:
            tft_standby(mytft)
            while True: # stay there until reset
                pyb.stop()

        if (file_index % BANNER_COUNTER) == 1 and has_banner == True:
            displayfile(mytft, BANNER_NAME, width, height)
            display_batlevel(mytft, batval)
            pyb.delay(BANNER_TIME)

        if displayfile(mytft, name, width, height):
            display_batlevel(mytft, batval)
            pyb.delay(PICT_TIME)

        if PIR_flag == False: ## For one picture activity, check inactivity counter
            start -= 1
            if start <= 0:  # no activity,  long enough
                if TESTMODE == False:
                    tft_standby(mytft) # switch TFT off and ports inactive
                    pyb.delay(200)
                    pyb.stop()  # go to sleep Only PIR Sensor may wake me up
                    pyb.hard_reset() # will do all the re-init
                else:
                    print("Should switch off here for a second")
                    mytft.clrSCR()
                    mytft.setTextStyle((255,255,255), None, 0, font14)
                    mytft.setTextPos(0, 0)
                    pyb.delay(100)
                    batval = adc.read()
                    mytft.printString("{:.3}V - {}".format(((batval * 3.3 * SCALING) / 4096) + OFFSET, file_index))
                    mytft.printNewline()
                    mytft.printCR()
                    mytft.printString("Should switch off here for a second")
                    pyb.delay(3000)
                PIR_flag = False
                start = COUNTER  # reset timer
        else: # activity. restart counter
            PIR_flag = False
            start = COUNTER  # reset timer
Пример #29
0
    hard_reset = 0
    if soft_reset_count % 40 == 0:
        hard_reset = 1
    soft_reset_count += 1
    hard_reset_count += hard_reset
    with open("/sd/sd_check.vars",  "w") as vars_file:
        vars_file.write('%d %d ' % (hard_reset_count, soft_reset_count))
    pyb.sync()
    vcp = pyb.USB_VCP()
    if vcp.any():
        print("Key press detected on USB - stopping")
    else:
        uart = pyb.UART(6, 115200)
        if uart.any():
            print("Key press detected on USB - stopping")
        else:
            pyb.delay(100)
            if hard_reset:
                pyb.hard_reset()
            pyb.soft_reset()
else:
    print('##############################################################')
    print('##############################################################')
    print("###");
    print("### SD card NOT present");
    print("###");
    print('##############################################################')
    print('##############################################################')
    pyb.delay(3000)

    stop_int.disable()
    led_pin.low()
    pyb.hard_reset() #reset and reboot
    print("stop pressed")
    start_pressed = 0
    
stop_int = pyb.ExtInt(stop_pin, pyb.ExtInt.IRQ_FALLING, pyb.Pin.PULL_UP, stop_callback)

while (1):
  #global pyb
  print("one loop passed-----"+str(start_pressed))
  sleep(1)
  if start_pressed == 1:
    uart.write(cmd_dis_standby+'\r') # Disable standby from last heating cycle
    led_pin.high() 
    #sleep(10) #for test
    uart.write(cmd_prefix+'%05X'%t1_set+'\r') # Set temperature point 1, i.e. 20C
    sleep(t1_last*60) #Keep t1_set for t1_last minutes
    #sleep(2) #for test
    for i in range (t1_set, t2_set+1, t1_t2_step): #Increase 1C per loop
      uart.write(cmd_prefix+'%05X'%i+'\r') # Increase temperature point 1 until t2_set
      sleep((t1_t2_last*60/((t2_set-t1_set)/t1_t2_step)))
      #sleep(1) #for test
    sleep(t2_last*60) #Keep t2_set for t2_last minutes
    #sleep(300) #for test
    uart.write(cmd_standby+'\r') # Shut off heater
    sleep(off_last*60) #Keep off state for off_last minutes
    #sleep(2) #for test
    led_pin.low() 
    pyb.hard_reset() # Mission accomplished then reset and reboot