### Complete Working Example Source: https://github.com/pubnub/c/blob/master/_autodocs/MANIFEST.md A comprehensive example demonstrating a complete workflow or use case with the PubNub C SDK. This serves as a practical guide for implementing specific features. ```c /* Complete working examples */ ``` -------------------------------- ### Usage Guide Source: https://github.com/pubnub/c/blob/master/_autodocs/MANIFEST.md A step-by-step guide on how to use the documentation effectively. ```APIDOC ## Usage 1. Start with `README.md` for an overview. 2. Use `INDEX.md` to find your specific use case. 3. Follow links to detailed module documentation. 4. Reference `types.md` for type definitions. 5. Consult `errors.md` for error handling information. 6. Check `configuration.md` for setup options. ``` -------------------------------- ### PubNub C++ Publish and Subscribe Example Source: https://github.com/pubnub/c/blob/master/_autodocs/api-reference/pubnub-cpp.md A complete C++ usage example demonstrating how to initialize the PubNub client, set security keys, publish a message to a channel, and subscribe to receive messages. It includes error handling for the publish operation. ```cpp #include #include #include #include #include int main() { pubnub_sync *sync = pubnub_sync_init(); PubNub p("demo", "demo", &pubnub_sync_callbacks, sync); // Set security p.set_secret_key("my-secret"); p.set_cipher_key("my-cipher"); // Publish json_object *msg = json_object_new_object(); json_object_object_add(msg, "text", json_object_new_string("Hello from C++\n")); p.publish("my_channel", *msg); json_object_put(msg); PubNub_sync_reply pub_reply = pubnub_sync_last_reply(sync); if (pub_reply.result() != PNR_OK) { std::cerr << "Publish failed" << std::endl; return EXIT_FAILURE; } // Subscribe p.subscribe("my_channel"); PubNub_sync_reply sub_reply = pubnub_sync_last_reply(sync); if (sub_reply.result() == PNR_OK) { json_object *messages = sub_reply.response(); std::cout << "Received: " << json_object_get_string(messages) << std::endl; } return EXIT_SUCCESS; } ``` -------------------------------- ### Build Pidgin/Finch Plugin on Mac Source: https://github.com/pubnub/c/blob/master/examples/libpurple/README.md Installs MacPorts, required libraries, clones the PubNub C library, builds and installs the common library, and copies the plugin to the user's purple directory. ```bash install macports (macports.org) sudo port install pidgin +finch sudo port install json-c sudo port install libevent git clone https://github.com/pubnub/c.git cd c/libpubnub make -f Makefile.darwin sudo make -f Makefile.darwin install cd ../examples/libpurple make mkdir -p ~/.purple/plugins cp libpubnub.so ~/.purple/plugins ``` -------------------------------- ### C Synchronous Usage Example Source: https://github.com/pubnub/c/blob/master/_autodocs/MANIFEST.md Demonstrates how to use the PubNub C SDK for synchronous operations. This example would typically involve initializing the PubNub context, performing an operation, and then checking the result. ```c /* C synchronous usage */ ``` -------------------------------- ### Build Pidgin/Finch Plugin on Linux Source: https://github.com/pubnub/c/blob/master/examples/libpurple/README.md Installs dependencies, clones the PubNub C library, builds the common library, and installs the Pidgin/Finch plugin on Linux systems. ```bash sudo apt-get install libpurple-dev libevent-dev libjson0-dev libcurl4-openssl-dev libssl-dev git clone git://github.com/pubnub/c cd c make sudo make install cd examples/libpurple make deb # optionaly sudo make install ``` -------------------------------- ### Start Media Player Source: https://github.com/pubnub/c/blob/master/examples/rpi-mplayer/README.md Start the PubNub media player on a Raspberry Pi, setting its ID to 1. ```bash ./pubnub-rpi-mplayer -i 1 ``` -------------------------------- ### C++ Usage Example Source: https://github.com/pubnub/c/blob/master/_autodocs/MANIFEST.md Provides an example of how to integrate and use the PubNub C++ API. This would showcase the object-oriented approach provided by the C++ wrapper. ```cpp /* C++ usage */ ``` -------------------------------- ### Command Line Synopsis Source: https://github.com/pubnub/c/blob/master/examples/rpi-wiringpi/README.md Example of how to run the PubNub Raspberry Pi control application from the command line, specifying input/output pins and a device ID. ```bash ./pubnub-rpi-wiringpi -i 1 -r 4,10 -w 12,13 ``` -------------------------------- ### Subscribe to a Channel (Synchronous Loop) Source: https://github.com/pubnub/c/blob/master/_autodocs/api-reference/pubnub-messaging.md This example demonstrates how to subscribe to a channel and continuously receive new messages using a synchronous approach. The loop should be managed to avoid blocking indefinitely. ```c #include #include #include struct pubnub_sync *sync = pubnub_sync_init(); struct pubnub *p = pubnub_init("demo", "demo", &pubnub_sync_callbacks, sync); // Subscribe to a channel do { pubnub_subscribe(p, "my_channel", -1, NULL, NULL); if (pubnub_sync_last_result(sync) != PNR_OK) { fprintf(stderr, "Subscribe failed\n"); break; } json_object *messages = pubnub_sync_last_response(sync); int count = json_object_array_length(messages); if (count == 0) { printf("No new messages\n"); } else { char **channels = pubnub_sync_last_channels(sync); for (int i = 0; i < count; i++) { json_object *msg = json_object_array_get_idx(messages, i); printf("[%s]: %s\n", channels[i], json_object_get_string(msg)); } } json_object_put(messages); sleep(1); } while (1); pubnub_done(p); ``` -------------------------------- ### C API Subscribe Example Source: https://github.com/pubnub/c/blob/master/_autodocs/api-reference/pubnub-cpp-sync.md Demonstrates subscribing to a channel using the C API. Manual memory management is required for channels and response objects. ```c pubnub_subscribe(p, "my_channel", -1, NULL, NULL); if (pubnub_sync_last_result(sync) != PNR_OK) { printf("Subscribe failed\n"); return EXIT_FAILURE; } json_object *msg = pubnub_sync_last_response(sync); char **channels = pubnub_sync_last_channels(sync); printf("[%s]: %s\n", channels[0], json_object_get_string(msg)); free(channels[0]); free(channels); json_object_put(msg); ``` -------------------------------- ### Initialize and Configure PubNub C SDK Source: https://github.com/pubnub/c/blob/master/_autodocs/configuration.md This example demonstrates the complete initialization and configuration process for the PubNub C SDK. It covers setting up required parameters like publish and subscribe keys, callbacks, and optional configurations for security, presence, error handling, and server origin. ```c #include #include int main(void) { // Initialize frontend struct pubnub_sync *sync = pubnub_sync_init(); // Create context with required configuration struct pubnub *p = pubnub_init( "demo-publish-key", // publish key "demo-subscribe-key", // subscribe key &pubnub_sync_callbacks, // callbacks sync // callback data ); // Configure security (optional) pubnub_set_secret_key(p, "demo-secret-key"); pubnub_set_cipher_key(p, "demo-cipher-key"); // Configure presence (optional) pubnub_set_uuid(p, "my-user-id"); // Configure error handling (optional) pubnub_error_policy(p, ~(1< channels = reply.channels(); json_object *msg = reply.response(); std::cout << "[" << channels[0] << "]: " << json_object_get_string(msg) << std::endl; // No manual memory management needed ``` -------------------------------- ### Error Handling Pattern Example Source: https://github.com/pubnub/c/blob/master/_autodocs/MANIFEST.md Shows a common pattern for handling errors returned by PubNub SDK operations. This example would likely involve checking the result code of an operation and taking appropriate action. ```c /* Error handling patterns */ ``` -------------------------------- ### Initialize PubNub with libevent Frontend Source: https://github.com/pubnub/c/blob/master/_autodocs/api-reference/pubnub-libevent.md Initialize the libevent frontend context and then use it to initialize a PubNub context. This setup is for asynchronous operations using libevent. ```c #include #include #include // Create libevent event base struct event_base *evbase = event_base_new(); if (!evbase) { fprintf(stderr, "Failed to create event base\n"); return EXIT_FAILURE; } // Initialize libevent frontend struct pubnub_libevent *libevent_ctx = pubnub_libevent_init(evbase); if (!libevent_ctx) { fprintf(stderr, "Failed to initialize libevent frontend\n"); event_base_free(evbase); return EXIT_FAILURE; } // Create PubNub context struct pubnub *p = pubnub_init("demo", "demo", &pubnub_libevent_callbacks, libevent_ctx); // Issue async operations pubnub_publish(p, "my_channel", msg, -1, publish_cb, NULL); // Run event loop event_base_dispatch(evbase); // Cleanup pubnub_done(p); event_base_free(evbase); ``` -------------------------------- ### Format and Style Guidelines Source: https://github.com/pubnub/c/blob/master/_autodocs/MANIFEST.md Guidelines for the format and style of the documented code, including function signatures, parameters, examples, and cross-references. ```APIDOC ## Format and Style Guidelines Each documented function/method includes: - Full function/method signature with exact types. - Parameter table with type, required/optional, default, and description. - Return type and its meaning. - Result codes and error conditions. - Trigger points for errors. - Retry behavior. - Concrete usage examples (not test code). - Source file references with line numbers. - Cross-references to related functions. Tables are used for: - Parameters - Error codes - Configuration options - Type fields - Result codes - Trade-offs and comparisons Code examples cover: - C synchronous usage - C asynchronous usage - C++ usage - Error handling patterns - Complete working examples (not test framework code). ``` -------------------------------- ### Synchronous Time Retrieval and Latency Estimation Source: https://github.com/pubnub/c/blob/master/_autodocs/api-reference/pubnub-time.md This example demonstrates how to retrieve the server time synchronously and calculate the network round-trip time. It requires initializing PubNub, recording local time before and after the request, and processing the JSON response. ```c #include #include #include #include struct pubnub_sync *sync = pubnub_sync_init(); struct pubnub *p = pubnub_init("demo", "demo", &pubnub_sync_callbacks, sync); // Record local time before request struct timespec local_start; clock_gettime(CLOCK_MONOTONIC, &local_start); // Get server time pubnub_time(p, -1, NULL, NULL); // Record local time after response struct timespec local_end; clock_gettime(CLOCK_MONOTONIC, &local_end); if (pubnub_sync_last_result(sync) != PNR_OK) { fprintf(stderr, "Time query failed\n"); goto cleanup; } json_object *response = pubnub_sync_last_response(sync); int64_t server_time = json_object_get_int64(response); // Calculate round-trip time in nanoseconds uint64_t rtt_ns = (uint64_t)(local_end.tv_sec - local_start.tv_sec) * 1000000000 + (local_end.tv_nsec - local_start.tv_nsec); double rtt_ms = rtt_ns / 1000000.0; printf("Server time: %lld microseconds since epoch\n", (long long)server_time); printf("Network latency: %.2f ms\n", rtt_ms / 2.0); json_object_put(response); cleanup: pubnub_done(p); ``` -------------------------------- ### PubNub C++ Sync Last Reply Example Source: https://github.com/pubnub/c/blob/master/_autodocs/api-reference/pubnub-cpp-sync.md Demonstrates how to use `pubnub_sync_last_reply` to retrieve results from synchronous PubNub operations like publish, history, and subscribe. It includes error checking and response parsing. ```cpp #include #include #include #include int main() { pubnub_sync *sync = pubnub_sync_init(); PubNub p("demo", "demo", &pubnub_sync_callbacks, sync); // Publish json_object *msg = json_object_new_object(); json_object_object_add(msg, "text", json_object_new_string("Hello")); p.publish("my_channel", *msg); json_object_put(msg); // Get reply PubNub_sync_reply pub_reply = pubnub_sync_last_reply(sync); if (pub_reply.result() != PNR_OK) { std::cerr << "Publish error" << std::endl; return EXIT_FAILURE; } std::cout << "Published: " << json_object_get_string(pub_reply.response()) << std::endl; // History p.history("my_channel", 10); PubNub_sync_reply hist_reply = pubnub_sync_last_reply(sync); if (hist_reply.result() == PNR_OK) { json_object *messages = hist_reply.response(); int count = json_object_array_length(messages); std::cout << "Got " << count << " history messages" << std::endl; } // Subscribe do { p.subscribe("my_channel"); PubNub_sync_reply sub_reply = pubnub_sync_last_reply(sync); if (sub_reply.result() != PNR_OK) { std::cerr << "Subscribe error" << std::endl; break; } json_object *messages = sub_reply.response(); int count = json_object_array_length(messages); if (count == 0) { std::cout << "No new messages" << std::endl; } else { std::vector channels = sub_reply.channels(); for (int i = 0; i < count; i++) { json_object *msg = json_object_array_get_idx(messages, i); std::cout << "[" << channels[i] << "]: " << json_object_get_string(msg) << std::endl; } } } while (true); return EXIT_SUCCESS; } ``` -------------------------------- ### C Asynchronous Usage Example Source: https://github.com/pubnub/c/blob/master/_autodocs/MANIFEST.md Illustrates the asynchronous usage pattern of the PubNub C SDK, likely involving callbacks for handling responses and errors. This is suitable for non-blocking operations. ```c /* C asynchronous usage */ ``` -------------------------------- ### Automatic Encryption/Decryption with PubNub Crypto Source: https://github.com/pubnub/c/blob/master/_autodocs/api-reference/pubnub-crypto.md This example demonstrates how to configure PubNub for automatic message signing and encryption/decryption by setting the secret and cipher keys. It shows publishing a sensitive message and then subscribing to receive it, with PubNub handling the crypto operations transparently. ```c #include #include #include struct pubnub_sync *sync = pubnub_sync_init(); struct pubnub *p = pubnub_init("demo", "demo", &pubnub_sync_callbacks, sync); // Configure security pubnub_set_secret_key(p, "my-secret-key"); // Auto-sign pubnub_set_cipher_key(p, "my-cipher-key"); // Auto-encrypt // Publish - message is automatically encrypted and signed json_object *msg = json_object_new_object(); json_object_object_add(msg, "text", json_object_new_string("sensitive data")); pubnub_publish(p, "secure_channel", msg, -1, NULL, NULL); json_object_put(msg); // Subscribe - messages are automatically decrypted pubnub_subscribe(p, "secure_channel", -1, NULL, NULL); if (pubnub_sync_last_result(sync) == PNR_OK) { json_object *received = pubnub_sync_last_response(sync); printf("Received (auto-decrypted): %s\n", json_object_get_string(received)); json_object_put(received); } pubnub_done(p); ``` -------------------------------- ### Asynchronous Time Retrieval Source: https://github.com/pubnub/c/blob/master/_autodocs/api-reference/pubnub-time.md This example shows how to retrieve the server time asynchronously using a callback function. The callback is invoked upon completion of the time retrieval request. ```c static void time_callback(struct pubnub *p, enum pubnub_res result, struct json_object *response, void *ctx_data, void *call_data) { if (result != PNR_OK) { fprintf(stderr, "Time query failed: %d\n", result); return; } int64_t server_time = json_object_get_int64(response); printf("Server time: %lld microseconds\n", (long long)server_time); } // Request time asynchronously pubnub_time(p, -1, time_callback, NULL); ``` -------------------------------- ### C++ Synopsis for PubNub Library Source: https://github.com/pubnub/c/blob/master/README.md Shows the C++ interface for the PubNub library, wrapping the C library for a more C++ friendly experience. Similar setup to the C version. ```cpp #include #include #include pubnub_sync *sync = pubnub_sync_init(); PubNub p("demo", "demo", &pubnub_sync_callbacks, sync); p.publish("my_channel", json_object); do { p.subscribe("my_channel"); PubNub_sync_reply reply = pubnub_sync_last_reply(sync); if (reply.result() != PNR_OK) exit(EXIT_FAILURE); json_object *msg = reply.response(); for (int i = 0; i < json_object_array_length(msg); i++) { json_object *msg1 = json_object_array_get_idx(msg, i); std::cout << "received: " << json_object_get_string(msg1) << std::endl; } } while (1); ``` -------------------------------- ### Retrieve and Process Channel History (C) Source: https://github.com/pubnub/c/blob/master/_autodocs/api-reference/pubnub-history.md Example demonstrating how to retrieve the last 10 messages from 'my_channel' using the synchronous history API. It includes error checking and iterates through the JSON response to print each message. ```c #include #include #include struct pubnub_sync *sync = pubnub_sync_init(); struct pubnub *p = pubnub_init("demo", "demo", &pubnub_sync_callbacks, sync); // Retrieve last 10 messages pubnub_history(p, "my_channel", 10, -1, NULL, NULL); if (pubnub_sync_last_result(sync) != PNR_OK) { fprintf(stderr, "History retrieval failed\n"); goto cleanup; } json_object *messages = pubnub_sync_last_response(sync); if (!json_object_is_type(messages, json_type_array)) { fprintf(stderr, "Unexpected response format\n"); json_object_put(messages); goto cleanup; } int count = json_object_array_length(messages); printf("Retrieved %d messages\n", count); for (int i = 0; i < count; i++) { json_object *msg = json_object_array_get_idx(messages, i); printf("%d: %s\n", i, json_object_get_string(msg)); } json_object_put(messages); cleanup: pubnub_done(p); ``` -------------------------------- ### Retrieve Message History with Timetokens (C) Source: https://github.com/pubnub/c/blob/master/_autodocs/api-reference/pubnub-history.md Example demonstrating how to retrieve message history including timetokens using the PubNub History Ex API. It shows initialization, calling the function, checking for errors, and parsing the JSON response to extract messages and their associated timetokens. ```c #include #include #include struct pubnub_sync *sync = pubnub_sync_init(); struct pubnub *p = pubnub_init("demo", "demo", &pubnub_sync_callbacks, sync); // Get history with timetokens pubnub_history_ex(p, "my_channel", 10, -1, NULL, NULL, 1); if (pubnub_sync_last_result(sync) != PNR_OK) { fprintf(stderr, "History retrieval failed\n"); goto cleanup; } json_object *response = pubnub_sync_last_response(sync); // Response is [messages_array, start_timetoken, end_timetoken] json_object *messages_with_tokens = json_object_array_get_idx(response, 0); json_object *start_tt = json_object_array_get_idx(response, 1); json_object *end_tt = json_object_array_get_idx(response, 2); int count = json_object_array_length(messages_with_tokens); printf("Retrieved %d messages (tokens from %s to %s)\n", count, json_object_get_string(start_tt), json_object_get_string(end_tt)); for (int i = 0; i < count; i++) { json_object *item = json_object_array_get_idx(messages_with_tokens, i); json_object *msg = json_object_object_get(item, "message"); json_object *token = json_object_object_get(item, "timetoken"); printf("[%s]: %s\n", json_object_get_string(token), json_object_get_string(msg)); } json_object_put(response); cleanup: pubnub_done(p); ``` -------------------------------- ### Build and Run Tests (Linux/Mac OS X) Source: https://github.com/pubnub/c/blob/master/tests/README.md Compile the tests using 'make' and then execute the compiled test binary './libtest'. This is the standard procedure for running tests on Linux and Mac OS X after setting up the environment. ```bash make ./libtest ``` -------------------------------- ### Initialize PubNub Sync Frontend Source: https://github.com/pubnub/c/blob/master/_autodocs/api-reference/pubnub-sync.md Initializes the sync frontend context and the PubNub client. Pass `pubnub_sync_callbacks` to `pubnub_init()` for synchronous operation. ```c struct pubnub_sync *sync = pubnub_sync_init(); struct pubnub *p = pubnub_init("demo", "demo", &pubnub_sync_callbacks, sync); ``` -------------------------------- ### Initialize and Configure PubNub C++ SDK Source: https://github.com/pubnub/c/blob/master/_autodocs/configuration.md This snippet shows how to initialize the PubNub C++ SDK with keys and configure various options like secret key, cipher key, UUID, error policy, and origin. It's useful for setting up the client for communication. ```cpp #include #include int main() { pubnub_sync *sync = pubnub_sync_init(); // Create context PubNub p("demo-publish-key", "demo-subscribe-key", &pubnub_sync_callbacks, sync); // Configure options p.set_secret_key("demo-secret-key"); p.set_cipher_key("demo-cipher-key"); p.set_uuid("my-user-id"); p.error_policy(~(1< ch; ch.push_back("channel1"); ch.push_back("channel2"); p.subscribe_multi(ch); PubNub_sync_reply reply = pubnub_sync_last_reply(sync); if (reply.result() == PNR_OK) { json_object *messages = reply.response(); std::vector msg_channels = reply.channels(); int count = json_object_array_length(messages); for (int i = 0; i < count; i++) { json_object *msg = json_object_array_get_idx(messages, i); std::cout << "[" << msg_channels[i] << "]:" << json_object_get_string(msg) << std::endl; } } ``` -------------------------------- ### Time Synchronization Source: https://github.com/pubnub/c/blob/master/_autodocs/INDEX.md Function to get the server timestamp for latency estimation. ```APIDOC ## pubnub_time() ### Description Retrieves the current server timestamp for latency estimation. ### Method N/A (C function) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ``` -------------------------------- ### pubnub_sync_init Source: https://github.com/pubnub/c/blob/master/_autodocs/api-reference/pubnub-sync.md Initializes the sync frontend context. This must be called before initializing the main PubNub context with `pubnub_init()` and passing `pubnub_sync_callbacks`. ```APIDOC ## pubnub_sync_init ### Description Initialize the sync frontend context. ### Method `struct pubnub_sync *pubnub_sync_init(void);` ### Parameters None ### Returns Pointer to initialized sync frontend context, or NULL on failure. ### Notes - Must be called before passing to `pubnub_init()` - Allocates memory that will be freed when the associated pubnub context is destroyed - Returns opaque structure; only used with other `pubnub_sync_*` functions ### Example ```c #include #include struct pubnub_sync *sync = pubnub_sync_init(); if (!sync) { fprintf(stderr, "Failed to initialize sync frontend\n"); return EXIT_FAILURE; } struct pubnub *p = pubnub_init("demo", "demo", &pubnub_sync_callbacks, sync); ``` ``` -------------------------------- ### pubnub_here_now() Source: https://github.com/pubnub/c/blob/master/_autodocs/INDEX.md Gets the current occupancy of a channel, returning a list of users currently subscribed. ```APIDOC ## pubnub_here_now() ### Description Gets the current occupancy of a channel, returning a list of users currently subscribed. ### Method Not specified (assumed to be an SDK function call) ### Endpoint Not applicable (SDK function) ### Parameters - **pubnub** (struct pubnub *) - Required - Pointer to the PubNub context. - **channel** (const char *) - Required - The channel to get occupancy for. - **callback** (function pointer) - Optional - Callback function to handle the here_now result. ### Request Example ```c struct pubnub *p = pubnub_init(...); pubnub_here_now(p, "my_channel", my_here_now_callback); ``` ### Response #### Success Response Indicated by the callback function being invoked with a success status and channel occupancy information. #### Response Example Callback invoked with channel occupancy data. ``` -------------------------------- ### Player Status Message (Idle) Source: https://github.com/pubnub/c/blob/master/examples/rpi-mplayer/README.md Example of a status message sent by the player to the 'rpi_mplayer_status' channel when idle. ```json {"id":1, "status":"idle"} ``` -------------------------------- ### Player Status Message (Playing) Source: https://github.com/pubnub/c/blob/master/examples/rpi-mplayer/README.md Example of a status message sent by the player to the 'rpi_mplayer_status' channel when playing a file. ```json {"id":1, "status":"playing", "file":"song.mp3"} ``` -------------------------------- ### Get Current UUID in PubNub C++ Source: https://github.com/pubnub/c/blob/master/_autodocs/api-reference/pubnub-cpp.md Retrieve the unique identifier for the current PubNub client context. This UUID can be auto-generated or explicitly set. ```cpp std::string current_uuid(); ``` ```cpp std::cout << "My UUID: " << p.current_uuid() << std::endl; ``` -------------------------------- ### Build libevent with nmake Source: https://github.com/pubnub/c/blob/master/msvc/README.md Instructions for building the libevent library using nmake. Assumes the source code has been unpacked. ```bash nmake -f Makefile.nmake ``` -------------------------------- ### Download Google Test Framework Source: https://github.com/pubnub/c/blob/master/tests/README.md Download the googletest framework source code. This is the first step for setting up the testing environment on non-Debian Linux and Mac OS X systems. ```bash wget http://googletest.googlecode.com/files/gtest-1.7.0.zip ``` -------------------------------- ### Initialize PubNub Context (C) Source: https://github.com/pubnub/c/blob/master/_autodocs/configuration.md Initializes a PubNub context with publish and subscribe keys, and a callback structure. Keys are copied and can be freed after the call. The callback structure is mandatory. ```c struct pubnub *pubnub_init( const char *publish_key, const char *subscribe_key, const struct pubnub_callbacks *cb, void *cb_data ); ``` -------------------------------- ### Initialize PubNub Sync Frontend Context Source: https://github.com/pubnub/c/blob/master/_autodocs/api-reference/pubnub-sync.md Initializes the sync frontend context. This must be called before passing the context to `pubnub_init()`. It allocates memory that is freed when the PubNub context is destroyed. ```c #include #include struct pubnub_sync *sync = pubnub_sync_init(); if (!sync) { fprintf(stderr, "Failed to initialize sync frontend\n"); return EXIT_FAILURE; } struct pubnub *p = pubnub_init("demo", "demo", &pubnub_sync_callbacks, sync); ``` -------------------------------- ### Initialize PubNub Context (C++) Source: https://github.com/pubnub/c/blob/master/_autodocs/api-reference/pubnub-cpp.md Initializes a PubNub context using publish and subscribe keys, along with a callback structure and user data. This constructor is thread-unsafe during libcurl initialization. A single context can only handle one operation at a time. Use with `pubnub_sync_callbacks` for synchronous operations. ```cpp #include #include pubnub_sync *sync = pubnub_sync_init(); PubNub p("demo", "demo", &pubnub_sync_callbacks, sync); // Use p for operations... ``` -------------------------------- ### Get Server Time (C++) Source: https://github.com/pubnub/c/blob/master/_autodocs/api-reference/pubnub-cpp.md Retrieve the current time from the PubNub server. This can be used for synchronization or logging purposes. An optional timeout and callback are supported for asynchronous calls. ```cpp void time( long timeout = -1, PubNub_time_cb cb = NULL, void *cb_data = NULL ); ``` ```cpp p.time(); ``` -------------------------------- ### Build openssl with nmake Source: https://github.com/pubnub/c/blob/master/msvc/README.md Instructions for building the openssl library using nmake with Visual C++. Requires ActivePerl and specific configuration flags. ```bash perl Configure VC-WIN32 no-asm --prefix=../openssl ms\do_ms nmake -f ms\ntdll.mak nmake -f ms\ntdll.mak install ``` -------------------------------- ### Get Last PubNub Operation Result Source: https://github.com/pubnub/c/blob/master/_autodocs/api-reference/pubnub-sync.md Retrieves the result code of the most recent PubNub operation. Always check this before accessing the response. The result persists until the next operation. ```c pubnub_subscribe(p, "my_channel", -1, NULL, NULL); enum pubnub_res result = pubnub_sync_last_result(sync); if (result != PNR_OK) { const char *result_str[] = { "OK", "OCCUPIED", "TIMEOUT", "IO_ERROR", "HTTP_ERROR", "FORMAT_ERROR", "CANCELLED" }; fprintf(stderr, "Subscribe failed: %s\n", result_str[result]); return EXIT_FAILURE; } // Safe to access response now json_object *msg = pubnub_sync_last_response(sync); ``` -------------------------------- ### PubNub Constructor (Credentials and Callbacks) Source: https://github.com/pubnub/c/blob/master/_autodocs/api-reference/pubnub-cpp.md Initializes a PubNub context using publish and subscribe keys, along with a callback structure and associated data. This constructor is similar to the C API's `pubnub_init()` and handles libcurl initialization. Note that a single context can only manage one operation at a time. ```APIDOC ## PubNub(const std::string &publish_key, const std::string &subscribe_key, const struct pubnub_callbacks *cb, void *cb_data) ### Description Initializes a PubNub context with credentials and callbacks. This is the primary constructor for setting up a new PubNub instance with specific keys and a callback mechanism for handling asynchronous operations. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method Constructor ### Endpoint N/A ### Parameters - **publish_key** (`const std::string &`) - Required - PubNub publish key. - **subscribe_key** (`const std::string &`) - Required - PubNub subscribe key. - **cb** (`const struct pubnub_callbacks *`) - Required - Callback structure containing function pointers for various PubNub events. - **cb_data** (`void *`) - Optional - Callback context data, which will be passed to the callback functions. ### Notes - Initializes libcurl on the first call (not thread-safe across threads). - A single context can handle only one operation at a time. - For synchronous operations, use with `pubnub_sync_callbacks`. ### Example ```cpp #include #include pubnub_sync *sync = pubnub_sync_init(); PubNub p("demo", "demo", &pubnub_sync_callbacks, sync); // Use p for operations... ``` ``` -------------------------------- ### Check Publish Operation Result Source: https://github.com/pubnub/c/blob/master/_autodocs/api-reference/pubnub-cpp-sync.md Use the `result()` method to check the outcome of a publish operation. Ensure the operation completed successfully before processing the response. This example demonstrates checking for `PNR_OK`. ```cpp pubnub_sync *sync = pubnub_sync_init(); PubNub p("demo", "demo", &pubnub_sync_callbacks, sync); p.publish("my_channel", *msg); PubNub_sync_reply reply = pubnub_sync_last_reply(sync); if (reply.result() != PNR_OK) { std::cerr << "Publish failed: " << reply.result() << std::endl; return EXIT_FAILURE; } ``` -------------------------------- ### Documented Configuration Options Source: https://github.com/pubnub/c/blob/master/_autodocs/MANIFEST.md Details on all available configuration options for the PubNub client. ```APIDOC ## Documented Configuration Options - Publish key (required) - Subscribe key (required) - Secret key (for message signing) - Cipher key (for message encryption) - Origin server - UUID - No-signal flag - Error retry policy - SSL certificates - Resume on reconnect ``` -------------------------------- ### Get Channel Presence Information (C++) Source: https://github.com/pubnub/c/blob/master/_autodocs/api-reference/pubnub-cpp.md Query for current presence information on a channel, such as the number of users currently connected. This function allows for a custom timeout and an optional callback for asynchronous handling. ```cpp void here_now( const std::string &channel, long timeout = -1, PubNub_here_now_cb cb = NULL, void *cb_data = NULL ); ``` ```cpp p.here_now("my_channel"); ``` -------------------------------- ### Get Last PubNub Operation Response Source: https://github.com/pubnub/c/blob/master/_autodocs/api-reference/pubnub-sync.md Retrieves the JSON response from the last PubNub operation. The caller must call `json_object_put()` to release the reference. The reference is valid only until the next PubNub operation. ```c pubnub_publish(p, "my_channel", msg, -1, NULL, NULL); if (pubnub_sync_last_result(sync) != PNR_OK) { fprintf(stderr, "Publish failed\n"); goto cleanup; } json_object *response = pubnub_sync_last_response(sync); printf("Publish response: %s\n", json_object_get_string(response)); json_object_put(response); // Release reference cleanup: // ... ``` -------------------------------- ### pubnub_init() Source: https://github.com/pubnub/c/blob/master/_autodocs/INDEX.md Initializes a new PubNub context, which is required before calling other PubNub functions. ```APIDOC ## pubnub_init() ### Description Initializes a new PubNub context, which is required before calling other PubNub functions. ### Method Not specified (assumed to be an SDK function call) ### Endpoint Not applicable (SDK function) ### Parameters None explicitly mentioned for basic initialization, but configuration functions like `pubnub_set_secret_key()` can be called subsequently. ### Request Example ```c struct pubnub *p = pubnub_init(); ``` ### Response #### Success Response A pointer to a newly created `struct pubnub` context. #### Response Example `struct pubnub *p` (pointer to context) ``` -------------------------------- ### Core Context Initialization, Configuration, and Lifecycle Management Source: https://github.com/pubnub/c/blob/master/_autodocs/INDEX.md Functions for initializing and finalizing the PubNub context, configuring essential parameters like secret keys, cipher keys, origin, and UUID, managing state serialization, and accessing API version constants. ```APIDOC ## pubnub_init() / pubnub_done() ### Description Initializes and finalizes the PubNub context, managing the lifecycle of the SDK. ### Method N/A (C functions) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ## Context Configuration ### Description Configure essential parameters for the PubNub context, including secret key, cipher key, origin, and UUID. ### Method N/A (C functions) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ## State Serialization ### Description Manages the serialization and deserialization of PubNub context state. ### Method N/A (C functions) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ## API Version Constants ### Description Provides constants for the PubNub SDK API version. ### Method N/A ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ``` -------------------------------- ### Get JSON Response from Operation Source: https://github.com/pubnub/c/blob/master/_autodocs/api-reference/pubnub-cpp-sync.md Retrieve the JSON response from a PubNub operation using the `response()` method. The format of the response varies by operation. The returned `json_object` pointer is valid for the lifetime of the `PubNub_sync_reply` instance. ```cpp PubNub_sync_reply reply = pubnub_sync_last_reply(sync); json_object *resp = reply.response(); std::cout << "Response: " << json_object_get_string(resp) << std::endl; // If you need to preserve the response beyond reply lifetime: json_object *saved_resp = resp; json_object_get(saved_resp); // Increment reference count // Later, when done: json_object_put(saved_resp); ``` -------------------------------- ### pubnub_serialize() / pubnub_init_serialized() Source: https://github.com/pubnub/c/blob/master/_autodocs/INDEX.md Handles state persistence by serializing and initializing PubNub contexts. ```APIDOC ## pubnub_serialize() / pubnub_init_serialized() ### Description Handles state persistence by serializing and initializing PubNub contexts. ### Method Not specified (assumed to be an SDK function call) ### Endpoint Not applicable (SDK function) ### Parameters - **pubnub** (struct pubnub *) - Required - Pointer to the PubNub context. - **data** (const char *) - Required - Serialized data string. - **len** (size_t) - Required - Length of the serialized data. ### Request Example ```c struct pubnub *p = pubnub_init(...); // ... serialize context ... char *serialized_data = pubnub_serialize(p, ...); pubnub_init_serialized(p, serialized_data, strlen(serialized_data)); ``` ### Response #### Success Response Indicated by successful serialization or initialization of the context from serialized data. #### Response Example State persisted or restored. ``` -------------------------------- ### Get Current PubNub UUID Source: https://github.com/pubnub/c/blob/master/_autodocs/api-reference/pubnub-core.md Retrieves the UUID associated with the PubNub context. The UUID is auto-generated randomly during initialization and is visible to other clients in here_now operations. The lifetime of the returned string is tied to the context's lifetime. ```c const char *uuid = pubnub_current_uuid(p); printf("My UUID: %s\n", uuid); ``` -------------------------------- ### pubnub_init Source: https://github.com/pubnub/c/blob/master/_autodocs/api-reference/pubnub-core.md Initializes a PubNub context with publish and subscribe keys, and callback handlers for event integration. It returns a pointer to the initialized context or NULL on failure. ```APIDOC ## pubnub_init ### Description Initialize the PubNub context with credentials and callback handlers. ### Signature ```c struct pubnub *pubnub_init( const char *publish_key, const char *subscribe_key, const struct pubnub_callbacks *cb, void *cb_data ); ``` ### Parameters #### Path Parameters - **publish_key** (const char *) - Required - PubNub publish key for authentication - **subscribe_key** (const char *) - Required - PubNub subscribe key for authentication - **cb** (const struct pubnub_callbacks *) - Required - Callback structure implementing event loop integration - **cb_data** (void *) - Required - Context data passed to all callbacks ### Returns Pointer to an initialized `struct pubnub` context, or NULL on failure. ### Notes - This function calls `curl_global_init()` on first invocation, which is not thread-safe. If other threads are running, call `curl_global_init()` before spawning threads. - The returned context can service only a single request at a time. - Multiple contexts can be maintained independently. ### Example ```c #include #include struct pubnub_sync *sync = pubnub_sync_init(); struct pubnub *p = pubnub_init( "demo", // publish_key "demo", // subscribe_key &pubnub_sync_callbacks, // callbacks sync // callback data ); // Use context... pubnub_done(p); ``` ``` -------------------------------- ### Core Functions Source: https://github.com/pubnub/c/blob/master/_autodocs/MANIFEST.md Documentation for essential PubNub C SDK functions including initialization, deinitialization, serialization, and serialized initialization. ```APIDOC ## Core Functions ### pubnub_init #### Description Initializes a PubNub context. ### pubnub_done #### Description Deinitializes a PubNub context and frees associated resources. ### pubnub_serialize #### Description Serializes the current state of a PubNub context. ### pubnub_init_serialized #### Description Initializes a PubNub context from a serialized state. ``` -------------------------------- ### Query Channel Presence with pubnub_here_now Source: https://github.com/pubnub/c/blob/master/_autodocs/api-reference/pubnub-presence.md Use this function to get the current occupancy and list of UUIDs for clients subscribed to a channel. It can be called synchronously or asynchronously using a callback. Ensure PubNub context and sync utilities are initialized before use. ```c #include #include #include struct pubnub_sync *sync = pubnub_sync_init(); struct pubnub *p = pubnub_init("demo", "demo", &pubnub_sync_callbacks, sync); // Query presence on a channel pubnub_here_now(p, "my_channel", -1, NULL, NULL); if (pubnub_sync_last_result(sync) != PNR_OK) { fprintf(stderr, "Here-now query failed\n"); goto cleanup; } json_object *response = pubnub_sync_last_response(sync); // Get occupancy json_object *occupancy_obj = json_object_object_get(response, "occupancy"); int occupancy = json_object_get_int(occupancy_obj); printf("Occupancy: %d clients\n", occupancy); // Get UUIDs json_object *uuids_array = json_object_object_get(response, "uuids"); int uuid_count = json_object_array_length(uuids_array); printf("Clients:\n"); for (int i = 0; i < uuid_count; i++) { json_object *uuid_obj = json_object_array_get_idx(uuids_array, i); const char *uuid = json_object_get_string(uuid_obj); printf(" - %s\n", uuid); } json_object_put(response); cleanup: pubnub_done(p); ``` -------------------------------- ### C Synopsis for PubNub Library Source: https://github.com/pubnub/c/blob/master/README.md Demonstrates the basic usage of the PubNub C library for publishing and subscribing to messages. Requires libevent, libjson, libcurl, and OpenSSL. ```c #include #include #include struct pubnub_sync *sync = pubnub_sync_init(); struct pubnub *p = pubnub_init("demo", "demo", &pubnub_sync_callbacks, sync); pubnub_publish(p, "my_channel", json_object, -1, NULL, NULL); do { pubnub_subscribe(p, "my_channel", -1, NULL, NULL); if (pubnub_sync_last_result(sync) != PNR_OK) exit(EXIT_FAILURE); struct json_object *msg = pubnub_sync_last_response(sync); for (int i = 0; i < json_object_array_length(msg); i++) { json_object *msg1 = json_object_array_get_idx(msg, i); printf("received: %s\n", json_object_get_string(msg1)); } } while (1); ```