Configuration API for Mbed SDK

Mbed complete Application Programming Interface (API) reference for building real-time applications on PubNub, including basic usage and sample code.

Configuration

This page describes the preprocessor definitions (macros) that configure C‑Core. They live in the pubnub_config.h header file. The header file differs by platform. Some definitions that do not apply to a platform may be omitted.

Any definitions that you find in pubnub_config.h and that are not listed here should not be changed.

PUBNUB_CTX_MAX: maximum number of contexts

Maximum number of PubNub contexts that can be used at the same time. It applies only to statically allocated contexts. On hosted platforms (POSIX, Windows...), contexts are dynamic by default, so this is ignored. Select the allocation module (static or dynamic) at link time.

A context is used to publish messages or subscribe to (get) them.

Each context consumes memory. Set a realistic limit.

A typical configuration may consist of a single PubNub context for channel subscription and another PubNub context that will periodically publish messages about device status (with timeout lower than message generation frequency). This only needs two contexts.

Another typical setup may have a single subscription context and maintain a pool of contexts for each publish call triggered by an external event, like a button push. This would need N+1 contexts, N being the number of external events.

You can use a single context, but you cannot publish and subscribe on it at the same time. This may cause lost messages.

PUBNUB_BUF_MAXLEN: size of HTTP buffer

Size of the HTTP buffer, in bytes. It heavily impacts the context memory size and sets the upper bound on the URL‑encoded message size. For messages up to 2 KB, set about 2500 for PUBNUB_BUF_MAXLEN. For larger messages, increase the buffer.

You can set this via compiler options. If not, change the default value in the header.

PUBNUB_DYNAMIC_REPLY_BUFFER: use dynamic reply buffer

Set to false (0) to use a static buffer and then set its size via PUBNUB_REPLY_MAXLEN. Set to true (anything !=0) to use a dynamic buffer, that is, dynamically try to allocate as much memory as needed for the buffer.

Default on hosted platforms (Windows, POSIX...) is to use a dynamic reply buffer. Be aware that this can involve large amounts of data (megabytes). If memory is constrained, prefer a static reply buffer. If the reply exceeds the size of your statically allocated buffer, the transaction will fail. Choose the option that best suits your application.

PUBNUB_REPLY_MAXLEN: reply static length

This is only significant if PUBNUB_DYNAMIC_REPLY_BUFFER is true. In that case it defines the size, in octets, of the reply buffer. It will hold the whole (HTTP) body of the reply, not the (HTTP) headers.

Replies of API calls longer than this will be discarded and an error will be reported. Specifically, this may cause lost messages returned by subscribe if too many too large messages got queued on the PubNub server.

PUBNUB_ORIGIN: the DNS hostname of PubNub

This is the DNS hostname for the PubNub network. In most cases, do not change this. If enabled (see PUBNUB_ORIGIN_SETTABLE), you can set origin at runtime.

If you must set it at compile time to save RAM and do not need runtime changes, edit this macro.

PUBNUB_ORIGIN_SETTABLE: is origin settable at runtime

If true (!=0), the origin can be changed at runtime. This adds a small memory cost.

If false (==0), the origin cannot be changed at runtime. Use this to reduce RAM usage.

PUBNUB_DEFAULT_TRANSACTION_TIMER: duration of transaction timeout

Duration of the transaction timeout set during context initialization, in milliseconds. Timeout duration in the context can be changed by the user after initialization (at runtime).

This is used only if timer support is enabled (default on hosted platforms).

PUBNUB_CALLBACK_THREAD_STACK_SIZE_KB: size of the PubNub thread

Stack size (in kilobytes) for the polling thread when using the callback interface. Smaller values save memory, but avoid less than 64 KB.

Set 0 to use the default. Ignored by the sync interface.

PUBNUB_PROXY_API: enable proxy support

Set true (!=0) to enable proxy support (default on hosted platforms). Configure host, port, and protocol with the C‑Core APIs.

Set false (==0) to disable proxy support and reduce code size.

Depending on your build, you may also need to exclude proxy modules from compilation and linking. See the sample makefiles.

PUBNUB_MAX_PROXY_HOSTNAME_LENGTH: max length of proxy hostname

Maximum length (characters) of the proxy host name stored in the context. Set this to fit your proxy names. One host name is stored per context.

PUBNUB_ONLY_PUBSUB: use only publish&subscribe

Set true (!=0) to support only Publish and Subscribe. Default is false on hosted platforms.

