Initialization and Shutdown of Nabto Edge Embedded SDK C api

This document describes initialization and shutdown of the Nabto Edge Embedded SDK. For more specific information about futures and listeners see Futures in Nabto Edge

Initialization of Resources

The Nabto Edge Embedded SDK has several functions which allocate objects. E.g., nabto_device_new, nabto_device_listener_new and nabto_device_future_new; these functions can return NULL if an error occured. That means it is necessary to check the return value before using these objects:

{
    NabtoDevice* device = nabto_device_new();
    if (device == NULL) {
        // handle error.
    }
}

After a resource has been allocated, it is often necessary to initialize the resource. This is resource specific so look at the documentation for the specific resource for detailed information.

Order of Resource Initalization and Freeing

A good rule of thumb is to free resources in the opposite order they were created. e.g.:

{
    // initialization order
    NabtoDevice* device = nabto_device_new();
    NabtoDeviceFuture* future = nabto_device_future_new(device);
    NabtoDeviceListener* listener = nabto_device_listener_new(device);

    // cleanup order
    nabto_device_listener_free(listener);
    nabto_device_future_free(future);
    nabto_device_free(device);
}

But special attention needs to be given to listeners: They need to be stopped and finished before they can be freed:

{
    // initialization order
    NabtoDevice* device = nabto_device_new();
    ...
    NabtoDeviceListener* listener = nabto_device_listener_new(device);
    nabto_device_coap_init_listener(device, listener, ..., ...);
    nabto_device_listener_new_coap_request(listener, ...);
    // Wait for coap requests in another thread or by a future callback.

    // This is too early as the listener is probably still in use. It needs to be stoppped
    // and not being used anymore first.
    // nabto_device_listener_free(listener)

    nabto_device_listener_stop(listener);

    // This is still too early as the nabto_device_listener_stop is nonblocking. So the resource is still in use.
    // The listener gets a NABTO_DEVICE_EC_STOPPED error code when it can be freed. Else we need to wait to after
    // nabto_device_stop() which blocks until all outstanding operations have been finished.
    //nabto_device_listener_free(listener)

    nabto_device_stop(device);
    nabto_device_listener_free(listener);
    nabto_device_free(device);
}

Examples

We have a few test cases which shows how a device can properly be shutdown: Shutdown Examples.