Ejemplo n.º 1
0
def rm_r(dir: str) -> None:
    os.chdir(dir)
    for f in os.listdir():
        try:
            os.remove(f)
        except OSError:
            pass
    for f in os.listdir():
        rm_r(f)
    os.chdir("..")
    os.rmdir(dir)
Ejemplo n.º 2
0
def remove_unwanted(dir_or_file: str):
    # remove the leading slashes, since the whole system works on relative paths.
    if dir_or_file.startswith("/"):
        dir_or_file = dir_or_file[1:]
    try:
        # if its a directory, then it should provide some children.
        children = os.listdir(dir_or_file)
    except OSError:
        # probably a file, remove if not required.
        rm_if_not_required(dir_or_file)
    else:
        # probably a directory, remove if not required.
        rmdir_if_not_required(dir_or_file)

        # queue the children to be inspected in next iteration (with correct path).
        for child in children:
            remove_unwanted(dir_or_file + "/" + child)  # pass the full path.
Ejemplo n.º 3
0
    def stat(self, path):
        print(self.id, 'stat', path)
        return (self.id,)
    def statvfs(self, path):
        print(self.id, 'statvfs', path)
        return (self.id,)
    def open(self, file, mode):
        print(self.id, 'open', file, mode)


# first we umount any existing mount points the target may have
try:
    uos.umount('/')
except OSError:
    pass
for path in uos.listdir('/'):
    uos.umount('/' + path)

# 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())
Ejemplo n.º 4
0
import gc
import webrepl
import network
import ujson as json
import uos as os

webrepl.start()
ap_if = network.WLAN(network.AP_IF)
ap_setup_file = "accesspoint.json"

if ap_setup_file in os.listdir():
    # Start the access point.
    if not ap_if.active():
        ap_if.active(True)
    with open(ap_setup_file, "r") as f:
        access_point = json.load(f)
        ap_if.config(essid=access_point["essid"],
                     channel=access_point["channel"],
                     password=access_point["password"])
else:
    if ap_if.active():
        ap_if.active(False)

sta_if = network.WLAN(network.STA_IF)
sta_setup_file = "networks.json"
if sta_setup_file in os.listdir():
    with open(sta_setup_file, "r") as f:
        network_data = json.load(f)
    if not sta_if.active():
        sta_if.active(True)
    available_networks = sta_if.scan()
Ejemplo n.º 5
0
app_file_bytes = bytearray(50)

nvs.get_blob("uninstall_name", app_bytes)
nvs.get_blob("uninstall_file", app_file_bytes)

app = app_bytes.decode("utf-8").rstrip('\x00')
app_file = app_file_bytes.decode("utf-8").rstrip('\x00')

if (not app) or not (app_file):
    system.home()

agreed = interface.confirmation_dialog('Uninstall \'%s\'?' % app)
if not agreed:
    system.home()

interface.loading_text("Removing " + app + "...")
install_path = woezel.get_install_path()
print(app)
print(app_file)
print(install_path)
for rm_file in os.listdir("%s/%s" % (install_path, app_file)):
    os.remove("%s/%s/%s" % (install_path, app_file, rm_file))
os.rmdir("%s/%s" % (install_path, app_file))

nvs.set_blob('uninstall_name', '')
nvs.set_blob('uninstall_file', '')
nvs.commit()

interface.skippabletext("Uninstall completed!")
system.home()
Ejemplo n.º 6
0
def isdir(path):
    try:
        os.listdir(path)
        return True
    except:
        return False
Ejemplo n.º 7
0
    except KeyboardInterrupt:
        sys.exit()

else:
    should_connect_spike_prime = but_a.value() != 0

    initialize_camera()

    task = kpu.load(FEATURE_MODEL)
    info = kpu.netinfo(task)

    feature_list = []

    try:
        files = uos.listdir(IMAGES_DIR)
        for class_num in range(1, MAX_CLASS + 1):
            img_file = str(class_num) + ".jpg"
            if img_file in files:
                img = image.Image(IMAGES_DIR + "/" + img_file, copy_to_fb=True)
                img.draw_rectangle(0,
                                   60,
                                   320,
                                   1,
                                   color=(0, 144, 255),
                                   thickness=10)
                img.draw_string(50,
                                55,
                                "Class:%d" % (class_num, ),
                                color=(255, 255, 255),
                                scale=1)
Ejemplo n.º 8
0
    def umount(self):
        print("umount")

    def open(self, file, mode):
        print("open", file, mode)
        if file not in self.files:
            raise OSError(2)  # ENOENT
        return File(self.files[file])


# First umount any existing mount points the target may have.
try:
    uos.umount("/")
except OSError:
    pass
for path in uos.listdir("/"):
    uos.umount("/" + path)

# Create and mount the VFS object.
files = {
    "/test.py": "print(123)",
}
fs = Filesystem(files)
uos.mount(fs, "/test_mnt")

# Test execfile with a file that doesn't exist.
try:
    execfile("/test_mnt/noexist.py")
except OSError:
    print("OSError")
