# OddSockets C SDK

A lightweight C SDK for the OddSockets real-time messaging platform, optimized for embedded systems and IoT devices.

## Features

- **Lightweight**: Minimal memory footprint for resource-constrained devices
- **Cross-platform**: Works on Linux, embedded Linux, FreeRTOS, and other POSIX systems
- **WebSocket Support**: Built-in WebSocket client with SSL/TLS support
- **Manager Discovery**: Automatic manager endpoint discovery
- **Session Stickiness**: Maintains consistent worker connections
- **Message Size Validation**: Industry-standard 32KB message limits
- **Error Handling**: Comprehensive error codes and handling
- **Thread-safe**: Safe for multi-threaded applications

## Quick Start

```c
#include "oddsockets.h"

// Initialize the SDK
oddsockets_config_t config = {
    .api_key = "your-api-key",
    .user_id = "user123",
    .auto_connect = true
};

oddsockets_client_t* client = oddsockets_create(&config);

// Create a channel
oddsockets_channel_t* channel = oddsockets_channel_create(client, "my-channel");

// Subscribe to messages
void on_message(const char* channel_name, const char* message, void* user_data) {
    printf("Received: %s\n", message);
}

oddsockets_channel_subscribe(channel, on_message, NULL);

// Publish a message
oddsockets_channel_publish(channel, "Hello, World!", NULL);

// Cleanup
oddsockets_channel_destroy(channel);
oddsockets_destroy(client);
```

## Building

### Prerequisites

- GCC or Clang compiler
- CMake 3.10+
- libcurl (for HTTP requests)
- OpenSSL (for WebSocket SSL/TLS)
- libwebsockets (for WebSocket client)

### Build Instructions

```bash
mkdir build
cd build
cmake ..
make
```

### Cross-compilation for Embedded Systems

```bash
# For ARM embedded systems
cmake -DCMAKE_TOOLCHAIN_FILE=cmake/arm-linux-gnueabihf.cmake ..
make

# For custom embedded targets
cmake -DCMAKE_TOOLCHAIN_FILE=your-toolchain.cmake ..
make
```

## Installation

### System Installation

```bash
sudo make install
```

### Embedded Integration

Copy the following files to your project:
- `src/oddsockets.h` - Main header
- `src/oddsockets.c` - Main implementation
- `src/channel.c` - Channel implementation
- `src/manager_discovery.c` - Manager discovery
- `src/websocket_client.c` - WebSocket client
- `src/message_validator.c` - Message validation

## API Reference

### Client Management

```c
// Create client
oddsockets_client_t* oddsockets_create(const oddsockets_config_t* config);

// Connect to platform
int oddsockets_connect(oddsockets_client_t* client);

// Disconnect
int oddsockets_disconnect(oddsockets_client_t* client);

// Get connection state
oddsockets_state_t oddsockets_get_state(oddsockets_client_t* client);

// Cleanup
void oddsockets_destroy(oddsockets_client_t* client);
```

### Channel Operations

```c
// Create channel
oddsockets_channel_t* oddsockets_channel_create(oddsockets_client_t* client, const char* name);

// Subscribe
int oddsockets_channel_subscribe(oddsockets_channel_t* channel, 
                                oddsockets_message_callback_t callback, 
                                void* user_data);

// Publish
int oddsockets_channel_publish(oddsockets_channel_t* channel, 
                              const char* message, 
                              const oddsockets_publish_options_t* options);

// Unsubscribe
int oddsockets_channel_unsubscribe(oddsockets_channel_t* channel);

// Get history
int oddsockets_channel_get_history(oddsockets_channel_t* channel,
                                  oddsockets_history_callback_t callback,
                                  const oddsockets_history_options_t* options);

// Cleanup
void oddsockets_channel_destroy(oddsockets_channel_t* channel);
```

## Configuration

### Basic Configuration

```c
oddsockets_config_t config = {
    .api_key = "your-api-key",
    .user_id = "optional-user-id",
    .auto_connect = true,
    .reconnect_attempts = 5,
    .reconnect_delay_ms = 1000,
    .connection_timeout_ms = 10000,
    .message_timeout_ms = 5000
};
```

### Advanced Configuration

