Back to Documentation

C++ SDK Examples

Real-world examples showing how to use the OddSockets C++ SDK for embedded systems and IoT devices

Download Basic Example
Basic Usage
Available
Simple example showing how to connect, subscribe to a channel, and publish messages using the core C++ SDK functionality.
#include 
#include 

int main() {
    // Create configuration
    oddsockets::Config config;
    config.apiKey = "ak_live_1234567890abcdef";
    config.userId = "user123";
    
    // Create client
    auto client = std::make_unique(config);
    
    // Connect to platform
    auto connectFuture = client->connect();
    bool connected = connectFuture.get();
    
    if (connected) {
        // Get a channel
        auto channel = client->channel("my-channel");
        
        // Subscribe to messages
        channel->subscribe([](const std::string& message) {
            std::cout << "Received: " << message << std::endl;
        });
        
        // Publish a message
        auto publishFuture = channel->publish("Hello from C++!");
        auto result = publishFuture.get();
        
        if (result.success) {
            std::cout << "Message published successfully!" << std::endl;
        }
    }
    
    return 0;
}
Embedded System
Available
Optimized example for embedded systems with custom memory allocator, resource limits, and single-threaded operation.
#include 

// Custom allocator for embedded systems
class EmbeddedAllocator {
public:
    static void* allocate(size_t size) {
        return malloc(size);
    }
    
    static void deallocate(void* ptr) {
        free(ptr);
    }
};

int main() {
    // Set custom allocator
    oddsockets::setCustomAllocator();
    
    // Minimal configuration for embedded systems
    oddsockets::Config config;
    config.apiKey = "ak_live_1234567890abcdef";
    config.maxChannels = 4;           // Limit channels
    config.maxMessageSize = 1024;     // Smaller messages
    config.enableLogging = false;     // Disable logging
    config.enableSSL = false;         // Disable SSL if not needed
    config.enableThreading = false;   // Single-threaded mode
    
    auto client = std::make_unique(config);
    
    // Connect and use...
    auto connectFuture = client->connect();
    bool connected = connectFuture.get();
    
    if (connected) {
        auto channel = client->channel("iot-data");
        
        // Process events manually in single-threaded mode
        while (client->isConnected()) {
            client->processEvents();
            std::this_thread::sleep_for(std::chrono::milliseconds(10));
        }
    }
    
    return 0;
}
Arduino ESP32
Available
Complete Arduino sketch for ESP32 showing WiFi connection, sensor data publishing, and message handling.
#include 
#include 

const char* ssid = "your-wifi-ssid";
const char* password = "your-wifi-password";

std::unique_ptr client;

void setup() {
    Serial.begin(115200);
    
    // Connect to WiFi
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
        delay(1000);
        Serial.println("Connecting to WiFi...");
    }
    
    // Configure OddSockets for ESP32
    oddsockets::Config config;
    config.apiKey = "ak_live_1234567890abcdef";
    config.maxChannels = 2;
    config.maxMessageSize = 1024;
    config.enableLogging = false;
    
    client = std::make_unique(config);
    
    // Connect and subscribe
    auto connectFuture = client->connect();
    if (connectFuture.get()) {
        auto channel = client->channel("sensor-data");
        
        channel->subscribe([](const std::string& message) {
            Serial.println(("Received: " + message).c_str());
        });
    }
}

void loop() {
    // Process events
    client->processEvents();
    
    // Send sensor data every 10 seconds
    static unsigned long lastSend = 0;
    if (millis() - lastSend > 10000) {
        auto channel = client->channel("sensor-data");
        
        String sensorData = "{\"temperature\": " + String(random(20, 30)) + 
                           ", \"humidity\": " + String(random(40, 60)) + "}";
        
        channel->publish(sensorData.c_str());
        lastSend = millis();
    }
    
    delay(10);
}
Raspberry Pi
Available
IoT device control example for Raspberry Pi with GPIO control, button monitoring, and remote commands.
#include 
#include 
#include 
#include 

const int LED_PIN = 18;
const int BUTTON_PIN = 24;

int main() {
    // Initialize WiringPi
    wiringPiSetupGpio();
    pinMode(LED_PIN, OUTPUT);
    pinMode(BUTTON_PIN, INPUT);
    pullUpDnControl(BUTTON_PIN, PUD_UP);
    
    // Configure OddSockets
    oddsockets::Config config;
    config.apiKey = "ak_live_1234567890abcdef";
    config.userId = "raspberry-pi-001";
    
    auto client = std::make_unique(config);
    
    // Connect
    auto connectFuture = client->connect();
    if (!connectFuture.get()) {
        std::cerr << "Failed to connect!" << std::endl;
        return 1;
    }
    
    auto controlChannel = client->channel("device-control");
    auto statusChannel = client->channel("device-status");
    
    // Subscribe to control commands
    controlChannel->subscribe([](const std::string& message) {
        std::cout << "Control command: " << message << std::endl;
        
        if (message == "LED_ON") {
            digitalWrite(LED_PIN, HIGH);
        } else if (message == "LED_OFF") {
            digitalWrite(LED_PIN, LOW);
        }
    });
    
    // Monitor button and send status
    bool lastButtonState = HIGH;
    
    while (client->isConnected()) {
        client->processEvents();
        
        // Check button state
        bool buttonState = digitalRead(BUTTON_PIN);
        if (buttonState != lastButtonState && buttonState == LOW) {
            statusChannel->publish("BUTTON_PRESSED");
            std::cout << "Button pressed!" << std::endl;
        }
        lastButtonState = buttonState;
        
        std::this_thread::sleep_for(std::chrono::milliseconds(50));
    }
    
    return 0;
}
FreeRTOS
Available
Real-time operating system integration with FreeRTOS tasks, custom allocator, and message queues.
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include 