Ejemplo n.º 9
0
Archivo: cli.py Proyecto: educoay/Dobby
def Run():
    # Dict to hold config
    Config = {}
    # Print entry message
    print("\n   Dobby Command Line Interface\n")
    # Start eternal input loop
    while True:
        # Get_CLI_Input will break true when the user has requested we boot the system
        # After the needed settings is entered
        # This function is the CLI interface printing information and writing settings
        # Get user entry
        try:
            User_Entry = input("Dobby CLI: ")
        except (EOFError, KeyboardInterrupt):
            # If we got interrupted exit
            print("\n\n   Leaving CLI.\n")
            sys.exit()

        # Check if the 200 pound gorilla pressed enter without entering a command
        if User_Entry == "":
            continue

        # Check what we got from the user
        # ---------------------------------------- Help ----------------------------------------
        elif User_Entry.lower() == "help":
            print()
            print("Options marked with * is required configuration")
            print("Avalible commands:")
            print()
            print("   System:")
            print(
                "      boot - Boots the system after neede settings have been entered"
            )
            print("      cat <path> - Prints the content of a file from path")
            print(
                "      config check - Lists all missing settings needed to start Dobby"
            )
            print(
                "      config delete <config name or path> - Deleted the config with the given name or path"
            )
            print("      config dir - Lists all the config files in '/conf'")
            print(
                "      config list - Lists all settings needed to start Dobby and the current value"
            )
            print(
                "      config load <path> - Default: /conf/device.json - Loads the given config"
            )
            print("      config save - Saves the config to file system")
            print("      free memory - Prints the amount of free memory")
            print("      json - Paste a json config string")
            print("      ll <path> - Default: / - Lists content of path")
            print(
                "      log level <1-5> - Default: 1 - 0: Debug - 1: Info - 2: Warning - 3: Error - 4: Critical - 5: Fatal"
            )
            print()
            print("   Communication:")
            print("      wifi ssid <ssid> *")
            print("      wifi password <password> *")
            print()
            print("      mqtt broker <ip address> *")
            print("      mqtt port <port> - Default: 1883")
            print("      mqtt user <username> *")
            print("      mqtt password <password> *")
            print()
            print()
            continue

        # ---------------------------------------- Boot ----------------------------------------
        elif User_Entry.lower() == "boot":

            # Add default settings if needed
            Config.update(DobbyConfig.Defaults_Device(Config))

            # Check if we got all needed settings
            if DobbyConfig.Check_Device(Config) == True:
                # Save config to fs
                if DobbyConfig.Save('device.json', Config) == True:
                    print("   Config saved")
                else:
                    print("   Unable to save config quitting")
                    sys.exit()
                # Log event
                print("   Base config OK. Rebooting")
                # Reboot the device since there is not enough memory to load dobby
                machine.reset()
            else:
                print("   Base config requirements not met unable to boot")
                continue

        # ---------------------------------------- cat ----------------------------------------
        elif User_Entry.lower().startswith("cat ") == True:
            # Check if we got a config store on local fs
            try:

                f = open(User_Entry[4:])
                cat_String = f.read()
                f.close()
            # No config store on fs or other error
            except OSError as e:
                print("   File: " + str[User_Entry[4:]])
                continue

        # ---------------------------------------- Config * ----------------------------------------
        elif User_Entry.lower().startswith("config ") == True:

            # User_Entry[7:] = remove "config " or "CONFIG " or any other combination there of
            User_Entry = User_Entry[7:]

            # ---------------------------------------- Config check ----------------------------------------
            if User_Entry.lower() == "check":
                # Check if we got all needed settings
                if DobbyConfig.Check_Device(Config) == True:
                    print("   Check passed")
                else:
                    print("   Check failed")
                # continue so we dont trigger unknown command
                continue

            # ---------------------------------------- Config delete ----------------------------------------
            elif User_Entry.lower().startswith("delete ") == True:
                User_Entry = User_Entry[7:]
                # Delete file and get resoult
                Resoult = DobbyConfig.Delete(User_Entry)
                if Resoult == True:
                    print("   Config file deleted: " + User_Entry)
                else:
                    print("   Unable to delete config file: " + User_Entry)
                continue

            # ---------------------------------------- Config dir ----------------------------------------
            elif User_Entry.lower() == "dir":

                # for loop to print files in config dir
                for Entry in uos.listdir('/conf'):
                    # print each line stripping ".json" from file name
                    print("   ", Entry.replace(".json", ""))
                continue

            # ---------------------------------------- Config list ----------------------------------------
            elif User_Entry.lower() == "list":
                List_String = ""

                # Add default if missing
                Config.update(DobbyConfig.Defaults_Device(Config))

                # Generate string
                Print_String = ""
                for Key, Value in Config.items():
                    Print_String = Print_String + "   " + str(
                        Key.replace('_', " ")) + ": " + str(Value) + "\n"

                print("\n" + Print_String)
                continue

            # ---------------------------------------- Config load ----------------------------------------
            elif User_Entry.lower().startswith("load") == True:
                # Load with no config specified defaulting to /conf/device.json
                if User_Entry.lower() == "config load":
                    # Load the config
                    Config = DobbyConfig.Load(Config_Name='device',
                                              Delete_On_Error=False)
                else:
                    # Load the config
                    Config = DobbyConfig.Load(Config_Name=None,
                                              Delete_On_Error=False,
                                              Full_Path=User_Entry[12:])
                # Check if we cloud load the config
                if Config == False:
                    Config = {}
                    print("   Unable to load config")
                    # Add defaults
                    Config.update(DobbyConfig.Defaults_Device(Config))
                else:
                    # Add defaults
                    Config.update(DobbyConfig.Defaults_Device(Config))
                    print("   Gonfig loaded")
                continue

            # ---------------------------------------- Config Save ----------------------------------------
            elif User_Entry.lower() == "save":
                # Try to save config
                if DobbyConfig.Save('device.json', Config) == True:
                    print("   Config saved to: /conf/device.json")
                else:
                    print("   Unable to save config")
                continue

            # ---------------------------------------- Unknown command ----------------------------------------
            # Remember continue above so we dont trigger this
            else:
                print("Unknown config command: " + User_Entry)
                # since the 200 pound gorilla entered "config " and then someting incorrect
                # we need to continue because it was a config command and we dont need to check for other matchers
                continue

        # ---------------------------------------- Header ----------------------------------------
        elif User_Entry.lower().startswith("header ") == True:
            Config["Header"] = User_Entry
            continue
        # Hostname
        elif User_Entry.lower().startswith("hostname ") == True:
            Config["Hostname"] = User_Entry[9:]
            continue
        # Exit
        elif User_Entry.lower() == "exit":
            print("Quitting Dobby...")
            sys.exit()
        # ½ory
        elif User_Entry.lower() == "free memory":
            print('   Free memory: ' + str(gc.mem_free()))
            continue
        # json
        elif User_Entry.lower() == "json":
            # Get json string from user
            json_Config = input("Please paste json config string: ")

            # Try to parse json
            try:
                # parse json to config dict
                Config = ujson.loads(json_Config)
            except ValueError:
                print()
                print("   Invalid json string")
                print()
                continue
            # Add default settings if needed
            Config.update(DobbyConfig.Defaults_Device(Config))
            # Log Event
            print("   json config applied")
            continue
        # log level
        elif User_Entry.lower().startswith("log level ") == True:
            # Check if the log level is valid
            ## Invalid level
            if int(User_Entry[10:]) not in range(0, 6):
                print()
                print("   Incorrect log level: " + User_Entry[10:])
                print()
            ## Valid level
            else:
                Config["Log_Level"] = int(User_Entry[10:])
            continue
        # ll
        elif User_Entry.lower().startswith("ll") == True:
            ll_Resoult = ""
            # ll /
            if User_Entry.lower() == "ll":
                ll_Resoult = uos.listdir()
            # ll <path>
            else:
                # Try to list path
                try:
                    ll_Resoult = uos.listdir(User_Entry[3:])
                # If failed report dir missing
                except OSError:
                    print()
                    print("   No sucth dir: " + User_Entry[3:])
                    print()
                    continue
            # Print listdir
            print()
            print(ll_Resoult)
            print()
            # continue so we dont trigger unknown command
            continue

        # ---------------------------------------- wifi ----------------------------------------
        elif User_Entry.lower().startswith("wifi ") == True:
            # User_Entry[5:] = remove "wifi " or "WIFI " or any other combination there of
            # wifi SSID
            if User_Entry[5:].lower().startswith("ssid ") == True:
                Config["WiFi_SSID"] = User_Entry[10:]
                continue
            # wifi Password
            elif User_Entry[5:].lower().startswith("password ") == True:
                Config["WiFi_Password"] = User_Entry[14:]
                continue

        # ---------------------------------------- mqtt ----------------------------------------
        elif User_Entry.lower().startswith("mqtt ") == True:
            # User_Entry[5:] = remove "mqtt " or "MQTT " or any other combination there of
            # MQTT broker
            if User_Entry[5:].lower().startswith("broker ") == True:
                Config["MQTT_Broker"] = User_Entry[12:]
                continue
            # MQTT Port
            elif User_Entry[5:].lower().startswith("port ") == True:
                Config["MQTT_Port"] = User_Entry[10:]
                continue
            # MQTT Username
            elif User_Entry[5:].lower().startswith("user ") == True:
                Config["MQTT_Username"] = User_Entry[10:]
                continue
            # MQTT Password
            elif User_Entry[5:].lower().startswith("password ") == True:
                Config["MQTT_Password"] = User_Entry[14:]
                continue

        # ---------------------------------------- Unknown command ----------------------------------------
        # Remember continue above so we dontr trigger this
        else:
            print("Unknown command: " + User_Entry)

    print()
    print("   Exitting Dobby Command Line Interface.")
    print()