```c
oddsockets_config_t config = {
    .api_key = "your-api-key",
    .user_id = "user123",
    .auto_connect = false,
    .reconnect_attempts = 10,
    .reconnect_delay_ms = 2000,
    .connection_timeout_ms = 15000,
    .message_timeout_ms = 10000,
    .enable_ssl = true,
    .ssl_verify_peer = true,
    .ca_cert_path = "/etc/ssl/certs/ca-certificates.crt",
    .log_level = ODDSOCKETS_LOG_INFO
};
```

## Error Handling

```c
int result = oddsockets_connect(client);
if (result != ODDSOCKETS_SUCCESS) {
    switch (result) {
        case ODDSOCKETS_ERROR_INVALID_API_KEY:
            printf("Invalid API key\n");
            break;
        case ODDSOCKETS_ERROR_CONNECTION_FAILED:
            printf("Connection failed\n");
            break;
        case ODDSOCKETS_ERROR_TIMEOUT:
            printf("Connection timeout\n");
            break;
        default:
            printf("Unknown error: %d\n", result);
    }
}
```

## Memory Management

The SDK is designed for memory-constrained environments:

- **Static allocation**: Optional compile-time memory allocation
- **Pool allocation**: Pre-allocated message and channel pools
- **Minimal heap usage**: Careful memory management
- **Leak detection**: Built-in memory leak detection in debug builds

### Memory Configuration

```c
// Compile-time configuration
#define ODDSOCKETS_MAX_CHANNELS 10
#define ODDSOCKETS_MAX_MESSAGE_SIZE 32768
#define ODDSOCKETS_MESSAGE_POOL_SIZE 50
#define ODDSOCKETS_ENABLE_STATIC_ALLOCATION 1
```

## Threading

The SDK is thread-safe and supports:

- **Callback threads**: Message callbacks run in separate threads
- **Connection management**: Thread-safe connection state management
- **Channel operations**: Thread-safe publish/subscribe operations

```c
// Thread-safe publishing from multiple threads
void* publisher_thread(void* arg) {
    oddsockets_channel_t* channel = (oddsockets_channel_t*)arg;
    
    for (int i = 0; i < 100; i++) {
        char message[64];
        snprintf(message, sizeof(message), "Message %d", i);
        oddsockets_channel_publish(channel, message, NULL);
        usleep(100000); // 100ms
    }
    
    return NULL;
}
```

## Embedded Systems Support

### FreeRTOS Integration

```c
#include "FreeRTOS.h"
#include "task.h"
#include "oddsockets.h"

void oddsockets_task(void* parameters) {
    oddsockets_config_t config = {
        .api_key = "your-api-key",
        .auto_connect = true
    };
    
    oddsockets_client_t* client = oddsockets_create(&config);
    
    // Your application logic here
    
    while (1) {
        oddsockets_process_events(client);
        vTaskDelay(pdMS_TO_TICKS(10));
    }
}

void app_main() {
    xTaskCreate(oddsockets_task, "oddsockets", 4096, NULL, 5, NULL);
}
```

### Arduino Integration

```c
#include <WiFi.h>
#include "oddsockets.h"

oddsockets_client_t* client;

void setup() {
    Serial.begin(115200);
    
    // Connect to WiFi
    WiFi.begin("your-ssid", "your-password");
    while (WiFi.status() != WL_CONNECTED) {
        delay(1000);
    }
    
    // Initialize OddSockets
    oddsockets_config_t config = {
        .api_key = "your-api-key",
        .auto_connect = true
    };
    
    client = oddsockets_create(&config);
}

void loop() {
    oddsockets_process_events(client);
    delay(10);
}
```

## Examples

See the `examples/` directory for complete examples:

- `basic_usage.c` - Basic pub/sub example
- `embedded_example.c` - Embedded system example
- `freertos_example.c` - FreeRTOS integration
- `arduino_example.c` - Arduino integration
- `multi_channel.c` - Multiple channel management
- `presence_tracking.c` - Presence and user state

## License

MIT License - see LICENSE file for details.

## Support

- Documentation: https://docs.oddsockets.com/sdks/c
- Issues: https://github.com/oddsockets/c-sdk/issues
- Community: https://discord.gg/oddsockets
