Exemple #1
0
    def OTA(topic, msg):
        if topic != OTA_TOPIC:
            callback(topic, msg)
            return

        log("Receiving OTA update..")
        if len(msg) < 45:  # 40 is the length of the sha1
            log("Something wrong with the message")
            log(msg)
            return

        data = msg.decode('ascii').split("|")
        log(data)
        log("Target IP: %s, Target Port: %s, Local filename: %s, hash: %s" %
            (data[0], data[1], data[2], data[3]))
        success = receive_ota(data[0], int(data[1]), data[3])
        # ip, port, hash
        if not success:
            log("File transfer failed. Not overwriting local file.")
            return

        log("renaming tmp to %s" % data[2])
        uos.rename('tmp', data[2])

        reboot = True
        if len(data) == 5:
            reboot = int(data[4])

        if reboot:
            log('Restarting, as requested by OTA (or default)')
            reset()
        else:
            log('Not restarting, as requested by OTA')
Exemple #2
0
 async def readinto_safe(self, file_path):
     try:
         await self.readinto(str(file_path) + '_tmp')
         uos.rename(file_path + '_tmp', file_path)
         return True
     except:
         return False
Exemple #3
0
def test(bdev, vfs_class):
    print("test", vfs_class)

    # mkfs
    vfs_class.mkfs(bdev)

    # construction
    vfs = vfs_class(bdev)

    # mount
    uos.mount(vfs, "/lfs")

    # import
    with open("/lfs/lfsmod.py", "w") as f:
        f.write('print("hello from lfs")\n')
    import lfsmod

    # import package
    uos.mkdir("/lfs/lfspkg")
    with open("/lfs/lfspkg/__init__.py", "w") as f:
        f.write('print("package")\n')
    import lfspkg

    # chdir and import module from current directory (needs "" in sys.path)
    uos.mkdir("/lfs/subdir")
    uos.chdir("/lfs/subdir")
    uos.rename("/lfs/lfsmod.py", "/lfs/subdir/lfsmod2.py")
    import lfsmod2

    # umount
    uos.umount("/lfs")

    # clear imported modules
    sys.modules.clear()
Exemple #4
0
    def emit(self, record):
        """Write to file."""
        msg = self.formatter.format(record)
        s_len = len(msg)

        if self.maxBytes and self.backupCount and self._counter + s_len > self.maxBytes:
            # remove the last backup file if it is there
            try_remove(self.filename + ".{0}".format(self.backupCount))

            for i in range(self.backupCount - 1, 0, -1):
                if i < self.backupCount:
                    try:
                        os.rename(
                            self.filename + ".{0}".format(i),
                            self.filename + ".{0}".format(i + 1),
                        )
                    except OSError:
                        print("LOG emit error")
                        pass

            os.rename(self.filename, self.filename + ".1")
            self._counter = 0

        with open(self.filename, "a") as f:
            # print("file opened")
            f.write(msg + "\n")

        self._counter += s_len
Exemple #5
0
 def _rotateLogs(self):
     """Don't have rename function in my micropython build"""
     self.fh.close()
     if self.exists(self.last_log):
         uos.unlink(self.last_log)
     uos.rename(self.current_log, self.last_log)
     self.fh = open(self.current_log, mode="w")
Exemple #6
0
def move_fd(old_fd, new_fd, sock=None):
    try:
        uos.rename(old_fd, new_fd)
    except:
        out = "could not move %s" % old_fd
        print(out)
        send_output(sock, out)
Exemple #7
0
 def revert():
     backup_list = LoraOTA.find_backups()
     for backup in backup_list:
         idx = backup.find('.bak')
         new_filename = backup[:idx]
         uos.rename(backup, new_filename)
     print('Error: Reverting to old firmware')
     machine.reset()
def disable_boot():
    l = uos.listdir()
    if "boot.disabled" not in l and "boot.py" in l:
        uos.rename("boot.py", "boot.disabled")
    else:
        print(
            "Unable to disable boot! Either boot is already disabled or you are in the wrong uos dir"
        )