Ejemplo n.º 10
0
wait(1)
tmp_str = str(esp32.hall_sensor())
label_data_hall.setText("Hall sensor: " + tmp_str)
tmp_str = str("%.1f" % ((esp32.raw_temperature() - 32) / 1.8))
label_data_T_CPU.setText("T_CPU: " + tmp_str)
rtc.datetime()
#rtc.now()
#label_info_t.setText(str rtc.now() )
# display mpy info
label_info.setText(str(uos.uname()))
gc.collect()
wait(2)
label_info.setText("Free HEAP: " + str(gc.mem_free()) + " Bytes")

wait(2)
tmp_str = str(uos.listdir())
label_info_t.setText("Flash root: ")
label_info.setText(tmp_str)
#uos.listdir() # list all root files

wait(2)
#UOS api  file access
#need code to check if SD is mounted
#need code to check if SD is mounted
try:
    os.mountsd()
    SD_mounted_flag = True
except:
    SD_mounted_flag = False
    pass
Ejemplo n.º 11
0
        return (self.id,)

    def statvfs(self, path):
        print(self.id, "statvfs", path)
        return (self.id,)

    def open(self, file, mode):
        print(self.id, "open", file, mode)


# first we umount any existing mount points the target may have
try:
    uos.umount("/")
except OSError:
    pass
for path in uos.listdir("/"):
    uos.umount("/" + path)

# 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())
Ejemplo n.º 12
0
def server_recv():
    print("~~~~~~~~~~~~~~~~SERVER_RECV~~~~~~~~~~~~~~~~~~~~~~")
    HOST = configure[0]
    PORT = 8005
    print(HOST)
    print(PORT)
    pyb.LED(2).on()
    uos.chdir("/")
    s = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM)
    s.bind((HOST, PORT))
    s.listen(100)
    conn, address = s.accept()
    print(address)
    begin_time = pyb.millis()
    print("begin time in server_recv:", begin_time)
    filename = "general_txt.txt"
    f = open(filename, "wb")
    print("opened file")
    while True:
        try:
            veri = conn.recv(512)
            f.write(veri)
        except Exception as e:
            print(e)
            print("no more bytes - finished receiving text file")
            break
    f.close()
    conn.close()
    s.close()
    print("connection closed - text file closed")
    f = open(filename, "r")
    lines = f.read().splitlines()
    n = len(lines)
    print("lines = " + str(n))
    print(lines)
    f.close()
    nochange = []
    nochange.append('no change')
    if nochange[0] == lines[1]:
        end_time1 = pyb.elapsed_millis(begin_time)
        print("end time1 in server_recv:", end_time1)
        send_time1 = 150000 - end_time1
        print("send time1 in server_recv:", send_time1)
        pyb.LED(2).off()
        return send_time1, lines[0]
    else:
        uos.chdir("/CamFaces")
        directory = "/CamFaces"
        for filename in uos.listdir(directory):
            if filename.endswith(".pgm"):
                uos.remove(directory + "/" + filename)
                continue
            else:
                print("file found not of type pgm")
                continue
        print("deleted all old photos")
        uos.chdir("/")
        with open('camfaces_txt.txt', 'w') as filetxt:
            for listitem in lines:
                filetxt.write('%s\n' % listitem)
            filetxt.close()

        PORT += 1
        print(PORT)
        s = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM)
        s.bind((HOST, PORT))
        s.listen(100)
        conn, address = s.accept()
        print(address)

        filename = "face_filesizes.txt"
        f = open(filename, "wb")
        print("opened file")
        while True:
            try:
                veri = conn.recv(512)
                f.write(veri)
            except Exception as e:
                print(e)
                print("no more bytes - finished receiving text file")
                break
        f.close()
        conn.close()
        s.close()
        print("connection closed - face filesize file closed")
        f = open(filename, "r")
        filesizes = f.read().splitlines()
        r = len(filesizes)
        print("filesizes = " + str(r))
        print(filesizes)
        f.close()

        i = 1
        m = 1
        k = 0
        try:
            s = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM)
            PORT += 1
            print(PORT)
            s.bind((HOST, PORT))
            s.listen(100)
            conn, address = s.accept()
            print(address)
        except Exception as e:
            print(e)
        uos.chdir("/CamFaces")
        while m < n:
            filesize_str = filesizes[k]
            filesize = int(filesize_str)
            filepicname = lines[m]
            print(filepicname)
            f = open(filepicname, "wb")
            print("opened file")
            while (filesize > 0):
                try:
                    veri = conn.recv(1)
                    #print(len(veri))
                    f.write(veri)
                    filesize -= len(veri)
                except Exception as e:
                    print(e)
                    print("no more bytes - received full image")
                    break

            f.close()
            print("picture written to file and closed.")

            i += 1
            m += 1
            k += 1
        conn.close()
        s.close()
        print("connection and socket closed")
        pyb.LED(2).off()
        end_time2 = pyb.elapsed_millis(begin_time)
        print("end time2 in server_recv:", end_time2)
        send_time2 = 150000 - end_time2
        print("send time2 in server_recv:", send_time2)
        gc.collect()
        return send_time2, lines[0]
