FTP可以连接成功
This commit is contained in:
@@ -220,6 +220,8 @@ HAL_Init() → SystemClock_Config() → MX_GPIO_Init() → MX_USART1_UART_Init()
|
||||
- **Trap 06** TCP KeepAlive 参数非 500ms 倍数
|
||||
- **Trap 07** TCP 关闭误用 disconnect 导致 FIN_WAIT_2
|
||||
- **Trap 08** RECV 中断电平触发无限循环
|
||||
- **Trap 09** PHY link up 后立即 open_socket 失败(需启动延时 + 重试兜底)
|
||||
- **Trap 10** 消息队列值拷贝导致结果回传丢失(改用 xTaskNotify 通知值)
|
||||
|
||||
当前已记录陷阱(GD5F2GQ5UE):
|
||||
- **Trap 01** 块擦除地址错误(`byte_addr → page_addr`),导致先前所有实验结论无效。详见 `docs/GD5F2GQ5UE_Trap_Records.md`
|
||||
|
||||
@@ -607,6 +607,9 @@ int lftpd_start(const char *directory, int port, lftpd_t *lftpd)
|
||||
handle_control_channel(&client);
|
||||
lftpd->client = NULL;
|
||||
|
||||
/* 等待 CH395F 稳定(Trap 09) */
|
||||
vTaskDelay(pdMS_TO_TICKS(200));
|
||||
|
||||
/* standalone mode: socket was closed in handle_control_channel,
|
||||
* loop back to create a new listener */
|
||||
}
|
||||
|
||||
@@ -38,6 +38,7 @@ static net_sock_t s_net_socks[NET_MAX_SOCKETS]; /* Socket 控制块数组 */
|
||||
static int s_net_errno = 0; /* 最后错误码 */
|
||||
static uint8_t s_net_initialized = 0; /* 初始化标志 */
|
||||
static uint8_t s_local_ip[4]; /* 本机 IP 缓存(网络序,net_getsockname 用) */
|
||||
static uint16_t s_dynamic_port = 49152; /* 动态端口分配起始值 */
|
||||
|
||||
/*
|
||||
* 消息队列 - 线程安全核心
|
||||
@@ -431,6 +432,15 @@ int net_bind(int sockfd, const struct net_sockaddr *addr, int addrlen) {
|
||||
/* 设置本地端口(转换为主机序) */
|
||||
p_sock->local_port = net_ntohs(p_addr_in->sin_port);
|
||||
|
||||
/* port=0 时自动分配动态端口(49152~65535) */
|
||||
if (p_sock->local_port == 0) {
|
||||
p_sock->local_port = s_dynamic_port;
|
||||
s_dynamic_port++;
|
||||
if (s_dynamic_port > 65535) {
|
||||
s_dynamic_port = 49152;
|
||||
}
|
||||
}
|
||||
|
||||
/* UDP (SOCK_DGRAM): 直接在此打开 CH395F Socket */
|
||||
if (p_sock->type == NET_SOCK_DGRAM) {
|
||||
uint8_t status;
|
||||
@@ -595,7 +605,12 @@ static int net_accept_locked(int sockfd, struct net_sockaddr *addr, int *addrlen
|
||||
int i;
|
||||
|
||||
p_listen_sock = &s_net_socks[sockfd];
|
||||
if (!p_listen_sock->in_use || p_listen_sock->state != NET_SOCK_STATE_LISTENING) {
|
||||
if (!p_listen_sock->in_use) {
|
||||
s_net_errno = NET_ERR_INVAL;
|
||||
return -1;
|
||||
}
|
||||
if (p_listen_sock->state != NET_SOCK_STATE_LISTENING &&
|
||||
!(p_listen_sock->standalone_accept && p_listen_sock->state == NET_SOCK_STATE_ESTABLISHED)) {
|
||||
s_net_errno = NET_ERR_INVAL;
|
||||
return -1;
|
||||
}
|
||||
@@ -1461,7 +1476,7 @@ static void handle_disconnect_event(net_sock_t *p_sock) {
|
||||
memset(p_sock->remote_ip_arr, 0, 4);
|
||||
p_sock->remote_port = 0;
|
||||
p_sock->send_ready = 1;
|
||||
} else {
|
||||
} else if (p_sock->state != NET_SOCK_STATE_CLOSED) {
|
||||
/* 未预期的断开 */
|
||||
DBG_ERROR("sock%d disconnect in state %d", p_sock->ch395_sock, p_sock->state);
|
||||
fire_event(p_sock, NET_EVENT_DISCONNECTED);
|
||||
|
||||
@@ -1,71 +1,71 @@
|
||||
*** Using Compiler 'V5.06 update 7 (build 960)', folder: 'C:\Keil_v5\ARM\ARMCC\Bin'
|
||||
Rebuild target 'STM32F407-Demo'
|
||||
assembling startup_stm32f407xx.s...
|
||||
compiling ringbuf.c...
|
||||
compiling crc.c...
|
||||
compiling stm32f4xx_it.c...
|
||||
compiling ringbuf.c...
|
||||
compiling i2c.c...
|
||||
compiling stm32f4xx_hal_msp.c...
|
||||
compiling gpio.c...
|
||||
compiling usart.c...
|
||||
compiling spi.c...
|
||||
compiling gpio.c...
|
||||
compiling stm32f4xx_hal_timebase_tim.c...
|
||||
compiling stm32f4xx_hal_rcc_ex.c...
|
||||
compiling stm32f4xx_hal_flash_ex.c...
|
||||
compiling dma.c...
|
||||
compiling app_main.c...
|
||||
compiling sys_clock.c...
|
||||
compiling stm32f4xx_hal_flash_ramfunc.c...
|
||||
compiling stm32f4xx_hal_gpio.c...
|
||||
compiling stm32f4xx_hal_flash.c...
|
||||
compiling stm32f4xx_hal_rcc.c...
|
||||
compiling adc_task.c...
|
||||
compiling stm32f4xx_hal_flash_ramfunc.c...
|
||||
compiling stm32f4xx_hal_msp.c...
|
||||
compiling stm32f4xx_it.c...
|
||||
compiling usart.c...
|
||||
compiling app_main.c...
|
||||
compiling stm32f4xx_hal_gpio.c...
|
||||
compiling sys_clock.c...
|
||||
compiling stm32f4xx_hal_flash_ex.c...
|
||||
compiling rs485_task.c...
|
||||
compiling stm32f4xx_hal_tim_ex.c...
|
||||
compiling main.c...
|
||||
compiling stm32f4xx_hal_rcc_ex.c...
|
||||
compiling net_task.c...
|
||||
compiling adc_task.c...
|
||||
compiling main.c...
|
||||
compiling stm32f4xx_hal_tim_ex.c...
|
||||
compiling stm32f4xx_hal_rcc.c...
|
||||
compiling freertos.c...
|
||||
compiling stm32f4xx_hal_tim.c...
|
||||
compiling stm32f4xx_hal_dma_ex.c...
|
||||
compiling stm32f4xx_hal_dma.c...
|
||||
compiling stm32f4xx_hal_pwr_ex.c...
|
||||
compiling lftpd_io.c...
|
||||
compiling lftpd_string.c...
|
||||
compiling croutine.c...
|
||||
compiling system_stm32f4xx.c...
|
||||
compiling stm32f4xx_hal_i2c_ex.c...
|
||||
compiling stm32f4xx_hal_cortex.c...
|
||||
compiling stm32f4xx_hal_dma_ex.c...
|
||||
compiling rs485.c...
|
||||
compiling stm32f4xx_hal.c...
|
||||
compiling stm32f4xx_hal_pwr_ex.c...
|
||||
compiling stm32f4xx_hal_pwr.c...
|
||||
compiling stm32f4xx_hal_exti.c...
|
||||
compiling lftpd_io.c...
|
||||
compiling stm32f4xx_hal_cortex.c...
|
||||
compiling stm32f4xx_hal.c...
|
||||
compiling rs485.c...
|
||||
compiling sd2506.c...
|
||||
compiling tpafe5160.c...
|
||||
compiling lftpd_string.c...
|
||||
compiling nand_ftl.c...
|
||||
compiling ch395f.c...
|
||||
compiling gd5f2gq5ue.c...
|
||||
compiling stm32f4xx_hal_uart.c...
|
||||
compiling net_select.c...
|
||||
compiling lftpd_inet.c...
|
||||
compiling stm32f4xx_hal_spi.c...
|
||||
compiling croutine.c...
|
||||
compiling ch395f_test.c...
|
||||
compiling event_groups.c...
|
||||
compiling list.c...
|
||||
compiling lftpd.c...
|
||||
compiling net_socket.c...
|
||||
compiling stm32f4xx_hal_i2c.c...
|
||||
compiling tpafe5160.c...
|
||||
compiling ch395f.c...
|
||||
compiling nand_ftl.c...
|
||||
compiling gd5f2gq5ue.c...
|
||||
compiling stm32f4xx_hal_uart.c...
|
||||
compiling ch395f_test.c...
|
||||
compiling stream_buffer.c...
|
||||
compiling net_select.c...
|
||||
compiling queue.c...
|
||||
compiling stm32f4xx_hal_spi.c...
|
||||
compiling lftpd_inet.c...
|
||||
compiling timers.c...
|
||||
compiling heap_4.c...
|
||||
compiling map.c...
|
||||
compiling tasks.c...
|
||||
compiling heap_4.c...
|
||||
compiling lftpd.c...
|
||||
compiling journal.c...
|
||||
compiling port.c...
|
||||
compiling stm32f4xx_hal_i2c.c...
|
||||
compiling net_socket.c...
|
||||
compiling map.c...
|
||||
compiling ff.c...
|
||||
compiling cmsis_os2.c...
|
||||
linking...
|
||||
Program Size: Code=57728 RO-data=2132 RW-data=392 ZI-data=54848
|
||||
Program Size: Code=57764 RO-data=2132 RW-data=392 ZI-data=54848
|
||||
FromELF: creating hex file...
|
||||
".\STM32F407-Demo\STM32F407-Demo.axf" - 0 Error(s), 0 Warning(s).
|
||||
Build Time Elapsed: 00:00:18
|
||||
Build Time Elapsed: 00:00:17
|
||||
|
||||
@@ -219,3 +219,70 @@ CH395F 的 RECV 中断是电平触发的——只要接收缓冲区有数据就
|
||||
|
||||
### UDP 发送缓冲
|
||||
- 每次 `ch395f_write_send_buf()` 后必须等待 `SINT_STAT_SENBUF_FREE` 中断,否则下次写入会被 CH395F 静默丢弃
|
||||
|
||||
---
|
||||
|
||||
## Trap 09:PHY link up 后立即 open_socket 失败
|
||||
|
||||
### 现象
|
||||
`net_listen()` 在 PHY_CHANGE 中断同一时刻调用 `ch395f_open_socket()` 返回错误码(非 BUSY 超时),导致首次 listen 失败。3 秒后重试成功。
|
||||
|
||||
```
|
||||
[NET] PHY_CHANGE: 0x08 ← PHY 刚 link up (100M FULL)
|
||||
[ERR] error listening on socket ← 同一秒 open_socket 失败
|
||||
[FTP] waiting for connection... ← 3秒后重试成功
|
||||
```
|
||||
|
||||
### 根因
|
||||
CH395F 的 PHY link up 后,内部 TCP/IP 协议栈需要额外时间完成初始化(ARP 缓存、路由表等)。在 PHY_CHANGE 中断触发的同一 `net_poll()` 迭代内立即调用 `OPEN_SOCKET`,芯片可能返回 `ERR_BUSY` 或其他错误码。
|
||||
|
||||
### 解决方案
|
||||
1. **应用层重试兜底**:FTP Server (`lftpd_start`) 的 `while(1)` 循环中,listen 失败后 `vTaskDelay(3000)` 重试,3 秒足够 PHY 稳定
|
||||
2. **启动延时消峰**:FTP 任务启动时 `osDelay(7000)`,等 netTask 完成 `net_init() → PHY 协商 → 首轮 net_poll()` 后再发起 listen,此时 PHY 已稳定 2 秒以上,首次就成功
|
||||
|
||||
### 注意事项
|
||||
- 此问题在单连接模式 (`FUN_PARA=0x00`) 和多连接模式 (`0x02`) 下均存在,与 FUN_PARA 无关
|
||||
- 如果多个应用任务同时启动 listen,可能全部首次失败、全部重试成功——建议各任务错峰启动
|
||||
|
||||
---
|
||||
|
||||
## Trap 10:消息队列值拷贝导致结果无法回传
|
||||
|
||||
### 现象
|
||||
`net_send()` / `net_recv()` / `net_listen()` / `net_accept()` / `net_close()` 等线程安全 API(通过消息队列委托 netTask 执行)永远返回 `-1`,即使 netTask 内部操作成功。
|
||||
|
||||
### 根因
|
||||
CMSIS-RTOS v2 `osMessageQueue` 传递 `net_msg_t` 结构体是**值拷贝**。调用方 puts 后 `msg.result = -1`(栈变量),netTask 侧 `osMessageQueueGet` 拿到的是**队列中的副本**,修改副本的 `msg.result = 0` 后 `xTaskNotifyGive` 通知调用方。调用方的栈变量 `msg.result` 仍然是 `-1`,从未被更新。
|
||||
|
||||
```c
|
||||
// 调用方(ftpTask)
|
||||
msg.result = -1;
|
||||
osMessageQueuePut(&msg); // 值拷贝到队列
|
||||
xTaskNotifyWait(¬ified); // 等待通知
|
||||
return msg.result; // 永远是 -1!
|
||||
|
||||
// 处理方(netTask)
|
||||
osMessageQueueGet(&msg); // 拿到的是队列副本
|
||||
msg.result = actual_result; // 修改的是副本
|
||||
xTaskNotify(...); // 通知回去了,但值丢了
|
||||
```
|
||||
|
||||
### 解决方案
|
||||
不通过消息队列回传结果,改用 **FreeRTOS 通知值**(notification value)携带返回值:
|
||||
|
||||
**Producer(netTask)**:
|
||||
```c
|
||||
xTaskNotify(msg.caller, (uint32_t)msg.result, eSetValueWithOverwrite);
|
||||
```
|
||||
|
||||
**Consumer(调用方)**:
|
||||
```c
|
||||
uint32_t notified;
|
||||
xTaskNotifyWait(0, 0, ¬ified, portMAX_DELAY);
|
||||
msg.result = (int)notified;
|
||||
```
|
||||
|
||||
### 注意事项
|
||||
- 指针成员(`msg.buf`)不受值拷贝影响——netTask 拿到的是同一个指针,可以读写调用方的缓冲区
|
||||
- `net_connect()` 不使用消息队列(在 netTask 内直接调用 `_locked` 版本),不受此 bug 影响
|
||||
- 内核级 API(`net_send_sock` / `net_recv_sock` / `net_listen_locked`)直接操作,同样不受影响
|
||||
|
||||
170
test/ftp_test.py
Normal file
170
test/ftp_test.py
Normal file
@@ -0,0 +1,170 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
FTP Server 测试脚本 — 连接 STM32F4 上的 lftpd 服务器
|
||||
用法:python ftp_test.py [--host 192.168.1.100] [--port 21]
|
||||
"""
|
||||
|
||||
import socket
|
||||
import sys
|
||||
import time
|
||||
import argparse
|
||||
|
||||
HOST = "192.168.1.100"
|
||||
PORT = 21
|
||||
TIMEOUT = 10.0
|
||||
|
||||
def recv_line(sock):
|
||||
"""读取 FTP 响应行(以 \r\n 结尾)"""
|
||||
data = b""
|
||||
sock.settimeout(TIMEOUT)
|
||||
while True:
|
||||
try:
|
||||
ch = sock.recv(1)
|
||||
except socket.timeout:
|
||||
print(f"[TIMEOUT] after receiving: {data!r}")
|
||||
return None
|
||||
if not ch:
|
||||
return data if data else None
|
||||
data += ch
|
||||
if data.endswith(b"\r\n"):
|
||||
return data
|
||||
|
||||
def send_cmd(sock, cmd):
|
||||
"""发送 FTP 命令并读取响应"""
|
||||
print(f">>> {cmd}")
|
||||
sock.sendall((cmd + "\r\n").encode())
|
||||
time.sleep(0.1)
|
||||
response = recv_line(sock)
|
||||
if response:
|
||||
print(f"<<< {response.decode(errors='replace').rstrip()}")
|
||||
else:
|
||||
print(f"<<< [NO RESPONSE / CONNECTION CLOSED]")
|
||||
return response
|
||||
|
||||
def parse_pasv(response):
|
||||
"""解析 PASV 227 响应,返回 (ip, port)"""
|
||||
import re
|
||||
m = re.search(r"(\d+),(\d+),(\d+),(\d+),(\d+),(\d+)", response.decode())
|
||||
if m:
|
||||
a, b, c, d, e, f = [int(x) for x in m.groups()]
|
||||
ip = f"{a}.{b}.{c}.{d}"
|
||||
port = e * 256 + f
|
||||
return ip, port
|
||||
return None, None
|
||||
|
||||
def test_ftp(host, port):
|
||||
print(f"=== FTP Test: {host}:{port} ===\n")
|
||||
|
||||
# 1. Connect
|
||||
print("[1] Connecting to control channel...")
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
sock.settimeout(TIMEOUT)
|
||||
try:
|
||||
sock.connect((host, port))
|
||||
print(f" Connected to {host}:{port}")
|
||||
except Exception as e:
|
||||
print(f" CONNECT FAILED: {e}")
|
||||
return False
|
||||
|
||||
# 2. Read welcome
|
||||
print("\n[2] Reading welcome banner...")
|
||||
resp = recv_line(sock)
|
||||
if resp:
|
||||
print(f" {resp.decode(errors='replace').rstrip()}")
|
||||
else:
|
||||
print(" NO WELCOME BANNER")
|
||||
sock.close()
|
||||
return False
|
||||
|
||||
# 3. Login
|
||||
print("\n[3] Login...")
|
||||
resp = send_cmd(sock, "USER anonymous")
|
||||
if not resp:
|
||||
sock.close()
|
||||
return False
|
||||
|
||||
resp = send_cmd(sock, "PASS test@test.com")
|
||||
if not resp:
|
||||
sock.close()
|
||||
return False
|
||||
|
||||
# 4. PWD
|
||||
print("\n[4] PWD...")
|
||||
resp = send_cmd(sock, "PWD")
|
||||
|
||||
# 5. PASV mode
|
||||
print("\n[5] PASV...")
|
||||
resp = send_cmd(sock, "PASV")
|
||||
if not resp:
|
||||
sock.close()
|
||||
return False
|
||||
|
||||
pasv_ip, pasv_port = parse_pasv(resp)
|
||||
if pasv_port is None:
|
||||
print(" FAILED to parse PASV response")
|
||||
# Try EPSV
|
||||
print("\n[5b] Trying EPSV...")
|
||||
resp = send_cmd(sock, "EPSV")
|
||||
if resp and b"229" in resp:
|
||||
import re
|
||||
m = re.search(r"\(\|\|\|(\d+)\|\)", resp.decode())
|
||||
if m:
|
||||
pasv_port = int(m.group(1))
|
||||
pasv_ip = host
|
||||
print(f" EPSV: {pasv_ip}:{pasv_port}")
|
||||
|
||||
if pasv_port is None:
|
||||
print(" PASV/EPSV FAILED, trying PORT mode...")
|
||||
# Skip data connection tests
|
||||
else:
|
||||
print(f" Data channel: {pasv_ip}:{pasv_port}")
|
||||
|
||||
# 6. LIST (correct PASV flow: connect data first, then send LIST)
|
||||
print("\n[6] LIST...")
|
||||
data_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
data_sock.settimeout(5.0)
|
||||
try:
|
||||
data_sock.connect((pasv_ip, pasv_port))
|
||||
print(f" Data connected to {pasv_ip}:{pasv_port}")
|
||||
send_cmd(sock, "LIST")
|
||||
data = b""
|
||||
while True:
|
||||
try:
|
||||
chunk = data_sock.recv(1024)
|
||||
if not chunk:
|
||||
break
|
||||
data += chunk
|
||||
except socket.timeout:
|
||||
break
|
||||
print(f" LIST result ({len(data)} bytes):")
|
||||
print(data.decode(errors='replace'))
|
||||
data_sock.close()
|
||||
except Exception as e:
|
||||
print(f" LIST FAILED: {e}")
|
||||
data_sock.close()
|
||||
|
||||
# Read LIST response
|
||||
resp = recv_line(sock)
|
||||
if resp:
|
||||
print(f" LIST response: {resp.decode(errors='replace').rstrip()}")
|
||||
|
||||
# 7. QUIT
|
||||
print("\n[7] QUIT...")
|
||||
send_cmd(sock, "QUIT")
|
||||
|
||||
sock.close()
|
||||
print("\n=== Test Complete ===")
|
||||
return True
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="FTP Server Test")
|
||||
parser.add_argument("--host", default=HOST, help=f"FTP server IP (default: {HOST})")
|
||||
parser.add_argument("--port", type=int, default=PORT, help=f"FTP server port (default: {PORT})")
|
||||
args = parser.parse_args()
|
||||
|
||||
success = test_ftp(args.host, args.port)
|
||||
sys.exit(0 if success else 1)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user