def enable_boot():
    l = uos.listdir()
    if "boot.disabled" in l:
        if "boot.py" in l:
            uos.remove("boot.py")

        uos.rename("boot.disabled", "boot.py")
    else:
        print("Unable to enable boot! Most likely is boot not disabled")
 def close_recorder(self):
     if self._rec == None:
         return
     filename = ure.sub("\.writing$", "", self._rec.filename)
     uos.rename(self._rec.filename, filename)
     self._rec.close()
     self._rec = None
     stat = uos.stat(filename)
     print("Close", filename, stat[6], stat)
Exemple #11
0
    def backup_file(self, filename):
        bak_path = "{}.bak".format(filename)

        # Delete previous backup if it exists
        try:
            uos.remove(bak_path)
        except OSError:
            pass  # There isnt a previous backup

        # Backup current file
        uos.rename(filename, bak_path)
Exemple #12
0
 def put_file(self, fname):
     if True:
         from uos import remove, rename
     tmpfile = fname + ".pyetmp"
     with open(tmpfile, "w") as f:
         for l in self.content:
             f.write(l + '\n')
     try:
         remove(fname)
     except:
         pass
     rename(tmpfile, fname)
Exemple #13
0
    def backup_file(self, f):
        bak_path = "{}.bak".format(f['dst_path'])
        dest_path = "{}".format(f['dst_path'])

        # Delete previous backup if it exists
        try:
            os.remove(bak_path)
        except OSError:
            pass  # There isnt a previous backup

        # Backup current file
        os.rename(dest_path, bak_path)
Exemple #14
0
def backup_old():
    try:
        nfn = "error_log_old.txt"
        try:
            uos.remove(nfn)
        except OSError:
            pass
        uos.rename("error_log.txt", nfn)
        return True
    except OSError:
        pass
    return False
Exemple #15
0
def SyncWget(mac,
             host,
             port,
             expSize,
             fn,
             targetPath="",
             tmpExt=".~",
             st=0,
             l=b'',
             lN=None):
    res = {'json': [], 'tags': [], 'size': 0}
    fpfn = targetPath + fn
    req = b'GET /sync/{}/{} HTTP/1.0\r\nHost: {}\r\n\r\n'.format(
        mac, fpfn, host)
    s = socket.socket()
    s.connect(socket.getaddrinfo(host, port)[0][4])
    s.send(req)
    while True:
        collect()
        if lN is not None: l = lN
        lN = s.readline() if st == 0 else s.read(512)
        if st == 0 and l == b'\r\n':
            st += 1
            fT = open(fpfn + tmpExt, 'wb+')
            continue
        if st == 1 and l == b'\r\n' and not lN: st += 1
        if st == 0 and l[:4] == b'ESP:':
            [
                res['tags'].append(t) for t in [
                    tg.strip() for tg in l.decode()[4:].split('#')
                    if len(tg.strip()) > 0
                ]
            ]
        if st == 1:
            res['size'] += len(l)
            fT.write(l)
            if 'getListDir' in res['tags'] and 'json' in res['tags']:
                res['json'].append(l)
        if not lN: break
    fT.close()
    s.close()
    del s
    if 'getListDir' in res['tags'] and 'json' in res['tags']:
        remove(fpfn + tmpExt)
        print('Removing {}'.format(fpfn + tmpExt))
        merge = ''.join([j.decode() for j in res['json']])
        return loads(merge)
    if expSize > 0 and expSize == res['size']:
        if fn in listdir(targetPath[:-1]): remove(fpfn)
        rename(fpfn + tmpExt, fpfn)
        print(fpfn, '\033[1;32m%s\033[0m' % ("Save done ;-D"))
        return True
    return False
Exemple #16
0
def move_f(source, destination):
    """Move file or directory with subfiles"""
    try:
        content = uos.listdir(source)
    except OSError:
        content = None

    if not content:
        uos.rename(source, destination)
        return

    for item in content:
        move_f('{}/{}'.format(source, item), '{}/{}'.format(destination, item))
