def init(opts=None): ''' Initialize the library and enter micropythons raw-REPL mode (takes bytes, doesn't echo back). ''' log.info('mpyesp8266 proxy init() called...') #get option connection string #DETAILS['device'] = opts['proxy'].get('device') #log.info('mpyesp8266 proxy DETAILS: ', ', '.join(DETAILS)) #try to connect try: DETAILS['pyboard'] = pyboard.Pyboard('/dev/ttyUSB0') DETAILS['connected'] = True DETAILS['pyboard'].enter_raw_repl() except pyboard.PyboardError: try: DETAILS['pyboard'] = pyboard.Pyboard('/dev/ttyUSB1') DETAILS['connected'] = True DETAILS['pyboard'].enter_raw_repl() except: DETAILS['connected'] = False except: DETAILS['connected'] = False #todo wrap #if successful # do whatever #else return false # DETAILS['initialized'] = True
def main(): cmd_parser = argparse.ArgumentParser(description='Run dynamic-native-module tests under MicroPython') cmd_parser.add_argument('-p', '--pyboard', action='store_true', help='run tests via pyboard.py') cmd_parser.add_argument('-d', '--device', default='/dev/ttyACM0', help='the device for pyboard.py') cmd_parser.add_argument('-a', '--arch', default='x64', help='native architecture of the target') cmd_parser.add_argument('files', nargs='*', help='input test files') args = cmd_parser.parse_args() target_truth = TargetSubprocess([CPYTHON3]) if args.pyboard: target = TargetPyboard(pyboard.Pyboard(args.device)) else: target = TargetSubprocess([MICROPYTHON]) stats = {'total': 0, 'pass': 0, 'fail':0, 'skip': 0} run_tests(target_truth, target, args, stats) target.close() target_truth.close() print('{} tests performed'.format(stats['total'])) print('{} tests passed'.format(stats['pass'])) if stats['fail']: print('{} tests failed'.format(stats['fail'])) if stats['skip']: print('{} tests skipped'.format(stats['skip'])) if stats['fail']: sys.exit(1)
def execfil(filename, device='/dev/ttyACM0'): pyb = pyboard.Pyboard(device) pyb.enter_raw_repl() output = pyb.execfile(filename) pyb.exit_raw_repl() pyb.close() return output
def main(): cmd_parser = argparse.ArgumentParser(description="Run benchmarks for MicroPython") cmd_parser.add_argument( "-t", "--diff-time", action="store_true", help="diff time outputs from a previous run" ) cmd_parser.add_argument( "-s", "--diff-score", action="store_true", help="diff score outputs from a previous run" ) cmd_parser.add_argument( "-p", "--pyboard", action="store_true", help="run tests via pyboard.py" ) cmd_parser.add_argument( "-d", "--device", default="/dev/ttyACM0", help="the device for pyboard.py" ) cmd_parser.add_argument("-a", "--average", default="8", help="averaging number") cmd_parser.add_argument( "--emit", default="bytecode", help="MicroPython emitter to use (bytecode or native)" ) cmd_parser.add_argument("N", nargs=1, help="N parameter (approximate target CPU frequency)") cmd_parser.add_argument("M", nargs=1, help="M parameter (approximate target heap in kbytes)") cmd_parser.add_argument("files", nargs="*", help="input test files") args = cmd_parser.parse_args() if args.diff_time or args.diff_score: compute_diff(args.N[0], args.M[0], args.diff_score) sys.exit(0) # N, M = 50, 25 # esp8266 # N, M = 100, 100 # pyboard, esp32 # N, M = 1000, 1000 # PC N = int(args.N[0]) M = int(args.M[0]) n_average = int(args.average) if args.pyboard: target = pyboard.Pyboard(args.device) target.enter_raw_repl() else: target = [MICROPYTHON, "-X", "emit=" + args.emit] if len(args.files) == 0: tests_skip = ("benchrun.py",) if M <= 25: # These scripts are too big to be compiled by the target tests_skip += ("bm_chaos.py", "bm_hexiom.py", "misc_raytrace.py") tests = sorted( BENCH_SCRIPT_DIR + test_file for test_file in os.listdir(BENCH_SCRIPT_DIR) if test_file.endswith(".py") and test_file not in tests_skip ) else: tests = sorted(args.files) print("N={} M={} n_average={}".format(N, M, n_average)) run_benchmarks(target, N, M, n_average, tests) if isinstance(target, pyboard.Pyboard): target.exit_raw_repl() target.close()
def main(): cmd_parser = argparse.ArgumentParser(description='Run tests for MicroPython.') cmd_parser.add_argument('--pyboard', action='store_true', help='run the tests on the pyboard') cmd_parser.add_argument('files', nargs='*', help='input test files') args = cmd_parser.parse_args() # Note pyboard support is copied over from run-tests, not testes, and likely needs revamping if args.pyboard: import pyboard pyb = pyboard.Pyboard('/dev/ttyACM0') pyb.enter_raw_repl() else: pyb = None if len(args.files) == 0: if pyb is None: # run PC tests test_dirs = ('internal_bench',) else: # run pyboard tests test_dirs = ('basics', 'float', 'pyb') tests = sorted(test_file for test_files in (glob('{}/*.py'.format(dir)) for dir in test_dirs) for test_file in test_files) else: # tests explicitly given tests = sorted(args.files) test_dict = defaultdict(lambda: []) for t in tests: m = re.match(r"(.+?)-(.+)\.py", t) if not m: continue test_dict[m.group(1)].append([t, None]) if not run_tests(pyb, test_dict): sys.exit(1)
def __init__(self, dev_in, dev_out=None, console=None, **kwargs): # TODO add option to not restart pyboard, to continue a previous session self.dev_in = dev_in self.dev_out = dev_out self._console = console self.exitcode = None self.pyb = None # type: pyboard.Pyboard try: self.fs_hook_code = (Path(mprepl_hook.__file__).parent / 'mprepl_hook.py').read_text() self.fs_util_code = (Path(mprepl_hook.__file__).parent / 'mprepl_utils.py').read_text() except Exception as ex: print(ex) raise if isinstance(dev_in, pyboard.Pyboard): self.pyb = dev_in self.dev_in = repr(dev_in) else: try: self.pyb = pyboard.Pyboard(dev_in, **kwargs) except pyboard.PyboardError: port = list(serial.tools.list_ports.grep(dev_in)) if not port: raise self.pyb = pyboard.Pyboard(port[0].device, **kwargs) fout = self.pyb.serial if dev_out is not None: try: fout = serial.Serial(dev_out) except serial.SerialException: port = list(serial.tools.list_ports.grep(dev_out)) if not port: raise for p in port: try: fout = serial.Serial(p.device) break except serial.SerialException: pass self.pyb.serial.timeout = 2.0 self.fout = fout self.cmd = PyboardCommand(self.pyb.serial, self.fout)
def create_pyboard(self): try: self.pyboard = pyb.Pyboard(self.tk_vars['port'].get(), self.tk_vars['baudrate'].get()) return True except Exception as e: logging.exception(e) tkmb.showerror('Creation failed!', 'Double-check that the baudrate is correct.') return False
def main(): #pyb1 = pyboard.Pyboard(device = "/dev/tty.usbmodem1412") pyb1 = pyboard.Pyboard(device="/dev/ttyACM0") pyb1.enter_raw_repl() pyb1.exec_('from resistor import Resistor') pyb1.exec_('res = Resistor()') pyb1.exec_('res.set_resistor(3400)') value = float(pyb1.exec_('res.get_resistor_string()')) value2 = float(pyb1.exec_('res.get_adc_string()')) print(value, value2) #pyb1.exec_('res.set_resistor(1500)') #pyb1.exit_raw_repl() #pyb1.close() #print("_______________") #output.decode("utf-8") #print(output) """
def flash_scripts(port, aws_config_file_path): global esp_board remove_some_dirs_from_path() esp_board = pyboard.Pyboard(port, 115200) try: esp_board.enter_raw_repl() except pyboard.PyboardError as er: print(er) esp_board.close() sys.exit(1) upload_dir(repo_path='src', device_path='') dev_create_dir(DEVICE_RESOURCES_FILE_DIR) aws_config_file_path = os.path.abspath(aws_config_file_path) upload_file(aws_config_file_path, AWS_CONFIG_DEVICE_FILE_PATH)
def main(): cmd_parser = argparse.ArgumentParser( description="Run dynamic-native-module tests under MicroPython") cmd_parser.add_argument("-p", "--pyboard", action="store_true", help="run tests via pyboard.py") cmd_parser.add_argument("-d", "--device", default="/dev/ttyACM0", help="the device for pyboard.py") cmd_parser.add_argument("-a", "--arch", default="x64", help="native architecture of the target") cmd_parser.add_argument("files", nargs="*", help="input test files") args = cmd_parser.parse_args() target_truth = TargetSubprocess([CPYTHON3]) if args.pyboard: global pyboard sys.path.append("../tools") import pyboard target = TargetPyboard(pyboard.Pyboard(args.device)) else: target = TargetSubprocess([MICROPYTHON]) stats = {"total": 0, "pass": 0, "fail": 0, "skip": 0} run_tests(target_truth, target, args, stats) target.close() target_truth.close() print("{} tests performed".format(stats["total"])) print("{} tests passed".format(stats["pass"])) if stats["fail"]: print("{} tests failed".format(stats["fail"])) if stats["skip"]: print("{} tests skipped".format(stats["skip"])) if stats["fail"]: sys.exit(1)
def main(): cmd_parser = argparse.ArgumentParser( description="Run tests for MicroPython.") cmd_parser.add_argument("--pyboard", action="store_true", help="run the tests on the pyboard") cmd_parser.add_argument("files", nargs="*", help="input test files") args = cmd_parser.parse_args() # Note pyboard support is copied over from run-tests.py, not tests, and likely needs revamping if args.pyboard: import pyboard pyb = pyboard.Pyboard("/dev/ttyACM0") pyb.enter_raw_repl() else: pyb = None if len(args.files) == 0: if pyb is None: # run PC tests test_dirs = ("internal_bench", ) else: # run pyboard tests test_dirs = ("basics", "float", "pyb") tests = sorted(test_file for test_files in (glob("{}/*.py".format(dir)) for dir in test_dirs) for test_file in test_files) else: # tests explicitly given tests = sorted(args.files) test_dict = defaultdict(lambda: []) for t in tests: m = re.match(r"(.+?)-(.+)\.py", t) if not m: continue test_dict[m.group(1)].append([t, None]) if not run_tests(pyb, test_dict): sys.exit(1)
import pyboard import matplotlib.pyplot as plt import numpy as np from scipy.optimize import curve_fit pyb = pyboard.Pyboard('/dev/ttyACM0', 115200) pyb.enter_raw_repl() repl = pyb.execfile('condensateur.py') pyb.close() data = repl.decode() x, y = eval(data) t = np.array(x) u = np.array(y) def expo(x, A, tau, xo): # Definition de la fonction return A * (1 - np.exp(-(x - xo) / tau)) # Expression du modèle (A, tau, xo), pcov = curve_fit(expo, t, u, p0=[1, 1, 1]) # Determination des paramètres du modèle print("A = ", A) # Affichage de A print("tau = ", tau) # Affichage de tau print("xo = ", xo) # Decalage temporel texte = "A = " + str(round(A, 2)) + " V\n" + "tau = " + str(round(tau, 0)) + " ms" tnew = np.linspace(-10, t.max(), 50)
def __init__(self, device): device = self.map_device_shortcut(device) self.device = device self.pyb = pyboard.Pyboard(device) self.pyb.enter_raw_repl() self.finished = True
def main(): """The main program.""" try: default_baud = int(os.getenv('RSHELL_BAUD')) except: default_baud = 115200 default_port = os.getenv('RSHELL_PORT') if not default_port: default_port = '/dev/ttyACM0' global BUFFER_SIZE try: default_buffer_size = int(os.getenv('RSHELL_BUFFER_SIZE')) except: default_buffer_size = BUFFER_SIZE parser = argparse.ArgumentParser( prog="rshell", usage="%(prog)s [options] [command]", description="Remote Shell for a MicroPython board.", epilog=("You can specify the default serial port using the " + "RSHELL_PORT environment variable.")) parser.add_argument("-b", "--baud", dest="baud", action="store", type=int, help="Set the baudrate used (default = %d)" % default_baud, default=default_baud) parser.add_argument( "--buffer-size", dest="buffer_size", action="store", type=int, help="Set the buffer size used for transfers (default = %d)" % default_buffer_size, default=default_buffer_size) parser.add_argument("-p", "--port", dest="port", help="Set the serial port to use (default '%s')" % default_port, default=default_port) parser.add_argument("-f", "--file", dest="filename", help="Specifies a file of commands to process.") parser.add_argument("-d", "--debug", dest="debug", action="store_true", help="Enable debug features", default=False) parser.add_argument("-n", "--nocolor", dest="nocolor", action="store_true", help="Turn off colorized output", default=False) parser.add_argument("--nowait", dest="wait", action="store_false", help="Don't wait for serial port", default=True) parser.add_argument("--timing", dest="timing", action="store_true", help="Print timing information about each command", default=False) parser.add_argument("cmd", nargs=argparse.REMAINDER, help="Optional command to execute") args = parser.parse_args(sys.argv[1:]) if args.debug: print("Debug = %s" % args.debug) print("Port = %s" % args.port) print("Baud = %d" % args.baud) print("Wait = %d" % args.wait) print("Timing = %d" % args.timing) print("Buffer_size = %d" % args.buffer_size) print("Cmd = [%s]" % ', '.join(args.cmd)) global DEBUG DEBUG = args.debug BUFFER_SIZE = args.buffer_size if args.nocolor: global DIR_COLOR, PROMPT_COLOR, PY_COLOR, END_COLOR DIR_COLOR = '' PROMPT_COLOR = '' PY_COLOR = '' END_COLOR = '' global pyb if args.wait and not os.path.exists(args.port): sys.stdout.write("Waiting for '%s' to exist" % args.port) sys.stdout.flush() while not os.path.exists(args.port): sys.stdout.write('.') sys.stdout.flush() time.sleep(0.5) sys.stdout.write("\n") pyb = pyboard.Pyboard(args.port, baudrate=args.baud) # Bluetooth devices take some time to connect at startup, and writes # issued while the remote isn't connected will fail. So we send newlines # with pauses until one of our writes suceeds. try: # we send a Control-C which should kill the current line # assuming we're talking to tha micropython repl. If we send # a newline, then the junk might get interpreted as a command # which will do who knows what. pyb.serial.write(b'\x03') except serial.serialutil.SerialException: # Write failed. Now report that we're waiting and keep trying until # a write succeeds sys.stdout.write("Waiting for transport to be connected.") while True: time.sleep(0.5) try: pyb.serial.write(b'\x03') break except serial.serialutil.SerialException: pass sys.stdout.write('.') sys.stdout.flush() sys.stdout.write('\n') # When connecting over wireless interface (like bluetooth), we often # get a bunch of junk on the RX line when connecting, especially the first # time after a powerup. So we drain that here. The junk can also originate # from the newlines that we sent above. save_timeout = pyb.serial.timeout pyb.serial.timeout = 0.5 junk = pyb.serial.read(10) if junk: sys.stdout.write('Removing junk from the Rx serial line ') timeout_count = 0 while timeout_count < 8: # We wait for 4 seconds with no data arriving sys.stdout.write('.') sys.stdout.flush() junk = pyb.serial.read(10) if junk: timeout_count = 0 else: timeout_count += 1 pyb.serial.write(b'\x03') sys.stdout.write('\n') pyb.serial.timeout = save_timeout # In theory the serial port is now ready for use. if remote_eval(test_buffer): global HAS_BUFFER HAS_BUFFER = True if DEBUG: print("Setting HAS_BUFFER to True") elif not remote_eval(test_unhexlify): print("rshell needs MicroPython firmware with ubinascii.unhexlify") return else: if DEBUG: print("MicroPython has unhexlify") global pyb_root_dirs pyb_root_dirs = ['/{}/'.format(dir) for dir in remote_eval(listdir, '/')] sync_time() if args.filename: with open(args.filename) as cmd_file: shell = Shell(stdin=cmd_file, filename=args.filename, timing=args.timing) shell.cmdloop('') else: cmd_line = ' '.join(args.cmd) if cmd_line == '': print('Welcome to rshell. Use Control-D to exit.') shell = Shell(timing=args.timing) shell.cmdloop(cmd_line)
''' temp_str = run_on_board(pb, ['print(blob.pMskSave1)'], no_print=False) temp_str = run_on_board(pb, ['print(blob.pMskSave2)'], no_print=False) ''' return img, blobs, t_ms # --------------------------------------------------------------------- if __name__ == '__main__': # Check for command line parameter(s) args = parseCmdLn() port = args.port # Connect to board try: pb = pyboard.Pyboard(port) pb.enter_raw_repl() print("Connected to MicroPython board via {0}".format(port)) except pyboard.PyboardError: print("ERROR: Could not connect to board") exit() # Connect to AMG8833 sensor via the board print("Searching for sensor ...") _ = run_on_board(pb, script_initialize_amg8833, wait_s=0.4) _ = run_on_board(pb, ["import blob"]) # Initialize GUI gui = FrontEndGUI(pb) print("Starting loop ...")
def program_board(serial_port, mac): pyb = pyboard.Pyboard(serial_port) run_program_script(pyb, mac) return detect_flashing_status(pyb)
def set_preampl_gain(gains_list): """ The gains_list, six or more integers of 0 and 1, is passed from the PC to the ESP8266 using the 'pyboard' library for the communication with the target board ESP8266 via the USB port. The code runned on the ESP8266 MicroPython puts the GPIO's to H or L state in corresponding to the gains_list values. :param: gains_list list of 1 or 0 integers :return: True if successful, else False """ N_BITS = len(gains_list) # Number of bits required """ The 'pyboard' module is imported here to allow the communication with the target board ESP8266 via the USB connection. The modules 'machine' and 'utime' are imported to the target ESP8266 using the 'exec' method of 'pyb' who is an instance of the class 'pyboard.Pyboard'. """ pyb = pyboard.Pyboard('/dev/ttyUSB0', 115200) # Port, Speed pyb.enter_raw_repl() # Entering in the raw mode pyb.exec('import machine') # exec commands in the ESP8266 space pyb.exec('import utime') # Timing library, equivalent to 'time' pyb.exec('machine.SOFT_RESET') # Reset the python interpreter, erase variables """ Disable the ESP8266 Wifi section reducing imput current from 80 mA to less 10 mA. """ pyb.exec('import network') pyb.exec('sta_if = network.WLAN(network.STA_IF)') pyb.exec('sta_if.active(False)') pyb.exec('ap_if = network.WLAN(network.AP_IF)') pyb.exec('ap_if.active(False)') """ Import variables to the ESP8266 working space: must be passed as strings. """ N = str(N_BITS) g = str(gains_list) pyb.exec('N_BITS = ' + N) # Assign to the ESP8266 space pyb.exec('gains_list = ' + g) pyb.exec('OFF = 0; ON = 1') pyb.exec('GPIO_PIN = (5, 4, 0, 2, 14, 12, 13, 15)') # ESP8266 pins whose names are: D1, D2, D3, D4, D5, D6, D7, D8 """ Put all output to Off """ pyb.exec('for i in GPIO_PIN: \n\t' + 'led = machine.Pin(i, machine.Pin.OUT) \n\t' + # Scanning from Left to Right (inessential) 'led.value(OFF)\n') """ Write the GPIO with assigned bit values """ pyb.exec('for i in range(N_BITS): \n\t' + 'led = machine.Pin(GPIO_PIN[i], machine.Pin.OUT) \n\t' + # Scanning from Left to Right 'val = gains_list[N_BITS-i-1] \n\t' + # Scanning from Right to Left 'led.value(val)\n') """ Invert the level of a selectable GPIO[n] to see if the seccessive check of all GPIO's is capable to catch the error, n must be changed in the testing phase. At the end of the test set: TEST_ERR = False """ if TEST_ERR: # Led_5 Led_4 Led_3 Led_2 Led_1 Led_0 # n : 5 4 3 2 1 0 pyb.exec('n = 3 \n' + 'led = machine.Pin(GPIO_PIN[n], machine.Pin.OUT) \n' + # Scanning from Left to Right 'val = bool(gains_list[n-i-1]) \n' + # Scanning from Right to Left 'led.value(not bool(val))\n') # # """ Read all used GPIO's and then verify if their states are correct. """ pyb.exec('status = []') pyb.exec('for i in range(N_BITS): \n\t' + 'led = machine.Pin(GPIO_PIN[N_BITS-i-1], machine.Pin.OUT) \n\t' + # Scanning from Right to Left 'status.append(led.value())\n') # # good = False status_str = pyb.exec('print(status)\n').decode() # Export from the ESP8266 space the bool is_OK print("status_str =", status_str[0:-2]) print("str(gains_list) =", str(gains_list)) is_good = status_str[0:-2] == str(gains_list) print(is_good) if is_good: return True else: return False
import re import matplotlib.pyplot as plt root = Tk.Tk() root.wm_title("Gleichstrombrücke") f = Figure(figsize=(5, 4), dpi=100) a = f.add_subplot(111) t = arange(0.0, 20.0, 1.0) s = [] a.set_ylim([0, 4200]) a.set_xlim([0, 100]) line1, = a.plot([], [], 'r.') #pyb1 = pyboard.Pyboard(device = "/dev/tty.usbmodem1412") pyb1 = pyboard.Pyboard(device="/dev/ttyACM0") pyb1.enter_raw_repl() #output = pyb1.execfile("test.py") pyb1.exec_('import time') pyb1.exec_('from resistor import Resistor') pyb1.exec_('res = Resistor()') value = 1000 def set_resistor_step(res1, res2, resistor_step=100.0, sleeptime=0.5): """Starts with a resistor value and increases the resistor in a specified step till the second resistor value.""" if res1 <= res2: if res1 < 1000.0: res1 = 1000.0 if res2 > 4196.875:
def __init__(self, device): self.device = device self.pyb = pyboard.Pyboard(device) self.pyb.enter_raw_repl() self.finished = True
def main(): cmd_parser = argparse.ArgumentParser( description='Run benchmarks for MicroPython') cmd_parser.add_argument('-t', '--diff-time', action='store_true', help='diff time outputs from a previous run') cmd_parser.add_argument('-s', '--diff-score', action='store_true', help='diff score outputs from a previous run') cmd_parser.add_argument('-p', '--pyboard', action='store_true', help='run tests via pyboard.py') cmd_parser.add_argument('-d', '--device', default='/dev/ttyACM0', help='the device for pyboard.py') cmd_parser.add_argument('-a', '--average', default='8', help='averaging number') cmd_parser.add_argument( 'N', nargs=1, help='N parameter (approximate target CPU frequency)') cmd_parser.add_argument( 'M', nargs=1, help='M parameter (approximate target heap in kbytes)') cmd_parser.add_argument('files', nargs='*', help='input test files') args = cmd_parser.parse_args() if args.diff_time or args.diff_score: compute_diff(args.N[0], args.M[0], args.diff_score) sys.exit(0) # N, M = 50, 25 # esp8266 # N, M = 100, 100 # pyboard, esp32 # N, M = 1000, 1000 # PC N = int(args.N[0]) M = int(args.M[0]) n_average = int(args.average) if args.pyboard: target = pyboard.Pyboard(args.device) target.enter_raw_repl() else: target = MICROPYTHON if len(args.files) == 0: tests_skip = ('benchrun.py', ) if M <= 25: # These scripts are too big to be compiled by the target tests_skip += ('bm_chaos.py', 'bm_hexiom.py', 'misc_raytrace.py') tests = sorted( BENCH_SCRIPT_DIR + test_file for test_file in os.listdir(BENCH_SCRIPT_DIR) if test_file.endswith('.py') and test_file not in tests_skip) else: tests = sorted(args.files) print('N={} M={} n_average={}'.format(N, M, n_average)) run_benchmarks(target, N, M, n_average, tests) if isinstance(target, pyboard.Pyboard): target.exit_raw_repl() target.close()
to_write = data[:1000] data = data[1000:] p.serial.write(to_write) p.serial.flush() log(p.read_until(1, b"#DONE\n")) device = '/dev/ttyACM0' try: # Close all processes talking to such device pkill("-f", device) except: pass p = pyboard.Pyboard(device) p.serial.write(b'\r\x03\x03') # ctrl-C twice: interrupt any running program p.serial.write(b'\x04') # ctrl-D: soft reset log(p.read_until(1, b"#READY TO UPLOAD\n")) for f in os.listdir('.'): if not f.endswith('.py'): continue copy(f) p.serial.write(b'\x04') # ctrl-D: soft reset
def __init__(self, dev='/dev/ttyACM0'): self.dev = dev self.pyb = pyboard.Pyboard(self.dev) self.pyb.enter_raw_repl() self.prikaz('import ovlhw411') print('pripojeno {}'.format(self.dev))
def test_board(serial_port, mac, fw_version): pyb = pyboard.Pyboard(serial_port) run_program_script(pyb, mac, fw_version) return detect_test_status(pyb)
print("let's just take up some space") print("let's just take up some space") print("let's just take up some space") print("let's just take up some space") print("let's just take up some space") print("let's just take up some space") print("let's just take up some space") print("let's just take up some space") print("let's just take up some space") print("let's just take up some space") print("let's just take up some space") print("let's just take up some space") print("let's just take up some space") print("let's just take up some space") print("let's just take up some space") """ pb = pyboard.Pyboard("/dev/ttyACM0") print("Got connection") pb.enter_raw_repl() pb.exec_(thread_script, data_consumer=print) #pb.exec_(direct_script, data_consumer=print) time.sleep(15) pb.serial.read_all( ) # Othewise exec_ gets confused by the output of the thread pb.enter_raw_repl() pb.exec_(second_script, data_consumer=print) pb.exec_("print('__thonny_helper' in dir())", data_consumer=print)
#!/usr/bin/env python3 import inspect import pyboard pyb = pyboard.Pyboard('/dev/cu.usbmodem3389337E34332') def remote(func): def wrapper(*args, **kwargs): return do_remote(func, *args, **kwargs) return wrapper def do_remote(func, *args, **kwargs): func_name = func.__name__ func_src = inspect.getsource(func).replace('@remote\n', '') args_arr = [repr(i) for i in args] kwargs_arr = ["{}={}".format(k, repr(v)) for k, v in kwargs.items()] func_src += 'print(repr(' + func_name + '(' + ', '.join( args_arr + kwargs_arr) + ')))\n' pyb.enter_raw_repl() output = pyb.exec(func_src) pyb.exit_raw_repl() return eval(output) @remote def foo(x): return x * 2
print('-----') return output def getHey(): return "Hey" def getWhy(): return "Why" def getInt(): return 23 def getList(): return [1, 2, 3] def getBytes(): return bytearray([1, 2, 3]) pybo = pyboard.Pyboard('COM5') pybo.enter_raw_repl() pybo.exec_("import ayo") print remote(pybo, getInt) print remote(pybo, getList) # print pybo.exec_raw("ayo.getInt()") # print pybo.exec_raw("ayo.getList()") # print pybo.exec_raw("ayo.getBytes()") pybo.exit_raw_repl() pybo.close()
def main(): cmd_parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description="""Run and manage tests for MicroPython. Tests are discovered by scanning test directories for .py files or using the specified test files. If test files nor directories are specified, the script expects to be ran in the tests directory (where this file is located) and the builtin tests suitable for the target platform are ran. When running tests, run-tests.py compares the MicroPython output of the test with the output produced by running the test through CPython unless a <test>.exp file is found, in which case it is used as comparison. If a test fails, run-tests.py produces a pair of <test>.out and <test>.exp files in the result directory with the MicroPython output and the expectations, respectively. """, epilog="""\ Options -i and -e can be multiple and processed in the order given. Regex "search" (vs "match") operation is used. An action (include/exclude) of the last matching regex is used: run-tests.py -i async - exclude all, then include tests containing "async" anywhere run-tests.py -e '/big.+int' - include all, then exclude by regex run-tests.py -e async -i async_foo - include all, exclude async, yet still include async_foo """, ) cmd_parser.add_argument("--target", default="unix", help="the target platform") cmd_parser.add_argument( "--device", default="/dev/ttyACM0", help="the serial device or the IP address of the pyboard", ) cmd_parser.add_argument( "-b", "--baudrate", default=115200, help="the baud rate of the serial device" ) cmd_parser.add_argument("-u", "--user", default="micro", help="the telnet login username") cmd_parser.add_argument("-p", "--password", default="python", help="the telnet login password") cmd_parser.add_argument( "-d", "--test-dirs", nargs="*", help="input test directories (if no files given)" ) cmd_parser.add_argument( "-r", "--result-dir", default=base_path("results"), help="directory for test results" ) cmd_parser.add_argument( "-e", "--exclude", action=append_filter, metavar="REGEX", dest="filters", help="exclude test by regex on path/name.py", ) cmd_parser.add_argument( "-i", "--include", action=append_filter, metavar="REGEX", dest="filters", help="include test by regex on path/name.py", ) cmd_parser.add_argument( "--write-exp", action="store_true", help="use CPython to generate .exp files to run tests w/o CPython", ) cmd_parser.add_argument( "--list-tests", action="store_true", help="list tests instead of running them" ) cmd_parser.add_argument( "--emit", default="bytecode", help="MicroPython emitter to use (bytecode or native)" ) cmd_parser.add_argument("--heapsize", help="heapsize to use (use default if not specified)") cmd_parser.add_argument( "--via-mpy", action="store_true", help="compile .py files to .mpy first" ) cmd_parser.add_argument("--mpy-cross-flags", default="", help="flags to pass to mpy-cross") cmd_parser.add_argument( "--keep-path", action="store_true", help="do not clear MICROPYPATH when running tests" ) cmd_parser.add_argument( "-j", "--jobs", default=multiprocessing.cpu_count(), metavar="N", type=int, help="Number of tests to run simultaneously", ) cmd_parser.add_argument("files", nargs="*", help="input test files") cmd_parser.add_argument( "--print-failures", action="store_true", help="print the diff of expected vs. actual output for failed tests and exit", ) cmd_parser.add_argument( "--clean-failures", action="store_true", help="delete the .exp and .out files from failed tests and exit", ) args = cmd_parser.parse_args() if args.print_failures: for exp in glob(os.path.join(args.result_dir, "*.exp")): testbase = exp[:-4] print() print("FAILURE {0}".format(testbase)) os.system("{0} {1}.exp {1}.out".format(DIFF, testbase)) sys.exit(0) if args.clean_failures: for f in glob(os.path.join(args.result_dir, "*.exp")) + glob( os.path.join(args.result_dir, "*.out") ): os.remove(f) sys.exit(0) LOCAL_TARGETS = ( "unix", "qemu-arm", ) EXTERNAL_TARGETS = ("pyboard", "wipy", "esp8266", "esp32", "minimal", "nrf") if args.target in LOCAL_TARGETS or args.list_tests: pyb = None elif args.target in EXTERNAL_TARGETS: global pyboard sys.path.append(base_path("../tools")) import pyboard pyb = pyboard.Pyboard(args.device, args.baudrate, args.user, args.password) pyb.enter_raw_repl() else: raise ValueError("target must be one of %s" % ", ".join(LOCAL_TARGETS + EXTERNAL_TARGETS)) if len(args.files) == 0: if args.test_dirs is None: test_dirs = ( "basics", "micropython", "misc", "extmod", ) if args.target == "pyboard": # run pyboard tests test_dirs += ("float", "stress", "pyb", "pybnative", "inlineasm") elif args.target in ("esp8266", "esp32", "minimal", "nrf"): test_dirs += ("float",) elif args.target == "wipy": # run WiPy tests test_dirs += ("wipy",) elif args.target == "unix": # run PC tests test_dirs += ( "float", "import", "io", "stress", "unicode", "unix", "cmdline", ) elif args.target == "qemu-arm": if not args.write_exp: raise ValueError("--target=qemu-arm must be used with --write-exp") # Generate expected output files for qemu run. # This list should match the test_dirs tuple in tinytest-codegen.py. test_dirs += ( "float", "inlineasm", "qemu-arm", ) else: # run tests from these directories test_dirs = args.test_dirs tests = sorted( test_file for test_files in (glob("{}/*.py".format(dir)) for dir in test_dirs) for test_file in test_files ) else: # tests explicitly given tests = args.files if not args.keep_path: # clear search path to make sure tests use only builtin modules and those in extmod os.environ["MICROPYPATH"] = ".frozen" + os.pathsep + base_path("../extmod") try: os.makedirs(args.result_dir, exist_ok=True) res = run_tests(pyb, tests, args, args.result_dir, args.jobs) finally: if pyb: pyb.close() if not res: sys.exit(1)
def send_file(pyb, src, dest): template = "with open('{}', 'w') as f:\n f.write('''{}''')\n\n" with open(src, 'r') as f: code = f.read() code = code.replace("\\", "\\\\") pyb.exec(template.format(dest, code)) print("Make sure your badge is connected and awake.") #print("Opening direct serial connection...") #with serial.Serial(SERIAL_PORT, SERIAL_BAUD) as f: # pass print("Opening pyboard connection...") pyb = pyboard.Pyboard(SERIAL_PORT) print("Starting python shell...") pyb.serial.write(b'\r\n') pyb.read_until(1, b"\r\n>>> ") print("Entering raw mode...") pyb.enter_raw_repl() for pair in sys.argv[1:]: src, _, dest = pair.partition(':') print("Sending file {} to {}...".format(src, dest)) send_file(pyb, src, dest) print("Exiting raw mode...") pyb.exit_raw_repl()
def test_board(serial_port): pyb = pyboard.Pyboard(serial_port) run_program_script(pyb) return detect_test_status(pyb)
import pyboard import sys PORT = sys.argv[1] pyb = pyboard.Pyboard(PORT) pyb.enter_raw_repl() result = 0 out = pyb.exec( """ try: import d1_mini import uasyncio import tm1640 import max7219 import ssd1306 except Exception as e: print('Test failed, %s: %s' % (e.__class__.__name__, str(e))) else: print('Test successful!') """ ) print(out) if b"Test successful!" not in out: result = -1 pyb.exit_raw_repl() result