Ejemplo n.º 13
0
def face_recog(pic_name, vi_ip):
    print("~~~~~~~~~~~~~~~~FACE_RECOG~~~~~~~~~~~~~~~~~~~~~~")
    gc.collect()
    snap_img = image.Image(pic_name, copy_to_fb=True).mask_ellipse()
    d0 = snap_img.find_lbp((0, 0, snap_img.width(), snap_img.height()))
    pyb.LED(2).on()
    pyb.LED(3).on()
    name_lbp_list = []
    uos.chdir("/CamFaces")
    for filename in uos.listdir("/CamFaces"):
        if filename.endswith(".pgm"):
            try:
                img = None
                img = image.Image(filename, copy_to_fb=True).mask_ellipse()
                sensor.alloc_extra_fb(img.width(), img.height(),
                                      sensor.GRAYSCALE)
                d1 = img.find_lbp((0, 0, img.width(), img.height()))
                dist = image.match_descriptor(d0, d1, 50)
                sensor.dealloc_extra_fb()
                pname = filename
                und_loc = pname.index('_')
                pname = pname[0:(und_loc)]
                name_lbp_list.append(pname)
                name_lbp_list.append(dist)
                continue
            except Exception as e:
                print(e)
                print("error producing LBP value")
        else:
            print("file found that is not of type pgm")
    print(name_lbp_list)
    gc.collect()
    end = 0
    name_avg = []
    i = 0
    start = 0
    while i < len(name_lbp_list):
        if ((i + 2) < len(name_lbp_list)) and (name_lbp_list[i] !=
                                               name_lbp_list[i + 2]):
            end = i + 2
            face = []
            face = name_lbp_list[start:end]
            print(face)
            j = 1
            sum_lbp = 0
            while j < len(face):
                sum_lbp += face[j]
                j += 2
            name_avg.append(face[0])
            name_avg.append(sum_lbp / (len(face) / 2))
            start = i + 2
        i += 2
    face = []
    face = name_lbp_list[(end):(len(name_lbp_list))]
    print(face)
    gc.collect()
    j = 1
    sum_lbp = 0
    while j < len(face):
        sum_lbp += face[j]
        j += 2
    name_avg.append(face[0])
    name_avg.append(sum_lbp / (len(face) / 2))
    print(name_avg)
    lbps = []
    k = 1
    while k < len(name_avg):
        lbps.append(name_avg[k])
        k += 2
    print(lbps)
    gc.collect()
    min_lbp = min(lbps)
    print(min_lbp)
    ind = lbps.index(min(lbps))
    ind += 1
    found_person = name_avg[2 * ind - 2]
    id_name = "The person you are looking at is: " + found_person
    print(id_name)
    uos.remove("/snapshot-person.pgm")
    pyb.LED(2).off()
    pyb.LED(3).off()
    chost = vi_ip
    cport = 8080
    client = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM)
    client.connect((chost, cport))
    print("connected to visually impaired user's smartphone")
    to_send = id_name + "\n"
    client.send(to_send.encode())
    print("sent name to phone")
    client.close()
    gc.collect()
    return
from machine import Pin, ADC
from time import time
import utime, ujson, uos

#.modes - a = writing appended (a+ writing/reading) .#
#.        w = writing from beginning of file.  Will create file (w+ writing/reading) .#
#.        r+ = reading/writing from beginning of file. Raises I/O error if doesn't exist .#
#.        b means binary

dataFile = "esp32-joystick.csv"
mode = "wb" if dataFile in uos.listdir() else "r+" #. Create data file and write out header .#
with open(dataFile, "wb") as f:
  f.write("file,sensor,type,data\n")


#. vref = 3.3 .#
numOfChannels = 2
chan = [x for x in range(numOfChannels)]   #. use two channels, 1 for X and 1 for Y direction .#
chan[0] = ADC(Pin(35))
chan[1] = ADC(Pin(34))
chan[0].atten(ADC.ATTN_11DB) #. Full range: 3.3V .#
chan[1].atten(ADC.ATTN_11DB) #. Full range: 3.3V    .#
numOfSamples = 10
sensorAve = [x for x in range(numOfChannels)]
sensorLastRead = [x for x in range(numOfChannels)]
for x in range(numOfChannels): #. initialize the first read for comparison later .#
    sensorLastRead[x] = chan[x].read()
adcValue = [x for x in range(numOfChannels)]
sensor = [[x for x in range(0, numOfSamples)] for x in range(0, numOfChannels)]

    
Ejemplo n.º 15
0
        #print( face['faceAttributes']['gender'] )
        #print( face['faceAttributes']['age'] )

        print( "with {} hair, {} and {}".format(
            face['faceAttributes']['hair']['hairColor'][0]['color'],  #main haircolor
            ", ".join( face['faceAttributes']['facialHair'] ),
            face['faceAttributes']['glasses'] 
        )) 
        emotion = face['faceAttributes']['emotion']
        print ( sorted(emotion, key=emotion.__getitem__)[:1] )
        # In order of sorted values: [1, 2, 3, 4]


#Demo from /flash/foto
if True:
    for fname in os.listdir('/flash/foto'):
        print('---------------------------------------------------------------')        
        print( "Foto : /flash/foto/{}".format(fname) )
        faces = detect_faces_binary( "/flash/foto/{}".format(fname))
        process_faces(faces)
        print('---------------------------------------------------------------')

#demo from /sd/foto
if False:
    os.sdconfig(os.SDMODE_SPI, clk=18, mosi=23, miso=19, cs=4)
    os.mountsd()
    for fname in os.listdir('/sd/foto2'):
        print('---------------------------------------------------------------')
        print( "Foto : /sd/foto/{}".format(fname) )
        faces = detect_faces_binary( "/sd/foto/{}".format(fname) )
        process_faces(faces)
Ejemplo n.º 16
0
def listdir_nohidden(path):
	for f in uos.listdir(path):
		if not f.startswith('.'):
			yield f
Ejemplo n.º 17
0
# Simple demo of FRAM on Pyboard I2C bus 2.
# assumes device has already been formatted
# Has been tested with two contiguous FRAM boards
import uos
from fram import FRAM
i2c = pyb.I2C(2, pyb.I2C.MASTER)
i2c.scan()
fram = FRAM(i2c, verbose=True)
pyb.mount(fram, '/fram')
uos.listdir('/fram')

