sensor.reset() sensor.set_pixformat(sensor.RGB565) sensor.set_framesize(sensor.QVGA) sensor.set_windowing((224, 224)) sensor.set_vflip(0) sensor.set_hmirror(0) sensor.run(1) if (paraFileName in filesInSd) and (lableFileName in filesInSd): print('parameter and label found, skip training.') else: print('parameter and label not found, start training.') counter = 0 labelCounter = 0 f = open('/sd/' + paraFileName, 'wb') for info in uos.ilistdir('/sd/'): #look for tm* directories if (info[1] == 0x4000 and info[0].startswith('tm_')): className = info[0][3:] classPath = '/sd/' + info[0] imgFileNames = uos.listdir(classPath) for imgFileName in imgFileNames: if (not imgFileName.startswith('.') ) and imgFileName.endswith('.jpg'): #avoid trash on mac myImage = image.Image(classPath + "/" + imgFileName) lcd.display(myImage, oft=(0, 0)) lcd.draw_string(0, 0, "Training " + imgFileName) myImage.pix_to_ai() fmap = kpu.forward(task, myImage) del myImage data = fmap[:] data = getNormalizedVec(data)
#!/opt/bin/lv_micropython import uos as os import uerrno as errno iter = os.ilistdir() IS_DIR = 0x4000 IS_REGULAR = 0x8000 while True: try: entry = next(iter) filename = entry[0] file_type = entry[1] if filename == 'boot.py': continue else: print("===============================") print(filename, end="") if file_type == IS_DIR: print(", File is a directory") print("===============================") else: print("\n===============================") #print("Contents:") #with open(filename) as f: # for line in enumerate(f): # print("{}".format(line[1]),end="") #print("") exec(open(filename).read(), globals()) except StopIteration: break
img_reader = None if snapshot_source else image.ImageReader("/img1.bin") # create a directory to hold images try: uos.mkdir("/binImgs") except OSError: print("path '/binImgs' already existed.") jMax = 0 tagFileName = 'img' while (True): clock.tick() img = sensor.snapshot() if snapshot_source else img_reader.next_frame( copy_to_fb=True, loop=False) # Do machine vision algorithms on the image here. imgDir = uos.ilistdir("/binImgs") for j in imgDir: if j[1] == 0x8000: imgFileName = j[0] if imgFileName[0:3] == tagFileName: if int(imgFileName[3:-4]) >= jMax: jMax = int(imgFileName[3:-4]) + 1 streamImgName = '/binImgs/' + tagFileName + str(jMax) + '.bmp' try: img.save(streamImgName) print('image ' + str(jMax) + ' saved.') except AttributeError: print("image save failed.") print(clock.fps())
def file_exists(filename): for file in uos.ilistdir(): if (file[0] == filename): return True return False
def main(): print( ' __ __ ___ _______ ______ _______ _______ __ __ _______ _______ ' ) print( '| |_| || | | || _ | | || || | | || || |' ) print( '| || | | || | || | _ || _ || |_| || _ || _____|' ) print( '| || | | || |_||_ | | | || |_| || || | | || |_____ ' ) print( '| || | | _|| __ || |_| || ___||_ _|| |_| ||_____ |' ) print( '| ||_|| || | | |_ | | | || || | | | | | _____| |' ) print( '|_| |_||___| |_______||___| |_||_______||___| |___| |_______||_______|' ) print('small OS for micropython ver ' + version + ' by theCodeman') print('https://github.com/TheCodeman/myos') print('MicroPython Version : {} Platform : {}'.format( sys.version, sys.platform)) timer.init(period=1000, mode=machine.Timer.PERIODIC, callback=intCallback) while True: str = input(uos.getcwd() + '>') cmd = str.split() # print(cmd) if len(str) != 0: if cmd[0] == 'cd': try: uos.chdir(cmd[1]) except: print('bad dir') elif cmd[0] == 'ls': print('Current Directory ', uos.getcwd()) total = 0 #F 1366 lora.py print('Type Size Filename') print('----------------------------------') if len(cmd) == 2: path = cmd[1] else: path = uos.getcwd() try: for l in uos.ilistdir(path): if l[1] & 0x4000: print('D{0:>31}'.format(l[0])) else: # F 3360 myos.py total += int(uos.stat(l[0])[6]) print('F {0:<8}{1:>16}'.format( uos.stat(l[0])[6], l[0])) print('----------------------------------') print('File Size Total: {0}'.format(total)) except Exception as e: print(e) elif cmd[0] == 'cp': if len(cmd) == 3: try: with open(cmd[1], 'rb') as source: print('Source {0}'.format(cmd[1])) data = source.read() source.close() except Exception as e: print(e) try: with open(cmd[2], 'wb') as dest: print('Dest {0}'.format(cmd[2])) dest.write(data) dest.close() except Exception as e: print(e) else: print( 'cp requires source filename and destination filename ' ) elif cmd[0] == 'run': if len(cmd) == 2: __import__(cmd[1]) del sys.modules[cmd[1]] else: print('Need File Name') elif cmd[0] == 'lr': if networkUp: if len(cmd) == 1: res = ssh.list(settings.remoteIP + settings.remotePath, settings.uname, settings.upass) else: res = ssh.list( settings.remoteIP + settings.remotePath + cmd[1], settings.uname, settings.upass) print(res[0]) if res[0] == 0: print(res[1]) print(res[2]) else: print('No Network Connection') elif cmd[0] == 'put': if networkUp: res = ssh.put(settings.remoteIP + settings.remotePath + cmd[1], settings.uname, settings.upass, file=cmd[1]) if res[0] == 0: print('File %s copied to %s' % (cmd[1], settings.remotePath)) else: print('No Network Connection') elif cmd[0] == 'get': if networkUp: res = ssh.get(settings.remoteIP + settings.remotePath + cmd[1], settings.uname, settings.upass, file='$$$.tmp') if res[0] == 0: try: uos.remove(cmd[1]) except: pass uos.rename('$$$.tmp', cmd[1]) print('File %s copied from %s' % (cmd[1], settings.remotePath)) else: uos.remove('$$$.tmp') print('File Not Found') else: print('No Network Connection') elif cmd[0] == 'edit': pye(cmd[1]) elif cmd[0] == 'rm': try: uos.remove(cmd[1]) except: print('no file') elif cmd[0] == 'md': try: uos.mkdir(cmd[1]) except: print("Need Directory Name") elif cmd[0] == 'rmdir': try: uos.rmdir(cmd[1]) except: print("Need Directory Name") elif cmd[0] == 'reset': machine.reset() elif cmd[0] == 'cat': line = 0 try: f = open(cmd[1], 'r') while True: str = f.readline() if str == "": break print(str, end="") line += 1 if line > 25: print( '----- press space to continue or q to quit -----', end="") ret = getch() print( '\r \r', end="") if ret == 'q': break else: line = 0 f.close() except: print('no file') elif cmd[0] == 'time': print('Time set to: {}'.format( utime.strftime('%c', utime.localtime()))) elif cmd[0] == 'df': if len(cmd) == 1: fs_stat = uos.statvfs(uos.getcwd()) else: fs_stat = uos.statvfs(cmd[1]) fs_size = fs_stat[0] * fs_stat[2] fs_free = fs_stat[0] * fs_stat[3] print('File System Size {:,} - Free Space {:,}'.format( fs_size, fs_free)) elif cmd[0] == 'wget': if networkUp: try: response = urequests.get(cmd[1]) if response.status_code == 200: print(type(response)) print(response.text) print(type(response.text)) fileName = cmd[1].split('/') print(fileName) print(fileName[-1]) f = open(fileName[-1], 'w') f.write(response.text) f.close() else: print('Error: {0} {1}'.format( response.status_code, response.reason.decode('utf-8'))) except Exception as e: print(e) else: print('No Network Connection') elif cmd[0] == 'wifi': try: if cmd[1] == 'active': nic.active(True) if cmd[1] == 'deactive': nic.active(False) if cmd[1] == 'config': status = nic.ifconfig() print( 'IP: {0}\n\rSubnet: {1}\r\nGateway: {2}\r\nDNS: {3}' .format(status[0], status[1], status[2], status[3])) if cmd[1] == 'isconnected': print(nic.isconnected()) if cmd[1] == 'connect': try: nic.connect(cmd[2], cmd[3]) except Exception as e: print(e) if cmd[1] == 'scan': stations = nic.scan() for s in stations: if s[4] == 0: authmode = 'Open' if s[4] == 1: authmode = 'Wep' if s[4] == 2: authmode = 'WPA-PSK' if s[4] == 3: authmode = 'WPA2-PSK' if s[4] == 4: authmode = 'WPA/WPA2-PSK' print( 'SSID: {0:<32} Channel: {1} RSSSI: {2} Auth Type: {3}' .format(s[0].decode('utf-8'), s[2], s[3], authmode)) except Exception as e: print(e) print(' no action') elif cmd[0] == 'umountsd': try: uos.umountsd() except Exception as e: print(e) elif cmd[0] == 'mountsd': try: uos.mountsd() except Exception as e: print(e) elif cmd[0] == 'help': print('Command List') print('----------------------------------') print('ls - list files current directory') print( 'lr - list files on remote server optional directory') print('cat - display file') print('rm - remove file') print('df - display drive space') print('time - display time and date') print('get - scp from server') print('put - scp to server') print('md - make directory') print('rmdir - remove directory') print('run - run python script') print('edit - edit file using pye') print('modules - list installed modules') print('reset - reset board') print('wget - get file over http and save to file') print('----------------------------------') elif cmd[0] == 'exit': timer.deinit() return 1 elif cmd[0] == 'update': if networkUp: res = ssh.get(settings.remoteIP + settings.remotePath + 'micropyos.py', settings.uname, settings.upass, file='$$$.tmp') if res[0] == 0: try: uos.remove('micropyos.py') except: pass uos.rename('$$$.tmp', 'micropyos.py') print('File %s copied from %s' % ('micropyos.py', settings.remotePath)) else: uos.remove('$$$.tmp') print('File Not Found') timer.deinit() return 2 else: print('No Network Connection') elif cmd[0] == 'modules': for m in sys.modules: print(m) elif cmd[0] == 'settings': pye('settings.py') else: print('unknown command')
# stat root dir print(uos.stat('/')) # statvfs root dir; verify that f_namemax has a sensible size print(uos.statvfs('/')[9] >= 32) # getcwd when in root dir print(uos.getcwd()) # basic mounting and listdir uos.mount(Filesystem(1), '/test_mnt') print(uos.listdir()) # ilistdir i = uos.ilistdir() print(next(i)) try: next(i) except StopIteration: print('StopIteration') try: next(i) except StopIteration: print('StopIteration') # referencing the mount point in different ways print(uos.listdir('test_mnt')) print(uos.listdir('/test_mnt')) # mounting another filesystem
def delete_files(): for num, filename in enumerate(uos.listdir()): print(filename) if (len(filename) > 9 and filename[-8:] == ".jpg.bmp"): uos.remove(filename) def list_files(): for num, filename in enumerate(uos.listdir()): if (len(filename) > 9 and filename[-8:] == ".jpg.bmp"): print("found file", filename) else: print(filename) list_files() for file in uos.ilistdir(): out_string = "" if (file[1] == 0x4000): print('d - -', file[0]) else: print('-', str(utime.localtime(uos.stat(file[0])[8])), str(uos.stat(file[0])[6]) + "B", file[0]) #for num, thing in enumerate(uos.stat(file[0])): #out_string += ('0x{0:02x}, '.format(thing)) #print(out_string)
def listdir(): return [directory for directory, _, _ in ilistdir()]
import sensor, image, pyb, time import uos # print("branch test.") record_time = 50000 # 50 seconds in milliseconds sensor.reset() sensor.set_pixformat(sensor.RGB565) # sensor.set_framesize(sensor.QQVGA) sensor.set_framesize(sensor.QVGA) # Set frame size to QVGA (320x240) # sensor.skip_frames(time = 2000) sensor.skip_frames(time=20000) clock = time.clock() curDir = uos.ilistdir() iMax = 0 tagFileName = 'img' for i in curDir: if i[1] == 0x8000: fileName = i[0] #print(fileName[0:5]) if fileName[0:3] == tagFileName: if int(fileName[3:-4]) >= iMax: iMax = int(fileName[3:-4]) + 1 streamFileName = tagFileName + str(iMax) + '.bin' img_writer = image.ImageWriter(streamFileName) # create a directory to hold images
import urequests from uhashlib import sha1 from ubinascii import hexlify else: import os as uos import requests as urequests from hashlib import sha1 from binascii import hexlify import stat try: uos.listdir() listdir = uos.listdir except AttributeError: listdir = lambda p: [ x[0] for x in uos.ilistdir(p) if not x[0] in ['.', '..'] ] __all__ = ["exists", "ls", "rm", "pwd", "mkdir", "cd", "mv", "saveas"] def exists(path): try: uos.stat(path) return True except OSError: return False def ls(path="./"): return listdir(path)
# Before we can import the user's keymap, we need to wrangle sys.path to # add our stub modules. Before we can do THAT, we have to figure out where # we actually are, and that's not the most trivial thing in MicroPython! # # The hack here is to see if we can find ourselves in whatever uPy thinks # the current directory is. If we can, we need to head up a level. Obviously, # if the layout of the KMK repo ever changes, this script will need updated # or all hell will break loose. # First, hack around https://github.com/micropython/micropython/issues/2322, # where frozen modules aren't available if MicroPython is running a script # rather than via REPL sys.path.insert(0, '') if any(fname == 'keymap_sanity_check.py' for fname, _, _ in uos.ilistdir()): sys.path.extend(('../', '../upy-unix-stubs/')) else: sys.path.extend(('./', './upy-unix-stubs')) user_keymap = __import__(user_keymap_file) if hasattr(user_keymap, 'cols') or hasattr(user_keymap, 'rows'): assert hasattr( user_keymap, 'cols'), 'Handwired keyboards must have both rows and cols defined' assert hasattr( user_keymap, 'rows'), 'Handwired keyboards must have both rows and cols defined' # Ensure that no pins are duplicated in a handwire config
# Hello World Example # # Welcome to the OpenMV IDE! Click on the green run arrow button below to run the script! import sensor, image, time import utime, urandom, uos sensor.reset() # Reset and initialize the sensor. sensor.set_pixformat( sensor.RGB565) # Set pixel format to RGB565 (or GRAYSCALE) sensor.set_framesize(sensor.QVGA) # Set frame size to QVGA (320x240) # sensor.set_framesize(sensor.VGA) sensor.skip_frames(time=2000) # Wait for settings take effect. clock = time.clock() # Create a clock object to track the FPS. curDir = uos.ilistdir() iMax = 0 for i in curDir: if i[1] == 0x8000: fileName = i[0] #print(fileName[0:5]) if fileName[0:3] == 'img': if int(fileName[3:-4]) >= iMax: iMax = int(fileName[3:-4]) + 1 streamFileName = 'img' + str(iMax) + '.bin' print(streamFileName) while (True): clock.tick() # Update the FPS clock. img = sensor.snapshot() # Take a picture and return the image.
async def clone_start(*a): # Begins cloning process, on target device. from files import CardSlot, CardMissingError ch = await ux_show_story( '''Insert a MicroSD card and press OK to start. A small \ file with an ephemeral public key will be written.''') if ch != 'y': return # pick a random key pair, just for this cloning session pair = ngu.secp256k1.keypair() my_pubkey = pair.pubkey().to_bytes(False) # write to SD Card, fixed filename for ease of use try: with CardSlot() as card: fname, nice = card.pick_filename('ccbk-start.json', overwrite=True) with open(fname, 'wb') as fd: fd.write(ujson.dumps(dict(pubkey=b2a_hex(my_pubkey)))) except CardMissingError: await needs_microsd() return except Exception as e: await ux_show_story('Error: ' + str(e)) return # Wait for incoming clone file, allow retries ch = await ux_show_story( '''Keep power on this Coldcard, and take MicroSD card \ to source Coldcard. Select Advanced > MicroSD > Clone Coldcard to write to card. Bring that card \ back and press OK to complete clone process.''') while 1: if ch != 'y': # try to clean up, but card probably not there? No errors. try: with CardSlot() as card: uos.remove(fname) except: pass await ux_dramatic_pause('Aborted.', 2) return # Hopefully we have a suitable 7z file now. Pubkey in the filename incoming = None try: with CardSlot() as card: for path in card.get_paths(): for fn, ftype, *var in uos.ilistdir(path): if fn.endswith('-ccbk.7z'): incoming = path + '/' + fn his_pubkey = a2b_hex(fn[0:66]) assert len(his_pubkey) == 33 assert 2 <= his_pubkey[0] <= 3 break except CardMissingError: await needs_microsd() continue except Exception as e: pass if incoming: break ch = await ux_show_story( "Clone file not found. OK to try again, X to stop.") # calculate point session_key = pair.ecdh_multiply(his_pubkey) # "password" is that hex value words = [b2a_hex(session_key).decode()] def delme(xfn): # Callback to delete file after its read; could still fail but # need to start over in that case anyway. uos.remove(xfn) uos.remove(fname) # ccbk-start.json # this will reset in successful case, no return (but delme is called) prob = await restore_complete_doit(incoming, words, file_cleanup=delme) if prob: await ux_show_story(prob, title='FAILED')
async def file_picker(msg, suffix=None, min_size=1, max_size=1000000, taster=None, choices=None, escape=None): # present a menu w/ a list of files... to be read # - optionally, enforce a max size, and provide a "tasting" function # - if msg==None, don't prompt, just do the search and return list # - if choices is provided; skip search process # - escape: allow these chars to skip picking process from menu import MenuSystem, MenuItem import uos from utils import get_filesize if choices is None: choices = [] try: with CardSlot() as card: sofar = set() for path in card.get_paths(): for fn, ftype, *var in uos.ilistdir(path): if ftype == 0x4000: # ignore subdirs continue if suffix and not fn.lower().endswith(suffix): # wrong suffix continue if fn[0] == '.': continue full_fname = path + '/' + fn # Conside file size # sigh, OS/filesystem variations file_size = var[1] if len(var) == 2 else get_filesize( full_fname) if not (min_size <= file_size <= max_size): continue if taster is not None: try: yummy = taster(full_fname) except IOError: #print("fail: %s" % full_fname) yummy = False if not yummy: continue label = fn while label in sofar: # just the file name isn't unique enough sometimes? # - shouldn't happen anymore now that we dno't support internal FS # - unless we do muliple paths label += path.split('/')[-1] + '/' + fn sofar.add(label) choices.append((label, path, fn)) except CardMissingError: # don't show anything if we're just gathering data if msg is not None: await needs_microsd() return None if msg is None: return choices if not choices: msg = 'Unable to find any suitable files for this operation. ' if suffix: msg += 'The filename must end in "%s". ' % suffix msg += '\n\nMaybe insert (another) SD card and try again?' await ux_show_story(msg) return # tell them they need to pick; can quit here too, but that's obvious. if len(choices) != 1: msg += '\n\nThere are %d files to pick from.' % len(choices) else: msg += '\n\nThere is only one file to pick from.' ch = await ux_show_story(msg, escape=escape) if escape and ch in escape: return ch if ch == 'x': return picked = [] async def clicked(_1, _2, item): picked.append('/'.join(item.arg)) the_ux.pop() items = [ MenuItem(label, f=clicked, arg=(path, fn)) for label, path, fn in choices ] if 0: # don't like; and now showing count on previous page if len(choices) == 1: # if only one choice, we could make the choice for them ... except very confusing items.append(MenuItem(' (one file)', f=None)) else: items.append(MenuItem(' (%d files)' % len(choices), f=None)) menu = MenuSystem(items) the_ux.push(menu) await menu.interact() return picked[0] if picked else None
def listdir(path): return [ item[0] for item in uos.ilistdir(path) if item[0] not in ('.', '..') ]
async def ondevice_multisig_create(mode='p2wsh', addr_fmt=AF_P2WSH): # collect all xpub- exports on current SD card (must be > 1) # - ask for M value # - create wallet, save and also export # - also create electrum skel to go with that # - only expected to work with our ccxp-foo.json export files. from actions import file_picker import uos, ujson from utils import get_filesize from main import settings chain = chains.current_chain() my_xfp = settings.get('xfp') xpubs = [] files = [] has_mine = False deriv = None try: with CardSlot() as card: for path in card.get_paths(): for fn, ftype, *var in uos.ilistdir(path): if ftype == 0x4000: # ignore subdirs continue if not fn.startswith('ccxp-') or not fn.endswith('.json'): # wrong prefix/suffix: ignore continue full_fname = path + '/' + fn # Conside file size # sigh, OS/filesystem variations file_size = var[1] if len(var) == 2 else get_filesize( full_fname) if not (0 <= file_size <= 1000): # out of range size continue try: with open(full_fname, 'rt') as fp: vals = ujson.load(fp) ln = vals.get(mode) # value in file is BE32, but we want LE32 internally xfp = str2xfp(vals['xfp']) if not deriv: deriv = vals[mode + '_deriv'] else: assert deriv == vals[mode + '_deriv'], "wrong derivation" node, _, _ = import_xpub(ln) if xfp == my_xfp: has_mine = True xpubs.append( (xfp, chain.serialize_public(node, AF_P2SH))) files.append(fn) except CardMissingError: raise except Exception as exc: # show something for coders, but no user feedback sys.print_exception(exc) continue except CardMissingError: await needs_microsd() return # remove dups; easy to happen if you double-tap the export delme = set() for i in range(len(xpubs)): for j in range(len(xpubs)): if j in delme: continue if i == j: continue if xpubs[i] == xpubs[j]: delme.add(j) if delme: xpubs = [x for idx, x in enumerate(xpubs) if idx not in delme] if not xpubs or len(xpubs) == 1 and has_mine: await ux_show_story( "Unable to find any Coldcard exported keys on this card. Must have filename: ccxp-....json" ) return # add myself if not included already if not has_mine: with stash.SensitiveValues() as sv: node = sv.derive_path(deriv) xpubs.append((my_xfp, chain.serialize_public(node, AF_P2SH))) N = len(xpubs) if N > MAX_SIGNERS: await ux_show_story("Too many signers, max is %d." % MAX_SIGNERS) return # pick useful M value to start assert N >= 2 M = (N - 1) if N < 4 else ((N // 2) + 1) while 1: msg = '''How many need to sign?\n %d of %d Press (7 or 9) to change M value, or OK \ to continue. If you expected more or less keys (N=%d #files=%d), \ then check card and file contents. Coldcard multisig setup file and an Electrum wallet file will be created automatically.\ ''' % (M, N, N, len(files)) ch = await ux_show_story(msg, escape='123479') if ch in '1234': M = min(N, int(ch)) # undocumented shortcut elif ch == '9': M = min(N, M + 1) elif ch == '7': M = max(1, M - 1) elif ch == 'x': await ux_dramatic_pause('Aborted.', 2) return elif ch == 'y': break # create appropriate object assert 1 <= M <= N <= MAX_SIGNERS name = 'CC-%d-of-%d' % (M, N) ms = MultisigWallet(name, (M, N), xpubs, chain_type=chain.ctype, common_prefix=deriv[2:], addr_fmt=addr_fmt) from auth import NewEnrollRequest, active_request active_request = NewEnrollRequest(ms, auto_export=True) # menu item case: add to stack from ux import the_ux the_ux.push(active_request)
#!/usr/bin/micropython import uos DIR = '/mnt/rwfs/upload/' result = '' ll = uos.ilistdir(DIR) for l in ll: name=l[0] if l[1] != 4: result += '<tr>' result += '<td>%s</td>' % name result += '<td><u onclick="downloadFile(\'%s\')" style="cursor: pointer">%s</u></td>' % ( name, name ) result += '<td><u onclick="deleteFile(\'%s\')" style="cursor: pointer">delete</u></td>' % name result += '<td><u onclick="setExecFile(\'%s\')" style="cursor: pointer">change exec</u></td>' % name result += '</tr>' print(result)
# stat root dir print(uos.stat("/")) # statvfs root dir; verify that f_namemax has a sensible size print(uos.statvfs("/")[9] >= 32) # getcwd when in root dir print(uos.getcwd()) # basic mounting and listdir uos.mount(Filesystem(1), "/test_mnt") print(uos.listdir()) # ilistdir i = uos.ilistdir() print(next(i)) try: next(i) except StopIteration: print("StopIteration") try: next(i) except StopIteration: print("StopIteration") # referencing the mount point in different ways print(uos.listdir("test_mnt")) print(uos.listdir("/test_mnt")) # mounting another filesystem
def databases(self): databases = [i[0] for i in uos.ilistdir(self.path)] return databases