This reduces code size if you do not need other transactions.

If you compile modules not needed in this mode, the build may warn. Many linkers drop unused modules automatically, but behavior depends on your toolchain.

You can set this via compiler options or edit the header default.

Initialization

You can make your own program or start by importing the sample program.

The sample targets the AT&T IoT Starter Kit, which uses the Freescale (now NXP) K64F and a WNC modem. If you use different hardware, change the networking library or driver. As far as the PubNub API is concerned, the sample works on other hardware.

If you want to make your own program from scratch, then:

  1. Import the PubNub library. For now, there is only the sync library.

  2. If your Mbed project does not already use it, import the network library. The sample uses the WNC modem library. The latest revision at the time of writing has build issues, but you do not need it. Use the revision from the URL.

  3. Add a pubnub_config.h to your program. You can copy the contents from the sample program and then customize it. All the options are documented. Here we show only the logging configuration near the end of pubnub_config.h:

    #include <MODSERIAL.h>
    extern MODSERIAL pc;
    #define PUBNUB_LOG_PRINTF(...) pc.printf(__VA_ARGS__)
    Comprehensive logging docs

    For detailed information about the C‑Core logging system, available log levels, and how to configure logging for debugging and troubleshooting, refer to the Logging document.

    This expects a MODSERIAL pc global object in your program. In the sample program, it is defined in main.cpp:

    MODSERIAL pc(USBTX,USBRX,256,256);

    You can define PUBNUB_LOG_PRINTF(...) to use any logging target.

  4. If your Mbed project does not already initialize it, initialize the networking library. The sample defines an object of class WNCInterface and then calls its init and connect member functions.

    WNCInterface eth;
    int main() {
    // .... some other init code, like serial port (`pc`)
    pc.printf("init() returned 0x%04X" CRLF, eth.init(NULL,&pc));
    eth.connect();
    pc.printf("IP Address: %s" CRLF, eth.getIPAddress());
    // now modem init is done, you can use PubNub C-Core APIs
    }
  5. After the modem has been initialized, you can use the PubNub C‑Core APIs like on any other supported platform.

Including the header

Your calling pattern (synchronous vs callback) determines which header to import. Learn more later in this guide.

At this time, only the sync pattern is supported on Mbed.

Sync

If using the synchronous (sync) pattern, import only pubnub_sync.h:

#include "pubnub_sync.h"

Memory allocation

This client uses dynamic memory allocation for PubNub contexts. Always use pubnub_alloc() to create a context (and check its return value) and pubnub_free() to dispose of a context.

Required UUID

Always set the UUID to uniquely identify the user or device that connects to PubNub. This UUID should be persisted and remain unchanged for the lifetime of the user or the device. If you do not set the UUID, you will not be able to connect to PubNub.

#include "pubnub_alloc.h"

int main() {
pubnub_t *ctx = pubnub_alloc();
if (NULL == ctx) {
return -1;
}
/* Do something with ctx...
and then: */
pubnub_free(ctx);
return 0
}

Timers

There is one timer: the total transaction timer. It starts when a transaction starts and stops when it finishes. If it expires, the transaction is cancelled locally. If a publish already reached the server, cancellation does not roll it back.

If the transaction timer expires, the outcome is timeout.

The actual duration can exceed what you set due to platform factors, but it is usually close.

Set the timer after initializing the context and before starting transactions. The setting applies to all transaction types.

Thread safety

C‑Core supports thread‑safe operation, though for performance you may choose not to use it. To enable thread safety, define the preprocessor symbol PUBNUB_THREADSAFE (the value does not matter). Define it in pubnub_config.h.

Thread-safe usage

Thread safety protects the PubNub context, not your application data. If you signal from callbacks to worker threads, synchronize your own data.

If you compiled thread-safety support in, you are free to access the same context from different threads, pretty much in any way you wish. However, there are some advised guidelines you should follow:

  • With the sync blocking interface, waiting threads may block for a long time. Avoid this if possible.
  • With the sync non‑blocking interface and pubnub_await, behavior is similar to the blocking interface.
  • With the sync non‑blocking interface and without pubnub_await, waiting threads block less. The main useful action is cancelling a transaction from another thread.
  • Avoid calling pubnub_await or pubnub_last_result from different threads; it makes debugging harder.
  • With the callback interface, avoid calling SDK functions from your callback except small helpers. It simplifies debugging.
Thread-unsafe usage