Ejemplo n.º 18
0
def setup():
    mainOctopus()
    print("Hello, this will help you initialize your ESP")
    print("ver: " + ver + " (c)octopusLAB")
    print("Press Ctrl+C to abort")

    # TODO improve this
    # prepare directory
    if 'config' not in uos.listdir():
        uos.mkdir('config')

    run = True
    while run:
        sele = setupMenu()

        if sele == "x":
            print("Setup - exit >")
            time.sleep_ms(2000)
            print("all OK, press CTRL+D to soft reboot")
            run = False

        if sele == "si":  #system_info()
            from util.sys_info import sys_info
            sys_info()

        if sele == "ds":
            print("Device setting:")
            print("   board_type  | soc_type (system on the board)")
            i = 0
            for di in devices:
                print(str(i) + ": " + str(di[0]) + " | " + str(di[1]))
                i = i + 1

            print()
            sd = input("select: ")
            #print(str(devices[int(sd)]))
            print("> " + str(devices[int(sd)][0]) + " | " +
                  str(devices[int(sd)][1]))

            dc = {}
            dc['board_type'] = str(
                devices[int(sd)][0]
            )  #input("Board type ('oLAB RobotBoard1' or 'oLAB IoTBoard1'): ")
            dc['soc_type'] = str(devices[int(
                sd)][1])  #input("SoC type ('esp32' or 'esp8266'): ")

            print("Writing to file config/device.json")
            with open('config/device.json', 'w') as f:
                ujson.dump(dc, f)
                # ujson.dump(wc, f, ensure_ascii=False, indent=4)

        if sele == "ios":
            print("I/O setting:")
            # io menu
            ioMenu()

        if sele == "iot":
            print("Testing I/O")
            from util import io_test
            io_test.all()

        if sele == "w":
            from util.wifi_connect import WiFiConnect
            w = WiFiConnect()

            sel_w = wifiMenu()

            if sel_w == "a":
                wifi_ssid = input("SSID: ")
                wifi_pass = input("PASSWORD: "******"r":
                wifi_ssid = input("SSID: ")
                w.remove_network(wifi_ssid)

            if sel_w == "s":
                print("Saved wifi networks")

                for k, v in w.config['networks'].items():
                    print("SSID: {0}".format(k))

        if sele == "cw":
            print("Connect WiFi >")
            from util.wifi_connect import WiFiConnect
            w = WiFiConnect()
            if w.connect():
                print("WiFi: OK")
            else:
                print("WiFi: Connect error, check configuration")

        if sele == "cl":
            print("Connect LAN >")
            import network
            lan = network.LAN(mdc=machine.Pin(23),
                              mdio=machine.Pin(18),
                              phy_type=network.PHY_LAN8720,
                              phy_addr=1,
                              clock_mode=network.ETH_CLOCK_GPIO17_OUT)
            lan.active(1)
            retry = 0
            while not lan.isconnected() or lan.ifconfig()[0] is '0.0.0.0':
                retry += 1
                time.sleep_ms(500)

                if retry > 20:
                    break

            if lan.isconnected():
                print("LAN: OK")
            else:
                print("LAN: Connect error, check cable or DHCP server")

        if sele == "mq":
            print("mqtt setup >")
            try:
                print()
                from util.mqtt import mqtt
                mqtt()
            except:
                print("Err.mqtt() or 'util.mqtt.py' does not exist")

        if sele == "st":
            print("Time setting >")
            rtc = machine.RTC()
            print(str(rtc.datetime()))
            setdatetime = input(
                "input 6 numbers - format: RRRRR,M,D,wd,h,m > ") + (",0,0")
            dt_str = setdatetime.split(",")
            print(str(dt_str))
            dt_int = [int(numeric_string) for numeric_string in dt_str]
            rtc.init(dt_int)
            print(str(rtc.datetime()))

        if sele == "sd":
            shutil()
            deplUrl = "https://octopusengine.org/download/micropython/stable.tar"
            deploy(deplUrl)

        if sele == "sde":
            shutil()
            deplUrl = "https://octopusengine.org/download/micropython/examples.tar"
            deploy(deplUrl)

        if sele == "sdp":
            shutil()
            deplUrl = "http://iot.petrkr.net/olab/latest.tar"
            deploy(deplUrl)

        if sele == "sdo":
            shutil()
            deplUrl = "https://octopusengine.org/download/latest.tar"
            deploy(deplUrl)

        if sele == "sdh":
            shutil()
            deplUrl = "https://octopusengine.org/download/hydroponics.tar"
            deploy(deplUrl)

        if sele == "wr":
            print("under reconstruction <")
            import esp
            esp.osdebug(None)
            import webrepl
            webrepl.start()
Ejemplo n.º 19
0
def list_files():
    from uos import listdir
    print()
    print("List of files on this device:")
    print('   %s' % '\n   '.join(map(str, sorted(listdir('/')))))
    print()
Ejemplo n.º 20
0
        while not wlan.isconnected():
            pass
    print('WiFi DHCP: ', wlan.ifconfig()[0])


# Set RTC using NTP
def ntp():
    print('')
    ntptime.host = key_store.get('ntp_host')
    print("NTP Server:", ntptime.host)
    while utime.time() < 10000:  # Retry until clock is set
        ntptime.settime()
        utime.sleep(1)
    print('UTC Time:   {}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}'.format(
        *utime.localtime()))
    print('')


# Suppress ESP debug messages in the REPL
def no_debug():
    esp.osdebug(None)


no_debug()
wlan_connect(ssid_name, ssid_pass)
ntp()

print("List of files on this device:")
print('   %s' % '\n   '.join(map(str, sorted(uos.listdir('/')))))
print('')
Ejemplo n.º 21
0
import ugfx, time, badge, machine, gc, system, virtualtimers, easydraw, wifi, rtc, term, term_menu, orientation, tasks.powermanagement as pm, uos, json, sys, tasks.otacheck as otacheck

# Default values
default_logo = '/media/hackerhotel.png'

# Read splashscreen configuration from NVS
cfg_term_menu = badge.nvs_get_u8('splash', 'term_menu', True)
cfg_wifi = badge.nvs_get_u8('splash', 'wifi', True)
cfg_services = badge.nvs_get_u8('splash', 'services', True)
cfg_logo = badge.nvs_get_str('splash', 'logo', default_logo)
cfg_nickname = badge.nvs_get_u8('splash', 'nickname', True)
cfg_led_animation = badge.nvs_get_str('splash', 'ledApp', None)

# Small hack to install logo if needed
try:
    media = uos.listdir("/media")
    if not "hackerhotel.png" in media:
        raise (BaseException("Logo not available"))
except:
    import dashboard.resources.png_hackerhotel

try:
    media = uos.listdir("/media")
    icons = [
        "alert", "bell", "bug", "busy", "charge", "crown", "earth", "flag",
        "music", "ok", "wifi", "usb"
    ]
    for icon in icons:
        if not icon + ".png" in media:
            raise (BaseException(""))
except:
Ejemplo n.º 22
0
#
# ディレクトリ・ファイル一覧を表示.
#

##################################################
# import
##################################################
import uos

##################################################
# main
##################################################
# 指定したディレクトリ内のディレクトリ一覧を取得
mount_points = uos.listdir("/")

# 全てのディレクトリに対して実行
for fs in mount_points:
    print("------------")
    # ディレクトリ名を表示
    print(" dir:", fs)
    # ディレクトリ内のファイル一覧を表示
    # (listdirメソッドの戻りを代入しない場合、コンソールに出力される)
    uos.listdir("/" + "flash")
Ejemplo n.º 23
0
 def list_dir(cls, path):
     try:
         return uos.listdir(path)
     except OSError as e:
         log.debug("LSDIR: {}".format(e))
         return []
Ejemplo n.º 24
0
    def start(self):

        DATA_PORT = 13333

        self.ftpsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.datasocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        self.ftpsocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.datasocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        self.ftpsocket.bind(socket.getaddrinfo("0.0.0.0", 21)[0][4])
        self.datasocket.bind(socket.getaddrinfo("0.0.0.0", DATA_PORT)[0][4])

        self.ftpsocket.listen(1)
        self.ftpsocket.settimeout(None)
        self.datasocket.listen(1)
        self.datasocket.settimeout(None)

        msg_250_OK = '250 OK\r\n'
        msg_550_fail = '550 Failed\r\n'
        self.wlan = network.WLAN(network.AP_IF)
        if self.wlan.active():
            ifconfig = self.wlan.ifconfig()
        else:
            self.wlan = network.WLAN(network.STA_IF)
            if self.wlan.active():
                ifconfig = self.wlan.ifconfig()
            else:
                dbg("No active connection")
                return
        addr = ifconfig[0]
        print("FTP Server started on ", addr)
        try:
            dataclient = None
            fromname = None
            do_run = True
            while do_run:
                cl, remote_addr = self.ftpsocket.accept()
                cl.settimeout(300)
                cwd = '/'
                try:
                    # dbg("FTP connection from:", remote_addr)
                    cl.sendall("220 Hello, this is the ESP8266/ESP32.\r\n")
                    while True:
                        gc.collect()
                        data = cl.readline().decode("utf-8").rstrip("\r\n")
                        if len(data) <= 0:
                            dbg("Client disappeared")
                            do_run = False
                            break

                        command = data.split(" ")[0].upper()
                        payload = data[len(command):].lstrip()

                        path = self.get_absolute_path(cwd, payload)

                        dbg("Command={}, Payload={}".format(command, payload))

                        if command == "USER":
                            cl.sendall("230 Logged in.\r\n")
                        elif command == "SYST":
                            cl.sendall("215 UNIX Type: L8\r\n")
                        elif command == "NOOP":
                            cl.sendall("200 OK\r\n")
                        elif command == "FEAT":
                            cl.sendall("211 no-features\r\n")
                        elif command == "PWD":
                            cl.sendall('257 "{}"\r\n'.format(cwd))
                        elif command == "CWD":
                            try:
                                files = uos.listdir(path)
                                cwd = path
                                cl.sendall(msg_250_OK)
                            except:
                                cl.sendall(msg_550_fail)
                        elif command == "CDUP":
                            cwd = self.get_absolute_path(cwd, "..")
                            cl.sendall(msg_250_OK)
                        elif command == "TYPE":
                            # probably should switch between binary and not
                            cl.sendall('200 Transfer mode set\r\n')
                        elif command == "SIZE":
                            try:
                                size = uos.stat(path)[6]
                                cl.sendall('213 {}\r\n'.format(size))
                            except:
                                cl.sendall(msg_550_fail)
                        elif command == "QUIT":
                            cl.sendall('221 Bye.\r\n')
                            do_run = False
                            break
                        elif command == "PASV":
                            cl.sendall(
                                '227 Entering Passive Mode ({},{},{}).\r\n'.
                                format(addr.replace('.', ','), DATA_PORT >> 8,
                                       DATA_PORT % 256))
                            dataclient, data_addr = self.datasocket.accept()
                            dbg("FTP Data connection from:", data_addr)
                        elif command == "LIST" or command == "NLST":
                            if not payload.startswith("-"):
                                place = path
                            else:
                                place = cwd
                            try:
                                self.send_list_data(
                                    place, dataclient, command == "LIST"
                                    or payload == "-l")
                                cl.sendall(
                                    "150 Here comes the directory listing.\r\n"
                                )
                                cl.sendall("226 Listed.\r\n")
                            except:
                                cl.sendall(msg_550_fail)
                            if dataclient is not None:
                                dataclient.close()
                                dataclient = None
                        elif command == "RETR":
                            try:
                                self.send_file_data(path, dataclient)
                                cl.sendall("150 Opening data connection.\r\n")
                                cl.sendall("226 Transfer complete.\r\n")
                            except:
                                cl.sendall(msg_550_fail)
                            if dataclient is not None:
                                dataclient.close()
                                dataclient = None
                        elif command == "STOR":
                            try:
                                cl.sendall("150 Ok to send data.\r\n")
                                self.save_file_data(path, dataclient)
                                cl.sendall("226 Transfer complete.\r\n")
                            except:
                                cl.sendall(msg_550_fail)
                            if dataclient is not None:
                                dataclient.close()
                                dataclient = None
                        elif command == "DELE":
                            try:
                                uos.remove(path)
                                cl.sendall(msg_250_OK)
                            except:
                                cl.sendall(msg_550_fail)
                        elif command == "RMD":
                            try:
                                uos.rmdir(path)
                                cl.sendall(msg_250_OK)
                            except:
                                cl.sendall(msg_550_fail)
                        elif command == "MKD":
                            try:
                                uos.mkdir(path)
                                cl.sendall(msg_250_OK)
                            except:
                                cl.sendall(msg_550_fail)
                        elif command == "RNFR":
                            fromname = path
                            cl.sendall("350 Rename from\r\n")
                        elif command == "RNTO":
                            if fromname is not None:
                                try:
                                    uos.rename(fromname, path)
                                    cl.sendall(msg_250_OK)
                                except:
                                    cl.sendall(msg_550_fail)
                            else:
                                cl.sendall(msg_550_fail)
                            fromname = None
                        elif command == "STAT":
                            if payload == "":
                                cl.sendall(
                                    "211-Connected to ({})\r\n"
                                    "    Data address ({})\r\n"
                                    "211 TYPE: Binary STRU: File MODE: Stream\r\n"
                                    .format(remote_addr[0], addr))
                            else:
                                cl.sendall("213-Directory listing:\r\n")
                                self.send_list_data(path, cl, True)
                                cl.sendall("213 Done.\r\n")
                        else:
                            cl.sendall("502 Unsupported command.\r\n")
                            dbg("Unsupported command {} with payload {}".
                                format(command, payload))
                except Exception as err:
                    dbg(err)

                finally:
                    cl.close()
                    cl = None
        finally:
            self.datasocket.close()
            self.ftpsocket.close()
            if dataclient is not None:
                dataclient.close()
Ejemplo n.º 25
0
import uos
# Creado por Daniel Alvarez ([email protected]) para curso de Python de EOI (eoi.es)

print(
    "En el sistema de archivos FAT de nuestro dispositivo, tenemos los siguientes ficheros:"
)
print(uos.listdir())
print("")
# help(uos) para ver el resto de opciones como borrar, renombrar, mover etc

# Escribir en un fichero
with open('sensor1.csv', 'w') as f:
    f.write("hora, temperatura\n")
    f.write("1, 23.5\n")
    f.write("2, 23.8\n")
    f.write("3, 24.1\n")

# Leer
with open("sensor1.csv", 'r') as f:
    print(f.read())
               cs=TFT_CS,
               dc=TFT_DC,
               rst=TFT_RST,
               power=TFT_ACC,
               backlight=TFT_LED,
               backlight_on=0 if TFT_LED_ACTIVE_LOW else 1,
               power_on=0 if TFT_ACC_ACTIVE_LOW else 1,
               width=240 if TFT_IS_PORTRAIT else 320,
               height=320 if TFT_IS_PORTRAIT else 240,
               rot=ili9341.PORTRAIT if TFT_IS_PORTRAIT else ili9341.LANDSCAPE)

