mqtt

package
v1.76.0 Latest Latest
Warning

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

Go to latest
Published: Aug 19, 2026 License: MIT Imports: 5 Imported by: 0

Documentation

Overview

Package mqtt 提供 MQTT 客户端集成(设备网关采集数据场景): 连接 Broker、订阅主题、发布消息、断线自动重连(基于 paho.mqtt.golang)。

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func SetGlobal

func SetGlobal(client *Client)

SetGlobal 设置全局客户端(NewClient 成功后自动调用)。

Types

type Client

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

Client MQTT 客户端。

func Get

func Get() *Client

Get 获取全局 MQTT 客户端;未连接返回 nil。

func NewClient

func NewClient(config Config, onMessage MessageHandler) (*Client, error)

NewClient 创建并连接 MQTT Broker(连接失败立即报错)。 onMessage 为全局默认消息回调(所有未单独指定 handler 的订阅共用)。

func (*Client) Close

func (c *Client) Close()

Close 断开连接(超时 2s)。

func (*Client) IsConnected

func (c *Client) IsConnected() bool

IsConnected 连接状态。

func (*Client) Native

func (c *Client) Native() mqttlib.Client

Native 返回原生 paho 客户端(高级操作入口)。

func (*Client) Publish

func (c *Client) Publish(topic string, qos byte, retained bool, payload []byte) error

Publish 发布消息(原始字节)。

func (*Client) PublishJSON

func (c *Client) PublishJSON(topic string, qos byte, value interface{}) error

PublishJSON 发布 JSON 消息(设备网关上报数据常用)。

func (*Client) Subscribe

func (c *Client) Subscribe(topic string, qos byte, handler MessageHandler) error

Subscribe 订阅主题。 qos:0 最多一次 / 1 至少一次 / 2 仅一次;handler 为空时走全局回调。

func (*Client) Unsubscribe

func (c *Client) Unsubscribe(topics ...string) error

Unsubscribe 取消订阅。

type Config

type Config struct {
	// Broker 地址(如 tcp://127.0.0.1:1883 或 ssl://host:8883)。
	Broker string
	// ClientID 客户端标识(网关/服务唯一;空则自动生成)。
	ClientID string
	// Username/Password 认证(可选)。
	Username string
	Password string
	// CleanSession 会话清理(默认 true;false 时断线保留订阅)。
	CleanSession bool
	// Timeout 连接超时(默认 10s)。
	Timeout time.Duration
	// AutoReconnect 断线自动重连(默认 true,paho 内置)。
	AutoReconnect bool
}

Config MQTT 客户端配置。

type MessageHandler

type MessageHandler func(topic string, payload []byte)

MessageHandler 消息回调(订阅处理)。

Jump to

Keyboard shortcuts

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