答应好的客户端代码来了,还是github上的代码,分为三个部分,config.json配置文件,ftplib库和main主程序,当然想合成一个自己改一下即可,也不难。
这个程序还是有点用处的,比如直接读取服务端的某个文件,也是无线传输的一种方式,当然由于esp32本身储存空间有限,只有几M,还是读取数据类的txt等比较合适。
踩坑提示:
win10建立ftp反而挺繁琐,而且会出现本地访问ftp有效,其他机器访问不行,这时候要把对应的进程文件通过防火墙即可,安卓倒是有一键建立ftp的app,比电脑方便多了。
下面上代码:
config.json
{
"wifi" : {"ssid": "findx3", "pass": "800080008000"},
"ftp" : {"host": "192.168.41.65", "port": 21, "user": "jd3096", "pass": "0403"},
}
main.py
from network import WLAN
import ftplib
import time
import ujson
import os
# load config file
with open("config.json") as fp:
config = ujson.load(fp)
# set wlan
wlan = WLAN()
wlan.active(True)
#wlan.init(mode=WLAN.STA_AP, channel=7, antenna=WLAN.INT_ANT, ssid="wipy-wlan")
#wlan.connect(config['wifi']['ssid'], auth=(WLAN.WPA2, config['wifi']['pass']))
print(config['wifi']['ssid'],config['wifi']['pass'],config['ftp']['host'],config['ftp']['port'],config['ftp']['user'],config['ftp']['pass'])
wlan.connect(config['wifi']['ssid'],config['wifi']['pass'])
while not wlan.isconnected():
time.sleep_ms(50)
print("WIFI CONNECTED")
print(wlan.ifconfig())
def print_screen(x):
print(x)
with ftplib.FTP() as ftp:
ftp.connect(config['ftp']['host'],port=config['ftp']['port'],timeout=0.1)
ftp.set_debuglevel(1)
ftp.login(config['ftp']['user'], config['ftp']['pass'])
print('login done')
# create folder test
ftp.mkd('test')
# cd to test
ftp.cwd('test')
# create a file and send it to the server
with open('test.txt', 'w+') as fp:
fp.write("Hello FTP...")
with open('test.txt', 'rb') as fp:
ftp.storbinary('STOR test_server.txt', fp, blocksize=8192,
callback=None, rest=None)
# dir
ftp.dir()
# get the file from the server
with open('test_server.txt', 'w+') as fp:
ftp.retrbinary("RETR test_server.txt", fp.write, blocksize=8192, rest=None)
with open('test_server.txt', 'r') as fp:
print(fp.read())
# remove files
ftp.delete('test_server.txt')
ftp.cwd('..')
#ftp.rmd('test')
ftp.quit()
os.remove('test.txt')
os.remove('test_server.txt')
print("DONE")
ftplib.py
try:
import usocket as _socket
except ImportError:
import socket as _socket
import ssl
import time
__all__ = (
"Error",
"FTP",
"error_perm",
"error_proto",
"error_reply",
"error_temp"
)
# Magic number from <socket.h>
# Process data out of band
MSG_OOB = 0x1
# The standard FTP server control port
FTP_PORT = 21
# The sizehint parameter passed to readline() calls
MAXLINE = 8192
# Line terminators (we always output CRLF, but accept any of CRLF, CR, LF)
CRLF = '\r\n'
B_CRLF = b'\r\n'
MIN_PORT = 40001
MAX_PORT = 40100
_GLOBAL_DEFAULT_TIMEOUT = object()
# For compatibility with CPython version with SSL support
_SSLSocket = None
# Exception raised when an error or invalid response is received
class Error(Exception):
"""Base FTP exception."""
pass
class error_reply(Error):
"""Unexpected [123]xx reply."""
pass
class error_temp(Error):
"""4xx errors."""
pass
class error_perm(Error):
"""5xx errors."""
pass
class error_proto(Error):
"""Response does not begin with [1-5]."""
pass
def _resolve_addr(addr):
if isinstance(addr, (bytes, bytearray)):
return addr
family = _socket.AF_INET
if len(addr) != 2:
family = _socket.AF_INET6
if not addr[0]:
host = "127.0.0.1" if family == _socket.AF_INET else "::1"
else:
host = addr[0]
return _socket.getaddrinfo(host, addr[1])
socket = _socket.socket
#if getattr(_socket, 'SocketType', None):
# socket = _socket.socket
#else:
#class socket:
# def __init__(self, *args):
# if args and isinstance(args[0], _socket.socket):
# self._sock = args[0]
# else:
# self._sock = _socket.socket(*args)
# def accept(self):
# s, addr = self._sock.accept()
# return self.__class__(s), addr
# def bind(self, addr):
# return self._sock.bind(_resolve_addr(addr))
# def connect(self, addr):
# return self._sock.connect(_resolve_addr(addr))
# def sendall(self, *args):
# return self._sock.send(*args)
# def __getattr__(self, name):
# return getattr(self._sock, name)
# def __enter__(self):
# return self._sock
# def __exit__(self, *args):
# self._sock.close()
# The main class itself
class FTP:
"""An FTP client class.
To create a connection, call the class using these arguments::
host, port, user, passwd, acct, timeout, source_address
The host, user, passwd and acct arguments are all strings, while port is an
integer. The default value for all is None, which means the following
defaults will be used: host: localhost, port: 21, user: 'anonymous',
passwd: anonymous@', acct: ''
timeout must be numeric and also defaults to None, meaning that no timeout
will be set on any ftp socket(s). If a timeout is passed, then this is now
the default timeout for all ftp socket operations for this instance.
If supplied, source_address must be a 2-tuple (host, port) for all sockets
created by this instance to bind to as their source address before
connecting.
If you pass a host name or address to the constructor, the 'connect' method
will be called directly with the host and port given. Otherwise use
'connect' later, optionally passing host and port arguments. If you also
pass a non-empty value for user, the 'login' method will be called with
user, passwd and acct given after calling 'connect'.
To download a file, use ftp.retrlines('RETR ' + filename), or
ftp.retrbinary() with slightly different arguments. To upload a file, use
ftp.storlines() or ftp.storbinary(), which have an open file as argument
(see their definitions below for details).
The download/upload functions first issue appropriate TYPE and PORT or PASV
commands.
"""
debugging = 0
host = None
port = FTP_PORT
timeout = _GLOBAL_DEFAULT_TIMEOUT
source_address = None
maxline = MAXLINE
sock = None
file = None
welcome = None
passiveserver = 1
encoding = "latin-1"
def __init__(self, host=None, port=None, user=None, passwd=None, acct=None,
timeout=_GLOBAL_DEFAULT_TIMEOUT, source_address=None):
"""Initialization method (called by class instantiation).
See class docstring for supported arguments.
"""
# These two settings are not tied to the connection, so if they are
# given, we override the defaults, regardless of whether an initial
# host to conenct to has been given or not.
if timeout is not None

本文介绍了一个基于 ESP32 的 FTP 客户端实现方案,该方案能够从 FTP 服务器读取文件,并提供了完整的源代码,包括配置文件、FTPLib 库及主程序。
最低0.47元/天 解锁文章
308

被折叠的 条评论
为什么被折叠?



