[作品提交] 【得捷Follow me第4期】项目总结

chrisrh   2024-3-1 16:16 楼主

对Follow me4项目的过往进行总结

因为是第一次应用树莓派的RP2040,很多地方比较生疏,所以选择了最为官方推荐的方案 W5500-EVB-Pico、 Adafruit Sharp Memory Display,跟在大家的后面,一起学习进步。

这次收获满满,认识了RP2040,了解了micro python和circuit python编程的方便,更是学到了许多TCP/IP相关的知识,收益颇丰!

汇总视频: 

202402181614

 


一、入门任务:

1、开发环境搭建,这里选择了micro python和circuit python进行后续工作,刷写固件也很方便

fm4_mv-1

 

2、LED灯BLINK闪闪,驱动液晶显示器进行显示

【得捷电子Follow me第4期】入门任务-开箱-开发环境搭建-BLINK - DigiKey得捷技术专区 - 电子工程世界-论坛 (eeworld.com.cn)

import machine  
import time

# 初始化LED引脚为输出模式  
led = machine.Pin('LED', machine.Pin.OUT)  
  
while True:  
    # 点亮LED  
    led.on()  
    time.sleep(1)  # 等待1秒钟  
      
    # 熄灭LED  
    led.off()  
    time.sleep(1)  # 等待1秒钟

3、驱动sharp的lcd屏幕,显示信息

【得捷电子Follow me第4期】入门任务->基础任务一 - DigiKey得捷技术专区 - 电子工程世界-论坛 (eeworld.com.cn)

import sys
import time
import board  
import digitalio  
import busio
import adafruit_sharpmemorydisplay

# 打印输入到stdout  
print("start:xxx")

# 初始化LED引脚  
led = digitalio.DigitalInOut(board.GP25)
led.direction = digitalio.Direction.OUTPUT 

# Initialize SPI bus and control pins
spi = busio.SPI(board.GP14, MOSI=board.GP15)
scs = digitalio.DigitalInOut(board.GP13)  # inverted chip select

# pass in the display size, width and height, as well
# display = adafruit_sharpmemorydisplay.SharpMemoryDisplay(spi, scs, 96, 96)
display = adafruit_sharpmemorydisplay.SharpMemoryDisplay(spi, scs, 144, 168)

print("Pixel test")

# Clear the display.  Always call show after changing pixels to make the display
# update visible!
display.fill(1)
display.show()

