不带系统的UDP发送数据为何还要接收函数?
凹特慢 2017-12-25 10:21:02 大家好,最近在做单片机UDP通信的例子,需求是:将数据通过UDP发送到上位机的网络助手。在参考例子时,发现在发送的时候必须要一个接收的函数,这个有点不理解,如果我只是想单独发送数据到上位机的网络串口助手,为何还需要接收函数?我的mcu不需要接收数据包啊,只管发送啊,上位机也没有往下发数据。
以下是我参考的例子,例子的功能是将接收到的数据再发出去,我将其再发出去的注释,并在主函数中加入自己发送数据的函数。发送hello到上位机。
main函数如下:
int main(void)
{
struct netif fsl_netif0;
ip4_addr_t fsl_netif0_ipaddr, fsl_netif0_netmask, fsl_netif0_gw;
CLOCK_EnableClock(kCLOCK_InputMux);
BOARD_InitPins();
BOARD_BootClockFROHF48M();
time_init();
IP4_ADDR(&fsl_netif0_ipaddr, configIP_ADDR0, configIP_ADDR1, configIP_ADDR2, configIP_ADDR3);
IP4_ADDR(&fsl_netif0_netmask, configNET_MASK0, configNET_MASK1, configNET_MASK2, configNET_MASK3);
IP4_ADDR(&fsl_netif0_gw, configGW_ADDR0, configGW_ADDR1, configGW_ADDR2, configGW_ADDR3);
lwip_init();
netif_add(&fsl_netif0, &fsl_netif0_ipaddr, &fsl_netif0_netmask, &fsl_netif0_gw, NULL, ethernetif_init,ethernet_input);
netif_set_default(&fsl_netif0);
netif_set_up(&fsl_netif0);
udpecho_raw_init();
struct pbuf *q = NULL;
const char* senddata = "Hello\n";
struct udp_pcb *upcb;
err_t stus;
upcb = udp_new();
udp_bind(upcb, IP_ADDR_ANY, 7);
q = pbuf_alloc(PBUF_TRANSPORT, strlen(senddata)+1, PBUF_ROM);
if(!q)
{
PRINTF("out of PBUF_RAM\n");
}
q->payload = (void *)senddata;
while (1)
{
udp_sendto(upcb, q, &fsl_netif0_gw, 7);
ethernetif_input(&fsl_netif0);
sys_check_timeouts(); /* Handle all system timeouts for all core protocols */
}
}
然后将原来接收后原封不动发送出去的部分给注释掉:
2.将udpecho_raw.c中的udpecho_raw_recv函数修改如下:红色部分为修改
static void udpecho_raw_recv(void *arg, struct udp_pcb *upcb, struct pbuf *p,
const ip_addr_t *addr, u16_t port)
{
// LWIP_UNUSED_ARG(arg);
// if (p != NULL) {
// /* send received packet back to sender */
// udp_sendto(upcb, p, addr, port);
// /* free the pbuf */
// pbuf_free(p);
// }
}
上述代码可以实现我需要的功能,就是发送hello到上位机,但是我不理解为何需要 ethernetif_input(&fsl_netif0);这个接收函数???因为目前我的MCU不需要接收啊,根据定义也是读数据的时候用到。
以下是关于该函数的说明和定义
/**
* This function should be called 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(struct netif *netif)
{
struct pbuf *p;
LWIP_ASSERT("netif != NULL", (netif != NULL));
/* move received packet into a new pbuf */
while ((p = low_level_input(netif)) != NULL)
{
/* pass all packets to ethernet_input, which decides what packets it supports */
if (netif->input(p, netif) != ERR_OK)
{
LWIP_DEBUGF(NETIF_DEBUG, ("ethernetif_input: IP input error\n"));
pbuf_free(p);
p = NULL;
}
}
}