2

I'm trying to write simple SNTP client for ESP8266 with lwip netconn API (using esp-open-rtos). The problem is that i cannot receive answer from server.

Code (without error checking and debug messgaes):

#include <string.h>

#include <lwip/api.h>
#include <lwip/err.h>

struct sntp_message
{
    u8_t li : 2;
    u8_t vn : 3;
    u8_t mode : 3;
    u8_t stratum;
    u8_t poll;
    u8_t precision;
    u32_t root_delay;
    u32_t root_dispersion;
    u32_t reference_identifier;
    u32_t reference_timestamp[2];
    u32_t originate_timestamp[2];
    u32_t receive_timestamp[2];
    u32_t transmit_timestamp[2];
} __attribute__((packed));

#define SNTP_MSG_LEN (sizeof(struct sntp_message))

int16_t sntp_sync(char* server)
{
    err_t err;
    int16_t result = ERR_OK;
    ip_addr_t sntp_server_address;
    struct netconn* connection = NULL;
    struct netbuf* send_buffer = NULL;
    struct netbuf* receive_buffer = NULL;
    struct sntp_message* send_buffer_data = NULL;

    err = netconn_gethostbyname(server, &sntp_server_address);
    connection = netconn_new(NETCONN_UDP);
    err = netconn_connect(connection, &sntp_server_address, 123);
    send_buffer = netbuf_new();
    send_buffer_data = netbuf_alloc(send_buffer, SNTP_MSG_LEN);
    memset(send_buffer_data, 0, SNTP_MSG_LEN);
    send_buffer_data->vn = 4;
    send_buffer_data->mode = 3; // Mode client.
    err = netconn_send(connection, send_buffer);
    err = netconn_recv(connection, &receive_buffer); // Here netconn_recv block my thread, and no data received. If i set timeout, i have timeout error.
    return result;
}

What can be wrong in my code? Do i need to bind my connection before receiving data (through netconn_bind)? Or i forgot something else?

mpromonet
  • 11,326
  • 43
  • 62
  • 91
Anton
  • 575
  • 2
  • 7
  • 27

1 Answers1

1

Do not invent bicycle. Simon Goldschmidt has already written SNTP for LwIP. Link. There you can found lwip-contrib description and git repo. You can also look for mirrors (may be upgraded) on github or anywhere.

kyb
  • 7,233
  • 5
  • 52
  • 105