#include "mbed.h" #include "mbed_trace.h" #include "NTPClient.h" #include "IoTConnectCommon.h" #include "IoTConnectClient.h" #include "IoTConnectHttpClient.h" #include "devices_settings.h" #define TRACE_GROUP "Main" NetworkInterface* network = NULL; IoTConnectEntry embest(ENTRY_EMBEST_COMPANY_NAME, ENTRY_EMBEST_CPID, ENTRY_EMBEST_ENV); IoTConnectDevice* stm32_dev; IoTConnectClient* client = NULL; IoTConnectHttpClient* http_client = 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; } int main() { 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 stm32_dev = new IoTConnectDevice(EMBEST_STM32L4_KIT_DEBUG_ID, EMBEST_STM32L4_KIT_DEBUG_NAME, &embest); // 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; } http_client = new IoTConnectHttpClient(network, stm32_dev); http_client->init_device_cfg(); client = new IoTConnectClient(network, stm32_dev); ret = client->connect(); if (ret != 0) { tr_error("Connect failed, exit"); return -1; } ret = client->subscribe(MQTT::QOS0); if (ret != 0) { tr_error("Failed to subscribe"); return -1; } ret = client->start_main_loop(); if (ret != 0) { tr_error("Failed to start client thread main loop"); return -1; } return 0; }