touch_setup = config.get('touch_pins')
TOUCH_CS = touch_setup.get('cs')
TOUCH_INTERRUPT = touch_setup.get('interrupt')

if TOUCH_CALI_FILE not in uos.listdir():
    touch = xpt2046(
        cs=TOUCH_CS,
        transpose=TFT_IS_PORTRAIT,
    )

    from touch_cali import TouchCali

    touch_cali = TouchCali(touch, config)
    touch_cali.start()

elif not TEMP_HAS_CALIBRATED:
    from temp_cali import TempCali

    temp_cali = TempCali(config)
    temp_cali.start()
Ejemplo n.º 27
0
# tear = pyb.Pin("TEAR", pyb.Pin.IN)
#ugfx.set_tear_line(1)

print("Graphics initalised")

# Set up static rendering matrices
camera_transform = createCameraMatrix(0, 0, -5.0)
proj = createProjectionMatrix(45.0, 100.0, 0.1)
camera_projection = proj.mul(camera_transform)

print("Camera initalised")

# Get the list of available objects, and load the first one
obj_vertices = []
obj_faces = []
print("available objects: {}", listdir(app_path))
objects = [
    x for x in listdir(app_path)
    if (((".obj" in x) | (".dat" in x)) & (x[0] != "."))
]
selected = 0
loadObject(objects[selected])

