main.cpp 1.8 KB
Newer Older
Yongjia Niu's avatar
Yongjia Niu committed
1
#include "mbed.h"
Yongjia Niu's avatar
Yongjia Niu committed
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include "mbed_trace.h"
#include "NTPClient.h"

#define TRACE_GROUP  "Main"


NetworkInterface* network = NULL;


NetworkInterface* connect_network() {
    NetworkInterface* net = NULL;

    tr_info("Opening network interface...");

    net = NetworkInterface::get_default_instance();
    if (!net) {
        tr_error("Unable to open network interface.");
        return NULL;
    }

    nsapi_error_t net_status = NSAPI_ERROR_NO_CONNECTION;
    while ((net_status = net->connect()) != NSAPI_ERROR_OK) {
        tr_error("Unable to connect to network (%d). Retrying...", net_status);
    }
    SocketAddress address;
    net->get_ip_address(&address);
    tr_info("Connected to the network successfully. IP address: %s\n", address.get_ip_address());

    return net;
}

int sync_rtc_time(NetworkInterface* net, const char* ntp_server = NULL) {
    const char* ntp_srv = NULL;

    if (net == NULL) {
        return -1;
    }

    if (ntp_server) {
        ntp_srv = ntp_server;
    } else {
        ntp_srv = "ntp.aliyun.com";
    }
    NTPClient ntp(net);
    ntp.set_server(ntp_srv, 123);
    tr_info("Try to get timestamp from %s", ntp_srv);
    time_t now = ntp.get_timestamp();
    if (now <= 0) {
        tr_error("Failed to retrieve the time from %s:123", ntp_srv);
        return -1;
    }
    set_time(now);
    tr_info("Time is now %s", ctime(&now));

    return 0;
}
Yongjia Niu's avatar
Yongjia Niu committed
58
59

int main() {
Yongjia Niu's avatar
Yongjia Niu committed
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
    int ret = 0;

    mbed_trace_init();

    #ifdef MBED_MAJOR_VERSION
        printf("Mbed OS version %d.%d.%d\n\n", MBED_MAJOR_VERSION, MBED_MINOR_VERSION, MBED_PATCH_VERSION);
    #endif

  // Connect to network
    network = connect_network();
    if (network == NULL) {
        return -1;
    }

    // sync the real time clock (RTC)
    ret = sync_rtc_time(network);
    if (ret != 0) {
        return ret;
    }

Yongjia Niu's avatar
Yongjia Niu committed
80
81
    return 0;
}