[原创] LM3开发笔记_8.Telnet协议的串口服务器

liongt   2010-12-25 22:18 楼主

 

快到年关了,项目上非常忙,很久没来了。今天抽空把俺用LM3S8962开发板做的串口服务器Telnet协议部分整理了一下。

这个串口服务器用来将telnet发送的指令通过串口转发到对应的设备,来获取设备状态和控制设备。比如查看设备的电流,电压和温度等等。

基于LwIP,直接上代码,有问题可跟贴

// 握手字符串

#define HANDSHAKE "Serial Server v1.0 Telnet System!\r\n"

// Telnet初始化
void TelnetCmd_init(void)
{
 struct tcp_pcb *pcb;
 
 /* Create a new TCP control block  */
 pcb = tcp_new();
 
 /* Using IP_ADDR_ANY allow the pcb to be used by any local interface */
 tcp_bind(pcb, IP_ADDR_ANY, 23);
 
 /* Set the connection to the LISTEN state */
 pcb = tcp_listen(pcb);
 
 /* Specify the function to be called when a connection is established */ 
 tcp_accept(pcb, TelnetCmd_accept);
}

// Telnet新连接处理函数
static err_t TelnetCmd_accept(void *arg, struct tcp_pcb *pcb, err_t err)
{
 /* Tell LwIP to associate this structure with this connection. */
 tcp_arg(pcb, mem_calloc(sizeof(CMDSTRUCT), 1)); 
 
 /* Configure LwIP to use our call back functions. */
 tcp_err(pcb, TelnetCmd_conn_err);
 tcp_recv(pcb, TelnetCmd_recv);
 
 tcp_write(pcb, HANDSHAKE, strlen(HANDSHAKE), TCP_WRITE_FLAG_COPY);
 
 return ERR_OK;
}

// Telnet接收处理函数
static err_t TelnetCmd_recv(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err)
{
 struct pbuf *q;
 CMDSTRUCT *pReceiveCmd;
 CMDSTRUCT SendCmd;
 static bool bAccepting = FALSE;
 int done;
 char *Word;
 char ch;
 int i;
 
 pReceiveCmd = (CMDSTRUCT *)arg;

 /* We perform here any necessary processing on the pbuf */
 if (p != NULL)
 {
  tcp_recved(pcb, p->tot_len);
  
  if(!pReceiveCmd)
  {
   pbuf_free(p);
   return ERR_ARG;
  }
  
  done = 0;
  for(q=p; q != NULL; q = q->next)
  {
   Word = q->payload;
   for(i=0; i<q->len && !done; i++)
   {
    ch = Word
;
    if('$' == ch)
    {
     bAccepting = TRUE;
     pReceiveCmd->length = 0;
    }   
    if(bAccepting)
    {
     if(pReceiveCmd->length < CMDBUFFERSIZE)
      pReceiveCmd->bytes[pReceiveCmd->length++] = ch;
     if(';' == ch || pReceiveCmd->length >= CMDBUFFERSIZE)
     {
      bAccepting = FALSE;
      done = 1;
     }
    }
   }
  }
  if(done)
  {
   if(UartApp_SendData(pReceiveCmd,&SendCmd))
   {
    tcp_write(pcb, SendCmd.bytes, SendCmd.length, TCP_WRITE_FLAG_COPY);
   }
   pReceiveCmd->length = 0;
  }
  /* End of processing, we free the pbuf */
  pbuf_free(p);
 }
 else if (err == ERR_OK)
 {
  mem_free(pReceiveCmd);
  return tcp_close(pcb);
 }
 return ERR_OK;
}

// Telnet错误处理

static void TelnetCmd_conn_err(void *arg, err_t err)
{
 CMDSTRUCT *cmd;
 cmd = (CMDSTRUCT *)arg;
 
 mem_free(cmd);
}

 

Telnet终端截图:

telnet.jpg

 

串口服务器的WebServer部分没有做完,时间不够了!

[ 本帖最后由 liongt 于 2010-12-25 22:36 编辑 ]

回复评论 (2)

关注
点赞  2012-1-12 11:12

关注

谢谢LZ的讲解!!!!!!
点赞  2012-7-20 11:39
电子工程世界版权所有 京B2-20211791 京ICP备10001474号-1 京公网安备 11010802033920号
    写回复