print("loaded object {}", objects[selected])

# Set up rotation tracking arrays
x_rotation = 0
z_rotation = 0
y_rotation = 0
# Smooth rotations over 5 frames
smoothing = 5
Ejemplo n.º 28
0
# Simple demo of FRAM on ESP8266 using pins marked on Feather Huzzah (4,5).
# assumes device has already been formatted
# Has been tested with two contiguous FRAM boards
from fram import FRAM
import uos
import machine
scl = machine.Pin(5, machine.Pin.OUT)
sda = machine.Pin(4, machine.Pin.OUT)
i2c = machine.I2C(scl, sda)
i2c.scan()
fram = FRAM(i2c, verbose=True)
uos.umount()  # alas can only mount one FS
fs = uos.VfsFat(fram, '/')
uos.listdir('/')
Ejemplo n.º 29
0
 def find_backups():
     backups = []
     for file in uos.listdir("/flash"):
         if file.endswith(".bak"):
             backups.append(file)
     return backups
Ejemplo n.º 30
0
    """
    Initialize the on-board LED which is on pin5 and active low
    """
    # The on-board led of the Wemos Lolin32 is low active
    onboard = machine.Signal(machine.Pin(OB_LED_PIN, machine.Pin.OUT, value=1),
                             invert=True)
    red = machine.Pin(RED_LED_PIN, machine.Pin.OUT)
    green = machine.Pin(GRN_LED_PIN, machine.Pin.OUT)
    return onboard, red, green


if machine.reset_cause() == machine.SOFT_RESET:
    import uos

    # 初次进入休眠状态
    if FIRSTSLEEP_TRIGGER in uos.listdir():
        uos.remove(FIRSTSLEEP_TRIGGER)
        with open(DEEPSLEEP_TRIGGER, 'w') as f:
            pass
        pull_hold_pins()
        machine.deepsleep(FIRSTSLEEP_MS)
    # 工作状态
    elif DEEPSLEEP_TRIGGER in uos.listdir():
        pull_hold_pins()
        machine.deepsleep(settings['deepSleepIntervalMs'])
    # FTP开启
    elif FTP_TRIGGER in uos.listdir():
        uos.remove(FTP_TRIGGER)
        _, _, _, wifi = initialization(init_gy521=False,
                                       init_ds18=False,
                                       init_bat=False,
Ejemplo n.º 31
0
def setup():
    print("Hello, this will help you initialize your ESP")
    print("Press Ctrl+C to abort")
    print()

    # TODO improve this
    # prepare directory
    if 'config' not in uos.listdir():
       uos.makedirs('config')

    run= True
    while run:
        sele = setupMenu()

        if sele == "e":
            print("Setup - exit >")
            time.sleep_ms(2000)
            print("all OK, press CTRL+D to soft reboot")
            run = False

        if sele == "si": #system_info()
            from util.sys_info import sys_info
            sys_info()

        if sele == "ds":
            print("Device setting:")
            print("   board_type  | soc_type (system on the board)")
            i=0
            for di in devices:
               print(str(i)+": "+str(di[0]) + " | " + str(di[1]))
               i=i+1

            print()
            sd = input("select: ")
            #print(str(devices[int(sd)]))
            print("> " + str(devices[int(sd)][0]) + " | " + str(devices[int(sd)][1]))

            dc = {}
            dc['board_type'] = str(devices[int(sd)][0]) #input("Board type ('oLAB RobotBoard1' or 'oLAB IoTBoard1'): ")
            dc['soc_type'] = str(devices[int(sd)][1])   #input("SoC type ('esp32' or 'esp8266'): ")

            print("Writing to file config/device.json")
            with open('config/device.json', 'w') as f:
                ujson.dump(dc, f)
                # ujson.dump(wc, f, ensure_ascii=False, indent=4)

        if sele == "sw":
            print("Set WiFi >")
            print()
            wc = {}
            wc['wifi_ssid'] = input("SSID: ")
            wc['wifi_pass'] = input("PASSWORD: "******"Writing to file config/wifi.json")
            with open('config/wifi.json', 'w') as f:
                ujson.dump(wc, f)
                # ujson.dump(wc, f, ensure_ascii=False, indent=4)

        if sele == "cw":
              print("Connect WiFi >")
              from util.wifi_connect import read_wifi_config, WiFiConnect
              time.sleep_ms(1000)
              wifi_config = read_wifi_config()
              print("config for: " + wifi_config["wifi_ssid"])
              w = WiFiConnect()
              w.connect(wifi_config["wifi_ssid"], wifi_config["wifi_pass"])
              print("WiFi: OK")

        if sele == "st":
            print("Time setting >")
            rtc = machine.RTC()
            print(str(rtc.datetime()))
            setdatetime = input("input 6 numbers - format: RRRRR,M,D,wd,h,m > ")+(",0,0")
            dt_str = setdatetime.split(",")
            print(str(dt_str))
            dt_int = [int(numeric_string) for numeric_string in dt_str]
            rtc.init(dt_int)
            print(str(rtc.datetime()))

        if sele == "sd":
            print("System download > (initial octopus modules)")
            import upip
            print("Installing shutil")
            upip.install("micropython-shutil")
            print("Running deploy")
            #deplUrl = "http://iot.petrkr.net/olab/latest.tar"
            #deplUrl = "http://octopuslab.cz/download/latest.tar"
            deplUrl = "http://octopusengine.org/download/latest.tar"
            deploy(deplUrl)
Ejemplo n.º 32
0
 def get_file(self, fname):
     if fname:
         try:
             self.fname = fname
             if fname in ('.', '..') or (os.stat(fname)[0] & 0x4000): ## Dir
                 os.chdir(fname)
                 self.work_dir = os.getcwd()  # let the os module do the normalization
                 self.fname = "/" if self.work_dir == "/" else self.work_dir.split("/")[-1]
                 self.content = ["Directory '{}'".format(self.work_dir), ""] + sorted(os.listdir('.'))
                 self.is_dir = True
             else:
                 if is_micropython:
                     with open(fname) as f:
                         self.content = f.readlines()
                 else:
                     with open(fname, errors="ignore") as f:
                         self.content = f.readlines()
                 self.write_tabs = False
                 i = 0
                 for l in self.content:
                     self.content[i] = self.expandtabs(l.rstrip())
                     i += 1
         except OSError:
             self.message = "Error: file '" + fname + "' may not exist"
     self.hash = self.hash_buffer()
Ejemplo n.º 33
0
            return self.SEC_SIZE


try:
    bdev = RAMFS(50)
    bdev2 = RAMFS(50)
except MemoryError:
    print("SKIP")
    raise SystemExit

# first we umount any existing mount points the target may have
try:
    uos.umount('/')
except OSError:
    pass
for path in uos.listdir('/'):
    uos.umount('/' + path)

uos.VfsFat.mkfs(bdev)
uos.mount(bdev, '/')

print(uos.getcwd())

f = open('test.txt', 'w')
f.write('hello')
f.close()

print(uos.listdir())
print(uos.listdir('/'))
print(uos.stat('')[:-3])
print(uos.stat('/')[:-3])
Ejemplo n.º 34
0
## /flash/boot.py
# This file is executed on every boot (including wake-boot from deepsleep)
from micropython import const
import machine
import uos
import sys

sys.path[1] = '/sd/lib'
sys.path.append('/sd')
sys.path.append('/flash/lib')

CS = machine.Pin(const(13))
SCK = machine.Pin(const(14))
MOSI = machine.Pin(const(15))
MISO = machine.Pin(const(2))

uos.sdconfig(uos.SDMODE_SPI, SCK, MOSI, MISO, CS)
uos.mountsd()

if 'main.py' in uos.listdir('/sd'):
    exec(open('/sd/main.py').read(), globals())
Ejemplo n.º 35
0
# Simple demo of FRAM on ESP8266 using pins marked on Feather Huzzah (4,5).
# assumes device has already been formatted
# Has been tested with two contiguous FRAM boards
from fram import FRAM
import uos
import machine
scl = machine.Pin(5, machine.Pin.OUT)
sda = machine.Pin(4, machine.Pin.OUT)
i2c = machine.I2C(scl, sda)
i2c.scan()
fram = FRAM(i2c, verbose=True)
uos.umount() # alas can only mount one FS
fs = uos.VfsFat(fram, '/')
uos.listdir('/')

Ejemplo n.º 36
0
import sensor, image, lcd
import KPU as kpu
import uos
import time

lcd.init()
lcd.rotation(2)
sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA)
sensor.set_windowing((224, 224))
sensor.set_vflip(1)
sensor.run(1)

classes = ["sakura"]
print(uos.listdir("/sd/"))

task = kpu.load("/sd/YOLO_best_mAP_75.kmodel")
kpu.set_outputs(
    task, 0, 7, 7, 30
)  #Reshape層の内容に応じて中身を変える必要がある #the actual shape needs to match the last layer shape of your model(before Reshape)

anchor = (0.57273, 0.677385, 1.87446, 2.06253, 3.33843, 5.47434, 7.88282,
          3.52778, 9.77052, 9.16828)
kpu.init_yolo2(task, 0.3, 0.3, 5, anchor)
#kpu.init_yolo2(task, 0.8, 0.9, 5, anchor)
print("start")
code = ""
while (True):
    img = sensor.snapshot()  #.rotation_corr(z_rotation=90.0)
    #a = img.pix_to_ai()