def test(bdev, vfs_class):
    print("test", vfs_class)

    # mkfs
    vfs_class.mkfs(bdev)

    # construction
    vfs = vfs_class(bdev)

    # mount
    uos.mount(vfs, "/lfs")

    # import
    with open("/lfs/lfsmod.py", "w") as f:
        f.write('print("hello from lfs")\n')
    import lfsmod

    # import package
    uos.mkdir("/lfs/lfspkg")
    with open("/lfs/lfspkg/__init__.py", "w") as f:
        f.write('print("package")\n')
    import lfspkg

    # chdir and import module from current directory (needs "" in sys.path)
    uos.mkdir("/lfs/subdir")
    uos.chdir("/lfs/subdir")
    uos.rename("/lfs/lfsmod.py", "/lfs/subdir/lfsmod2.py")
    import lfsmod2

    # umount
    uos.umount("/lfs")

    # mount read-only
    vfs = vfs_class(bdev)
    uos.mount(vfs, "/lfs", readonly=True)

    # test reading works
    with open("/lfs/subdir/lfsmod2.py") as f:
        print("lfsmod2.py:", f.read())

    # test writing fails
    try:
        open("/lfs/test_write", "w")
    except OSError as er:
        print(repr(er))

    # umount
    uos.umount("/lfs")

    # clear imported modules
    usys.modules.clear()
Exemple #18
0
def rename_file(nummer=0, filename=''):
    ''' Hernoemt het bestand of folder uit de <lijst> met volgnummer <nummer> naar <filename>.'''
    global lijst, pwd
    # hernoem bestand/folder
    try:
        uos.rename(lijst[nummer - 1], filename)
    except OSError as err:
        if err.args[0] == uerrno.EINVAL:
            show_error('Ongeldige bestand/folder naam! - %s' % err)
        else:
            show_error('Onbekende fout - %s' % err)
        return
    # update lijst
    get_files(pwd)
Exemple #19
0
 def put_file(self, fname):
     tmpfile = fname + ".pyetmp"
     with open(tmpfile, "w") as f:
         for l in self.content:
             if self.write_tabs == 'y':
                 f.write(self.packtabs(l))
             else:
                 f.write(l)
             f.write('\n')
     try:
         os.remove(fname)
     except:
         pass
     os.rename(tmpfile, fname)
Exemple #20
0
 def put_file(self, fname):
     if True:
         from uos import remove, rename
     tmpfile = fname + ".pyetmp"
     with open(tmpfile, "w") as f:
         for l in self.content:
             if self.write_tabs == "y":
                 f.write(self.packtabs(l) + "\n")
             else:
                 f.write(l + "\n")
     try:
         remove(fname)
     except:
         pass
     rename(tmpfile, fname)
Exemple #21
0
    def _write_to_file(self, filename, text):
        tmp_file = self.get_tmp_filename('/flash/' + filename)

        try:
            with open(tmp_file, 'w+') as fh:
                fh.write(text)
        except Exception as ex:
            print("Error writing to file: {}".format(ex))
            return False

        if self.file_exists('/flash/' + filename):
            self.backup_file('/flash/' + filename)
        uos.rename(tmp_file, '/flash/' + filename)

        return True
Exemple #22
0
def too_old(file):
    """Rename unsent files older than buffer days.

    Params:
        file(str)
    Returns:
        True or False
    """
    filename = file.split("/")[-1]
    pathname = file.replace("/" + file.split("/")[-1], "")
    if utime.mktime(utime.localtime()) - utime.mktime([int(filename[0:4]),int(filename[4:6]),int(filename[6:8]),0,0,0,0,0]) > constants.BUF_DAYS * 86400:
        uos.rename(file, pathname + "/" + constants.SENT_FILE_PFX + filename)
        if pathname + "/" + constants.TMP_FILE_PFX + filename in uos.listdir(pathname):
            uos.remove(pathname + "/" + constants.TMP_FILE_PFX + filename)
        return True
    return False
Exemple #23
0
 def mv(self, files, dest, opts):
     try:
         dir_dest = self.is_dir(uos.stat(dest)[0])
     except OSError:
         dir_dest = False
     if len(files) == 1 and not dir_dest:
         if 'v' in opts: print(dest)
         if 'n' not in opts: uos.rename(files[0], dest)
         return
     elif not dir_dest:
         print("Destination must be a directory.")
         return
     for f in files:
         f2 = self.path(dest, self.basename(f))
         if 'v' in opts: print(f2)
         if 'n' not in opts: uos.rename(f, f2)
