快到年关了,项目上非常忙,很久没来了。今天抽空把俺的串口服务器Telnet协议部分整理了一下。
串口服务器可以将telnet发送的指令通过串口转发到对应的设备,来获取设备状态和控制设备。比如查看设备的电流,电压和温度等等。
直接上代码,有问题可跟贴。
// 握手字符串
#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);
}
WebServer部分没有做完,时间不够了!