okiffsdk

package module
v1.1.8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 18, 2026 License: Apache-2.0 Imports: 8 Imported by: 0

README

okiff-sdk

Go SDK for connecting to and communicating over MQTT brokers. Built as a precompiled static library for performance, stability and ease of deployment.


Requirements

  • Go 1.23 or later
  • Linux x86-64 / ARM64
  • GCC (CGo build toolchain)
  • libpaho-mqtt3cs (SSL/TLS-capable Paho MQTT C client) installed system-wide

Install on Debian/Ubuntu:

sudo apt install gcc libpaho-mqtt-dev

(older Debian/Ubuntu releases package this as libpaho-mqtt3c-dev instead — either way, make sure libpaho-mqtt3cs.so is installed, not just the non-SSL libpaho-mqtt3c.so, or ssl:// connections will fail with BAD_PROTOCOL)

Install on Manjaro/Arch:

sudo pacman -S gcc paho-mqtt-c

Installation

Inside an existing Go module:

go get github.com/okiffms/okiff-sdk@latest

Quick Start

package main

import (
    "fmt"
    "time"

    okiffsdk "github.com/okiffms/okiff-sdk"
)

func main() {
    sdk := okiffsdk.New()
    defer sdk.Destroy()

    // Callbacks
    sdk.OnConnection(func(connected bool, rc int) {
        fmt.Printf("[onConnection] connected=%v rc=%d\n", connected, rc)
    })

    sdk.OnMessage(func(topic, payload string) {
        fmt.Printf("[onMessage] topic=%s payload=%s\n", topic, payload)
    })

    // Initialize and connect
    if err := sdk.Init(
        "my_client",
        "broker.example.com:port",
        "tcp",
        "username",
        "password/JWT",
        "ca_file",
        "cert_file",
        "key_file",
        "clean_session",
        "resume_subs",
        "connect_retry",
        "auto_reconnect",
        "connect_retry_interval",
        "max_reconnect_interval",
        "keep_alive",
        "ping_timeout",
        "write_timeout",
        "order_matters",
        "connect_timeout",
        "client_type"
    ); err != nil {
        fmt.Println("Init error:", err)
        return
    }

    ok := sdk.Connect()
    fmt.Println("Connect() =>", ok)

    // Publish and subscribe
    if ok {
        sdk.Subscribe("my/topic", 0)
        time.AfterFunc(500*time.Millisecond, func() {
            sdk.Publish("my/topic", "hello", 0, false)
        })
    }

    // Cleanup
    time.Sleep(5 * time.Second)
    sdk.Disconnect()
    sdk.Stop()
}

Paho Compatibility

If your application expects github.com/eclipse/paho.mqtt.golang.Client, use the compatibility adapter instead of passing *SDK directly:

package main

import (
    mqtt "github.com/eclipse/paho.mqtt.golang"
    okiffsdk "github.com/okiffms/okiff-sdk"
)

func main() {
    client, err := okiffsdk.Init(
        'my_client',
        'broker.example.com:port',
        'tcp',
        'username',
        'password',
        'ca_file',
        'cert_file',
        'key_file',
        'clean_session',
        'resume_subs',
        'connect_retry',
        'auto_reconnect',
        'connect_retry_interval',
        'max_reconnect_interval',
        'keep_alive',
        'ping_timeout',
        'write_timeout',
        'order_matters',
        'connect_timeout',
        'client_type'
    )
    if err != nil {
        panic(err)
    }

    var mqttClient mqtt.Client = client
    _ = mqttClient
}

If you already have an initialized *SDK, wrap it with sdk.AsPahoClient().


API Reference

New() *SDK

Allocates and returns a new SDK instance.


Init(clientId, brokerHost, protocol, username, password, caFile, certFile, keyFile string, ...) error

Initializes the SDK. Must be called before Connect.

Parameter Type Description
clientId string Unique identifier for this client
brokerHost string Broker address including port, e.g. broker.example.com:1883
protocol string Transport protocol: "tcp" or "ssl"
username string Authentication username
password string Authentication password
caFile string Path to the CA/trust-store certificate (for TLS/mTLS, e.g. "ssl" protocol). Pass "" to skip
certFile string Path to the client certificate (for mTLS). Pass "" to skip
keyFile string Path to the client private key (for mTLS). Pass "" to skip
cleanSession bool Start a clean MQTT session
resumeSubs bool Restore subscriptions after reconnect
connectRetry bool Retry the initial connection if it fails
autoReconnect bool Automatically reconnect after disconnect
connectRetryInterval int Initial retry interval (seconds)
maxReconnectInterval int Maximum reconnect interval (seconds)
keepAlive int MQTT keep-alive interval (seconds)
pingTimeout int Ping response timeout (seconds)
writeTimeout int Socket write timeout (seconds)
orderMatters bool Preserve message ordering
connectTimeout int Connection timeout (seconds)
edition str SDK edition (for example "Community" or "Enterprise")

Returns: nil on success, error if the internal client cannot be created.


Connect() bool

Connects to the broker.

Returns: true on success, false on failure.


Disconnect()

Gracefully disconnects from the broker.


Publish(topic, payload string, qos int, retained bool)

Publishes a message to a topic.

Parameter Type Description
topic string MQTT topic string
payload string Message body
qos int Quality of Service: 0, 1, or 2
retained bool Whether the broker retains the message

Subscribe(topic string, qos int) bool

Subscribes to a topic.

Parameter Type Description
topic string MQTT topic. Wildcards: + (single level), # (multi-level)
qos int Maximum QoS level for received messages

Returns: true on success, false on failure.


Unsubscribe(topic string)

Removes a topic subscription.

Parameter Type Description
topic string Exact topic string used in Subscribe

OnMessage(handler func(topic, payload string))

Registers a callback invoked when a message arrives on any subscribed topic.

sdk.OnMessage(func(topic, payload string) {
    // topic   — topic on which the message was received
    // payload — message body
})

OnConnection(handler func(connected bool, rc int))

Registers a callback invoked on every connection state change.

sdk.OnConnection(func(connected bool, rc int) {
    // connected — true = connected, false = disconnected or lost
    // rc        — 0 = clean disconnect, -1 = unexpected loss
})
Event connected rc
Connect() succeeds true 0
Disconnect() called false 0
Broker drops connection false -1

IsConnected() bool

Returns the current connection state.


Stop()

Stops all activity and releases all resources. Must be called after Disconnect.


Destroy()

Frees the SDK handle. Must be called after Stop. Idiomatic usage:

sdk := okiffsdk.New()
defer sdk.Destroy()

License

Proprietary — all rights reserved.

Documentation

Overview

Package okiffsdk provides Go bindings for the Okiff MQTT SDK. It wraps a prebuilt static library (libokiff_sdk.a) via CGo.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Init added in v1.0.5

func Init(clientID, brokerHost, protocol, username, password string) (mqtt.Client, error)

Init creates, initializes, and returns a Paho-compatible MQTT client.

Types

type ConnectionHandler

type ConnectionHandler func(connected bool, rc int)

ConnectionHandler is called on every connection state change. connected: true = connected, false = disconnected or lost. rc: 0 = clean disconnect, -1 = unexpected loss.

type MessageHandler

type MessageHandler func(topic, payload string)

MessageHandler is called when a message arrives on a subscribed topic.

type PahoClient added in v1.0.5

type PahoClient struct {
	// contains filtered or unexported fields
}

PahoClient adapts SDK to the github.com/eclipse/paho.mqtt.golang Client interface.

func NewPahoClient added in v1.0.5

func NewPahoClient(clientID, brokerHost, protocol, username, password string) (*PahoClient, error)

NewPahoClient creates, initializes, and returns a Paho-compatible client adapter.

func WrapPahoClient added in v1.0.5

func WrapPahoClient(sdk *SDK) *PahoClient

WrapPahoClient exposes an initialized SDK as a Paho-compatible client.

func (*PahoClient) AddRoute added in v1.0.5

func (c *PahoClient) AddRoute(topic string, callback mqtt.MessageHandler)

func (*PahoClient) Close added in v1.0.5

func (c *PahoClient) Close()

Close releases the underlying SDK resources.

func (*PahoClient) Connect added in v1.0.5

func (c *PahoClient) Connect() mqtt.Token

func (*PahoClient) Destroy added in v1.0.5

func (c *PahoClient) Destroy()

Destroy destroys the underlying SDK handle.

func (*PahoClient) Disconnect added in v1.0.5

func (c *PahoClient) Disconnect(quiesce uint)

func (*PahoClient) IsConnected added in v1.0.5

func (c *PahoClient) IsConnected() bool

func (*PahoClient) IsConnectionOpen added in v1.0.5

func (c *PahoClient) IsConnectionOpen() bool

func (*PahoClient) OptionsReader added in v1.0.5

func (c *PahoClient) OptionsReader() mqtt.ClientOptionsReader

func (*PahoClient) Publish added in v1.0.5

func (c *PahoClient) Publish(topic string, qos byte, retained bool, payload interface{}) mqtt.Token

func (*PahoClient) SDK added in v1.0.5

func (c *PahoClient) SDK() *SDK

SDK returns the underlying SDK handle.

func (*PahoClient) Stop added in v1.0.5

func (c *PahoClient) Stop()

Stop stops the underlying SDK.

func (*PahoClient) Subscribe added in v1.0.5

func (c *PahoClient) Subscribe(topic string, qos byte, callback mqtt.MessageHandler) mqtt.Token

func (*PahoClient) SubscribeMultiple added in v1.0.5

func (c *PahoClient) SubscribeMultiple(filters map[string]byte, callback mqtt.MessageHandler) mqtt.Token

func (*PahoClient) Unsubscribe added in v1.0.5

func (c *PahoClient) Unsubscribe(topics ...string) mqtt.Token

type SDK

type SDK struct {
	// contains filtered or unexported fields
}

SDK is the main client handle. Create one with New().

func New

func New() *SDK

New allocates and returns a new SDK instance.

func (*SDK) AsPahoClient added in v1.0.5

func (s *SDK) AsPahoClient() *PahoClient

AsPahoClient exposes the SDK instance as a Paho-compatible client.

func (*SDK) Connect

func (s *SDK) Connect() bool

Connect establishes the connection to the broker. Returns true on success, false on failure.

func (*SDK) Destroy

func (s *SDK) Destroy()

Destroy frees the SDK handle. Call after Stop.

func (*SDK) Disconnect

func (s *SDK) Disconnect()

Disconnect gracefully disconnects from the broker.

func (*SDK) Init

func (s *SDK) Init(
	clientId, brokerHost, protocol, username, password string,
	caFile, certFile, keyFile string,
	cleanSession bool,
	resumeSubs bool,
	connectRetry bool,
	autoReconnect bool,
	connectRetryInterval int,
	maxReconnectInterval int,
	keepAlive int,
	pingTimeout int,
	writeTimeout int,
	orderMatters bool,
	connectTimeout int,
	edition string,
) error

Init initializes the MQTT client. Must be called before Connect.

func (*SDK) IsConnected

func (s *SDK) IsConnected() bool

IsConnected returns the current connection state.

func (*SDK) OnConnection

func (s *SDK) OnConnection(h ConnectionHandler)

OnConnection registers a callback invoked on every connection state change. Replaces any previously registered handler.

func (*SDK) OnMessage

func (s *SDK) OnMessage(h MessageHandler)

OnMessage registers a callback invoked when a message arrives on any subscribed topic. Replaces any previously registered handler.

func (*SDK) Publish

func (s *SDK) Publish(topic, payload string, qos int, retained bool)

Publish sends a message to a topic. qos: 0 = at most once, 1 = at least once, 2 = exactly once. retained: broker stores the message for future new subscribers.

func (*SDK) Stop

func (s *SDK) Stop()

Stop stops all activity and releases all resources. Must be called as the final cleanup step, after Disconnect.

func (*SDK) Subscribe

func (s *SDK) Subscribe(topic string, qos int) bool

Subscribe registers a subscription on the given topic. Returns true on success, false on failure.

func (*SDK) Unsubscribe

func (s *SDK) Unsubscribe(topic string)

Unsubscribe removes a topic subscription.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL