我正在使用UDP来从ntp服务器获取当前时间。
在我期待服务器响应之前,一切似乎都没问题。所以我有两种方法,第一种方法将请求发送到ntp服务器,第二种方法接收响应。我对第一个问题没有问题,但在第二个问题上,我正在努力使用sl_RecvFRom函数,因为应用程序永远不会从它返回。
我将在这里添加这两个函数的代码。
static returnTypes_t bsdUdpServer( uint16_t AddrSize){
int16_t Status = (int16_t) ZERO;
SockID = sl_Socket(SL_AF_INET,SL_SOCK_DGRAM, (uint32_t) ZERO);
if (SockID < 0){
printf("error on sl_Socket\n\r");
return SOCKET_ERROR;
}
Status = sl_Bind(SockID, (SlSockAddr_t *) &LocalAddr, AddrSize);
if (Status < 0){
printf("problem on sl_Bind\n\r");
return SOCKET_ERROR;
}
Status = sl_RecvFrom(SockID, packetBuffer, NTP_PACKET_SIZE * sizeof(uint8_t), (uint32_t) ZERO, (SlSockAddr_t *) &Addr, &AddrSize);
if (Status < (int16_t) ZERO){
printf("error - no bytes received: %d\n\r", (int16_t)Status);
return SOCKET_ERROR;
}
Status = sl_Close(SockID);
if (Status < 0)
printf("problem on sl_Close\n\r");
uint16_t highWord = index3 << 16 | index2;
uint16_t lowWord = index1 << 16 | index0;
uint32_t secondsSince1900 = highWord << 16 | lowWord;
printf("Seconds since 1 Janeiro de 1900: %ld\n\r", secondsSince1900);
return (STATUS_OK);
}
static returnTypes_t bsdUdpClient(uint16_t AddrSize) {
int16_t Status = (int16_t) ZERO;
memset(packetBuffer, 0, NTP_PACKET_SIZE);
packetBuffer[0] = 0xE3; //0b11100011; // LI, Version, Mode
packetBuffer[1] = 0x00; // Stratum, or type of clock
packetBuffer[2] = 0x06; // Polling Interval
packetBuffer[3] = 0xEC; // Peer Clock Precision
// 8 bytes of zero for Root Delay & Root Dispersion
packetBuffer[12] = 49;
packetBuffer[13] = 0x4E;
packetBuffer[14] = 49;
packetBuffer[15] = 52;
SockID = sl_Socket(SL_AF_INET, SL_SOCK_DGRAM, (uint32_t) ZERO);
if (SockID < (int16_t) ZERO)
return (SOCKET_ERROR);
Status = sl_SendTo(SockID, packetBuffer, NTP_PACKET_SIZE * sizeof(uint8_t), (uint32_t) ZERO, (SlSockAddr_t *) &Addr, AddrSize);
if (Status <= (int16_t) ZERO) {
Status = sl_Close(SockID);
if (Status < 0)
return (SEND_ERROR);
return (SEND_ERROR);
}
Status = sl_Close(SockID);
if (Status < 0)
return (SEND_ERROR);
return (STATUS_OK);
}