// FreeRTOS allocator
class FreeRTOSAllocator {
public:
    static void* allocate(size_t size) {
        return pvPortMalloc(size);
    }
    
    static void deallocate(void* ptr) {
        vPortFree(ptr);
    }
};

std::unique_ptr client;
QueueHandle_t messageQueue;

void oddSocketsTask(void* parameters) {
    // Set FreeRTOS allocator
    oddsockets::setCustomAllocator();
    
    // Configure for FreeRTOS
    oddsockets::Config config;
    config.apiKey = "ak_live_1234567890abcdef";
    config.maxChannels = 1;
    config.maxMessageSize = 256;
    config.enableLogging = false;
    config.enableThreading = false;  // Use FreeRTOS tasks instead
    
    client = std::make_unique(config);
    
    // Connect
    auto connectFuture = client->connect();
    if (connectFuture.get()) {
        auto channel = client->channel("freertos-device");
        
        channel->subscribe([](const std::string& message) {
            // Send message to queue for processing by other tasks
            const char* msg = message.c_str();
            xQueueSend(messageQueue, &msg, portMAX_DELAY);
        });
        
        // Main event loop
        while (1) {
            client->processEvents();
            vTaskDelay(pdMS_TO_TICKS(10));
        }
    }
    
    vTaskDelete(NULL);
}

void sensorTask(void* parameters) {
    while (1) {
        // Read sensor data
        float temperature = readTemperatureSensor();
        float humidity = readHumiditySensor();
        
        // Create JSON message
        char buffer[128];
        snprintf(buffer, sizeof(buffer), 
                "{\"temp\": %.2f, \"humidity\": %.2f}", 
                temperature, humidity);
        
        // Publish sensor data
        if (client && client->isConnected()) {
            auto channel = client->channel("freertos-device");
            channel->publish(std::string(buffer));
        }
        
        vTaskDelay(pdMS_TO_TICKS(30000)); // 30 seconds
    }
}

int main() {
    // Create message queue
    messageQueue = xQueueCreate(10, sizeof(char*));
    
    // Create tasks
    xTaskCreate(oddSocketsTask, "OddSockets", 4096, NULL, 2, NULL);
    xTaskCreate(sensorTask, "Sensor", 2048, NULL, 1, NULL);
    
    // Start scheduler
    vTaskStartScheduler();
    
    return 0;
}
Cross-Platform Desktop
Available
Desktop application example that works on Windows, macOS, and Linux with platform-specific optimizations.
#include 
#include 
#include 
#include 

#ifdef _WIN32
    #include 
#else
    #include 
#endif

class CrossPlatformApp {
private:
    std::unique_ptr client;
    std::atomic running{true};
    
public:
    void run() {
        // Configure client
        oddsockets::Config config;
        config.apiKey = "ak_live_1234567890abcdef";
        config.userId = getSystemId();
        
        // Platform-specific optimizations
        #ifdef __EMBEDDED__
            config.maxChannels = 2;
            config.enableLogging = false;
        #else
            config.maxChannels = 10;
            config.enableLogging = true;
        #endif
        
        client = std::make_unique(config);
        
        // Connect
        auto connectFuture = client->connect();
        if (!connectFuture.get()) {
            std::cerr << "Failed to connect!" << std::endl;
            return;
        }
        
        std::cout << "Connected to OddSockets!" << std::endl;
        
        // Setup channels
        auto chatChannel = client->channel("cross-platform-chat");
        auto statusChannel = client->channel("system-status");
        
        // Subscribe to chat
        chatChannel->subscribe([this](const std::string& message) {
            std::cout << "Chat: " << message << std::endl;
        });
        
        // Send periodic status updates
        std::thread statusThread([this, statusChannel]() {
            while (running) {
                std::string status = getSystemStatus();
                statusChannel->publish(status);
                
                std::this_thread::sleep_for(std::chrono::seconds(60));
            }
        });
        
        // Main loop
        std::string input;
        while (running && std::getline(std::cin, input)) {
            if (input == "/quit") {
                running = false;
                break;
            }
            
            chatChannel->publish(input);
        }
        
        statusThread.join();
        client->disconnect();
    }
    
private:
    std::string getSystemId() {
        #ifdef _WIN32
            char computerName[MAX_COMPUTERNAME_LENGTH + 1];
            DWORD size = sizeof(computerName);
            GetComputerNameA(computerName, &size);
            return std::string(computerName);
        #else
            char hostname[256];
            gethostname(hostname, sizeof(hostname));
            return std::string(hostname);
        #endif
    }
    
    std::string getSystemStatus() {
        // Platform-specific system info
        return R"({"platform": ")" + getPlatformName() + R"(", "uptime": )" + 
               std::to_string(getUptime()) + "}";
    }
    
    std::string getPlatformName() {
        #ifdef _WIN32
            return "Windows";
        #elif __linux__
            return "Linux";
        #elif __APPLE__
            return "macOS";
        #else
            return "Unknown";
        #endif
    }
    
    long getUptime() {
        #ifdef _WIN32
            return GetTickCount64() / 1000;
        #else
            return time(nullptr);
        #endif
    }
};

int main() {
    CrossPlatformApp app;
    app.run();
    return 0;
}