### Start Docker Services Source: https://pkg.go.dev/github.com/eclipse/paho.golang/autopaho/examples/docker Initializes the publisher, subscriber, and Mosquitto containers in the background. ```bash docker-compose up --build --detach ``` -------------------------------- ### Run TestServer Source: https://pkg.go.dev/github.com/eclipse/paho.golang/internal/basictestserver Starts the test server execution. ```go func (t *TestServer) Run() ``` -------------------------------- ### Install Eclipse Paho Go Client Source: https://pkg.go.dev/github.com/eclipse/paho.golang Use 'go get' to manually add the library as a dependency. Ensure you are using Go Modules for package management. ```go go get github.com/eclipse/paho.golang ``` -------------------------------- ### Create New Store Instance Source: https://pkg.go.dev/github.com/eclipse/paho.golang/paho/store/memory Initializes and returns a new instance of the in-memory Store. No specific setup is required before calling this function. ```go func New() *Store ``` -------------------------------- ### Initiate reauthentication with the server Source: https://pkg.go.dev/github.com/eclipse/paho.golang/paho Starts a reauthentication process by sending an Auth packet. Relies on the AuthHandler for subsequent server requests. ```go func (c *Client) Authenticate(ctx context.Context, a *Auth) (*AuthResponse, error) ``` -------------------------------- ### Get store string representation Source: https://pkg.go.dev/github.com/eclipse/paho.golang/paho/store/file Provides a string representation of the store for debugging. ```go func (s *Store) String() string ``` -------------------------------- ### Get User Property by Key Source: https://pkg.go.dev/github.com/eclipse/paho.golang/paho Retrieves the value of the first user property matching the given key. Returns an empty string if the key is not found. Note: Multiple entries with the same key are permitted; use GetAll for all matches. ```go func (u UserProperties) Get(key string) string ``` -------------------------------- ### Create Custom Exponential Backoff Strategy Source: https://pkg.go.dev/github.com/eclipse/paho.golang/autopaho Provides a flexible way to create an exponential backoff function. It generates a random duration within a range, starting from a minimum value up to a dynamically increasing maximum value. The maximum value grows exponentially with each attempt, capped by the overall maximum delay. ```go func NewExponentialBackoff( minDelay time.Duration, maxDelay time.Duration, initialMaxDelay time.Duration, factor float32, ) Backoff ``` -------------------------------- ### Initialize TestServer Source: https://pkg.go.dev/github.com/eclipse/paho.golang/internal/basictestserver Creates a new instance of TestServer. ```go func New(logger Logger) *TestServer ``` -------------------------------- ### Client Configuration and Creation Source: https://pkg.go.dev/github.com/eclipse/paho.golang/paho Details on how to configure and create a new MQTT client instance. ```APIDOC ## Client Configuration and Creation ### Description Explains how to set up client configuration and instantiate a new client. ### Functions #### NewClient Creates a new MQTT client instance. - **Method**: POST - **Endpoint**: N/A (Function) - **Parameters**: - `conf` (ClientConfig) - Required - Configuration for the new client. - **Returns**: (*Client, error) ### Types #### ClientConfig Represents the configuration options for an MQTT client. - **Fields**: (Details not provided in source text) #### Client Represents the MQTT client. - **Methods**: (See Client Operations API section) ``` -------------------------------- ### Retrieve client ID Source: https://pkg.go.dev/github.com/eclipse/paho.golang/paho Gets the client ID from the configuration, useful for handlers that require it. ```go func (c *Client) ClientID() string ``` -------------------------------- ### Initialize file store Source: https://pkg.go.dev/github.com/eclipse/paho.golang/paho/store/file Creates a new file store instance. Verifies path usability by performing file operations. ```go func New(path string, prefix string, extension string) (*Store, error) ``` -------------------------------- ### Manage DefaultPinger lifecycle Source: https://pkg.go.dev/github.com/eclipse/paho.golang/paho Methods for creating, running, and configuring the DefaultPinger. ```go func NewDefaultPinger() *DefaultPinger ``` ```go func (p *DefaultPinger) PacketReceived() ``` ```go func (p *DefaultPinger) PacketSent() ``` ```go func (p *DefaultPinger) PingResp() ``` ```go func (p *DefaultPinger) Run(ctx context.Context, conn net.Conn, keepAlive uint16) error ``` ```go func (p *DefaultPinger) SetDebug(debug log.Logger) ``` -------------------------------- ### Get Packet Subscribe from Paho Subscribe Source: https://pkg.go.dev/github.com/eclipse/paho.golang/paho Converts a paho library Subscribe structure to the packets library's Subscribe structure. ```go func (s *Subscribe) Packet() *packets.Subscribe ``` -------------------------------- ### Get Packet Suback from Paho Suback Source: https://pkg.go.dev/github.com/eclipse/paho.golang/paho Converts a paho library Suback structure to the packets library's Suback structure. ```go func (s *Suback) Packet() *packets.Suback ``` -------------------------------- ### Client Configuration and Connection Source: https://pkg.go.dev/github.com/eclipse/paho.golang/paho Details on creating and configuring an MQTT client instance. ```APIDOC ## NewClient ### Description Creates a new default instance of an MQTT client. The client uses provided PingHandler, MessageID, and StandardRouter implementations, and a noop Persistence. These should be replaced if desired before the client is connected. client.Conn *MUST* be set to an already connected net.Conn before Connect() is called. ### Method ``` func NewClient(conf ClientConfig) *Client ``` ### Parameters #### Request Body - **conf** (ClientConfig) - Required - Configuration for the new client instance. ``` ```APIDOC ## Client.Conn ### Description This field must be set to an already connected net.Conn before the Connect() method is called. ### Type ```go *net.Conn ``` ``` -------------------------------- ### Create New Test Server Instance Source: https://pkg.go.dev/github.com/eclipse/paho.golang/internal/testserver Creates a new instance of the test server simulator. Requires a Logger implementation. ```go func New(logger Logger) *Instance ``` -------------------------------- ### Define Backoff Function Type Source: https://pkg.go.dev/github.com/eclipse/paho.golang/autopaho Defines the signature for a backoff function, which computes the duration for the Nth reconnection attempt. The attempt count starts at 0, representing the delay before the first attempt. ```go type Backoff func(attempt int) time.Duration ``` -------------------------------- ### Initialize AutoPaho Router Source: https://pkg.go.dev/github.com/eclipse/paho.golang/autopaho/examples/router Create a new instance of the standard router. ```go router := paho.NewStandardRouter() ``` -------------------------------- ### Connect to Test Server Source: https://pkg.go.dev/github.com/eclipse/paho.golang/internal/testserver Establishes a connection to the test server. Returns a net.Conn, a channel that closes on shutdown, and an error if connection fails. ```go func (i *Instance) Connect(ctx context.Context) (net.Conn, chan struct{}, error) ``` -------------------------------- ### Packet Interface Definition in Go Source: https://pkg.go.dev/github.com/eclipse/paho.golang/paho/session Defines the Packet interface for MQTT packets. It includes methods to set and get the packet identifier and to write the packet's data to an io.Writer. This interface is used for transmitting packets with identifiers. ```go type Packet interface { SetIdentifier(uint16) // Sets the packet identifier Type() byte // Gets the packet type WriteTo(io.Writer) (int64, error) } ``` -------------------------------- ### Create NewStateInfo Instance Source: https://pkg.go.dev/github.com/eclipse/paho.golang/internal/testserver Use NewStateInfo to create a new StateInfo object, initializing it with the provided control packet, QOS, topic, and payload. ```go func NewStateInfo(sent *packets.ControlPacket, qos byte, topic string, payload []byte) *StateInfo ``` -------------------------------- ### Initialize New Handler Source: https://pkg.go.dev/github.com/eclipse/paho.golang/autopaho/extensions/rpc Creates a new Handler instance. Requires a context and HandlerOpts for configuration. ```go func NewHandler(ctx context.Context, opts HandlerOpts) (*Handler, error) ``` -------------------------------- ### Initialize Connect properties Source: https://pkg.go.dev/github.com/eclipse/paho.golang/paho Methods to populate properties for the Connect packet and its Will message. ```go func (c *Connect) InitProperties(p *packets.Properties) ``` ```go func (c *Connect) InitWillProperties(p *packets.Properties) ``` -------------------------------- ### Basic AutoPaho MQTT Client Usage Source: https://pkg.go.dev/github.com/eclipse/paho.golang/autopaho Demonstrates initializing a connection manager, handling connection events, and publishing messages. Subscriptions should be managed within the OnConnectionUp callback to ensure persistence across reconnections. ```go func main() { // App will run until cancelled by user (e.g. ctrl-c) ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer stop() // We will connect to the Eclipse test server (note that you may see messages that other users publish) u, err := url.Parse("mqtt://mqtt.eclipseprojects.io:1883") if err != nil { panic(err) } cliCfg := autopaho.ClientConfig{ ServerUrls: []*url.URL{u}, KeepAlive: 20, // Keepalive message should be sent every 20 seconds // CleanStartOnInitialConnection defaults to false. Setting this to true will clear the session on the first connection. CleanStartOnInitialConnection: false, // SessionExpiryInterval - Seconds that a session will survive after disconnection. // It is important to set this because otherwise, any queued messages will be lost if the connection drops and // the server will not queue messages while it is down. The specific setting will depend upon your needs // (60 = 1 minute, 3600 = 1 hour, 86400 = one day, 0xFFFFFFFE = 136 years, 0xFFFFFFFF = don't expire) SessionExpiryInterval: 60, OnConnectionUp: func(cm *autopaho.ConnectionManager, connAck *paho.Connack) { fmt.Println("mqtt connection up") // Subscribing in the OnConnectionUp callback is recommended (ensures the subscription is reestablished if // the connection drops) if _, err := cm.Subscribe(context.Background(), &paho.Subscribe{ Subscriptions: []paho.SubscribeOptions{ {Topic: topic, QoS: 1}, }, }); err != nil { fmt.Printf("failed to subscribe (%s). This is likely to mean no messages will be received.", err) } fmt.Println("mqtt subscription made") }, OnConnectError: func(err error) { fmt.Printf("error whilst attempting connection: %s\n", err) }, // eclipse/paho.golang/paho provides base mqtt functionality, the below config will be passed in for each connection ClientConfig: paho.ClientConfig{ // If you are using QOS 1/2, then it's important to specify a client id (which must be unique) ClientID: clientID, // OnPublishReceived is a slice of functions that will be called when a message is received. // You can write the function(s) yourself or use the supplied Router OnPublishReceived: []func(paho.PublishReceived) (bool, error){ func(pr paho.PublishReceived) (bool, error) { fmt.Printf("received message on topic %s; body: %s (retain: %t)\n", pr.Packet.Topic, pr.Packet.Payload, pr.Packet.Retain) return true, nil }}, OnClientError: func(err error) { fmt.Printf("client error: %s\n", err) }, OnServerDisconnect: func(d *paho.Disconnect) { if d.Properties != nil { fmt.Printf("server requested disconnect: %s\n", d.Properties.ReasonString) } else { fmt.Printf("server requested disconnect; reason code: %d\n", d.ReasonCode) } }, }, } c, err := autopaho.NewConnection(ctx, cliCfg) // starts process; will reconnect until context cancelled if err != nil { panic(err) } // Wait for the connection to come up if err = c.AwaitConnection(ctx); err != nil { panic(err) } ticker := time.NewTicker(time.Second) msgCount := 0 defer ticker.Stop() for { select { case <-ticker.C: msgCount++ // Publish a test message (use PublishViaQueue if you don't want to wait for a response) if _, err = c.Publish(ctx, &paho.Publish{ QoS: 1, Topic: topic, Payload: []byte("TestMessage: " + strconv.Itoa(msgCount)), }); err != nil { if ctx.Err() == nil { panic(err) // Publish will exit when context cancelled or if something went wrong } } continue case <-ctx.Done(): } break } fmt.Println("signal caught - exiting") <-c.Done() // Wait for clean shutdown (cancelling the context triggered the shutdown) } ``` -------------------------------- ### Connect client to MQTT server Source: https://pkg.go.dev/github.com/eclipse/paho.golang/paho Establishes an MQTT connection using a pre-prepared Connect packet. Returns Connack on success or an error on failure. ```go func (c *Client) Connect(ctx context.Context, cp *Connect) (*Connack, error) ``` -------------------------------- ### Instantiate StandardRouter Source: https://pkg.go.dev/github.com/eclipse/paho.golang/paho Creates and returns a new instance of StandardRouter. ```go func NewStandardRouter() *StandardRouter ``` -------------------------------- ### Create New MQTT Client Instance Source: https://pkg.go.dev/github.com/eclipse/paho.golang/paho Creates a new default instance of an MQTT client using the provided ClientConfig. Ensure client.Conn is set to a connected net.Conn before calling Connect(). ```go func NewClient(conf ClientConfig) *Client ``` -------------------------------- ### Instance Management Source: https://pkg.go.dev/github.com/eclipse/paho.golang/internal/testserver Methods for creating and managing the test server instance, including connection handling and packet callbacks. ```APIDOC ## func New ### Description Creates a new instance of the simulator. ### Parameters - **logger** (Logger) - Required - Logger instance mirroring paho.Logger. ## func (*Instance) Connect ### Description Establishes a connection to the test server. ### Parameters - **ctx** (context.Context) - Required - Context for the connection. ### Response - **net.Conn** - Connection object to pass to paho. - **chan struct{}** - Channel closed when connection has shutdown. - **error** - Error if connection fails. ## func (*Instance) SetConnectCallback ### Description Sets a callback that will be called before the response to a CONNECT packet is sent. The CONNACK packet may be altered if required. ### Parameters - **callback** (func(cp *packets.Connect, cap *packets.Connack)) - Required - Callback function. ## func (*Instance) SetPacketReceivedCallback ### Description Sets a callback that will be called whenever a packet is received. If the callback returns an error, the connection will be dropped. ### Parameters - **callback** (func(publish *packets.ControlPacket) error) - Required - Callback function. ``` -------------------------------- ### Handler Initialization and Request Handling Source: https://pkg.go.dev/github.com/eclipse/paho.golang/autopaho/extensions/rpc This section covers the creation of a new Handler instance and how to process incoming requests. ```APIDOC ## NewHandler ### Description Creates a new Handler instance with the provided options. ### Method `func NewHandler(ctx context.Context, opts HandlerOpts) (*Handler, error)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go // Example usage (assuming opts is defined) // handler, err := NewHandler(ctx, opts) ``` ### Response #### Success Response (200) - **Handler** (*Handler) - A pointer to the newly created Handler. - **error** (*error) - An error if the handler creation fails. #### Response Example ```json { "handler": "", "error": null } ``` ## Handler.Request ### Description Processes an incoming MQTT publish message and returns a response. ### Method `func (h *Handler) Request(ctx context.Context, pb *paho.Publish) (resp *paho.Publish, err error)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **pb** (*paho.Publish) - The incoming publish message. ### Request Example ```go // Example usage (assuming handler and publishMessage are defined) // response, err := handler.Request(ctx, publishMessage) ``` ### Response #### Success Response (200) - **resp** (*paho.Publish) - The response publish message. - **err** (*error) - An error if the request processing fails. #### Response Example ```json { "resp": "", "err": null } ``` ``` -------------------------------- ### Handler Initialization and Request/Response Source: https://pkg.go.dev/github.com/eclipse/paho.golang/paho/extensions/rpc Provides details on how to create a new Handler instance and use its Request method for RPC-style communication. ```APIDOC ## func NewHandler ### Description Creates a new Handler instance for managing request/response interactions with a paho MQTT v5 client. ### Signature ```go func NewHandler(ctx context.Context, c *paho.Client) (*Handler, error) ``` ### Parameters - **ctx** (context.Context) - Required - The context for the operation. - **c** (*paho.Client) - Required - The paho MQTT v5 client instance. ### Returns - **(*Handler, error)** - A pointer to the created Handler and an error if creation fails. --- ## func (*Handler) Request ### Description Sends a publish message and waits for a response, facilitating RPC-style communication. ### Signature ```go func (h *Handler) Request(ctx context.Context, pb *paho.Publish) (*paho.Publish, error) ``` ### Parameters - **ctx** (context.Context) - Required - The context for the operation. - **pb** (*paho.Publish) - Required - The publish message containing the request. ### Returns - **(*paho.Publish, error)** - The response publish message and an error if the request fails. ``` -------------------------------- ### Subscribe to MQTT topics Source: https://pkg.go.dev/github.com/eclipse/paho.golang/paho Sends a subscription request to the server, blocking for a Suback response. Returns the Suback and any errors. ```go func (c *Client) Subscribe(ctx context.Context, s *Subscribe) (*Suback, error) ``` -------------------------------- ### New Queue Initialization Source: https://pkg.go.dev/github.com/eclipse/paho.golang/autopaho/queue/file Creates a new file-based queue instance. It verifies the usability of the provided path by performing a write, read, and delete operation. ```APIDOC ## func New ### Description Creates a new file-based queue. Note that a file is written, read and deleted as part of this process to check that the path is usable. NOTE: Order is maintained using file ModTime, so there may be issues if the interval between messages is less than the file system ModTime resolution. ### Parameters #### Path Parameters - **path** (string) - Required - The directory path for the queue. - **prefix** (string) - Required - The file prefix for queue items. - **extension** (string) - Required - The file extension for queue items. ### Response - **Queue** (struct) - The initialized queue instance. - **error** (error) - Returns an error if the path is not usable. ``` -------------------------------- ### Auth.String Method Source: https://pkg.go.dev/github.com/eclipse/paho.golang/packets Provides a string representation of the Auth packet. ```go func (a *Auth) String() string ``` -------------------------------- ### Create New State Instance Source: https://pkg.go.dev/github.com/eclipse/paho.golang/paho/session/state New creates a new state instance, persisting information using the provided storers. ```go func New(client storer, server storer) *State ``` -------------------------------- ### Create Default Exponential Backoff Strategy Source: https://pkg.go.dev/github.com/eclipse/paho.golang/autopaho Returns an exponential backoff function with default configuration values. These defaults include a minimum delay of 5 seconds, a maximum delay of 10 minutes, an initial maximum delay of 10 seconds, and a factor of 1.5 for exponential increase. ```go func DefaultExponentialBackoff() Backoff ``` -------------------------------- ### Handler Configuration Options Source: https://pkg.go.dev/github.com/eclipse/paho.golang/autopaho/extensions/rpc HandlerOpts specifies the configuration for the Handler, including the connection manager, router, response topic format, and client ID. ```go type HandlerOpts struct { Conn *autopaho.ConnectionManager Router paho.Router ResponseTopicFmt string ClientID string } ``` -------------------------------- ### TestLog Printf Method Source: https://pkg.go.dev/github.com/eclipse/paho.golang/paho/log Formats arguments like fmt.Printf and records the text in the test log. Output is conditional on test success or specific arguments to 'go test'. ```go func (t *TestLog) Printf(format string, v ...interface{}) ``` -------------------------------- ### Configure Paho Go MQTT Client Source: https://pkg.go.dev/github.com/eclipse/paho.golang/paho ClientConfig holds user-configurable options for the MQTT client. Defaults are provided for several options, but not all are required. ```go type ClientConfig struct { ClientID string // Conn is the connection to broker. // BEWARE that most wrapped net.Conn implementations like tls.Conn are // not thread safe for writing. To fix, use packets.NewThreadSafeConn // wrapper or extend the custom net.Conn struct with sync.Locker. Conn net.Conn Session session.SessionManager AuthHandler Auther PingHandler Pinger // Router - new inbound messages will be passed to the `Route(*packets.Publish)` function. // // Depreciated: If a router is provided, it will now be added to the end of the OnPublishReceived // slice (which provides a more flexible approach to handling incoming messages). Router Router // OnPublishReceived provides a slice of callbacks; additional handlers may be added after the client has been // created via the AddOnPublishReceived function (Client holds a copy of the slice; OnPublishReceived will not change). // When a `PUBLISH` is received, the callbacks will be called in order. If a callback processes the message, // then it should return true. This boolean, and any errors, will be passed to subsequent handlers. OnPublishReceived []func(PublishReceived) (bool, error) PacketTimeout time.Duration // OnServerDisconnect is called only when a packets.DISCONNECT is received from server OnServerDisconnect func(*Disconnect) // OnClientError is for example called on net.Error. Note that this may be called multiple times and may be // called following a successful `Disconnect`. See autopaho.errorHandler for an example. OnClientError func(error) // PublishHook allows a user provided function to be called before // a Publish packet is sent allowing it to inspect or modify the // Publish, an example of the utility of this is provided in the // Topic Alias Handler extension which will automatically assign // and use topic alias values rather than topic strings. PublishHook func(*Publish) // EnableManualAcknowledgment is used to control the acknowledgment of packets manually. // BEWARE that the MQTT specs require clients to send acknowledgments in the order in which the corresponding // PUBLISH packets were received. // Consider the following scenario: the client receives packets 1,2,3,4 // If you acknowledge 3 first, no ack is actually sent to the server but it's buffered until also 1 and 2 // are acknowledged. EnableManualAcknowledgment bool // SendAcksInterval is used only when EnableManualAcknowledgment is true // it determines how often the client tries to send a batch of acknowledgments in the right order to the server. SendAcksInterval time.Duration // contains filtered or unexported fields } ``` -------------------------------- ### StandardRouter Implementation Source: https://pkg.go.dev/github.com/eclipse/paho.golang/paho A library-provided implementation of the Router interface supporting unique and multiple MessageHandlers per topic. ```go type StandardRouter struct { sync.RWMutex // contains filtered or unexported fields } ``` -------------------------------- ### ConnectionManager Type and Initialization Source: https://pkg.go.dev/github.com/eclipse/paho.golang/autopaho Manages the MQTT server connection and provides publication capabilities. ```go type ConnectionManager struct { // contains filtered or unexported fields } ``` ```go func NewConnection(ctx context.Context, cfg ClientConfig) (*ConnectionManager, error) ``` -------------------------------- ### Properties Methods Source: https://pkg.go.dev/github.com/eclipse/paho.golang/packets Methods for packing and unpacking properties for MQTT control packets. ```APIDOC ## Properties.PackBuf ### Description PackBuf will create a bytes.Buffer of the packed properties, it will only pack the properties appropriate to the packet type p even though other properties may exist, it will silently ignore them. ### Method (*Properties) PackBuf ### Parameters - p (byte) - Required - The packet type to filter properties for. ### Response Example ```go // Example response structure (actual return is *bytes.Buffer) { // ... packed properties ... } ``` ``` ```APIDOC ## Properties.Unpack ### Description Unpack takes a buffer of bytes and reads out the defined properties filling in the appropriate entries in the struct, it returns the number of bytes used to store the Prop data and any error in decoding them. ### Method (*Properties) Unpack ### Parameters - r (*bytes.Buffer) - Required - The buffer containing the packed properties. - p (byte) - Required - The packet type to determine which properties to unpack. ### Response #### Success Response - int64 - The number of bytes used to store the property data. - error - nil if unpacking is successful. #### Response Example ```go // Example successful response { "bytesUsed": 10, "error": null } ``` ``` -------------------------------- ### Instantiate StandardRouter with Default Handler Source: https://pkg.go.dev/github.com/eclipse/paho.golang/paho Creates a StandardRouter instance with a default handler set for messages that do not match any specific topic handlers. ```go func NewStandardRouterWithDefault(h MessageHandler) *StandardRouter ``` -------------------------------- ### Initialize Connack Properties Source: https://pkg.go.dev/github.com/eclipse/paho.golang/paho InitProperties takes a lower-level Properties struct and completes the properties of the Connack on which it is called. ```go func (c *Connack) InitProperties(p *packets.Properties) ``` -------------------------------- ### TestServer API Source: https://pkg.go.dev/github.com/eclipse/paho.golang/internal/basictestserver Provides methods for creating, managing, and interacting with a basic MQTT test server. ```APIDOC ## TestServer Type ### Description Represents a basic test server for MQTT clients. ### Methods #### New ```go func New(logger Logger) *TestServer ``` **Description**: Creates a new TestServer instance. **Parameters**: - **logger** (Logger) - Required - A logger implementation. #### ClientConn ```go func (t *TestServer) ClientConn() net.Conn ``` **Description**: Returns a connection to be used when creating the Paho Client. #### ReceivedPubacks ```go func (t *TestServer) ReceivedPubacks() []packets.Puback ``` **Description**: Returns a slice of received PUBACK packets. #### ReceivedPubrecs ```go func (t *TestServer) ReceivedPubrecs() []packets.Pubrec ``` **Description**: Returns a slice of received PUBREC packets. #### Run ```go func (t *TestServer) Run() ``` **Description**: Starts the test server. #### SendPacket ```go func (t *TestServer) SendPacket(p packets.Packet) error ``` **Description**: Sends a packet to the client. **Parameters**: - **p** (packets.Packet) - Required - The packet to send. #### SetResponse ```go func (t *TestServer) SetResponse(pt byte, p packets.Packet) ``` **Description**: Sets a response packet for a given packet type. **Parameters**: - **pt** (byte) - Required - The type of packet to respond to. - **p** (packets.Packet) - Required - The response packet. #### Stop ```go func (t *TestServer) Stop() ``` **Description**: Stops the test server. ``` -------------------------------- ### Define Publish Options Source: https://pkg.go.dev/github.com/eclipse/paho.golang/paho Configuration for modifying Publish behavior, including blocking or asynchronous sending. ```go type PublishMethod int ``` ```go const ( PublishMethod_Blocking PublishMethod = iota // by default PublishWithOptions will block until the publish transaction is complete PublishMethod_AsyncSend // PublishWithOptions will add the message to the session and then return (no method to check status is provided) ) ``` ```go type PublishOptions struct { // Method enables a degree of control over how PublishWithOptions operates Method PublishMethod } ``` -------------------------------- ### POST /connection/authenticate Source: https://pkg.go.dev/github.com/eclipse/paho.golang/autopaho Initiates reauthentication of credentials with the MQTT server. ```APIDOC ## POST /connection/authenticate ### Description Initiates a reauthentication process by sending an initial Auth packet to the server. ### Method POST ### Endpoint /connection/authenticate ### Request Body - **a** (*paho.Auth) - Required - The authentication packet. ### Response #### Success Response (200) - **response** (*paho.AuthResponse) - The authentication response from the server. ``` -------------------------------- ### Hook into MQTT Publish Source: https://pkg.go.dev/github.com/eclipse/paho.golang/paho/extensions/topicaliases Executes before a publish is sent to automatically replace topic names with alias numbers. ```go func (t *TAHandler) PublishHook(p *paho.Publish) ``` -------------------------------- ### Define Connect struct Source: https://pkg.go.dev/github.com/eclipse/paho.golang/paho Represents the MQTT Connect packet structure. ```go type Connect struct { Password []byte Username string ClientID string Properties *ConnectProperties WillMessage *WillMessage WillProperties *WillProperties KeepAlive uint16 CleanStart bool UsernameFlag bool PasswordFlag bool } ``` -------------------------------- ### SubOptions Structure and Methods Source: https://pkg.go.dev/github.com/eclipse/paho.golang/packets Represents subscription options and provides methods to pack or unpack the options, excluding the topic field. ```go type SubOptions struct { Topic string QoS byte RetainHandling byte NoLocal bool RetainAsPublished bool } ``` ```go func (s *SubOptions) Pack() byte ``` ```go func (s *SubOptions) Unpack(r *bytes.Buffer) error ``` -------------------------------- ### View Container Logs Source: https://pkg.go.dev/github.com/eclipse/paho.golang/autopaho/examples/docker Displays logs for all services or specifically for the subscriber container. ```bash docker-compose logs --follow ``` ```bash docker-compose logs --follow sub ``` -------------------------------- ### Publish message with custom options Source: https://pkg.go.dev/github.com/eclipse/paho.golang/paho Sends a Publish packet with options to customize behavior, blocking by default. Returns PublishResponse for QOS1+, or a default success for QOS0. May outlive the connection for QOS1+. ```go func (c *Client) PublishWithOptions(ctx context.Context, p *Publish, o PublishOptions) (*PublishResponse, error) ``` -------------------------------- ### Define Publish Struct Source: https://pkg.go.dev/github.com/eclipse/paho.golang/paho Represents an MQTT Publish packet. ```go type Publish struct { PacketID uint16 QoS byte Retain bool Topic string Properties *PublishProperties Payload []byte // contains filtered or unexported fields } ``` -------------------------------- ### Helper Function: Uint32 Source: https://pkg.go.dev/github.com/eclipse/paho.golang/paho Returns a pointer to a uint32 with the given value. ```go func Uint32(u uint32) *uint32 ``` -------------------------------- ### Manage Router Handlers Source: https://pkg.go.dev/github.com/eclipse/paho.golang/autopaho/examples/router Register, unregister, and set default handlers for specific MQTT topics. ```go router.DefaultHandler(func(p *paho.Publish) { fmt.Printf("defaulthandler received message with topic: %s\n", p.Topic) }) router.RegisterHandler("test/test/#", func(p *paho.Publish) { fmt.Printf("test/test/# received message with topic: %s\n", p.Topic) }) router.UnregisterHandler("test/test/#") ``` -------------------------------- ### ClientConfig Source: https://pkg.go.dev/github.com/eclipse/paho.golang/paho Configuration options for the MQTT client. Allows customization of connection details, session management, authentication, and message handling. ```APIDOC ## ClientConfig ### Description ClientConfig are the user-configurable options for the client. An instance of this struct is passed into NewClient(). Not all options are required to be set; defaults are provided for Persistence, MIDs, PingHandler, PacketTimeout, and Router. ### Fields - **ClientID** (string) - The identifier for the client. - **Conn** (net.Conn) - The underlying network connection to the broker. **BEWARE**: Most wrapped net.Conn implementations like tls.Conn are not thread-safe for writing. To fix this, use packets.NewThreadSafeConn wrapper or extend the custom net.Conn struct with sync.Locker. - **Session** (session.SessionManager) - Manages the client's session state. - **AuthHandler** (Auther) - Handles authentication challenges. - **PingHandler** (Pinger) - Handles keep-alive ping requests. - **Router** (Router) - (Deprecated) Routes new inbound messages. If provided, it will be added to the end of the OnPublishReceived slice. - **OnPublishReceived** ([]func(PublishReceived) (bool, error)) - A slice of callbacks to be executed when a PUBLISH message is received. Callbacks are executed in order. If a callback returns true, it indicates the message has been processed, and subsequent handlers may not be called. Additional handlers can be added after client creation using AddOnPublishReceived. - **PacketTimeout** (time.Duration) - The timeout duration for packet operations. - **OnServerDisconnect** (func(*Disconnect)) - A callback function invoked when a packets.DISCONNECT packet is received from the server. - **OnClientError** (func(error)) - A callback function for handling client-side errors, such as network errors. This may be called multiple times and after a successful disconnect. - **PublishHook** (func(*Publish)) - A user-provided function called before a Publish packet is sent, allowing inspection or modification of the packet. - **EnableManualAcknowledgment** (bool) - Controls manual acknowledgment of packets. If true, acknowledgments must be sent manually in the order specified by MQTT specs. - **SendAcksInterval** (time.Duration) - Used only when EnableManualAcknowledgment is true; determines the interval for sending batched acknowledgments. ### Example Usage ```go import ( "net" "time" "github.com/eclipse/paho.golang/paho" "github.com/eclipse/paho.golang/paho/session" ) // Example connection conn, err := net.Dial("tcp", "your.mqtt.broker:1883") if err != nil { // handle error } config := paho.ClientConfig{ ClientID: "my-client-id", Conn: conn, PacketTimeout: 5 * time.Second, OnPublishReceived: []func(paho.PublishReceived) (bool, error){ func(msg paho.PublishReceived) (bool, error) { // Process received message return true, nil // Message processed }, }, } // client, err := paho.NewClient(config) ``` ``` -------------------------------- ### String Representation of Store Source: https://pkg.go.dev/github.com/eclipse/paho.golang/paho/store/memory Provides a human-readable string representation of the store's contents, primarily for debugging purposes. ```go func (m *Store) String() string ``` -------------------------------- ### Create New File-Based Queue Source: https://pkg.go.dev/github.com/eclipse/paho.golang/autopaho/queue/file Creates a new file-based queue. It performs a test write/read/delete to ensure the path is usable. Note that file modification times are used for ordering, which may cause issues if messages are enqueued faster than the file system's ModTime resolution. ```go func New(path string, prefix string, extension string) (*Queue, error) ``` -------------------------------- ### Implement Pingresp WriteTo Method Source: https://pkg.go.dev/github.com/eclipse/paho.golang/packets Provides the implementation for the WriteTo method required by the Packet interface for Pingresp packets. ```go func (p *Pingresp) WriteTo(w io.Writer) (int64, error) ``` -------------------------------- ### Configure ClientConfig for Routing Source: https://pkg.go.dev/github.com/eclipse/paho.golang/autopaho/examples/router Integrate the router into the AutoPaho ClientConfig by setting the OnPublishReceived callback. ```go autopaho.ClientConfig{ OnPublishReceived: []func (paho.PublishReceived) (bool, error){ func (pr paho.PublishReceived) (bool, error) { router.Route(pr.Packet.Packet()) return true, nil // we assume that the router handles all messages (todo: amend router API) }}, } ``` -------------------------------- ### Initialize Disconnect properties Source: https://pkg.go.dev/github.com/eclipse/paho.golang/paho Method to populate properties for the Disconnect packet. ```go func (d *Disconnect) InitProperties(p *packets.Properties) ``` -------------------------------- ### TestLog Println Method Source: https://pkg.go.dev/github.com/eclipse/paho.golang/paho/log Prints arguments to the test log. Output is conditional on test success or specific arguments to 'go test'. ```go func (t *TestLog) Println(v ...interface{}) ``` -------------------------------- ### Implement Pingreq WriteTo Method Source: https://pkg.go.dev/github.com/eclipse/paho.golang/packets Provides the implementation for the WriteTo method required by the Packet interface for Pingreq packets. ```go func (p *Pingreq) WriteTo(w io.Writer) (int64, error) ``` -------------------------------- ### State Management API Source: https://pkg.go.dev/github.com/eclipse/paho.golang/paho/session/state Methods for initializing and interacting with the MQTT session state manager. ```APIDOC ## State Management ### Description Functions to initialize and manage the session state for MQTT clients. ### Methods - **New(client storer, server storer) *State**: Creates a new state instance using provided storers for persistence. - **NewInMemory() *State**: Returns a default State instance that stores all information in memory. - **Ack(pb *packets.Publish) error**: Acknowledges a published message. - **AddToSession(ctx context.Context, packet session.Packet, resp chan<- packets.ControlPacket) error**: Adds a packet to the session state, including message identifier allocation. - **Close() error**: Closes the session state. ### Parameters #### AddToSession - **ctx** (context.Context) - Required - The context for the operation. - **packet** (session.Packet) - Required - The packet to add to the session. - **resp** (chan<- packets.ControlPacket) - Required - Channel to receive responses regarding message acknowledgement or removal. ``` -------------------------------- ### Publish Unpack Implementation Source: https://pkg.go.dev/github.com/eclipse/paho.golang/packets Implements the Unpack method for the Publish control packet, reading data from a bytes.Buffer. ```go func (p *Publish) Unpack(r *bytes.Buffer) error ``` -------------------------------- ### Process MQTT Publish for Request/Response Source: https://pkg.go.dev/github.com/eclipse/paho.golang/autopaho/extensions/rpc The Request method handles incoming MQTT publish messages and returns a response. It takes a context and a publish message, returning a response publish message and an error. ```go func (h *Handler) Request(ctx context.Context, pb *paho.Publish) (resp *paho.Publish, err error) ``` -------------------------------- ### Subscribe to MQTT Topics Source: https://pkg.go.dev/github.com/eclipse/paho.golang/autopaho Subscribe sends a subscription request to the MQTT server and waits for a Suback response or timeout. It requires a pre-prepared Subscribe packet and returns the Suback or any errors encountered. ```go func (c *ConnectionManager) Subscribe(ctx context.Context, s *paho.Subscribe) (*paho.Suback, error) ``` -------------------------------- ### Implement Pingreq String Method Source: https://pkg.go.dev/github.com/eclipse/paho.golang/packets Provides the String method for Pingreq packets, added in v0.11.0. ```go func (p *Pingreq) String() string ``` -------------------------------- ### MQTT Client Struct Source: https://pkg.go.dev/github.com/eclipse/paho.golang/paho Represents an MQTT client. It contains internal fields for managing the client's state and connection. ```go type Client struct { // contains filtered or unexported fields } ``` -------------------------------- ### GetAll User Properties by Key Source: https://pkg.go.dev/github.com/eclipse/paho.golang/paho Retrieves all values of user properties matching the given key. Returns a nil slice if no matches are found. ```go func (u UserProperties) GetAll(key string) []string ``` -------------------------------- ### Pubcomp Reason Code String Representation Source: https://pkg.go.dev/github.com/eclipse/paho.golang/packets Returns a human-readable string for the Pubcomp's ReasonCode. ```go func (p *Pubcomp) Reason() string ``` -------------------------------- ### Reset credentials Source: https://pkg.go.dev/github.com/eclipse/paho.golang/autopaho Clears the username and password fields from the configuration. ```go func (cfg *ClientConfig) ResetUsernamePassword() ``` -------------------------------- ### Puback WriteTo Implementation Source: https://pkg.go.dev/github.com/eclipse/paho.golang/packets Implements the WriteTo method for the Puback control packet, writing packet data to an io.Writer. ```go func (p *Puback) WriteTo(w io.Writer) (int64, error) ``` -------------------------------- ### Implement Pingreq Unpack Method Source: https://pkg.go.dev/github.com/eclipse/paho.golang/packets Provides the implementation for the Unpack method required by the Packet interface for Pingreq packets. ```go func (p *Pingreq) Unpack(r *bytes.Buffer) error ``` -------------------------------- ### POST /connection/publish Source: https://pkg.go.dev/github.com/eclipse/paho.golang/autopaho Publishes a message to the MQTT server using a pre-prepared PUBLISH packet. ```APIDOC ## POST /connection/publish ### Description Sends a publication to the MQTT server. This method blocks until the appropriate response is received or a timeout occurs. ### Method POST ### Endpoint /connection/publish ### Request Body - **p** (*paho.Publish) - Required - A pre-prepared PUBLISH packet. ### Response #### Success Response (200) - **response** (*paho.PublishResponse) - The response message from the server. ``` -------------------------------- ### Implement Pingresp Unpack Method Source: https://pkg.go.dev/github.com/eclipse/paho.golang/packets Provides the implementation for the Unpack method required by the Packet interface for Pingresp packets. ```go func (p *Pingresp) Unpack(r *bytes.Buffer) error ``` -------------------------------- ### Implement Pingresp String Method Source: https://pkg.go.dev/github.com/eclipse/paho.golang/packets Provides the String method for Pingresp packets, added in v0.11.0. ```go func (p *Pingresp) String() string ``` -------------------------------- ### Implement Pingreq Buffers Method Source: https://pkg.go.dev/github.com/eclipse/paho.golang/packets Provides the implementation for the Buffers method required by the Packet interface for Pingreq packets. ```go func (p *Pingreq) Buffers() net.Buffers ``` -------------------------------- ### Implement Pingresp Buffers Method Source: https://pkg.go.dev/github.com/eclipse/paho.golang/packets Provides the implementation for the Buffers method required by the Packet interface for Pingresp packets. ```go func (p *Pingresp) Buffers() net.Buffers ``` -------------------------------- ### Puback Reason Code String Representation Source: https://pkg.go.dev/github.com/eclipse/paho.golang/packets Returns a human-readable string for the Puback's ReasonCode. ```go func (p *Puback) Reason() string ``` -------------------------------- ### ConnectionManager Operations Source: https://pkg.go.dev/github.com/eclipse/paho.golang/autopaho Methods for managing connection state, authentication, and message publication. ```go func (c *ConnectionManager) AddOnPublishReceived(f func(PublishReceived) (bool, error)) func() ``` ```go func (c *ConnectionManager) Authenticate(ctx context.Context, a *paho.Auth) (*paho.AuthResponse, error) ``` ```go func (c *ConnectionManager) AwaitConnection(ctx context.Context) error ``` ```go func (c *ConnectionManager) Disconnect(ctx context.Context) error ``` ```go func (c *ConnectionManager) Done() <-chan struct{} ``` ```go func (c *ConnectionManager) Publish(ctx context.Context, p *paho.Publish) (*paho.PublishResponse, error) ``` -------------------------------- ### Helper Function: Byte Source: https://pkg.go.dev/github.com/eclipse/paho.golang/paho Returns a pointer to a byte with the given value. ```go func Byte(b byte) *byte ``` -------------------------------- ### Implement FixedHeader WriteTo Method Source: https://pkg.go.dev/github.com/eclipse/paho.golang/packets Implements the WriteTo method for FixedHeader to produce the wire format byte representation. ```go func (f *FixedHeader) WriteTo(w io.Writer) (int64, error) ``` -------------------------------- ### Initialize TAHandler Source: https://pkg.go.dev/github.com/eclipse/paho.golang/paho/extensions/topicaliases Creates a new instance of TAHandler with a specified maximum number of aliases. ```go func NewTAHandler(max uint16) *TAHandler ``` -------------------------------- ### Publish Method Operations Source: https://pkg.go.dev/github.com/eclipse/paho.golang/paho Methods for interacting with the Publish struct. ```go func (p *Publish) Duplicate() bool ``` ```go func (p *Publish) InitProperties(prop *packets.Properties) ``` ```go func (p *Publish) Packet() *packets.Publish ``` ```go func (p *Publish) String() string ``` -------------------------------- ### Reset store Source: https://pkg.go.dev/github.com/eclipse/paho.golang/paho/store/file Clears all messages from the store. ```go func (s *Store) Reset() error ``` -------------------------------- ### Connect Packet Structure and Methods Source: https://pkg.go.dev/github.com/eclipse/paho.golang/packets Defines the Connect variable header and methods for flag manipulation and packet processing. ```go type Connect struct { WillMessage []byte Password []byte Username string ProtocolName string ClientID string WillTopic string Properties *Properties WillProperties *Properties KeepAlive uint16 ProtocolVersion byte WillQOS byte PasswordFlag bool UsernameFlag bool WillRetain bool WillFlag bool CleanStart bool } ``` ```go func (c *Connect) Buffers() net.Buffers ``` ```go func (c *Connect) PackFlags() (f byte) ``` ```go func (c *Connect) String() string ``` ```go func (c *Connect) Unpack(r *bytes.Buffer) error ``` ```go func (c *Connect) UnpackFlags(b byte) ``` ```go func (c *Connect) WriteTo(w io.Writer) (int64, error) ``` -------------------------------- ### Pubcomp Unpack Implementation Source: https://pkg.go.dev/github.com/eclipse/paho.golang/packets Implements the Unpack method for the Pubcomp control packet, reading data from a bytes.Buffer. ```go func (p *Pubcomp) Unpack(r *bytes.Buffer) error ``` -------------------------------- ### MQTT PUBCOMP Reason Codes Source: https://pkg.go.dev/github.com/eclipse/paho.golang/packets Constants for PUBCOMP (Publish Complete) reason codes. PubcompSuccess is 0x00. ```go const ( PubcompSuccess = 0x00 PubcompPacketIdentifierNotFound = 0x92 ) ``` -------------------------------- ### UserProperties.GetAll Source: https://pkg.go.dev/github.com/eclipse/paho.golang/paho Returns all matching user properties by key, added in v0.10.0. ```APIDOC ## UserProperties.GetAll (v0.10.0+) ### Description GetAll returns a slice of all entries in the UserProperties that match key, or a nil slice if none were found. ### Method Signature ```go func (u UserProperties) GetAll(key string) []string ``` ``` -------------------------------- ### Publish WriteTo Implementation Source: https://pkg.go.dev/github.com/eclipse/paho.golang/packets Implements the WriteTo method for the Publish control packet, writing packet data to an io.Writer. ```go func (p *Publish) WriteTo(w io.Writer) (int64, error) ``` -------------------------------- ### Connect Source: https://pkg.go.dev/github.com/eclipse/paho.golang/paho Represents the MQTT Connect packet and provides methods for packet conversion and property initialization. ```APIDOC ## Connect ### Description Connect is a representation of the MQTT Connect packet. ### Fields - **Password** ([]byte) - Optional - **Username** (string) - Optional - **ClientID** (string) - Optional - **Properties** (*ConnectProperties) - Optional - **WillMessage** (*WillMessage) - Optional - **WillProperties** (*WillProperties) - Optional - **KeepAlive** (uint16) - Optional - **CleanStart** (bool) - Optional - **UsernameFlag** (bool) - Optional - **PasswordFlag** (bool) - Optional ### Methods #### ConnectFromPacketConnect ```go func ConnectFromPacketConnect(p *packets.Connect) *Connect ``` ConnectFromPacketConnect takes a packets library Connect and returns a paho library Connect. #### InitProperties ```go func (c *Connect) InitProperties(p *packets.Properties) ``` InitProperties is a function that takes a lower level Properties struct and completes the properties of the Connect on which it is called. #### InitWillProperties ```go func (c *Connect) InitWillProperties(p *packets.Properties) ``` InitWillProperties is a function that takes a lower level Properties struct and completes the properties of the Will in the Connect on which it is called. #### Packet ```go func (c *Connect) Packet() *packets.Connect ``` Packet returns a packets library Connect from the paho Connect on which it is called. ``` -------------------------------- ### Initialize Subscribe Properties from Packet Properties Source: https://pkg.go.dev/github.com/eclipse/paho.golang/paho Initializes the Subscribe packet's properties using a Properties struct from the packets library. ```go func (s *Subscribe) InitProperties(prop *packets.Properties) ``` -------------------------------- ### Auth.Unpack Method Source: https://pkg.go.dev/github.com/eclipse/paho.golang/packets Implementation of the interface required function for a packet, unpacking data from a buffer. ```go func (a *Auth) Unpack(r *bytes.Buffer) error ``` -------------------------------- ### Enqueue Item to Queue Source: https://pkg.go.dev/github.com/eclipse/paho.golang/autopaho/queue/file Adds an item to the queue. The item is provided as an io.Reader. ```go func (q *Queue) Enqueue(p io.Reader) error ```