If you compile without thread safety, the SDK is not thread safe. Do not use one context from more than one thread at the same time. In multithreaded code:

  1. Prefer using a context from only the thread that created it.
  2. If that is not possible, add your own synchronization (for example, condition variables, mutexes, or message queues).
  3. With the callback interface, you can start a transaction in one thread and then use the context only in the callback. This is safe.
Context usage

Keep in mind that it is perfectly safe to use different contexts from different threads at the same time. To each (thread) its own (context).

Transaction and operation

The Mbed C SDK operates as a set of transactions. A transaction is one message exchange between the SDK and the PubNub service. The SDK sequences transactions that together implement an operation.

Status and events

The SDK provides status and event identifiers that help you track transaction outcomes and detect normal or error conditions. Common status codes include:

  1. PNR_OK: Success, the transaction finished successfully.
  2. PNR_STARTED: The previously initiated transaction has started.
  3. PNR_IN_PROGRESS: Indicates that the previous transaction with PubNub service is still in progress.

Refer to the API docs for a complete list of status identifiers supported by the library.

Events are PubNub REST operations initiated by the SDK, such as subscribe and publish. A client subscribing to a channel is a subscribe event, and a client publishing a message to a channel is a publish event.

Some of the common event identifiers are as follows:

  1. PBTT_SUBSCRIBE: Subscriber operation
  2. PBTT_PUBLISH: Publish operation

Refer to the API docs for a complete list of operations supported by the SDK.

Calling patterns

This SDK provides a sync interface for retrieving the outcome of a PubNub request, transaction, or operation. The callback (notification) interface may be provided later.

Sync

The sync interface works like this:

  1. Start a transaction (say, publish - using pubnub_publish()).
  2. Either pubnub_await() the outcome, or use your own loop in which you check if (PNR_STARTED != pubnub_last_result()).
  3. Handle the outcome as you wish.

This is illustrated in the Hello World example below (which is the same for any platform that supports the sync interface).

Initialize the client context

Use this function to initialize the PubNub client context and set account credentials such as publish_key and subscribe_key.

Method(s)

To initialize PubNub, use the following method in the Mbed SDK:

void pubnub_init (pubnub_t *p, const char *publish_key, const char *subscribe_key)
* required
ParameterDescription
p *
Type: pubnub_t*
Pointer to the Context to initialize (use pubnub_alloc() to obtain it)
publish_key *
Type: char *
Pointer to the string of the key to use when publishing messages.
subscribe_key *
Type: char *
Pointer to the string of the key to use when subscribing to messages

Sample code

Initialize the PubNub client API

Required UUID

Always set the UUID to uniquely identify the user or device that connects to PubNub. This UUID should be persisted and remain unchanged for the lifetime of the user or the device. If you do not set the UUID, you will not be able to connect to PubNub.

pubnub_t *ctx = pubnub_alloc();
if (NULL == ctx) {
puts("Couldn't allocate a Pubnub context");
return -1;
}
pubnub_init(ctx, "demo", "demo");
pubnub_set_uuid(ctx, "myUniqueUUID");
pubnub_set_ssl_options(ctx, true, true, true);

Returns

Returns a PubNub instance for APIs like pubnub_publish(), pubnub_subscribe(), pubnub_history(), and pubnub_here_now().

Other examples

Initialize the client

Required UUID

Always set the UUID to uniquely identify the user or device that connects to PubNub. This UUID should be persisted and remain unchanged for the lifetime of the user or the device. If you do not set the UUID, you will not be able to connect to PubNub.

pubnub_init(
ctx,
/*publish key*/"demo",
/*subscribe key*/"demo"
);

Initialization for a read‑only client

If a client will only read messages and never publish to a channel, you can omit the publish_key when initializing the client:

Required UUID

Always set the UUID to uniquely identify the user or device that connects to PubNub. This UUID should be persisted and remain unchanged for the lifetime of the user or the device. If you do not set the UUID, you will not be able to connect to PubNub.

pubnub_init(ctx, "", "demo");

Use a custom UUID

Set a custom UUID to identify your users.

Required UUID

Always set the UUID to uniquely identify the user or device that connects to PubNub. This UUID should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UUID, you won't be able to connect to PubNub.

pubnub_t *pn = pubnub_alloc();
pubnub_init(pn, "myPublishKey", "mySubscribeKey");
pubnub_set_uuid(pn, "myUniqueUUID");

Initializing with SSL enabled

This example shows how to enable SSL. Initialize the client and enable SSL options, then subscribe and publish as usual.

