最近在学习LWIP的协议栈,打算移植到FreeRTOS上
网上找了资料,原子的用的是F4的平台,LWIP1.4.1的版本,操作系统使用的是UCOS的,野火使用的是LWIP2.0.1的版本,操作系统使用的是FreeRTOS的,但是用的是HAL库,不太适合我这种初学的。所以只有自己捣鼓了。
本人使用:STM32F107+LWIP1.4.1+FreeRTOS9.0.0
链接: link.
本文使用的网卡PHY芯片型号是DP83848,工作在MII接口模式,时钟频率是25MHz。
现在的LwIP版本已经发展到了lwIP 2.0.3 版。
但是看了具体的代码后发现一些跟1.4.1对比之下不同之处,其中包含但不全部:
1、IPv4和IPv6的实现代码混合起来,而1.4.1是分开的,通过预处理宏可以分开编译。
2、增加了一些常用的网络组件或应用程序,其中包括了基于tcp接口实现的MQTT协议。
本人也曾试图移植lwIP 2.0.2,发现IPv6实现会被编译进去,并且由此产生一些函数调用问题,在我们的固件库中以及mdk的库中不支持相关函数,另外,本项目用的芯片并不支持IPv6,而相关代码会增加ROM空间的占用,没有必要,而LwIP2.0.2以上的版本所带的MQTT协议实现也可以移植过来到LwIP-1.4.1上使用。
因此还是选用LwIP的1.4.1这个经典版本。但后面的MQTT协议实现没有用LwIP2.0.2版的实现代码,而是比较接近paho.mqtt.embedded-c版的一个实现。
以下是具体移植过程:
LwIP的官方网站:http://savannah.nongnu.org/projects/lwip/
LwIP-1.4.1下载地址:http://download.savannah.nongnu.org/releases/lwip/lwip-1.4.1.zip
或:http://ftp.yzu.edu.tw/nongnu/lwip/lwip-1.4.1.zip
或:https://gitee.com/null_926_6734/CongXiangYingGuanFangHuoQiJingXiangXiaZaiDeMouXieYuanDaiMa/raw/master/lwip-1.4.1.zip
contrib-1.4.1.zip
contrib-1.4.1里面含有官方的移植示例,有windows和unix操作系统下的移植,和某些非操作系统的移植。
在本项目的移植中需要用到一些头文件,可以在contrib-1.4.1中找到。
我是用的PHY芯片的83848,用的是RMII的模式工作的。
#include "lwip/debug.h"
#include "lwip/def.h"
#include "lwip/sys.h"
#include "lwip/mem.h"
#include "lwip/mem.h"
#include "arch/sys_arch.h"
#define SYS_ARCH_BLOCKING_TICKTIMEOUT ((portTickType)10000)
/* This is the number of threads that can be started with sys_thread_new() */
#define SYS_THREAD_MAX 6
/* Structure associating a thread to a struct sys_timeouts */
/* 将线程与结构sys_timeouts关联的结构 */
struct TimeoutlistPerThread {
sys_thread_t pid; /* The thread id */
};
/* Thread & struct sys_timeouts association statically allocated per thread.
Note: SYS_THREAD_MAX is the max number of thread created by sys_thread_new()
that can run simultaneously; it is defined in conf_lwip_threads.h. */
static struct TimeoutlistPerThread Threads_TimeoutsList[SYS_THREAD_MAX];
/* Number of active threads. */
static u16_t NbActiveThreads = 0;
/**
* \brief Initialize the sys_arch layer.
*/
void sys_init(void)
{
int i;
/* Initialize the the per-thread sys_timeouts structures
make sure there are no valid pids in the list */
for (i = 0; i < SYS_THREAD_MAX; i++) {
Threads_TimeoutsList[i].pid = 0;
}
/* Keep track of how many threads have been created */
NbActiveThreads = 0;
}
/**
* \brief Creates and returns a new semaphore.
*
* \param sem Pointer to the semaphore.
* \param count Initial state of the semaphore.
*
* \return ERR_OK for OK, other value indicates error.
*/
err_t sys_sem_new(sys_sem_t *sem, u8_t count)
{
err_t err_sem = ERR_MEM;
/* Sanity check */
if (sem != NULL) {
portENTER_CRITICAL();
vSemaphoreCreateBinary( *sem );
if (*sem != SYS_SEM_NULL) {
#if SYS_STATS
lwip_stats.sys.sem.used++;
if (lwip_stats.sys.sem.used > lwip_stats.sys.sem.max) {
lwip_stats.sys.sem.max = lwip_stats.sys.sem.used;
}
#endif /* SYS_STATS */
if (0 == count) { /* Means we want the sem to be
unavailable at init state. */
xSemaphoreTake( *sem, 1);
}
err_sem = ERR_OK;
}
portEXIT_CRITICAL();
}
return err_sem;
}
/**
* \brief Frees a semaphore created by sys_sem_new.
*
* \param sem Pointer to the semaphore.
*/
void sys_sem_free(sys_sem_t *sem)
{
/* Sanity check */
if (sem != NULL) {
if (SYS_SEM_NULL != *sem) {
#if SYS_STATS
lwip_stats.sys.sem.used--;
#endif /* SYS_STATS */
vQueueDelete( *sem );
}
}
}
/**
* \brief Signals (or releases) a semaphore.
*
* \param sem Pointer to the semaphore.
*/
void sys_sem_signal(sys_sem_t *sem)
{
/* Sanity check */
if (sem != NULL) {
xSemaphoreGive( *sem );
}
}
/**
* \brief Blocks the thread while waiting for the semaphore to be signaled.
* Note that there is another function sys_sem_wait in sys.c, but it is a wrapper
* for the sys_arch_sem_wait function. Please note that it is important for the
* semaphores to return an accurate count of elapsed milliseconds, since they are
* used to schedule timers in lwIP.
*
* \param sem Pointer to the semaphore.
* \param timeout The timeout parameter specifies how many milliseconds the
* function should block before returning; if the function times out, it should
* return SYS_ARCH_TIMEOUT. If timeout=0, then the function should block
* indefinitely. If the function acquires the semaphore, it should return how
* many milliseconds expired while waiting for the semaphore.
*
* \return SYS_ARCH_TIMEOUT if times out, ERR_MEM for semaphore erro otherwise
* return the milliseconds expired while waiting for the semaphore.
*/
u32_t sys_arch_sem_wait(sys_sem_t *sem, u32_t timeout)
{
portTickType TickStart;
portTickType TickStop;
/* Express the timeout in OS tick. */
portTickType TickElapsed = (portTickType)(timeout / portTICK_RATE_MS);
/* Sanity check */
if (sem != NULL) {
if (timeout && !TickElapsed) {
TickElapsed = 1; /* Wait at least one tick */
}
if (0 == TickElapsed) {
TickStart = xTaskGetTickCount();
/* If timeout=0, then the function should block indefinitely */
while (pdFALSE == xSemaphoreTake( *sem, SYS_ARCH_BLOCKING_TICKTIMEOUT )) {
}
} else {
TickStart = xTaskGetTickCount();
if (pdFALSE == xSemaphoreTake( *sem, TickElapsed )) {
/* if the function times out, it should return SYS_ARCH_TIMEOUT */
return(SYS_ARCH_TIMEOUT);
}
}
/* If the function acquires the semaphore, it should return how
many milliseconds expired while waiting for the semaphore */
TickStop = xTaskGetTickCount();
/* Take care of wrap-around */
if (TickStop >= TickStart) {
TickElapsed = TickStop - TickStart;
} else {
TickElapsed = portMAX_DELAY - TickStart + TickStop;
}
return(TickElapsed * portTICK_RATE_MS);
} else {
return (u32_t)ERR_MEM;
}
}
#ifndef sys_sem_valid
/**
* \brief Check if a sempahore is valid/allocated.
*
* \param sem Pointer to the semaphore.
*
* \return Semaphore number on valid, 0 for invalid.
*/
int sys_sem_valid(sys_sem_t *sem)
{
return ((int)(*sem));
}
#endif
#ifndef sys_sem_set_invalid
/**
* \brief Set a semaphore invalid.
*
* \param sem Pointer to the semaphore.
*/
void sys_sem_set_invalid(sys_sem_t *sem)
{
*sem = NULL;
}
#endif
/**
* \brief Creates an empty mailbox for maximum "size" elements. Elements stored
* in mailboxes are pointers.
*
* \param mBoxNew Pointer to the new mailbox.
* \param size Maximum "size" elements.
*
* \return ERR_OK if successfull or ERR_MEM on error.
*/
err_t sys_mbox_new(sys_mbox_t *mBoxNew, int size )
{
err_t err_mbox = ERR_MEM;
/* Sanity check */
if (mBoxNew != NULL) {
*mBoxNew = xQueueCreate( size, sizeof(void *));
#if SYS_STATS
if (SYS_MBOX_NULL != *mBoxNew) {
lwip_stats.sys.mbox.used++;
if (lwip_stats.sys.mbox.used > lwip_stats.sys.mbox.max) {
lwip_stats.sys.mbox.max = lwip_stats.sys.mbox.used;
}
}
#endif /* SYS_STATS */
err_mbox = ERR_OK;
}
return(err_mbox);
}
/**
* \brief Deallocates a mailbox.
* If there are messages still present in the mailbox when the mailbox is
* deallocated, it is an indication of a programming error in lwIP and the
* developer should be notified.
*
* \param mbox Pointer to the new mailbox.
*/
void sys_mbox_free(sys_mbox_t *mbox)
{
/* Sanity check */
if (mbox != NULL) {
if (SYS_MBOX_NULL != *mbox) {
#if SYS_STATS
lwip_stats.sys.mbox.used--;
#endif /* SYS_STATS */
vQueueDelete( *mbox );
}
}
}
/**
* \brief Posts the "msg" to the mailbox. This function have to block until the
* "msg" is really posted.
*
* \param mbox Pointer to the mailbox.
* \param msg Pointer to the message to be post.
*/
void sys_mbox_post(sys_mbox_t *mbox, void *msg)
{
/* Sanit check */
if (mbox != NULL) {
while (pdTRUE != xQueueSend( *mbox, &msg, SYS_ARCH_BLOCKING_TICKTIMEOUT )) {
}
}
}
/**
* \brief Try to posts the "msg" to the mailbox.
*
* \param mbox Pointer to the mailbox.
* \param msg Pointer to the message to be post.
*
* \return ERR_MEM if the mailbox is full otherwise ERR_OK if the "msg" is posted.
*/
err_t sys_mbox_trypost(sys_mbox_t *mbox, void *msg)
{
err_t err_mbox = ERR_MEM;
/* Sanity check */
if (mbox != NULL) {
if (errQUEUE_FULL != xQueueSend( *mbox, &msg, 0 )) {
err_mbox = ERR_OK;
}
}
return (err_mbox);
}
/**
* \brief Blocks the thread until a message arrives in the mailbox, but does not
* block the thread longer than "timeout" milliseconds (similar to the
* sys_arch_sem_wait() function).
*
* \param mbox Pointer to the mailbox.
* \param msg A result parameter that is set by the function (i.e., by doing
* "*msg = ptr"). The "msg" parameter maybe NULL to indicate that the message
* should be dropped.
* \timeout 0 indicates the thread should be blocked until a message arrives.
*
* \return Number of milliseconds spent waiting or SYS_ARCH_TIMEOUT if there was
* a timeout. Or ERR_MEM if invalid pointer to message box.
*/
u32_t sys_arch_mbox_fetch(sys_mbox_t *mbox, void **msg, u32_t timeout)
{
portTickType TickStart;
portTickType TickStop;
void *tempoptr;
/* Express the timeout in OS tick. */
portTickType TickElapsed = (portTickType)(timeout / portTICK_RATE_MS);
/* Sanity check */
if (mbox != NULL) {
if (timeout && !TickElapsed) {
TickElapsed = 1; /* Wait at least one tick */
}
if (msg == NULL) {
msg = &tempoptr;
}
/* NOTE: INCLUDE_xTaskGetSchedulerState must be set to 1 in
* FreeRTOSConfig.h for xTaskGetTickCount() to be available */
if (0 == TickElapsed) {
TickStart = xTaskGetTickCount();
/* If "timeout" is 0, the thread should be blocked until
* a message arrives */
while (pdFALSE == xQueueReceive( *mbox, &(*msg),
SYS_ARCH_BLOCKING_TICKTIMEOUT )) {
}
} else {
TickStart = xTaskGetTickCount();
if (pdFALSE == xQueueReceive( *mbox, &(*msg), TickElapsed )) {
*msg = NULL;
/* if the function times out, it should return
* SYS_ARCH_TIMEOUT. */
return(SYS_ARCH_TIMEOUT);
}
}
/* If the function gets a msg, it should return the number of ms
* spent waiting. */
TickStop = xTaskGetTickCount();
/* Take care of wrap-around. */
if (TickStop >= TickStart) {
TickElapsed = TickStop - TickStart;
} else {
TickElapsed = portMAX_DELAY - TickStart + TickStop;
}
return(TickElapsed * portTICK_RATE_MS);
} else {
return (u32_t)ERR_MEM;
}
}
/**
* \brief This is similar to sys_arch_mbox_fetch, however if a message is not
* present in the mailbox, it immediately returns with the code SYS_MBOX_EMPTY.
* On success 0 is returned.
*
* \param mbox Pointer to the mailbox.
* \param msg A result parameter that is set by the function (i.e., by doing
* "*msg = ptr"). The "msg" parameter maybe NULL to indicate that the message
* should be dropped.
*
* \return Number of milliseconds spent waiting or SYS_ARCH_TIMEOUT if there was
* a timeout. Or ERR_MEM if invalid pointer to message box.
*/
u32_t sys_arch_mbox_tryfetch(sys_mbox_t *mbox, void **msg)
{
void *tempoptr;
/* Sanity check */
if (mbox != NULL) {
if (msg == NULL) {
msg = &tempoptr;
}
if (pdFALSE == xQueueReceive( *mbox, &(*msg), 0 )) {
/* if a message is not present in the mailbox, it
* immediately returns with */
/* the code SYS_MBOX_EMPTY. */
return(SYS_MBOX_EMPTY);
}
/* On success 0 is returned. */
return(0);
} else {
return(SYS_MBOX_EMPTY);
}
}
#ifndef sys_mbox_valid
/**
* \brief Check if an mbox is valid/allocated.
*
* \param mbox Pointer to the mailbox.
*
* \return Mailbox for valid, 0 for invalid.
*/
int sys_mbox_valid(sys_mbox_t *mbox)
{
return ((int)(*mbox));
}
#endif
#ifndef sys_mbox_set_invalid
/**
* \brief Set an mbox invalid.
*
* \param mbox Pointer to the mailbox.
*/
void sys_mbox_set_invalid(sys_mbox_t *mbox)
{
*mbox = NULL;
}
#endif
/**
* \brief Instantiate a thread for lwIP. Both the id and the priority are
* system dependent.
*
* \param name Pointer to the thread name.
* \param thread Thread function.
* \param arg Argument will be passed into the thread().
* \param stacksize Stack size of the thread.
* \param prio Thread priority.
*
* \return The id of the new thread.
*/
sys_thread_t sys_thread_new(const char *name, lwip_thread_fn thread, void *arg,
int stacksize, int prio)
{
sys_thread_t newthread;
portBASE_TYPE result;
SYS_ARCH_DECL_PROTECT(protectionLevel);
result = xTaskCreate( thread, (const portCHAR *)name, stacksize, arg,
prio, &newthread );
/* Need to protect this -- preemption here could be a problem! */
SYS_ARCH_PROTECT(protectionLevel);
if (pdPASS == result) {
/* For each task created, store the task handle (pid) in the
* timers array. */
/* This scheme doesn't allow for threads to be deleted */
Threads_TimeoutsList[NbActiveThreads++].pid = newthread;
} else {
newthread = NULL;
}
SYS_ARCH_UNPROTECT(protectionLevel);
return(newthread);
}
/* Mutex functions: */
/** Define LWIP_COMPAT_MUTEX if the port has no mutexes and binary semaphores
* should be used instead */
#if !LWIP_COMPAT_MUTEX
/**
* \brief Create a new mutex.
*
* \param mutex Pointer to the mutex to create.
*
* \return A new mutex.
*/
err_t sys_mutex_new(sys_mutex_t *mutex)
{
}
/**
* \brief Lock a mutex.
*
* \param mutex the mutex to lock.
*/
void sys_mutex_lock(sys_mutex_t *mutex)
{
}
/**
* \brief Unlock a mutex.
*
* \param mutex the mutex to unlock.
*/
void sys_mutex_unlock(sys_mutex_t *mutex)
{
}
/**
* \brief Delete a semaphore.
*
* \param mutex the mutex to delete.
*/
void sys_mutex_free(sys_mutex_t *mutex)
{
}
#ifndef sys_mutex_valid
/**
* \brief Check if a mutex is valid/allocated.
*
* \param mutex Pointer to the mutex.
*
* \return Valid mutex number or 0 for invalid.
*/
int sys_mutex_valid(sys_mutex_t *mutex)
{
return ((int)(*mutex));
}
#endif
#ifndef sys_mutex_set_invalid
/**
* \brief Set a mutex invalid so that sys_mutex_valid returns 0.
*
* \param mutex Pointer to the mutex.
*/
void sys_mutex_set_invalid(sys_mutex_t *mutex)
{
*mutex = NULL;
}
#endif
#endif
/* This optional function does a "fast" critical region protection and returns
* the previous protection level. This function is only called during very short
* critical regions. An embedded system which supports ISR-based drivers might
* want to implement this function by disabling interrupts. Task-based systems
* might want to implement this by using a mutex or disabling tasking. This
* function should support recursive calls from the same task or interrupt. In
* other words, sys_arch_protect() could be called while already protected. In
* that case the return value indicates that it is already protected.*/
extern volatile unsigned portLONG ulCriticalNesting;
/**
* \brief Protect the system.
*
* \return 1 on success.
*/
sys_prot_t sys_arch_protect(void)
{
vPortEnterCritical();
return 1; /* Not used */
}
/**
* \brief Unprotect the system.
*
* \param pval Protect value.
*/
void sys_arch_unprotect(sys_prot_t pval)
{
vPortExitCritical();
}
/**
* \brief updata the system time.
*
* \param null.
*/
extern u32_t LWipTime;
u32_t sys_now(void)
{
return LWipTime;
}
#include "lwip/opt.h"
#include "lwip/def.h"
#include "lwip/mem.h"
#include "lwip/pbuf.h"
#include
#include
#include "netif/etharp.h"
#include "netif/ppp_oe.h"
#include "stm32_eth.h"
#include "Task_LwIP.h"
#include
#include "lwip/sys.h"
#include "lwip/timers.h"
//网卡的名字
#define IFNAME0 'e'
#define IFNAME1 'n'
#define ETH_DMARxDesc_FrameLengthShift 16 //DMA接收描述符,RDES0软件寄存器中描述帧长度的位的偏移值
#define ETH_ERROR ((u32)0) //出错代码
#define ETH_SUCCESS ((u32)1) //无错代码
#define ETH_RXBUFNB (5+3) //接收缓冲器数量
#define ETH_TXBUFNB (5-3) //发送缓冲器数量
/************************ FreeRTOS使用宏配置 ****************************/
#define netifINTERFACE_TASK_STACK_SIZE ( 350 )
#define netifGUARD_BLOCK_TIME ( 250 )
#define netifINTERFACE_TASK_PRIORITY ( configMAX_PRIORITIES - 1 )
static struct netif *s_pxNetIf = NULL;
xSemaphoreHandle s_xSemaphore = NULL;
#define emacBLOCK_TIME_WAITING_FOR_INPUT portMAX_DELAY//( ( portTickType ) 100 )
static void arp_timer(void *arg);
/************************ 分隔符 ****************************/
extern u8_t MACaddr[6]; //MAC地址,具有唯一性
extern ETH_DMADESCTypeDef *DMATxDescToSet; //当前DMA发送描述符指针,在以太网库文件中定义的
extern ETH_DMADESCTypeDef *DMARxDescToGet; //当前DMA接收描述符指针,在以太网库文件中定义的
ETH_DMADESCTypeDef DMARxDscrTab[ETH_RXBUFNB], DMATxDscrTab[ETH_TXBUFNB]; //发送和接收DMA描述符数组
uint8_t Rx_Buff[ETH_RXBUFNB][ETH_MAX_PACKET_SIZE], Tx_Buff[ETH_TXBUFNB][ETH_MAX_PACKET_SIZE];//发送和接收缓冲区
//数据帧结构体,和我们使用的网卡相关
typedef struct{
u32_t length; //帧长度
u32_t buffer; //缓冲区
ETH_DMADESCTypeDef *descriptor; //指向DMA描述符的指针
}FrameTypeDef;
//前置的函数声明
FrameTypeDef ETH_RxPkt_ChainMode(void); //网卡接收数据
u32_t ETH_GetCurrentTxBuffer(void); //获取当前DMA发送描述符下数据缓冲区指针
u32_t ETH_TxPkt_ChainMode(u16 FrameLength); //网卡发送数据
//接收数据函数
//看一看简单的框架和DMA描述符的结构
//整理思路如下
//当网卡接收到数据,会存放在接收缓冲区,接收DMA描述符下有指向其的指针
//我们还要实现一个网卡接收数据的函数ETH_TxPkt_ChainMode,同发送一样ST提供了例程
//得到缓冲区的数据后,我们要将其拷贝到pbuf结构中,供LWip使用
//所以我们最后将数据拷贝到pbuf后,将它作为函数返回值,返回
static struct pbuf * low_level_input(struct netif *netif)
{
struct pbuf *p, *q; //p要返回的数据,q拷贝数据时用于暂存数据
u16_t len; //保存接收到数据帧的长度
int l =0; //长度,for时暂存中间值
FrameTypeDef frame; //接受侦
u8 *buffer; //接收到数据的地址
p = NULL; //p向指向空,待用
frame = ETH_RxPkt_ChainMode();//接收数据帧
len = frame.length;//将数据帧长度存放在len内待用
buffer = (u8 *)frame.buffer; //得到数据区地址
p = pbuf_alloc(PBUF_RAW, len, PBUF_POOL);//内存池分配空间
if (p != NULL)//分配成功
{
for (q = p; q != NULL; q = q->next)//利用for循环拷贝数据
{
memcpy((u8_t*)q->payload, (u8_t*)&buffer[l], q->len);
l = l + q->len;
}
}
frame.descriptor->Status = ETH_DMARxDesc_OWN; //设置DMA占用描述符
if ((ETH->DMASR & ETH_DMASR_RBUS) != (u32)RESET) //通过判断ETH->DMASR寄存器位7,判断接收缓冲区可不可用
{
//接收缓冲区不可用,if成立
ETH->DMASR = ETH_DMASR_RBUS; //清除接收缓冲区不可用标志
ETH->DMARPDR = 0;//通过写ETH->DMARPDR寄存器,恢复DMA接收
}
return p;//返回数据
}
/**
* This function is the ethernetif_input task, it is processed when a packet
* is ready to be read from the interface. It uses the function low_level_input()
* that should handle the actual reception of bytes from the network
* interface. Then the type of the received packet is determined and
* the appropriate input function is called.
*
* @param netif the lwip network interface structure for this ethernetif
*/
void ethernetif_input( void * pvParameters )
{
struct pbuf *p;
for( ;; )
{
if (xSemaphoreTake( s_xSemaphore, emacBLOCK_TIME_WAITING_FOR_INPUT)==pdTRUE)
{
p = low_level_input( s_pxNetIf );//调用LWip源码处理数据
if (ERR_OK != s_pxNetIf->input( p, s_pxNetIf))
{//如果处理失败,释放掉pbuf空间
pbuf_free(p);
p=NULL;
}
}
}
}
//初始化函数
static void low_level_init(struct netif *netif)
{
struct ethernetif *ethernetif = netif->state;
uint8_t i;
netif->hwaddr_len = ETHARP_HWADDR_LEN; //设置MAC地址长度
netif->hwaddr[0] = lwipdev.mac[0]; //设置MAC地址,6位,地址唯一,不能重复
netif->hwaddr[1] = lwipdev.mac[1];
netif->hwaddr[2] = lwipdev.mac[2];
netif->hwaddr[3] = lwipdev.mac[3];
netif->hwaddr[4] = lwipdev.mac[4];
netif->hwaddr[5] = lwipdev.mac[5];
netif->mtu = 1500; //最大传输单元
//设置网卡功能
//NETIF_FLAG_BROADCAST允许广播
//NETIF_FLAG_ETHARP开启ARP功能
//NETIF_FLAG_LINK_UP设置后接口产生一个活跃的链接,要开启硬件校验
netif->flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP | NETIF_FLAG_LINK_UP;
s_pxNetIf =netif;
//创建信号量
if (s_xSemaphore == NULL)
{
s_xSemaphore= xSemaphoreCreateCounting(20,0);
}
//接下来我们要初始化发送和接收DMA描述符链表
//107VCT6采用链式结构
//我们要先创建DMA描述符数组
//DMA描述符内包含了一个指向接收和发送缓冲区的指针,我们还要创建接收和发送缓冲区,两个数组
ETH_DMATxDescChainInit(DMATxDscrTab, &Tx_Buff[0][0], ETH_TXBUFNB);//初始化发送DMA描述符链表
ETH_DMARxDescChainInit(DMARxDscrTab, &Rx_Buff[0][0], ETH_RXBUFNB);//初始化接收DMA描述符链表
//开启DMA描述符接收中断
for(i=0; i<ETH_RXBUFNB; i++)
{
ETH_DMARxDescReceiveITConfig(&DMARxDscrTab[i], ENABLE);
}
#if !CHECKSUM_GEN_ICMP //判断是否开启硬件校验,关闭软件校验
//开启发送帧校验
for(i=0; i<ETH_TXBUFNB; i++)
{
ETH_DMATxDescChecksumInsertionConfig(&DMATxDscrTab[i], ETH_DMATxDesc_ChecksumTCPUDPICMPFull);
}
#endif
//创建单独线程任务,接受来自网卡的数据
xTaskCreate( (TaskFunction_t )ethernetif_input, /* 任务入口函数 */
(const char* )"Eth_if",/* 任务名字 */
(uint16_t )netifINTERFACE_TASK_STACK_SIZE, /* 任务栈大小 */
(void* )NULL, /* 任务入口函数参数 */
(UBaseType_t )netifINTERFACE_TASK_PRIORITY, /* 任务的优先级 */
(TaskHandle_t* )NULL);/* 任务控制块指针 */
ETH_Start();//开启MAC和DMA
}
//发送数据函数
//看一看简单的框架和DMA描述符的结构
//整理思路如下
//要发送的数据存放在最为参数传进来的pubf下
//DMA发送描述符内有指向缓冲器的指针,而且我们也设置了缓冲区
//我们首先要得到描述符的DMA缓冲区指针,所以我们要实现一个ETH_GetCurrentTxBuffer函数
//接下来我们将pbuf的数据拷贝到缓冲区
//根据使用的网卡,写一个网卡发送数据的函数ETH_TxPkt_ChainMode
//这几个函数ST官方都给了基于DP83848的例程
static err_t low_level_output(struct netif *netif, struct pbuf *p)
{
static xSemaphoreHandle xTxSemaphore = NULL;
struct pbuf *q;
uint32_t l = 0;
u8 *buffer ;
if (xTxSemaphore == NULL)
{
vSemaphoreCreateBinary (xTxSemaphore);
}
if (xSemaphoreTake(xTxSemaphore, netifGUARD_BLOCK_TIME))
{
buffer = (u8 *)(ETH_GetCurrentTxBuffer());
for(q = p; q != NULL; q = q->next)
{
memcpy((u8_t*)&buffer[l], q->payload, q->len);
l = l + q->len;
}
ETH_TxPkt_ChainMode(l);
xSemaphoreGive(xTxSemaphore);
}
return ERR_OK;
}
/***************************************************/
/***************************************************/
/***************************************************/
static void arp_timer(void *arg)
{
etharp_tmr();
sys_timeout(ARP_TMR_INTERVAL, arp_timer, NULL);
}
/*************************************************************
*
*/
err_t ethernetif_init(struct netif *netif)
{
LWIP_ASSERT("netif != NULL", (netif != NULL));
#if LWIP_NETIF_HOSTNAME
netif->hostname = "lwip";//命名
#endif
//初始化netif相关字段
netif->name[0] = IFNAME0;
netif->name[1] = IFNAME1;
netif->output = etharp_output;
netif->linkoutput = low_level_output;
low_level_init(netif);
etharp_init();
sys_timeout(ARP_TMR_INTERVAL, arp_timer, NULL);
return ERR_OK;
}
//网卡接收数据函数
FrameTypeDef ETH_RxPkt_ChainMode(void)
{
u32 framelength = 0; //变量待用
FrameTypeDef frame = {0,0}; //帧结构待用
if((DMARxDescToGet->Status & ETH_DMARxDesc_OWN) != (u32)RESET)//如果DMA占用描述符成立
{
frame.length = ETH_ERROR; //存放错误代码
if ((ETH->DMASR & ETH_DMASR_RBUS) != (u32)RESET) //如果发送缓存不可用,if成立
{
ETH->DMASR = ETH_DMASR_RBUS; //清除接收缓冲区不可用标志
ETH->DMARPDR = 0;//通过写ETH->DMARPDR寄存器,恢复DMA接收
}
return frame; //返回帧结构
}
//如果上步if不成立,标志描述符由CPU占用
//又要进行3个判断
//ETH_DMARxDesc_ES判断接收中是否出错,成立表示没有错误发生
//ETH_DMARxDesc_LS判断是否到了最后一个缓冲区
//ETH_DMARxDesc_FS判断是否包含了帧的第一个缓冲区
if(((DMARxDescToGet->Status & ETH_DMARxDesc_ES) == (u32)RESET) &&
((DMARxDescToGet->Status & ETH_DMARxDesc_LS) != (u32)RESET) &&
((DMARxDescToGet->Status & ETH_DMARxDesc_FS) != (u32)RESET))
{
//都成立的话,得到帧长度值,
//DMA接收描述符RDES0软件寄存器位16-位29存放帧长度值
//右移16位,然后还要减去4个自己的CRC校验
framelength = ((DMARxDescToGet->Status & ETH_DMARxDesc_FL) >> ETH_DMARxDesc_FrameLengthShift) - 4;
frame.buffer = DMARxDescToGet->Buffer1Addr; //得到接收描述符下Buffer1Addr地址,它指向了数据缓冲区
}
else//如果上步if不成立
{
framelength = ETH_ERROR;//记录错误代码
}
frame.length = framelength; //将帧长度值,记录在frame结构体中的length成员
frame.descriptor = DMARxDescToGet;//frame结构体中的descriptor成员指向当前的DMA接收描述符
DMARxDescToGet = (ETH_DMADESCTypeDef*) (DMARxDescToGet->Buffer2NextDescAddr);//将当前接收DMA描述符指针,指向下一个接收DMA链表中的DMA描述符
return (frame); //返回帧结构
}
//网卡发送数据函数
u32_t ETH_TxPkt_ChainMode(u16 FrameLength)
{
if((DMATxDescToSet->Status & ETH_DMATxDesc_OWN) != (u32)RESET)//如果DMA占用描述符成立
{
return ETH_ERROR;//返回错误代码
}
//如果if不成立,表示CPU占用描述符
DMATxDescToSet->ControlBufferSize = (FrameLength & ETH_DMATxDesc_TBS1);//设置发送帧长度
DMATxDescToSet->Status |= ETH_DMATxDesc_LS | ETH_DMATxDesc_FS;//ETH_DMATxDesc_LS和ETH_DMATxDesc_FS置1,表示帧中存放了,第一个和最后一个分块
DMATxDescToSet->Status |= ETH_DMATxDesc_OWN;//把描述符给DMA使用
if ((ETH->DMASR & ETH_DMASR_TBUS) != (u32)RESET)//如果发送缓存不可用,if成立
{
ETH->DMASR = ETH_DMASR_TBUS;//清除发送缓存不可用标志
ETH->DMATPDR = 0;//写ETH->DMATPDR寄存器,以求回复发送流程
}
DMATxDescToSet = (ETH_DMADESCTypeDef*) (DMATxDescToSet->Buffer2NextDescAddr);//将当前发送DMA描述符指针,指向下一个发送DMA链表中的DMA描述符
return ETH_SUCCESS; //返回成功代码
}
//获取发送DMA描述符下的缓冲区
u32_t ETH_GetCurrentTxBuffer(void)
{
return (DMATxDescToSet->Buffer1Addr); //得到DMA描述符内Buffer1Addr地址。
}
#ifndef __LWIPOPTS_H__
#define __LWIPOPTS_H__
#define SYS_LIGHTWEIGHT_PROT 0 //关保护
//NO_SYS==1:不使用操作系统
#define NO_SYS 0 //1:不使用UCOS操作系统 0:使用操作系统
#ifndef CHECKSUM_GEN_ICMP
#define CHECKSUM_GEN_ICMP 0 //我们使用硬件校验,关闭软件校验
#endif
//使用4字节对齐模式
#define MEM_ALIGNMENT 4
//MEM_SIZE:heap内存的大小,如果在应用中有大量数据发送的话这个值最好设置大一点
#define MEM_SIZE (5*1024)//16000 //内存堆大小
//MEMP_NUM_PBUF:memp结构的pbuf数量,如果应用从ROM或者静态存储区发送大量数据时,这个值应该设置大一点
#define MEMP_NUM_PBUF 10
//MEMP_NUM_UDP_PCB:UDP协议控制块(PCB)数量.每个活动的UDP"连接"需要一个PCB.
#define MEMP_NUM_UDP_PCB 6
//MEMP_NUM_TCP_PCB:同时建立激活的TCP数量
#define MEMP_NUM_TCP_PCB 10
//MEMP_NUM_TCP_PCB_LISTEN:能够监听的TCP连接数量
#define MEMP_NUM_TCP_PCB_LISTEN 6
//MEMP_NUM_TCP_SEG:最多同时在队列中的TCP段数量
#define MEMP_NUM_TCP_SEG 15
//MEMP_NUM_SYS_TIMEOUT:能够同时激活的timeout个数
#define MEMP_NUM_SYS_TIMEOUT 8
/* ---------- Pbuf选项---------- */
//PBUF_POOL_SIZE:pbuf内存池个数.
#define PBUF_POOL_SIZE 20
//PBUF_POOL_BUFSIZE:每个pbuf内存池大小.
#define PBUF_POOL_BUFSIZE 512
/* ---------- TCP选项---------- */
#define LWIP_TCP 1 //为1是使用TCP
#define TCP_TTL 255//生存时间
/*当TCP的数据段超出队列时的控制位,当设备的内存过小的时候此项应为0*/
#define TCP_QUEUE_OOSEQ 0
//最大TCP分段
#define TCP_MSS (1500 - 40) //TCP_MSS = (MTU - IP报头大小 - TCP报头大小
//TCP发送缓冲区大小(bytes).
#define TCP_SND_BUF (4*TCP_MSS)
//TCP_SND_QUEUELEN: TCP发送缓冲区大小(pbuf).这个值最小为(2 * TCP_SND_BUF/TCP_MSS)
#define TCP_SND_QUEUELEN (2* TCP_SND_BUF/TCP_MSS)
//TCP发送窗口
#define TCP_WND (2*TCP_MSS)
/* ---------- ICMP选项---------- */
#define LWIP_ICMP 1 //使用ICMP协议
/* ---------- DHCP选项---------- */
//当使用DHCP时此位应该为1,LwIP 0.5.1版本中没有DHCP服务.
#define LWIP_DHCP 1
/* ---------- UDP选项 ---------- */
#define LWIP_UDP 1 //使用UDP服务
#define UDP_TTL 255 //UDP数据包生存时间
/* ---------- Statistics options ---------- */
#define LWIP_STATS 0
#define LWIP_PROVIDE_ERRNO 1
//STM32F4x7允许通过硬件识别和计算IP,UDP和ICMP的帧校验和
#define CHECKSUM_BY_HARDWARE //定义CHECKSUM_BY_HARDWARE,使用硬件帧校验
#ifdef CHECKSUM_BY_HARDWARE
//CHECKSUM_GEN_IP==0: 硬件生成IP数据包的帧校验和
#define CHECKSUM_GEN_IP 0
//CHECKSUM_GEN_UDP==0: 硬件生成UDP数据包的帧校验和
#define CHECKSUM_GEN_UDP 0
//CHECKSUM_GEN_TCP==0: 硬件生成TCP数据包的帧校验和
#define CHECKSUM_GEN_TCP 0
//CHECKSUM_CHECK_IP==0: 硬件检查输入的IP数据包帧校验和
#define CHECKSUM_CHECK_IP 0
//CHECKSUM_CHECK_UDP==0: 硬件检查输入的UDP数据包帧校验和
#define CHECKSUM_CHECK_UDP 0
//CHECKSUM_CHECK_TCP==0: 硬件检查输入的TCP数据包帧校验和
#define CHECKSUM_CHECK_TCP 0
#else
//CHECKSUM_GEN_IP==1: 软件生成IP数据包帧校验和
#define CHECKSUM_GEN_IP 1
// CHECKSUM_GEN_UDP==1: 软件生成UDOP数据包帧校验和
#define CHECKSUM_GEN_UDP 1
//CHECKSUM_GEN_TCP==1: 软件生成TCP数据包帧校验和
#define CHECKSUM_GEN_TCP 1
// CHECKSUM_CHECK_IP==1: 软件检查输入的IP数据包帧校验和
#define CHECKSUM_CHECK_IP 1
// CHECKSUM_CHECK_UDP==1: 软件检查输入的UDP数据包帧校验和
#define CHECKSUM_CHECK_UDP 1
//CHECKSUM_CHECK_TCP==1: 软件检查输入的TCP数据包帧校验和
#define CHECKSUM_CHECK_TCP 1
#endif
/*
---------------------------------
---------- OS options ----------
---------------------------------
*/
#define TCPIP_THREAD_STACKSIZE 1000
#define TCPIP_MBOX_SIZE 5
#define DEFAULT_UDP_RECVMBOX_SIZE 2000
#define DEFAULT_TCP_RECVMBOX_SIZE 2000
#define DEFAULT_ACCEPTMBOX_SIZE 2000
#define DEFAULT_THREAD_STACKSIZE 500
#define TCPIP_THREAD_PRIO (configMAX_PRIORITIES - 2)
/*
----------------------------------------------
---------- SequentialAPI选项----------
----------------------------------------------
*/
//LWIP_NETCONN==1:使能NETCON函数(要求使用api_lib.c)
#define LWIP_NETCONN 1
/*
------------------------------------
---------- Socket API选项----------
------------------------------------
*/
//LWIP_SOCKET==1:使能Socket API(要求使用sockets.c)
#define LWIP_SOCKET 1
#define LWIP_COMPAT_MUTEX 1
#define LWIP_SO_RCVTIMEO 1 //通过定义LWIP_SO_RCVTIMEO使能netconn结构体中recv_timeout,使用recv_timeout可以避免阻塞线程
/*
----------------------------------------
---------- Lwip调试选项----------
----------------------------------------
*/
//#define LWIP_DEBUG 1 //开启DEBUG选项
//#define ICMP_DEBUG 1 //开启/关闭ICMPdebug
#if 0
#define U8_F "c"
#define S8_F "c"
#define X8_F "x"
#define U16_F "u"
#define S16_F "d"
#define X16_F "x"
#define U32_F "u"
#define S32_F "d"
#define X32_F "x"
//extern void u2_printf(const char *pcString, ...);
extern void UARTprintf(const char *pcString, ...);
//#define LWIP_PLATFORM_DIAG(x) {u2_printf x;}
//#define LWIP_DEBUG
#define LWIP_DBG_MIN_LEVEL LWIP_DBG_LEVEL_OFF
//#define LWIP_DBG_MIN_LEVEL LWIP_DBG_LEVEL_WARNING
//#define LWIP_DBG_MIN_LEVEL LWIP_DBG_LEVEL_SERIOUS
//#define LWIP_DBG_MIN_LEVEL LWIP_DBG_LEVEL_SEVERE
//#define LWIP_DBG_TYPES_ON LWIP_DBG_ON
//#define LWIP_DBG_TYPES_ON (LWIP_DBG_ON|LWIP_DBG_TRACE|LWIP_DBG_STATE|LWIP_DBG_FRESH)
//#define ETHARP_DEBUG LWIP_DBG_ON
//#define NETIF_DEBUG LWIP_DBG_ON
//#define PBUF_DEBUG LWIP_DBG_ON
//#define API_LIB_DEBUG LWIP_DBG_ON
//#define API_MSG_DEBUG LWIP_DBG_ON
//#define SOCKETS_DEBUG LWIP_DBG_ON
//#define ICMP_DEBUG LWIP_DBG_ON
//#define IGMP_DEBUG LWIP_DBG_ON
//#define INET_DEBUG LWIP_DBG_ON
#define IP_DEBUG LWIP_DBG_ON
//#define IP_REASS_DEBUG LWIP_DBG_ON
//#define RAW_DEBUG LWIP_DBG_ON
//#define MEM_DEBUG LWIP_DBG_ON
//#define MEMP_DEBUG LWIP_DBG_ON
//#define SYS_DEBUG LWIP_DBG_ON
#define TCP_DEBUG LWIP_DBG_ON
//#define TCP_INPUT_DEBUG LWIP_DBG_ON
//#define TCP_FR_DEBUG LWIP_DBG_ON
//#define TCP_RTO_DEBUG LWIP_DBG_ON
//#define TCP_CWND_DEBUG LWIP_DBG_ON
//#define TCP_WND_DEBUG LWIP_DBG_ON
#define TCP_OUTPUT_DEBUG LWIP_DBG_ON
//#define TCP_RST_DEBUG LWIP_DBG_ON
//#define TCP_QLEN_DEBUG LWIP_DBG_ON
//#define UDP_DEBUG LWIP_DBG_ON
//#define TCPIP_DEBUG LWIP_DBG_ON
//#define PPP_DEBUG LWIP_DBG_ON
//#define SLIP_DEBUG LWIP_DBG_ON
//#define DHCP_DEBUG LWIP_DBG_ON
//#define AUTOIP_DEBUG LWIP_DBG_ON
//#define SNMP_MSG_DEBUG LWIP_DBG_ON
//#define SNMP_MIB_DEBUG LWIP_DBG_ON
//#define DNS_DEBUG LWIP_DBG_ON
#endif
#endif /* __LWIPOPTS_H__ */
主要的几个文件我罗列一下,不然太长了,还有为毛win10的edge支持的这么差,还要找个游览器才能写.