def MyRequestHandler(request, conn, buffer=1024): if request.method == "GET": uri = ( request.uri.path + ("/" if request.uri.path else "") + (request.uri.file if request.uri.file else "index.html") ) try: stat(uri) except: conn.send(b"HTTP/1.1 404 Not Found\r\n\r\n") return conn.send(b"HTTP/1.1 200 OK\r\n\r\n") _buf = bytearray(buffer) buf = memoryview(_buf) with open(uri, "rb") as file: while True: count = file.readinto(buf) if count: conn.send(buf[:count]) else: break conn.send(b"\r\n") else: # catch all request types conn.send(b"HTTP/1.1 403 Not Implemented\r\n\r\n")
def process(self, accept_timeout): client_sock = None f = None try: self._sock.settimeout(accept_timeout) client_sock, client_addr = self._sock.accept() if not client_sock: return print('WebServer - connection from', client_addr) client_sock.settimeout(0.3) first_line = client_sock.readline() if not first_line: client_sock.close() return parts = self._split(first_line, ' ') req_method = parts[0].upper() req_path = parts[1].lower() req_auth = None while True: line = client_sock.readline() if not line: break parts = self._split(line, ':') if len(parts) < 2: break if parts[0].lower() == 'authorization': req_auth = parts[1].strip().split()[1] if req_auth: user_pass = ubinascii.a2b_base64(req_auth).decode().split(':') else: user_pass = None if (not user_pass) or (user_pass[0] != self._user) or ( user_pass[1] != self._password): if user_pass: print('WebServer - access attempt from', client_addr) client_sock.send('HTTP/1.1 401 Unauthorized\r\n') client_sock.send( 'WWW-Authenticate: Basic realm="ExoSensePy"\r\n\r\n') client_sock.close() return print('WebServer - request from', client_addr, req_method, req_path) if req_path == '/config': if req_method == 'POST': state = 0 while True: line = client_sock.readline() if not line: break line = line.decode().strip() if state == 0: if line.startswith( 'Content-Disposition: ') and line.endswith( 'filename="config.py"'): state = 1 elif state == 1: if line == '': state = 2 f = open('config.py.tmp', 'wb') elif state == 2: if line.startswith('--'): f.close() state = 3 uos.remove('config.py') state = 4 uos.rename('config.py.tmp', 'config.py') state = 5 break f.write(line) f.write('\n') client_sock.readall() client_sock.send('HTTP/1.1 303 See Other\r\n') client_sock.send('Location: /?state={}\r\n'.format(state)) client_sock.send('Content-Type: text/html\r\n\r\n') if state == 5: print('Config uploaded - restarting in 2 sec...') time.sleep(2) machine.reset() else: client_sock.send('HTTP/1.1 200 OK\r\n') client_sock.send('Connection: close\r\n') try: stat = uos.stat("config.py") client_sock.send( 'Content-Disposition: attachment; filename=config.py\r\n' ) client_sock.send( 'Content-Type: application/force-download\r\n') client_sock.send( 'Content-Transfer-Encoding: binary\r\n') client_sock.send('Content-Length: {}\r\n\r\n'.format( stat[6])) f = open('config.py', 'rb') client_sock.send(f.read()) except Exception as e: client_sock.send('Content-Type: text/html\r\n\r\n') client_sock.send('Not configured') elif req_path == '/favicon.ico': client_sock.send('HTTP/1.1 404 Not Found\r\n') client_sock.send('Connection: close\r\n\r\n') else: client_sock.send('HTTP/1.1 200 OK\r\n') client_sock.send('Connection: close\r\n') client_sock.send('Content-Type: text/html\r\n') stat = uos.stat("index.html") client_sock.send('Content-Length: {}\r\n\r\n'.format(stat[6])) f = open('index.html', 'rb') client_sock.send(f.read()) except OSError as e: if e.args[0] != 11: # 11 = timeout expired print("WebServer - OSError:", e) sys.print_exception(e) except Exception as e: if self._run: print("WebServer - process error:", e) sys.print_exception(e) else: print("WebServer - process stopped") try: f.close() except Exception: pass try: client_sock.close() except Exception: pass
def ftpserver(): print("Starting ftp server. Version 1.1") DATA_PORT = 1050 ftpsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) datasocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #ftpsocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) #datasocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) ftpsocket.bind(socket.getaddrinfo("0.0.0.0", 21)[0][4]) datasocket.bind(socket.getaddrinfo("0.0.0.0", DATA_PORT)[0][4]) ftpsocket.listen(1) ftpsocket.settimeout(None) datasocket.listen(1) datasocket.settimeout(None) msg_250_OK = '250 OK\r\n' msg_550_fail = '550 Failed\r\n' addr = network.WLAN().ifconfig()[0] try: dataclient = None fromname = None do_run = True while do_run: cl, remote_addr = ftpsocket.accept() cl.settimeout(300) cwd = '/' try: # print("FTP connection from:", remote_addr) cl.sendall("220 Hello, this is the ESP32.\r\n") while True: gc.collect() data = cl.readline().decode("utf-8").rstrip("\r\n") if len(data) <= 0: print("Client disappeared") break command = data.split(" ")[0].upper() payload = data[len(command):].lstrip() path = get_absolute_path(cwd, payload) print("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 = 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') print("Received QUIT, but staying alive!") do_run = True elif command == "PASV": result = '227 Entering Passive Mode ({},{},{}).\r\n'.format( addr.replace('.', ','), DATA_PORT >> 8, DATA_PORT % 256) cl.sendall(result) print("Sending:", result) #dataclient, data_addr = datasocket.accept() #print("FTP Data connection from:", data_addr) elif command == "LIST" or command == "NLST": if not payload.startswith("-"): place = path else: place = cwd try: dataclient, data_addr = datasocket.accept() 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: dataclient, data_addr = datasocket.accept() 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") dataclient, data_addr = datasocket.accept() dataclient.setblocking(False) print("Socket accepted") 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") send_list_data(path, cl, True) cl.sendall("213 Done.\r\n") else: cl.sendall("502 Unsupported command.\r\n") print("Unsupported command {} with payload {}".format( command, payload)) except Exception as err: print(err) finally: cl.close() cl = None finally: datasocket.close() ftpsocket.close() if dataclient is not None: dataclient.close()
import gc import uos from flashbdev import bdev import createruuvi try: if bdev: uos.mount(bdev, "/") except OSError: import inisetup vfs = inisetup.setup() try: uos.stat('/main.py') except OSError: with open("/main.py", "w") as f: f.write("""import ruuvigw""") createruuvi.create() gc.collect()
def log_exception(exc, time_str="", to_print=True, to_file=False, fatal=False, reboot=False): s = "" # use built-in exception formatter if exc is not None: if "str" not in str(type(exc)): s = exc_to_str(exc) gc.collect() # use sys time if real time is not provided if time_str is None: time_str = "" if len(time_str) <= 0: time_str = "%u" % pyb.millis() if exc is not None: if "str" not in str(type(exc)): headstr = "ERROR[%s]: %s" % (time_str, str(type(exc))) # traceback made single line s = s.replace("\n ", " >> ") else: headstr = "MESSAGE[%s]: %s" % (time_str, exc) else: headstr = "UNKNOWN-EVENT[%s]" % time_str if to_print: print(headstr) print(s) if to_file: # append to this file fname = "error_log.txt" fsize = 0 retries = 0 while retries < 2: retries += 1 try: try: fsize = uos.stat(fname)[6] except OSError: # no such file, file size is 0 (unchanged) pass with open(fname, "wba+") as f: f.seek( fsize) # the append flag does not work in micropython f.write("\r\n") f.write(headstr + "\r\n") f.write(s + "\r\n") f.write("\r\n") break # done, no need to loop except: # something wrong happened # backup the old file, start a new one backup_old() continue if reboot: import machine machine.reset() if fatal or "IDE interrupt" in s: raise exc return headstr + "\r\n" + s
def file_size(path): return uos.stat(path)[6]
def __file_time(self): from uos import stat return stat(self.name)[8] # Get File Time
try: uos.mount(vfs, '/sd') except OSError as e: if len(e.args) > 0 and e.args[0] == errno.EPERM: print('Already mounted, skipping') pass else: print('problem mounting the sd card') sys.exit(-1) print("SD card successfully mounted") # check to see if /sd/data already exists try: uos.stat("/sd/data") print("/sd/data already exists, nothing to do") except OSError as e: if len(e.args) > 0 and e.args[0] == errno.ENOENT: print("/sd/data does not exist, creating it") uos.mkdir("/sd/data") # write hello.txt file to sd card print("Creating and writing the hello world file") f = open("/sd/data/hello.txt", "w") f.write("Hello World!\n") f.close() try:
def _file_exists(self, path): try: stat(path) return True except: return False
def size(fn): return stat(fn)[6]
def setup(self): print(kpu.memtest()) self._rec = None self._record_count = 0 self._loop_counter = 0 self._last_100ms_cnt = 0 self._next_loop_cmd_ms = 0 self._last_active_ms = 0 self._lcd_brightness = None self._charge_mode = None self._timestamp = None self._ramdisk_mount_point = "/ramdisk" self._task = None #self._mode = "rec" self._mode = "auto" self._flag_send_img_to_C = False self._axp192 = pmu.axp192() self._axp192.enableADCs(True) self._axp192.enableCoulombCounter(False) self.set_lcd_brightness(9) fm.register(board_info.BUTTON_A, fm.fpioa.GPIO1) self.button_a = GPIO(GPIO.GPIO1, GPIO.IN, GPIO.PULL_UP) fm.register(board_info.BUTTON_B, fm.fpioa.GPIO2) self.button_b = GPIO(GPIO.GPIO2, GPIO.IN, GPIO.PULL_UP) fm.register(35, fm.fpioa.UART2_TX, force=True) fm.register(34, fm.fpioa.UART2_RX, force=True) baud = 115200 # 115200 1500000 3000000 4500000 self.uart = UART(UART.UART2, baud, 8, 0, 0, timeout=1000, read_buf_len=4096) sensor.reset() sensor.set_pixformat(sensor.RGB565) #sensor.set_pixformat(sensor.GRAYSCALE) #sensor.set_framesize(sensor.QVGA) sensor.set_framesize(sensor.QQVGA) #sensor.set_vflip(1) #sensor.set_hmirror(1) # if set 1, storange color!!! #sensor.set_windowing((224, 224)) sensor.run(1) try: stat = uos.stat(self._ramdisk_mount_point) uos.umount(self._ramdisk_mount_point) # print("mount_point=", mount_point, " stat=", stat) except OSError as e: pass blkdev = RAMFlashDev() vfs = uos.VfsSpiffs(blkdev) vfs.mkfs(vfs) uos.mount(vfs, self._ramdisk_mount_point) lcd.init(freq=40000000) lcd.direction(lcd.YX_RLDU) lcd.clear(lcd.BLACK) lcd.draw_string(10, 10, "BeetleC_AutoDrive_V", lcd.CYAN, lcd.BLACK) if self._mode == "auto": #self._twoWheelSteeringThrottle = TwoWheelSteeringThrottle() print(kpu.memtest()) self._task = kpu.load("/sd/model.kmodel") print(kpu.memtest())
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()) # ilistdir i = uos.ilistdir() print(next(i)) try:
def main(): import time import uos from m5stack import lcd, buttonA, buttonB, buttonC import network import binascii DNAME_ROOT = 'wifi_analyzer' def drawNaviButton(strA='START', strB='STOP', strC='EXIT'): lcd.text(40, 215, strA, lcd.WHITE) lcd.text(135, 215, strB, lcd.WHITE) lcd.text(240, 215, strC, lcd.WHITE) def fnameGen(): currentFileList = list( filter(lambda x: 'WA_' in x, uos.listdir('/sd/' + DNAME_ROOT))) currentFileList = list(map(lambda x: x.lower(), currentFileList)) if 'wa_0001.csv' not in currentFileList: return 'WA_0001.csv' else: currentFileList.sort() newestFileName = currentFileList[-1] no = int(newestFileName[3:7]) return 'WA_%s.csv' % (('%4d' % (no + 1)).replace(' ', '0')) def resdisplay(apresults, n, time): lcd.rect(0, 0, 320, 24, lcd.BLUE, lcd.BLUE) lcd.font(lcd.FONT_Ubuntu, transparent=True) lcd.text(0, 2, 'N_AP:%d N_SCAN:%d TIME:%d' % (len(apresults), n, time), lcd.WHITE) lcd.rect(0, 24, 320, 186, lcd.BLACK, lcd.BLACK) lcd.setCursor(0, 24) lcd.font(lcd.FONT_DefaultSmall) if len(apresults) < 15: i = 0 for apresult in apresults: resstr = '%02d, ch: %02d, rs: %d, %s\n' % ( i + 1, apresult[2], apresult[3], apresult[0].decode()) lcd.print(resstr, color=lcd.WHITE) i = i + 1 else: for i in range(0, 15): apresult = apresults[i] resstr = '%02d, ch: %02d, rs: %d, %s\n' % ( i + 1, apresult[2], apresult[3], apresult[0].decode()) lcd.print(resstr, color=lcd.WHITE) try: uos.stat('/sd') except: try: uos.mountsd() except: lcd.println('No SD card is found.') return -1 try: sdFiles = uos.listdir('/sd') if DNAME_ROOT not in sdFiles: uos.mkdir('/sd/' + DNAME_ROOT) except: lcd.println('The SD card is not writable.') return -2 try: drawNaviButton() lcd.setCursor(0, 0) lcd.println('Press START to start') while not buttonA.isPressed(): time.sleep(.5) if buttonC.isPressed(): return 0 wlan = network.WLAN(network.STA_IF) wlan.active(True) fname = fnameGen() lcd.println('Recording into %s...' % fname) ts = time.time() n = 0 while not buttonB.isPressed(): buf = '' aps = wlan.scan() n += 1 te = time.time() - ts for ap in aps: # (ssid, bssid, primary_chan, rssi, auth_mode, auth_mode_string, hidden) mac = (binascii.hexlify(ap[1])).decode() mac = ':'.join([ mac[:2], mac[2:4], mac[4:6], mac[6:8], mac[8:10], mac[10:12] ]) buf += '%.3f,%s,%s,%d,%s\n' % (te, mac, ap[0].decode(), ap[3], ap[2]) print(buf + '---------------------') resdisplay(aps, n, int(te)) with open('/sd/' + DNAME_ROOT + '/' + fname, 'a') as o: o.write(buf) lcd.println('Exit.') except: print('Exit since error.') pass
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]) 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')
def exists(file): try: s = uos.stat(file) return True except: return False
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()) # ilistdir i = uos.ilistdir() print(next(i)) try:
def processCommand(self, command): if command == "USER": if self.user is None and self.passwd == None: self.cmd_client.write("230 Logged in.\r\n") else: if self.payload == self.user: self.cmd_client.write( "331 User name okay, need password.\r\n") else: self.msg_550_fail() elif command == "PASS": if self.user is None and self.passwd == None: self.cmd_client.write("230 Logged in.\r\n") else: if self.payload == self.passwd: self.cmd_client.write("230 Logged in.\r\n") else: self.msg_550_fail() elif command == "SYST": self.cmd_client.write("215 UNIX Type: L8\r\n") elif (command == "NOOP") or (command == "CLNT") or (command == "OPTS"): self.cmd_client.write("200 OK\r\n") elif command == "FEAT": self.cmd_client.write("502 no-features\r\n") elif command == "AUTH": self.cmd_client.write("504 not-supported\r\n") elif command == "PWD" or command == "XPWD": if self.debug: print(" CWD: [{}]".format(self.cwd)) self.cmd_client.write('257 "{}"\r\n'.format(self.cwd)) elif command == "CWD": try: files = uos.listdir( self.path) # will raise an error if wrong path self.cwd = self.path if self.debug: print(" CWD: [{}]".format(self.cwd)) self.msg_250_OK() except: self.cmd_client.write(self.msg_550_fail) elif command == "CDUP": self.cwd = MicroFtpSrv.get_absolute_path(self.cwd, "..") if self.debug: print(" CWD: [{}]".format(self.cwd)) self.msg_250_OK() elif command == "TYPE": # probably should switch between binary and not self.cmd_client.write('200 Transfer mode set\r\n') elif command == "SIZE": try: size = uos.stat(self.path)[6] self.cmd_client.write('213 {}\r\n'.format(size)) except: self.cmd_client.write(self.msg_550_fail) elif command == "MDTM": try: time = uos.stat(self.path)[7] self.cmd_client.write('213 {}\r\n'.format(time)) except: self.cmd_client.write(self.msg_550_fail) elif command == "QUIT": self.cmd_client.write('221 Bye.\r\n') if not self.threaded: self.do_run = False # ---- Commands using data channel --------------------------------------------------- elif command == "PORT": # ==== The client requests data in ACTIVE mode ==== raddrs = self.payload.split(",") raddr = raddrs[0] + '.' + raddrs[1] + '.' + raddrs[ 2] + '.' + raddrs[3] rport = int(raddrs[4]) * 256 + int(raddrs[5]) active_addr = (raddr, rport) # Create client socket to connect to the FTP client's data port self.dataclient = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP) self.dataclient.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.dataclient.settimeout(1) if self.debug: print("Active mode requested, connect to {}:{}".format( raddr, rport)) self.active_mode = True self.cmd_client.write('200 PORT command successful\r\n') # Connect to the client IP address and port FROM local PORT 20 utime.sleep_ms(100) try: self.dataclient.connect(active_addr, 20) self.data_request = True except: if self.debug: print("No active data connection") self.dataclient = None self.msg_550_fail() elif command == "PASV": # ==== The client requests data in PASSIVE mode ==== if self.passive is True: self.active_mode = False if self.debug: print("Passive mode requested") result = '227 Entering Passive Mode ({},{},{}).\r\n'.format( self.local_IP.replace('.', ','), self._passive_port >> 8, self._passive_port % 256) self.cmd_client.write(result) if self.debug: print("Waiting for data connection") # === Accept the data connection from client === self.dataclient, data_addr = self.datasocket.accepted() if self.dataclient is None: if self.debug: print("No passive data connection") self.msg_550_fail() else: if self.debug: print("Data connection from:", data_addr) self.dataclient.settimeout(1) self.data_request = True else: self.msg_550_fail() utime.sleep_ms(50) elif command == "LIST" or command == "NLST": if not self.payload.startswith("-"): place = self.path else: place = self.cwd if self.debug: print("LIST:", place) if self.dataclient is None: self.msg_550_fail() else: try: # Some clients requires the following confirmation, some don't self.cmd_client.write( "150 OK Directory listing follows.\r\n") # send the listing self.send_list_data(place, self.dataclient, ((command == "LIST") or (self.payload == "-l"))) self.cmd_client.write("226 Listed.\r\n") except: self.msg_550_fail() utime.sleep_ms(50) elif command == "RETR": if self.debug: print(" CWD: [{}]".format(self.cwd)) self.last_transfer_save = False if self.dataclient is None: self.msg_550_fail() else: # Some clients requires the following confirmation, some don't self.cmd_client.write("150 OK Ready to send data.\r\n") # send the file if self.send_file_data(0) is True: self.last_transfer_path = None self.cmd_client.write("226 Transfer complete.\r\n") else: self.last_transfer_path = self.path self.msg_550_fail() elif (command == "STOR") or (command == "APPE"): if self.debug: print(" CWD: [{}]".format(self.cwd)) self.last_transfer_save = True if self.dataclient is None: self.msg_550_fail() else: # Some clients requires the following confirmation, some don't # Check if data already received utime.sleep_ms(100) if (self.dataclient.inbuf() == 0): # nothing received, send request self.cmd_client.write("150 OK Ready to receive data.\r\n") # receive the file if command == "STOR": res = self.save_file_data(0) else: res = self.save_file_data(-1) if res is True: self.last_transfer_path = None self.cmd_client.write("226 Transfer complete.\r\n") else: self.last_transfer_path = self.path self.msg_550_fail() elif (command == "REST") and (last_transfer_path is not None): if self.debug: print(" CWD: [{}]".format(self.cwd)) if self.dataclient is None: self.msg_550_fail() else: if self.last_transfer_save is True: # Some clients requires the following confirmation, some don't self.cmd_client.write("150 OK Ready to receive data.\r\n") # receive the file res = self.save_file_data(int(self.payload)) else: # Some clients requires the following confirmation, some don't self.cmd_client.write("150 OK Ready to send data.\r\n") # send the file try: pos = int(self.payload) res = self.send_file_data(pos) except: res = False if res is True: self.last_transfer_path = None self.cmd_client.write("226 Transfer complete.\r\n") else: self.last_transfer_path = self.path self.msg_550_fail() # ------------------------------------------------------------------------------------ elif command == "DELE": try: uos.remove(self.path) self.msg_250_OK() except: self.msg_550_fail() elif command == "RMD": try: uos.rmdir(self.path) self.msg_250_OK() except: self.msg_550_fail() elif command == "MKD": try: uos.mkdir(self.path) self.msg_250_OK() except: self.msg_550_fail() elif command == "RNFR": self.fromname = self.path try: _ = uos.stat(self.fromname) self.cmd_client.write("350 Rename from\r\n") except: self.msg_550_fail() elif command == "RNTO": if self.fromname is not None: try: uos.rename(self.fromname, self.path) self.msg_250_OK() except: self.msg_550_fail() else: self.msg_550_fail() self.fromname = None elif command == "STAT": if self.payload == "": self.cmd_client.write( "211-Connected to ({})\r\n" " Data address ({})\r\n" "211 TYPE: Binary STRU: File MODE: Stream\r\n".format( self.remote_addr[0], self.local_IP)) else: self.cmd_client.write("213-Directory listing:\r\n") self.send_list_data(self.cmd_client, True) self.cmd_client.write("213 Done.\r\n") else: self.cmd_client.write("502 Command not implemented.\r\n") if self.debug: print("Unsupported command [{}] with self.payload [{}]".format( command, self.payload))
async def send_file(self, filename, content_type=None, content_encoding=None, max_age=2592000): """Send local file as HTTP response. This function is generator. Arguments: filename - Name of file which exists in local filesystem Keyword arguments: content_type - Filetype. By default - None means auto-detect. max_age - Cache control. How long browser can keep this file on disk. By default - 30 days Set to 0 - to disable caching. Example 1: Default use case: await resp.send_file('images/cat.jpg') Example 2: Disable caching: await resp.send_file('static/index.html', max_age=0) Example 3: Override content type: await resp.send_file('static/file.bin', content_type='application/octet-stream') """ try: # Get file size stat = os.stat(filename) slen = str(stat[6]) self.add_header('Content-Length', slen) # Set content-type header (if possible) if content_type: self.add_header('Content-Type', content_type) else: # Auto-detect mime type based on file extension (eg. .css) file_extension = "." + filename.split(".")[-1] if file_extension in MIME_TYPES_PER_EXT: self.add_header('Content-Type', MIME_TYPES_PER_EXT[file_extension]) # Add content-encoding, if any if content_encoding: self.add_header('Content-Encoding', content_encoding) # Since this is static content is totally make sense # to tell browser to cache it, however, you can always # override it by setting max_age to zero self.add_header('Cache-Control', 'max-age={}, public'.format(max_age)) with open(filename) as f: await self._send_headers() gc.collect() buf = bytearray(128) while True: size = f.readinto(buf) if size == 0: break await self.send(buf, sz=size) except OSError as e: # special handling for ENOENT / EACCESS if e.args[0] in (errno.ENOENT, errno.EACCES): raise HTTPException(404) else: raise
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]) 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")
import array import dht11Raw import uos from machine import Pin, PWM #initialize the array to 32 zeros pwmData = array.array("I", [0] * 32) # check if the data directory exists, if not, create it try: uos.stat("/data") except OSError as e: if len(e.args) > 0 and e.args[0] == errno.ENOENT: print("/data does not exist, creating it") uos.mkdir("/data") # open the file /data/pwm.txt f = open("/data/pwm.txt", "w") pwmSource = PWM(Pin(18), freq=10000, duty=920) pwmSampler = Pin(19) dht11Raw.dht11ReadRaw(pwmSampler, pwmData) for i in range(32): # the 'new' way of formatting the number dataString = '0x{:08x}\n'.format(pwmData[i]) print(dataString, end="") # the 'old' way of formatting
def gen_page(conn, main_file, add_files=[], add_dir=None, debug=False): total_size = 0 total_size += uos.stat(main_file)[6] flist = [] # find all files required and add them to the list # also estimate the content length if add_dir is not None: try: lst = uos.listdir(add_dir) for i in lst: pt = add_dir + "/" + i if pt not in add_files: add_files.append(pt) except OSError as exc: exclogger.log_exception(exc) for i in add_files: try: total_size = uos.stat(i)[6] + 200 flist.append(i) except OSError as exc: exclogger.log_exception(exc) if debug: print("gen_page \"%s\" sz %u files %u ..." % (main_file, total_size, len(flist)), end="") conn.write(default_reply_header(content_length=total_size)) sent = 0 seekpos = 0 with open(main_file, "rb") as f: headstr = "" while "</title>" not in headstr: headstr += f.read(1).decode("ascii") seekpos += 1 sent += 1 conn.write(headstr + "\r\n") sent += 2 if debug: print("-", end="") # trying not to have more than one file open at once for fn in flist: try: with open(fn, "rb") as f: if fn.lower().endswith(".js"): s = "\r\n<script type=\"text/javascript\">\r\n" sent += len(s) conn.write(s) sent += stream_file(conn, f) s = "\r\n</script>\r\n" sent += len(s) conn.write(s) elif fn.lower().endswith(".css"): s = "\r\n<style type=\"text/css\">\r\n" sent += len(s) conn.write(s) sent += stream_file(conn, f) s = "\r\n</style>\r\n" sent += len(s) conn.write(s) else: raise Exception("unsupported file type") if debug: print("=", end="") except OSError as exc: exclogger.log_exception(exc) # send the rest of the file with open(main_file, "rb") as f: f.seek(seekpos) sent += stream_html_to_body(conn, f) sent += stream_file(conn, f) if debug: print("+", end="") # pad the end while sent < total_size - 2: conn.write(" ") sent += 1 if debug: print(" done!") conn.close()
def exists(path): try: uos.stat(path) return True except OSError: return False
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: while True: 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 " + uos.uname()[4] + ".\r\n") while True: 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" or command == "XPWD": 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" or command == "XRMD": try: uos.rmdir(path) cl.sendall(msg_250_OK) except: cl.sendall(msg_550_fail) elif command == "MKD" or command == "XMKD": 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 == "MDTM": try: tm = localtime(uos.stat(path)[8]) cl.sendall( '213 {:04d}{:02d}{:02d}{:02d}{:02d}{:02d}\r\n' .format(*tm[0:6])) except: cl.sendall('550 Fail\r\n') 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 if dataclient is not None: dataclient.close() finally: self.datasocket.close() self.ftpsocket.close()
import esp import uos filename = "csv_data_file.txt" # Get some statistics: print( "Available flash space: ", esp.flash_size()) # This will give you the total amount of Flash available partition = Partition(Partition.RUNNING) print( partition.info() ) # Print out information about the running flash partition on which you can store your files. file_stats = uos.stat(filename) print( "File size before write: ", file_stats[6] ) # the item at index 6 of the tupple contains the total bytes in the file. # This loop will add 10 lines that contain dummy comma-delimited data. for x in range(10): random_temp = random.randint(0, 50) random_humi = random.randint(20, 90) random_pres = random.randint(900, 1100) # in hPa file = open(filename, "a") # Append to the end of an existing file #new_entry = str(random_temp) + "," + str(random_humi) + "," + str(random_pres) + "\n" # Create the string that contains the dummy CSV data new_entry = "{},{},{}\n".format(random_temp, random_humi, random_pres) file.write(new_entry) file.close()
# Test for VfsPosix try: import uos uos.VfsPosix except (ImportError, AttributeError): print("SKIP") raise SystemExit # We need a directory for testing that doesn't already exist. # Skip the test if it does exist. temp_dir = "micropy_test_dir" try: uos.stat(temp_dir) print("SKIP") raise SystemExit except OSError: pass # getcwd and chdir curdir = uos.getcwd() uos.chdir("/") print(uos.getcwd()) uos.chdir(curdir) print(uos.getcwd() == curdir) # stat print(type(uos.stat("/"))) # listdir and ilistdir
def exec_ftp_command(self, cl): global datasocket global client_busy global my_ip_addr try: gc.collect() data = cl.readline().decode("utf-8").rstrip("\r\n") if len(data) <= 0: # No data, close # This part is NOT CLEAN; there is still a chance that a # closing data connection will be signalled as closing # command connection log_msg(1, "*** No data, assume QUIT") close_client(cl) return if client_busy: # check if another client is busy cl.sendall("400 Device busy.\r\n") # tell so the remote client return # and quit client_busy = True # now it's my turn # check for log-in state may done here, like # if self.logged_in == False and not command in\ # ("USER", "PASS", "QUIT"): # cl.sendall("530 Not logged in.\r\n") # return command = data.split()[0].upper() payload = data[len(command):].lstrip() # partition is missing path = self.get_absolute_path(self.cwd, payload) log_msg(1, "Command={}, Payload={}".format(command, payload)) if command == "USER": # self.logged_in = True cl.sendall("230 Logged in.\r\n") # If you want to see a password,return # "331 Need password.\r\n" instead # If you want to reject an user, return # "530 Not logged in.\r\n" elif command == "PASS": # you may check here for a valid password and return # "530 Not logged in.\r\n" in case it's wrong # self.logged_in = True cl.sendall("230 Logged in.\r\n") elif command == "SYST": cl.sendall("215 UNIX Type: L8\r\n") elif command in ("TYPE", "NOOP", "ABOR"): # just accept & ignore cl.sendall('200 OK\r\n') elif command == "QUIT": cl.sendall('221 Bye.\r\n') close_client(cl) elif command == "PWD" or command == "XPWD": cl.sendall('257 "{}"\r\n'.format(self.cwd)) elif command == "CWD" or command == "XCWD": try: if (uos.stat(path)[0] & 0o170000) == 0o040000: self.cwd = path cl.sendall('250 OK\r\n') else: cl.sendall('550 Fail\r\n') except: cl.sendall('550 Fail\r\n') elif command == "PASV": cl.sendall('227 Entering Passive Mode ({},{},{}).\r\n'.format( self.pasv_data_addr.replace('.', ','), _DATA_PORT >> 8, _DATA_PORT % 256)) self.active = False elif command == "PORT": items = payload.split(",") if len(items) >= 6: self.act_data_addr = '.'.join(items[:4]) if self.act_data_addr == "127.0.1.1": # replace by command session addr self.act_data_addr = self.remote_addr self.DATA_PORT = int(items[4]) * 256 + int(items[5]) cl.sendall('200 OK\r\n') self.active = True else: cl.sendall('504 Fail\r\n') elif command == "LIST" or command == "NLST": if payload.startswith("-"): option = payload.split()[0].lower() path = self.get_absolute_path( self.cwd, payload[len(option):].lstrip()) else: option = "" try: data_client = self.open_dataclient() cl.sendall("150 Directory listing:\r\n") self.send_list_data(path, data_client, command == "LIST" or 'l' in option) cl.sendall("226 Done.\r\n") data_client.close() except: cl.sendall('550 Fail\r\n') if data_client is not None: data_client.close() elif command == "RETR": try: data_client = self.open_dataclient() cl.sendall("150 Opened data connection.\r\n") self.send_file_data(path, data_client) # if the next statement is reached, # the data_client was closed. data_client = None cl.sendall("226 Done.\r\n") except: cl.sendall('550 Fail\r\n') if data_client is not None: data_client.close() elif command == "STOR" or command == "APPE": try: data_client = self.open_dataclient() cl.sendall("150 Opened data connection.\r\n") self.save_file_data(path, data_client, "w" if command == "STOR" else "a") # if the next statement is reached, # the data_client was closed. data_client = None cl.sendall("226 Done.\r\n") except: cl.sendall('550 Fail\r\n') if data_client is not None: data_client.close() elif command == "SIZE": try: cl.sendall('213 {}\r\n'.format(uos.stat(path)[6])) except: cl.sendall('550 Fail\r\n') elif command == "MDTM": try: tm = localtime(uos.stat(path)[8]) cl.sendall( '213 {:04d}{:02d}{:02d}{:02d}{:02d}{:02d}\r\n'.format( *tm[0:6])) except: cl.sendall('550 Fail\r\n') elif command == "STAT": if payload == "": cl.sendall("211-Connected to ({})\r\n" " Data address ({})\r\n" " TYPE: Binary STRU: File MODE: Stream\r\n" " Session timeout {}\r\n" "211 Client count is {}\r\n".format( self.remote_addr, self.pasv_data_addr, _COMMAND_TIMEOUT, len(client_list))) else: cl.sendall("213-Directory listing:\r\n") self.send_list_data(path, cl, True) cl.sendall("213 Done.\r\n") elif command == "DELE": try: uos.remove(path) cl.sendall('250 OK\r\n') except: cl.sendall('550 Fail\r\n') elif command == "RNFR": try: # just test if the name exists, exception if not uos.stat(path) self.fromname = path cl.sendall("350 Rename from\r\n") except: cl.sendall('550 Fail\r\n') elif command == "RNTO": try: uos.rename(self.fromname, path) cl.sendall('250 OK\r\n') except: cl.sendall('550 Fail\r\n') self.fromname = None elif command == "CDUP" or command == "XCUP": self.cwd = self.get_absolute_path(self.cwd, "..") cl.sendall('250 OK\r\n') elif command == "RMD" or command == "XRMD": try: uos.rmdir(path) cl.sendall('250 OK\r\n') except: cl.sendall('550 Fail\r\n') elif command == "MKD" or command == "XMKD": try: uos.mkdir(path) cl.sendall('250 OK\r\n') except: cl.sendall('550 Fail\r\n') else: cl.sendall("502 Unsupported command.\r\n") # log_msg(2, # "Unsupported command {} with payload {}".format(command, # payload)) # handle unexpected errors except Exception as err: log_msg(1, "Exception in exec_ftp_command: {}".format(err)) # tidy up before leaving client_busy = False
def stat(name): return stat_result(uos.stat(name))
def writeFile(): global previostimeM global previostimeH global previostimeD global previostimeMn ### WRITE TO FILE FOR HOUR if math.fabs(utime.localtime()[4] - previostimeM) >= 1: previostimeM = utime.localtime()[4] if math.fabs(utime.localtime()[3] - previostimeH) >= 1: previostimeH = utime.localtime()[3] ### create table file try: os.mkdir('/sd/'+str(utime.localtime()[0]) + '_' + str(utime.localtime()[1]) + '_' + str(utime.localtime()[2])) name = '/sd/'+str(utime.localtime()[0]) + '_' + str(utime.localtime()[1]) + '_' + str(utime.localtime()[2]) + '/' + str(utime.localtime()[0]) + '_' + str(utime.localtime()[1]) + '_' + str(utime.localtime()[2]) + '_' + str(utime.localtime()[3]) + '.csv' file = open(name, 'a+') wrstring = 'date' + ';' + 'time' + ';' + 'temperature' + ';' + 'pressure' + ';' + 'humidity' + '\r\n' file.write(wrstring) file.close() except: wait(0.001) name = '/sd/'+str(utime.localtime()[0]) + '_' + str(utime.localtime()[1]) + '_' + str(utime.localtime()[2])+ '/' + str(utime.localtime()[0]) + '_' + str(utime.localtime()[1]) + '_' + str(utime.localtime()[2]) + '_' + str(utime.localtime()[3]) + '.csv' file = open(name, 'a') year = str(utime.localtime()[0]) month = str(utime.localtime()[1]) day = str(utime.localtime()[2]) hour = str(utime.localtime()[3]) minute = str(utime.localtime()[4]) second = str(utime.localtime()[5]) # temperature, pressure and humidity temperature =str(env0.temperature()) pressure = str(env0.pressure()) humidity = str(env0.humidity()) wrstring = year + '.' + month + '.' + day + ';' + hour + ':' + minute + ':' + second + ';' + temperature + ';' + pressure + ';' + humidity + '\r\n' file.write(wrstring) file.close() ### WRITE TO FILE FOR DAY if math.fabs(utime.localtime()[4] - previostimeD) >= 5: previostimeD = utime.localtime()[4] ### create table file try: uos.stat('/sd/'+str(utime.localtime()[0]) + '_' + str(utime.localtime()[1]) + '_' + str(utime.localtime()[2]) + '/day_' + str(utime.localtime()[2]) + '.csv') except: name = '/sd/'+str(utime.localtime()[0]) + '_' + str(utime.localtime()[1]) + '_' + str(utime.localtime()[2]) + '/day_' + str(utime.localtime()[2]) + '.csv' file = open(name, 'a+') wrstring = 'date' + ';' + 'time' + ';' + 'temperature' + ';' + 'pressure' + ';' + 'humidity' + '\r\n' file.write(wrstring) file.close() name = '/sd/'+str(utime.localtime()[0]) + '_' + str(utime.localtime()[1]) + '_' + str(utime.localtime()[2]) + '/day_' + str(utime.localtime()[2]) + '.csv' file = open(name, 'a') wrstring = year + '.' + month + '.' + day + ';' + hour + ':' + minute + ':' + second + ';' + temperature + ';' + pressure + ';' + humidity + '\r\n' file.write(wrstring) file.close() ### WRITE TO FILE FOR MONTH if math.fabs(utime.localtime()[4] - previostimeMn) >= 20: previostimeMn = utime.localtime()[4] ### create table file try: uos.stat('/sd/month_' + str(utime.localtime()[1]) + '.csv') except: name = '/sd/month_' + str(utime.localtime()[1]) + '.csv' file = open(name, 'a+') wrstring = 'date' + ';' + 'time' + ';' + 'temperature' + ';' + 'pressure' + ';' + 'humidity' + '\r\n' file.write(wrstring) file.close() name = '/sd/month_' + str(utime.localtime()[1]) + '.csv' file = open(name, 'a') wrstring = year + '.' + month + '.' + day + ';' + hour + ':' + minute + ':' + second + ';' + temperature + ';' + pressure + ';' + humidity + '\r\n' file.write(wrstring) file.close()
def lstat(name): return stat_result(uos.stat(name, False))
def get_filesize(fn): # like os.path.getsize() import uos return uos.stat(fn)[6]
# test 8/16/32/64 bit signed/unsigned integer arguments and return types for ffi functions # requires ffi_lib.c to be compiled as: $(CC) -shared -o ffi_lib.so ffi_lib.c import uos, usys try: import ffi except ImportError: print("SKIP") raise SystemExit ffi_lib_filename = "./" + usys.argv[0].rsplit("/", 1)[0] + "/ffi_lib.so" try: uos.stat(ffi_lib_filename) except OSError: print("SKIP") raise SystemExit ffi_lib = ffi.open(ffi_lib_filename) f8i = ffi_lib.func("b", "f8i", "b") f8u = ffi_lib.func("B", "f8u", "B") f16i = ffi_lib.func("h", "f16i", "h") f16u = ffi_lib.func("H", "f16u", "H") f32i = ffi_lib.func("i", "f32i", "i") f32u = ffi_lib.func("I", "f32u", "I") f64i = ffi_lib.func("q", "f64i", "q") f64u = ffi_lib.func("Q", "f64u", "Q") for func_name in ("f8i", "f8u", "f16i", "f16u", "f32i", "f32u", "f64i", "f64u"):
def ftpserver(): DATA_PORT = 13333 ftpsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) datasocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ftpsocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) datasocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) ftpsocket.bind(socket.getaddrinfo("0.0.0.0", 21)[0][4]) datasocket.bind(socket.getaddrinfo("0.0.0.0", DATA_PORT)[0][4]) ftpsocket.listen(1) ftpsocket.settimeout(None) datasocket.listen(1) datasocket.settimeout(None) msg_250_OK = '250 OK\r\n' msg_550_fail = '550 Failed\r\n' # check for an active interface, STA first wlan = network.WLAN(network.STA_IF) if wlan.active(): addr = wlan.ifconfig()[0] else: wlan = network.WLAN(network.AP_IF) if wlan.active(): addr = wlan.ifconfig()[0] else: print("No active connection") return print("FTP Server started on ", addr) try: dataclient = None fromname = None do_run = True while do_run: cl, remote_addr = ftpsocket.accept() cl.settimeout(300) cwd = '/' try: # print("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: print("Client disappeared") do_run = False break command = data.split(" ")[0].upper() payload = data[len(command):].lstrip() path = get_absolute_path(cwd, payload) print("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" or command == "XPWD": cl.sendall('257 "{}"\r\n'.format(cwd)) elif command == "CWD" or command == "XCWD": try: files = uos.listdir(path) cwd = path cl.sendall(msg_250_OK) except: cl.sendall(msg_550_fail) elif command == "CDUP": cwd = 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 = datasocket.accept() print("FTP Data connection from:", data_addr) DATA_PORT = 13333 active = False elif command == "PORT": items = payload.split(",") if len(items) >= 6: data_addr = '.'.join(items[:4]) if data_addr == "127.0.1.1": # replace by command session addr data_addr = remote_addr DATA_PORT = int(items[4]) * 256 + int(items[5]) dataclient = socket.socket(socket.AF_INET, socket.SOCK_STREAM) dataclient.settimeout(10) dataclient.connect((data_addr, DATA_PORT)) print("FTP Data connection with:", data_addr) cl.sendall('200 OK\r\n') active = True else: cl.sendall('504 Fail\r\n') elif command == "LIST" or command == "NLST": if not payload.startswith("-"): place = path else: place = cwd try: cl.sendall( "150 Here comes the directory listing.\r\n") send_list_data( place, dataclient, command == "LIST" or payload == "-l") 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: cl.sendall("150 Opening data connection.\r\n") send_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 == "STOR": try: cl.sendall("150 Ok to send data.\r\n") 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" or command == "XRMD": try: uos.rmdir(path) cl.sendall(msg_250_OK) except: cl.sendall(msg_550_fail) elif command == "MKD" or command == "XMKD": 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") send_list_data(path, cl, True) cl.sendall("213 Done.\r\n") else: cl.sendall("502 Unsupported command.\r\n") print("Unsupported command {} with payload {}".format( command, payload)) except Exception as err: print(err) finally: cl.close() cl = None finally: datasocket.close() ftpsocket.close() if dataclient is not None: dataclient.close()
def envia_archivo_multipart(self, canal_id, arch, comando, nombre, comentario=''): limite = ubinascii.hexlify(uos.urandom(16)).decode('ascii') cadenados = b'--' cadenados += limite cadenados += '\r\n' cadenados += b'content-disposition: form-data; name= "chat_id"\r\n\r\n' cadenados += canal_id cadenados += b'\r\n--' cadenados += limite cadenados += b'\r\n' if comentario != '': cadenados += b'content-disposition: form-data; name= "caption"\r\n\r\n' cadenados += comentario cadenados += b'\r\n--' cadenados += limite cadenados += b'\r\n' cadenados += b'content-disposition: form-data; name= "' cadenados += nombre cadenados += b'"; filename= "file.jpg"\r\n' cadenados += b'Content-Type: image-jpeg\r\n\r\n' cadenatres = b'\r\n--' cadenatres += limite cadenatres += b'--\r\n' gc.collect() x = uos.stat(arch) tamarch = x[6] Tamanyo_total = str(tamarch + len(cadenados) + len(cadenatres)) archivo = "" gc.collect() cadenainicio = b'POST /bot' cadenainicio += self.token cadenainicio += b'/' cadenainicio += comando cadenainicio += b' HTTP/1.1\r\n' cadenainicio += b'Host: api.telegram.org\r\n' cadenainicio += b'User-Agent: KmiZbot/v1.0\r\n' cadenainicio += b'Accept: */*\r\n' cadenainicio += b'Content-Length: ' cadenainicio += Tamanyo_total cadenainicio += b'\r\n' cadenainicio += b'Content-Type: multipart/form-data; boundary=' cadenainicio += limite cadenainicio += b'\r\n\r\n' self.usock.write(cadenainicio) self.usock.write(cadenados) f = open(arch, "rb") contenido = bytearray(f.read(512), 'utf-8') while contenido: self.usock.write(contenido) contenido = bytearray(f.read(512), 'utf-8') gc.collect() f.close() self.usock.write(cadenatres) gc.collect() data = self.usock.readline() while data: # if '200 OK' in data:break data = self.usock.readline()