mbed_example / Mbed OS cellular-example
Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 #include "mbed.h"
00002 #include "OnboardCellularInterface.h"
00003 
00004 /* SIM pin code goes here */
00005 #define PIN_CODE    "1234"
00006 
00007 /* Network credentials like APN go here, e.g.,
00008     "apn, username, password" */
00009 #define CREDENTIALS "internet"
00010 
00011 /* Number of retries */
00012 #define RETRY_COUNT 3
00013 
00014 OnboardCellularInterface iface;
00015 
00016 nsapi_error_t do_connect()
00017 {
00018     nsapi_error_t retcode;
00019     bool disconnected = false;
00020     uint8_t retry_counter = 0;
00021 
00022     while (!iface.is_connected()) {
00023 
00024         retcode = iface.connect();
00025         if (retcode == NSAPI_ERROR_AUTH_FAILURE) {
00026             printf("\n\nAuthentication Failure. Exiting application\n");
00027             return retcode;
00028         } else if (retcode != NSAPI_ERROR_OK) {
00029             printf("\n\nCouldn't connect: %d, will retry\n", retcode);
00030             retry_counter++;
00031             continue;
00032         } else if (retcode != NSAPI_ERROR_OK && retry_counter > RETRY_COUNT) {
00033             printf("\n\nFatal connection failure: %d\n", retcode);
00034             return retcode;
00035         }
00036 
00037         break;
00038     }
00039 
00040     printf("\n\nConnection Established.\n");
00041 
00042     return NSAPI_ERROR_OK;
00043 }
00044 
00045 int main()
00046 {
00047     /* Set Pin code for SIM card */
00048     iface.set_sim_pin(PIN_CODE);
00049 
00050     /* Set network credentials here, e.g., APN*/
00051     iface.set_credentials(CREDENTIALS);
00052 
00053     printf("\n\nmbed-os-example-cellular, Connecting...\n");
00054 
00055     /* Attempt to connect to a cellular network */
00056     if (do_connect() == NSAPI_ERROR_OK) {
00057         printf("\n\nSuccess. Exiting \n\n");
00058         return 0;
00059     }
00060 
00061     printf("\n\nFailure. Exiting \n\n");
00062     return -1;
00063 }