Exemple #24
0
    def _totally_sent(self, file, tmp_file, sent_file):
        """Marks file as sent.

        Params:
            tmp_file(str)
            sent_file(str)
        """
        if self._is_new_day(file):
            try:
                uos.rename(file, sent_file)
                try:
                    uos.remove(tmp_file)
                except:
                    print("UNABLE TO REMOVE {} FILE".format(tmp_file))
            except:
                print("UNABLE TO RENAME {} FILE".format(file))
Exemple #25
0
    def delete_file(self, f):
        bak_path = "/{}.bak_del".format(f)
        dest_path = "/{}".format(f)

        # Delete previous delete backup if it exists
        try:
            os.remove(bak_path)
        except OSError:
            pass  # There isnt a previous delete backup

        # Backup current file
        # if it exists
        try:
            os.stat(dest_path)  #raises exception if file does not exist
            os.rename(dest_path, bak_path)
        except:
            print("Warning: could not delete (rename to .bak_del) the file ",
                  dest_path)
Exemple #26
0
    def log_rotate(self):
        for i in range(self._file_count - 1, 0, -1):
            old_filename = '{}.{}'.format(self._file_full_path, i)
            new_filename = '{}.{}'.format(self._file_full_path, i + 1)
            try:
                uos.rename(old_filename, new_filename)
            except:
                pass

        try:
            uos.remove('{}.{}'.format(self._file_full_path, self._file_count))
        except:
            pass

        self._file.close()
        uos.rename(self._file_full_path, self._file_full_path + '.1')

        self._file = open(self._file_full_path, 'at')
Exemple #27
0
def perform_software_update():
    global HTTP_CLIENT
    if not HTTP_CLIENT:
        HTTP_CLIENT = HttpClient()
    machine.WDT()
    manage_memory()
    version_data = load_version()
    device_type = get_device_type()
    srv_url = updates_url()
    srv_index = load_srv_json('index', srv_url=srv_url)
    machine.resetWDT()
    srv_versions = load_srv_json('devices', srv_url=srv_url)
    machine.resetWDT()
    if srv_index:
        for path, entry in srv_index.items():
            if 'devices_types' in entry and 'base' not in entry[
                    'devices_types'] and device_type not in entry[
                        'devices_types']:
                continue
            if path in version_data['files'] and version_data['files'][
                    path] == entry['hash']:
                continue
            local_path = entry['path'] if 'path' in entry else path
            print(local_path)
            ensure_file_path(local_path)
            file_url = srv_url + 'software/' + path
            print(file_url)
            while version_data['files'].get(path) != entry['hash']:
                if HTTP_CLIENT.get_to_file(file_url, 'file_buf'):
                    try:
                        uos.remove(local_path)
                    except OSError:
                        pass
                    uos.rename('file_buf', local_path)
                    if version_data['hash']:
                        version_data['hash'] = None
                    version_data['files'][path] = entry['hash']
                    save_version(version_data)
                    print('complete')
        machine.resetWDT()
        version_data['hash'] = srv_versions[device_type]
        version_data['update'] = False
        save_version(version_data)
    machine.reset()
Exemple #28
0
def move_Files():
    global file_Required
    global file_Path
    global file_Action
    global files_toProcess
    global files_Processed
    global temp_Path
    global reboot

    i = 0
    uos.chdir(temp_Path)
    while i < files_Processed:
        if file_Action[i] == "1":
            try:
                uos.replace(file_Required[i],
                            file_Path[i] + "/" + file_Required[i])
                time.sleep(0.5)
            except OSError:
                uos.rename(file_Required[i],
                           file_Path[i] + "/" + file_Required[i])
                i = i + 1
                pass
            else:
                i = i + 1
        elif file_Action[i] == "2" or file_Action[i] == "3":
            try:
                uos.rename(file_Required[i],
                           file_Path[i] + "/" + file_Required[i])
                time.sleep(0.5)
            except OSError:
                uos.replace(file_Required[i],
                            file_Path[i] + "/" + file_Required[i])
                i = i + 1
                pass
            else:
                i = i + 1
        else:
            pass
    file_Required.clear()
    file_Path.clear()
    file_Action.clear()
    files_toProcess = 0
    files_Processed = 0
    reboot = True