Required UUID

Always set the UUID to uniquely identify the user or device that connects to PubNub. This UUID should be persisted and remain unchanged for the lifetime of the user or the device. If you do not set the UUID, you will not be able to connect to PubNub.

pubnub_t *ctx = pubnub_alloc();
if (NULL == ctx) {
puts("Couldn't allocate a Pubnub context");
return -1;
}
pubnub_init(ctx, "demo", "demo");
pubnub_set_uuid(ctx, "myUniqueUUID");
pubnub_set_ssl_options(ctx, true, true, true);

UUID

Use these functions to set or get a UUID at runtime.

Method(s)

To set or get UUID, use the following methods in the Mbed SDK:

void pubnub_set_uuid (pubnub_t *p, const char *uuid)
* required
ParameterDescription
p *
Type: pubnub_t*
Pointer to PubNub context
uuid *
Type: const char*
Pointer to uuid string
char const *pubnub_uuid_get(pubnub_t *p)
* required
ParameterDescription
p *
Type: pubnub_t*
Pointer to pubnub client context.

After pubnub_init(), it returns NULL until you change it to non‑NULL via pubnub_set_uuid().

Sample code

Set UUID

Required UUID

Always set the UUID to uniquely identify the user or device that connects to PubNub. This UUID should be persisted and remain unchanged for the lifetime of the user or the device. If you do not set the UUID, you will not be able to connect to PubNub.

pubnub_t *ctx = pubnub_alloc();
if (NULL == ctx) {
puts("Couldn't allocate a Pubnub context");
return -1;
}
pubnub_init(ctx, "myPublishKey", "mySubscribeKey");
pubnub_set_uuid(ctx, "myUniqueUUID");

Get UUID

printf("UUID is %s", pubnub_uuid_get(ctx));

Returns

Get UUID returns the following output:

TypeDescription
char const*
UUID for context. Null if not set.

Other examples

Initialize with a custom UUID

Required UUID

Always set the UUID to uniquely identify the user or device that connects to PubNub. This UUID should be persisted and remain unchanged for the lifetime of the user or the device. If you do not set the UUID, you will not be able to connect to PubNub.

pubnub_t *ctx = pubnub_alloc();
if (NULL == ctx) {
puts("Couldn't allocate a Pubnub context");
return -1;
}

struct Pubnub_UUID uuid;
char random_uuid;
if (0 == pubnub_generate_uuid_v4_random(&uuid)) {
random_uuid = pubnub_uuid_to_string(&uuid).uuid;
pubnub_init(ctx, "myPublishKey", "mySubscribeKey");
pubnub_set_uuid(ctx, random_uuid);
}

pubnub_free(ctx);

Authentication key

Set and get the user's auth key.

Method(s)

pubnub_set_auth(pubnub_t* p, const char* auth)
* required
ParameterDescription
p *
Type: pubnub_t*
Pointer to pubnub client context
auth
Type: const char*
Pointer to auth string. NULL to unset
char const *pubnub_auth_get(pubnub_t *p)
* required
ParameterDescription
p *
Type: pubnub_t*
Pointer to pubnub client context

Sample code

Set auth key

pubnub_t *ctx = pubnub_alloc();
if (NULL == ctx) {
puts("Couldn't allocate a Pubnub context");
return -1;
}
pubnub_init(ctx, "demo", "demo");
pubnub_set_auth(ctx, "my_new_authkey");

Get auth key

pubnub_t *ctx = pubnub_alloc();
if (NULL == ctx) {
puts("Couldn't allocate a Pubnub context");
return -1;
}
pubnub_init(ctx, "demo", "demo");
pubnub_set_auth(ctx, "my_auth_key");
printf("Auth Key is %s", pubnub_auth_get(ctx));

Returns

Get auth key returns the current authentication key.

Origin

Sets the origin (DNS host) for context p. If runtime origin is disabled, the call fails. NULL resets the origin to the default.

Method

To set the origin for a PubNub context use:

int pubnub_origin_set(pubnub_t *p, char const *origin)
* required
ParameterDescription
p *
Type: pubnub_t *
PubNub context to set origin for
Origin
Type: char const*
The origin to use for context p. If NULL, the default origin will be set.
To request a custom domain, contact support and follow the request process.

Sample code

Set the origin to the European data center explicitly:

pubnub_origin_set(pn, "ps.pndsn.com");

Returns

TypeDescription
int
0: success, -1: fail
Last updated on