# Set a pixel in the origin 0,0 position.
display.pixel(0, 0, 0)
# Set a pixel in the middle position.
display.pixel(display.width // 2, display.width // 2, 0)
# Set a pixel in the opposite corner position.
display.pixel(display.width - 1, display.height - 1, 0)
display.show()
time.sleep(2)

print("Lines test")
# we'll draw from corner to corner, lets define all the pair coordinates here
corners = (
    (0, 0),
    (0, display.height - 1),
    (display.width - 1, 0),
    (display.width - 1, display.height - 1),
)
display.fill(1)
for corner_from in corners:
    for corner_to in corners:
        display.line(corner_from[0], corner_from[1], corner_to[0], corner_to[1], 0)
display.show()
time.sleep(2)

print("Rectangle test")
display.fill(1)
w_delta = display.width / 10
h_delta = display.height / 10
for i in range(11):
    display.rect(0, 0, int(w_delta * i), int(h_delta * i), 0)
display.show()
time.sleep(2)

print("Text test")
display.fill(1)

display.text(" hello world!", 0, 0, 0)
display.text(" This is the", 0, 8, 0)
display.text(" CircuitPython", 0, 16, 0)
display.text("adafruit library", 0, 24, 0)
display.text(" for the SHARP", 0, 32, 0)
display.text(" Memory Display :) ", 0, 40, 0)
display.show()

# 循环使能LED点亮  
while True:  
    # 点亮LED  
    led.value = True  
    time.sleep(1)  
    led.value = False  
    time.sleep(1)

cb31256870ea5d56a1dedf6a911c69a4

 

二、基础任务一

完成主控板W5500初始化(静态IP配置),并能使用局域网电脑ping通,同时W5500可以ping通互联网站点;通过抓包软件(Wireshark、Sniffer等)抓取ping报文析。

【得捷电子Follow me第4期】入门任务->基础任务一 - DigiKey得捷技术专区 - 电子工程世界-论坛 (eeworld.com.cn)

import board
import busio
import digitalio
import time
from adafruit_wiznet5k.adafruit_wiznet5k import WIZNET5K

##SPI0
SPI0_SCK = board.GP18
SPI0_TX = board.GP19
SPI0_RX = board.GP16
SPI0_CSn = board.GP17

##reset
W5x00_RSTn = board.GP20

print("Wiznet5k Ping Test (no DHCP)")

# Setup your network configuration below
# random MAC, later should change this value on your vendor ID
MY_MAC = (0x00, 0x01, 0x02, 0x03, 0x04, 0x05)
IP_ADDRESS = (192, 168, 1, 100)
SUBNET_MASK = (255, 255, 255, 0)
GATEWAY_ADDRESS = (192, 168, 1, 1)
DNS_SERVER = (8, 8, 8, 8)

led = digitalio.DigitalInOut(board.GP25)
led.direction = digitalio.Direction.OUTPUT

ethernetRst = digitalio.DigitalInOut(W5x00_RSTn)
ethernetRst.direction = digitalio.Direction.OUTPUT

# For Adafruit Ethernet FeatherWing
cs = digitalio.DigitalInOut(SPI0_CSn)
# For Particle Ethernet FeatherWing
# cs = digitalio.DigitalInOut(board.D5)
spi_bus = busio.SPI(SPI0_SCK, MOSI=SPI0_TX, MISO=SPI0_RX)

# Reset W5500 first
ethernetRst.value = False
time.sleep(1)
ethernetRst.value = True

# Initialize ethernet interface with DHCP
# eth = WIZNET5K(spi_bus, cs)
# Initialize ethernet interface without DHCP
eth = WIZNET5K(spi_bus, cs, is_dhcp=False, mac=MY_MAC)

# Set network configuration
eth.ifconfig = (IP_ADDRESS, SUBNET_MASK, GATEWAY_ADDRESS, DNS_SERVER)

print("Chip Version:", eth.chip)
print("MAC Address:", [hex(i) for i in eth.mac_address])
print("My IP address is:", eth.pretty_ip(eth.ip_address))

while True:
    led.value = not led.value
    time.sleep(1)

print("Done!")

设置静态IP:

IP_ADDRESS = (192, 168, 1, 100)

SUBNET_MASK = (255, 255, 255, 0)

GATEWAY_ADDRESS = (192, 168, 1, 1)

 

同一路由下,本机的IP为192.168.1.33,然后在CMD中使用ping  192, 168, 1, 100完成静态IP的ping

fm4_mv2

 

三、基础任务二

主控板建立TCP/IP或UDP服务器,使用TCP/IP或UDP客户端进行连接与发送数据,主控板接收数据并显示,通过抓包软件抓取交互报文

【得捷电子Follow me第4期】基础任务二-TCP server和UDP server - DigiKey得捷技术专区 - 电子工程世界-论坛 (eeworld.com.cn)

3.1、TCP Server

将pico+W5500通过网线接到路由或者交换机上,这里主机地址是192.168.31.171

将pico+W5500配置为192.168.31.100,端口号2233

import board
import busio
import digitalio
import time
import array

from adafruit_wiznet5k.adafruit_wiznet5k import WIZNET5K
import adafruit_wiznet5k.adafruit_wiznet5k_socket as socket
import adafruit_sharpmemorydisplay

'''LED init'''
led = digitalio.DigitalInOut(board.GP25)
led.direction = digitalio.Direction.OUTPUT

'''Sharp Display init'''
# Initialize SPI bus and control pins
spi = busio.SPI(board.GP14, MOSI=board.GP15)
scs = digitalio.DigitalInOut(board.GP13)  # inverted chip select

# pass in the display size, width and height, as well
# display = adafruit_sharpmemorydisplay.SharpMemoryDisplay(spi, scs, 96, 96)
display = adafruit_sharpmemorydisplay.SharpMemoryDisplay(spi, scs, 144, 168)

'''W5500 init start'''
##SPI0-W5500
SPI0_SCK = board.GP18
SPI0_TX = board.GP19
SPI0_RX = board.GP16
SPI0_CSn = board.GP17

##reset
W5x00_RSTn = board.GP20

print("Wiznet5k Simple TCP Server Test")

# Setup your network configuration below
# random MAC, later should change this value on your vendor ID
#MY_MAC = (0x00, 0x01, 0x02, 0x03, 0x04, 0x05)
IP_ADDRESS = (192, 168, 31, 100)
SUBNET_MASK = (255, 255, 0, 0)
GATEWAY_ADDRESS = (192, 168, 31, 1)
DNS_SERVER = (8, 8, 8, 8)

ethernetRst = digitalio.DigitalInOut(W5x00_RSTn)
ethernetRst.direction = digitalio.Direction.OUTPUT

# For Adafruit Ethernet FeatherWing
cs = digitalio.DigitalInOut(SPI0_CSn)
# For Particle Ethernet FeatherWing
# cs = digitalio.DigitalInOut(board.D5)

spi_bus = busio.SPI(SPI0_SCK, MOSI=SPI0_TX, MISO=SPI0_RX)

# Reset W5500 first
ethernetRst.value = False
time.sleep(1)
ethernetRst.value = True

# # Initialize ethernet interface without DHCP
eth = WIZNET5K(spi_bus, cs, is_dhcp=False)#, mac=MY_MAC, debug=True)
# # Set network configuration
eth.ifconfig = (IP_ADDRESS, SUBNET_MASK, GATEWAY_ADDRESS, DNS_SERVER)

# Initialize ethernet interface with DHCP
#eth = WIZNET5K(spi_bus, cs, is_dhcp=True, mac=MY_MAC, debug=True)

print("Chip Version:", eth.chip)
print("MAC Address:", [hex(i) for i in eth.mac_address])
print("My IP address is:", eth.pretty_ip(eth.ip_address))

'''W5500 init end'''

'''TCP socket init'''
# Initialize a socket for our server
socket.set_interface(eth)
server = socket.socket()  # Allocate socket for the server
server_ip = None  # IP address of server
server_port = 2233  # Port to listen on
server.bind((server_ip, server_port))  # Bind to IP and Port
server.listen()  # Begin listening for incoming clients
#conn, addr = server.accept()  # Wait for a connection from a client.
#print("socket connected")

'''display show'''
display.fill(1)
chip_version = "chip version:" + eth.chip
display.text(chip_version, 0, 0, 0)
ip_addr = "ip:" + eth.pretty_ip(eth.ip_address)
display.text(ip_addr, 0, 10, 0)
mac_addr = "mac:" + eth.pretty_mac(eth.mac_address)
display.text(mac_addr, 0, 20, 0)
display.show()

row = 30
print("socket connected")

while True:
    # Maintain DHCP lease
    #eth.maintain_dhcp_lease()
    
    led.value = not led.value
    time.sleep(1)
    
    with server:
        while True:
#           data = conn.recv(20)
            data,addr = server.recvfrom(20)
            if data:
                print(data)
                display.fill_rect(0,row,144,10,1)
                display.text(data.decode('utf-8'), 0, row, 0)
                display.show()

                row += 10
                if row > 150:
                    row = 30

fm4_mv3

LCD显示传输数据

ae7b4388745ec0c4bc29440cfa7e98d2

 

3.2、UDP Server

import board
import busio
import digitalio
import time
import array

from adafruit_wiznet5k.adafruit_wiznet5k import WIZNET5K
import adafruit_wiznet5k.adafruit_wiznet5k_socket as socket
import adafruit_sharpmemorydisplay

'''LED init'''
led = digitalio.DigitalInOut(board.GP25)
led.direction = digitalio.Direction.OUTPUT

'''Sharp Display init'''
# Initialize SPI bus and control pins
spi = busio.SPI(board.GP14, MOSI=board.GP15)
scs = digitalio.DigitalInOut(board.GP13)  # inverted chip select

# pass in the display size, width and height, as well
# display = adafruit_sharpmemorydisplay.SharpMemoryDisplay(spi, scs, 96, 96)
display = adafruit_sharpmemorydisplay.SharpMemoryDisplay(spi, scs, 144, 168)

'''W5500 init start'''
##SPI0-W5500
SPI0_SCK = board.GP18
SPI0_TX = board.GP19
SPI0_RX = board.GP16
SPI0_CSn = board.GP17

##reset
W5x00_RSTn = board.GP20

print("Wiznet5k Simple UDP Server Test")

# Setup your network configuration below
# random MAC, later should change this value on your vendor ID
#MY_MAC = (0x00, 0x01, 0x02, 0x03, 0x04, 0x05)
IP_ADDRESS = (192, 168, 31, 100)
SUBNET_MASK = (255, 255, 0, 0)
GATEWAY_ADDRESS = (192, 168, 31, 1)
DNS_SERVER = (8, 8, 8, 8)

ethernetRst = digitalio.DigitalInOut(W5x00_RSTn)
ethernetRst.direction = digitalio.Direction.OUTPUT

# For Adafruit Ethernet FeatherWing
cs = digitalio.DigitalInOut(SPI0_CSn)
# For Particle Ethernet FeatherWing
# cs = digitalio.DigitalInOut(board.D5)

spi_bus = busio.SPI(SPI0_SCK, MOSI=SPI0_TX, MISO=SPI0_RX)

# Reset W5500 first
ethernetRst.value = False
time.sleep(1)
ethernetRst.value = True

# # Initialize ethernet interface without DHCP
eth = WIZNET5K(spi_bus, cs, is_dhcp=False)#, mac=MY_MAC, debug=True)
# # Set network configuration
eth.ifconfig = (IP_ADDRESS, SUBNET_MASK, GATEWAY_ADDRESS, DNS_SERVER)

# Initialize ethernet interface with DHCP
#eth = WIZNET5K(spi_bus, cs, is_dhcp=True, mac=MY_MAC, debug=True)

print("Chip Version:", eth.chip)
print("MAC Address:", [hex(i) for i in eth.mac_address])
print("My IP address is:", eth.pretty_ip(eth.ip_address))

'''W5500 init end'''

'''UDP socket init'''
# Initialize a socket for our server
socket.set_interface(eth)
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  # Allocate socket for the server
server_ip = None  # IP address of server
server_port = 2233  # Port to listen on
server.bind((eth.pretty_ip(eth.ip_address), server_port))  # Bind to IP and Port
    

'''display show'''
display.fill(1)
chip_version = "chip version:" + eth.chip
display.text(chip_version, 0, 0, 0)
ip_addr = "ip:" + eth.pretty_ip(eth.ip_address)
display.text(ip_addr, 0, 10, 0)
mac_addr = "mac:" + eth.pretty_mac(eth.mac_address)
display.text(mac_addr, 0, 20, 0)
display.show()

row = 30
print("socket connected")

while True:
    # Maintain DHCP lease
    #eth.maintain_dhcp_lease()
    
    led.value = not led.value
    time.sleep(1)
    
    with server:
        while True:
#           data = conn.recv(20)
            data,addr = server.recvfrom(20)
            if data:
                print(data)
                display.fill_rect(0,row,144,10,1)
                display.text(data.decode('utf-8'), 0, row, 0)
                display.show()

                row += 10
                if row > 150:
                    row = 30
                    server.send(data)
                    #conn.send(data)  # Echo message back to client

 

四、进阶任务

从NTP服务器(注意数据交互格式的解析)同步时间,获取时间送显示屏(串口)显示

【得捷电子Follow me第4期】进阶任务-NTP同步时间 - DigiKey得捷技术专区 - 电子工程世界-论坛 (eeworld.com.cn)

基于socket的示例,导入adafruit的ntp库,进行时间的获取与同步,import adafruit_ntp

import board
import busio
import digitalio
import time
import array
import struct
import adafruit_requests as requests
from adafruit_wiznet5k.adafruit_wiznet5k import *
import adafruit_wiznet5k.adafruit_wiznet5k_socket as socket
from adafruit_wiznet5k.adafruit_wiznet5k_ntp import NTP
import adafruit_wiznet5k.adafruit_wiznet5k_dns as dns

import adafruit_ntp

days = ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
             
##SPI0
SPI0_SCK = board.GP18
SPI0_TX = board.GP19
SPI0_RX = board.GP16
SPI0_CSn = board.GP17

##reset
W5x00_RSTn = board.GP20

print("Wiznet5k NTP Client (DHCP)")

# Setup your network configuration below
# random MAC, later should change this value on your vendor ID
MY_MAC = (0x00, 0x01, 0x02, 0xFF, 0xFF, 0xFF)
IP_ADDRESS = (192, 168, 1, 24)
SUBNET_MASK = (255, 255, 255, 0)
GATEWAY_ADDRESS = (192, 168, 1, 1)
DNS_SERVER = (8, 8, 8, 8)
port = 5000
ntp_server_port= 123

led = digitalio.DigitalInOut(board.GP25)
led.direction = digitalio.Direction.OUTPUT

ethernetRst = digitalio.DigitalInOut(W5x00_RSTn)
ethernetRst.direction = digitalio.Direction.OUTPUT

# For Adafruit Ethernet FeatherWing
cs = digitalio.DigitalInOut(SPI0_CSn)

# cs = digitalio.DigitalInOut(board.D5)
spi_bus = busio.SPI(SPI0_SCK, MOSI=SPI0_TX, MISO=SPI0_RX)

# Reset W5500 first
ethernetRst.value = False
time.sleep(1)
ethernetRst.value = True

# Initialize ethernet interface without DHCP
#eth = WIZNET5K(spi_bus, cs, is_dhcp=False, mac=MY_MAC, debug=False)
# Initialize ethernet interface with DHCP
eth = WIZNET5K(spi_bus, cs, is_dhcp=True, mac=MY_MAC, debug=False)
print("Chip Version:", eth.chip)
print("MAC Address:", [hex(i) for i in eth.mac_address])
print("My IP address is:", eth.pretty_ip(eth.ip_address))

# Initialize a socket for our server
socket.set_interface(eth)
# Set network configuration
eth.ifconfig = (IP_ADDRESS, SUBNET_MASK, GATEWAY_ADDRESS, DNS_SERVER)

ntp = adafruit_ntp.NTP(socket)
print(ntp.datetime)

通过串口打印出相关信息和+8后的时间:2024.2.16.23:59:44

fm4_mv5

 

终极任务二

终极任务是使用外部存储器,组建简易FTP文件服务器,并能正常上传下载文件。

【得捷电子Follow me第4期】终极任务+总结 - DigiKey得捷技术专区 - 电子工程世界-论坛 (eeworld.com.cn)

这里借鉴并学习了其他小伙伴做的基于micropython的FTP服务器

import socket
import network
import uos
import gc
from time import localtime
from machine import Pin,SPI
import time

def w5x00_init():
    #spi init
    spi=SPI(0,2_000_000, mosi=Pin(19),miso=Pin(16),sck=Pin(18))
    nic = network.WIZNET5K(spi,Pin(17),Pin(20)) #spi,cs,reset pin
    nic.active(True)#network active
    nic.ifconfig(('192.168.1.100','255.255.255.0','192.168.1.1','8.8.8.8'))#Set static network address information
    while not nic.isconnected():
        time.sleep(1)
        print(nic.regs())#Print register information
        
    #Print network address information
    print("IP Address:",nic.ifconfig()[0])
    print("Subnet Mask:",nic.ifconfig()[1])
    print("Gateway:",nic.ifconfig()[2])
    print("DNS:",nic.ifconfig()[3])
    return nic

month_name = ["", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]

def send_list_data(path, dataclient, full):
    try: # whether path is a directory name
        for fname in uos.listdir(path):
            dataclient.sendall(make_description(path, fname, full))
    except: # path may be a file name or pattern
        pattern = path.split("/")[-1]
        path = path[:-(len(pattern) + 1)]
        if path == "": path = "/"
        for fname in uos.listdir(path):
            if fncmp(fname, pattern) == True:
                dataclient.sendall(make_description(path, fname, full))
                
def make_description(path, fname, full):
    if full:
        stat = uos.stat(get_absolute_path(path,fname))
        file_permissions = "drwxr-xr-x" if (stat[0] & 0o170000 == 0o040000) else "-rw-r--r--"
        file_size = stat[6]
        tm = localtime(stat[7])
        if tm[0] != localtime()[0]:
            description = "{}    1 owner group {:>10} {} {:2} {:>5} {}\r\n".format(
                file_permissions, file_size, month_name[tm[1]], tm[2], tm[0], fname)
        else:
            description = "{}    1 owner group {:>10} {} {:2} {:02}:{:02} {}\r\n".format(
                file_permissions, file_size, month_name[tm[1]], tm[2], tm[3], tm[4], fname)
    else:
        description = fname + "\r\n"
    return description
    
def send_file_data(path, dataclient):
    with open(path, "r") as file:
        chunk = file.read(512)
        while len(chunk) > 0:
            dataclient.sendall(chunk)
            chunk = file.read(512)

def save_file_data(path, dataclient, mode):
    with open(path, mode) as file:
        chunk = dataclient.read(512)
        while len(chunk) > 0:
            file.write(chunk)
            chunk = dataclient.read(512)

def get_absolute_path(cwd, payload):
    # Just a few special cases "..", "." and ""
    # If payload start's with /, set cwd to / 
    # and consider the remainder a relative path
    if payload.startswith('/'):
        cwd = "/"
    for token in payload.split("/"):
        if token == '..':
            if cwd != '/':
                cwd = '/'.join(cwd.split('/')[:-1])
                if cwd == '': 
                    cwd = '/'
        elif token != '.' and token != '':
            if cwd == '/':
                cwd += token
            else:
                cwd = cwd + '/' + token
    return cwd

# compare fname against pattern. Pattern may contain
# wildcards ? and *.
def fncmp(fname, pattern):
    pi = 0
    si = 0
    while pi < len(pattern) and si < len(fname):
        if (fname[si] == pattern[pi]) or (pattern[pi] == '?'):
            si += 1
            pi += 1
        else:
            if pattern[pi] == '*': # recurse
                if (pi + 1) == len(pattern):
                    return True
                while si < len(fname):
                    if fncmp(fname[si:], pattern[pi+1:]) == True:
                        return True
                    else:
                        si += 1
                return False
            else:
                return False
    if pi == len(pattern.rstrip("*"))  and si == len(fname):
        return True
    else:
        return False
    
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)
    datasocket.listen(1)
    datasocket.settimeout(10)

    msg_250_OK = '250 OK\r\n'
    msg_550_fail = '550 Failed\r\n'
    try:
        dataclient = None
        fromname = None
        while True:
            cl, remote_addr = ftpsocket.accept()
            cl.settimeout(300)
            cwd = '/'
            try:
                # print("FTP connection from:", remote_addr)
                cl.sendall("220 Hello, this is the ESP8266.\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={}, Path={}".format(command, payload, path))
                    
                    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')
                        break
                    elif command == "PASV":
                        addr = nic.ifconfig()[0]
                        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)
                    elif command == "LIST" or command == "NLST":
                        if not payload.startswith("-"):
                            place = path
                        else: 
                            place = cwd
                        try:
                            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:
                            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")
                            save_file_data(path, dataclient, "w")
                            cl.sendall("226 Transfer complete.\r\n")
                        except:
                            cl.sendall(msg_550_fail)
                        if dataclient is not None:
                            dataclient.close()
                            dataclient = None
                    elif command == "APPE":
                        try:
                            cl.sendall("150 Ok to send data.\r\n")
                            save_file_data(path, dataclient, "a")
                            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
                    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()

nic = w5x00_init()
ftpserver()

fm4_mv6

 


 

整个Follow me第四期下来,收获满满,自己作为小白,首先把pico裸机的外设端口学习了一遍,接着摸索着点亮了sharp的LCD屏幕,显示的那一瞬满是开心,也许电子这一行的快乐可能就是调通的那一刹那,后面在TCP/IP这块,配合着WiFi那块板子的调试进度,对client和servers有了更进一步的认知,在这块是真的学到了些许东西;最后的FTP服务器,自己没搞定,学习了论坛其他小伙伴的程序,后续随着自己的学习不断完善;

 


 

最后,谢谢得捷和EEworld的组织的这次活动,和给予的这次参与机会,组织的很棒。以后我会多加关注,积极参加论坛活动,多方面提升个人的知识,与大家一同进步,加油!

 

 

本帖最后由 chrisrh 于 2024-3-1 16:16 编辑

回复评论 (1)

恭喜大佬完成作品,参加这样的活动,能够拿的到开发板,学习到新技能,非常好的活动呀!
点赞  2024-3-2 06:30
电子工程世界版权所有 京B2-20211791 京ICP备10001474号-1 京公网安备 11010802033920号
    写回复