Exemple #29
0
    def action_files(method, loc, params, headers, conn, addr):
        if "/" in loc[7:]:  # only files in root dir are allowed
            raise FileServerError("not on root")

        file_name = loc[6:]

        if file_name in PROTECTED_FILES:
            raise FileServerError("restricted")

        try:
            stat = uos.stat(file_name)
        except OSError:
            if method == "GET" or method == "DELETE" or "rename" in params:
                return httpsrv.response(404, '"File Not Found"', httpsrv.CT_JSON)
        else:
            if stat[0] != 32768:
                raise FileServerError("restricted")

        if method == "DELETE":
            uos.remove(file_name)
            return httpsrv.response(200, '"OK"', httpsrv.CT_JSON)

        if method == "GET":
            with open(file_name, "rb") as file:
                # read from file, send to conn
                httpsrv.send_response(
                    conn, **(httpsrv.response(200, content_type=httpsrv.CT_PLAIN))
                )
                httpsrv.readall_from(file, into=conn)
            return None  # response already assembled above

        elif method == "PUT":
            if "rename" in params:
                uos.rename(file_name, params["rename"])
                return httpsrv.response(200, '"OK"', httpsrv.CT_JSON)

            with open(file_name, "wb") as file:
                # write to file, receive from conn
                httpsrv.readall_from(conn, into=file)
            return httpsrv.response(200, '"OK"', httpsrv.CT_JSON)
Exemple #30
0
    def update_reset(self):
        """
        old_file_list:下载完成文件之后,将original_file改名为-old-,以便更新失败系统恢复
        """
        for file in os.listdir():
            if file.startswith('-old-'):
                uos.remove(file)

        down_file_list, original_file_list, new_file_list = self.download_update_list_update(
            self.update_url)
        # 如果下载出现错误,则系统恢复
        if self.download_error:
            self.system_restore()
        else:
            old_file_list = []
            for original_file_name in original_file_list:
                # 把老文件重命名 + '-old-',除了config.json
                # original_file >> old_file
                # original_file_list >> old_file_list
                if original_file_name != 'config.json':
                    print('Rename:', original_file_name)
                    old_file_name = '{}{}'.format('-old-', original_file_name)
                    uos.rename(original_file_name, old_file_name)
                    old_file_list.append(old_file_name)

            for file in uos.listdir():
                if file.startswith('-new-'):
                    # 更新文件 -new-
                    uos.rename(file, file[5:])
                if file.startswith('-old-'):
                    # 删除文件 -old-
                    try:
                        uos.remove(file)
                    except Exception as e:
                        print('Delete {} fail!.'.format(file))
            # 重启
            reset()
Exemple #31
0
# mounting over an existing mount point
try:
    uos.mount(Filesystem(3), '/test_mnt2')
except OSError:
    print('OSError')

# mkdir of a mount point
try:
    uos.mkdir('/test_mnt')
except OSError:
    print('OSError')

# rename across a filesystem
try:
    uos.rename('/test_mnt/a', '/test_mnt2/b')
except OSError:
    print('OSError')

# delegating to mounted filesystem
uos.chdir('test_mnt')
print(uos.listdir())
print(uos.getcwd())
uos.mkdir('test_dir')
uos.remove('test_file')
uos.rename('test_file', 'test_file2')
uos.rmdir('test_dir')
print(uos.stat('test_file'))
print(uos.statvfs('/test_mnt'))
open('test_file')
open('test_file', 'wb')
f = open('test.txt', 'w')
f.write('hello')
f.close()

print(uos.listdir())
print(uos.listdir('/'))
print(uos.stat('')[:-3])
print(uos.stat('/')[:-3])
print(uos.stat('test.txt')[:-3])
print(uos.stat('/test.txt')[:-3])

f = open('/test.txt')
print(f.read())
f.close()

uos.rename('test.txt', 'test2.txt')
print(uos.listdir())
uos.rename('test2.txt', '/test3.txt')
print(uos.listdir())
uos.rename('/test3.txt', 'test4.txt')
print(uos.listdir())
uos.rename('/test4.txt', '/test5.txt')
print(uos.listdir())

uos.mkdir('dir')
print(uos.listdir())
uos.mkdir('/dir2')
print(uos.listdir())
uos.mkdir('dir/subdir')
print(uos.listdir('dir'))
for exist in ('', '/', 'dir', '/dir', 'dir/subdir'):