mqttcomms

package module
v0.2.20 Latest Latest
Warning

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

Go to latest
Published: Aug 25, 2026 License: GPL-3.0 Imports: 16 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

MqttComms: MQTT Protocol Handling for Opencaps Devices

AsyncAPI

Overview

MqttComms is a Go library designed to facilitate seamless communication between Opencaps devices and services using the MQTT protocol. It provides robust tools for encoding and decoding custom protocol messages, secure communication using TLS, and managing MQTT topics and methods.


Features

  • Secure MQTT Communication: Supports TLS for secure connections.
  • Automatic Certificate Renewal: Handles certificate expiration and reconnects automatically.
  • Topic Management: Predefined topics for various use cases.
  • Custom Protocol Support: Encode and decode messages with CRC validation.
  • Signal-Based Reconnection: Reconnects on receiving SIGHUP signals.
  • Flexible Configuration: Supports file-based or inline credentials.
  • AsyncAPI Specification: Complete API documentation in AsyncAPI 3.0 format.

API Documentation

The MQTT API is fully documented using the AsyncAPI specification.

View Documentation
Generate Documentation Locally
# Install AsyncAPI CLI
npm install -g @asyncapi/cli

# Validate the specification
asyncapi validate asyncapi.yaml

# Generate HTML documentation
asyncapi generate fromTemplate asyncapi.yaml @asyncapi/html-template -o docs

Installation

  1. Clone the repository:

    git clone https://github.com/opencaps/mqttcomms.git
    cd mqttcomms
    
  2. Install dependencies:

    go mod tidy
    

Configuration

The library uses the Conf struct (defined in conf.go) for configuration. Below are the key fields:

  • Client Identification:

    • ClientID: Unique identifier for the client.
    • UniqueID: Additional unique identifier.
  • Credentials:

    • CredFromFile: Boolean to indicate if credentials are read from a file.
    • MqttUser and MqttPass: Inline username and password.
    • MqttCredPath: Path to the credentials file.
  • TLS Configuration:

    • MqttCAPath: Path to the CA certificate.
    • MqttCertPath: Path to the client certificate.
    • MqttKeyPath: Path to the client key.
  • Broker Details:

    • MqttUrl: URL of the MQTT broker.
  • Renewal Mode:

    • RenewalMode: Mode for renewing the connection (expiracy or signal).

Usage

1. Initialize the Client

Create a new Client instance and initialize it with a configuration:

client := &mqttcomms.Client{}
conf := &mqttcomms.Conf{
    ClientID:     "example-client",
    MqttUrl:      "broker.example.com",
    MqttCAPath:   "/path/to/ca.crt",
    MqttCertPath: "/path/to/client.crt",
    MqttKeyPath:  "/path/to/client.key",
    RenewalMode:  mqttcomms.RenewalModeExpiracy,
}
client.InitMqtt(conf)
2. Connect to the Broker

Establish a connection to the MQTT broker:

client.Connect()
3. Subscribe to Topics

Subscribe to a topic and handle incoming messages:

client.Subscribe("example/topic", func(client MQTT.Client, msg MQTT.Message) {
    fmt.Println("Received message:", string(msg.Payload()))
})
4. Publish Messages

Publish a message to a topic:

err := client.WriteMQTT([]byte("Hello, MQTT!"), "example/topic")
if err != nil {
    fmt.Println("Error publishing message:", err)
}
5. Unsubscribe from Topics

Unsubscribe from a topic:

client.Unsubscribe("example/topic")

Topics

Predefined topics are available in topics.go:

  • Admin:

    • TopAdminEvt: Admin events.
    • TopAdminOrd: Admin orders.
  • Device:

    • TopDevEvt: Device events.
    • TopDevOrd: Device orders.
  • EnOcean:

    • TopEnoEvt: EnOcean events.
    • TopEnoOrd: EnOcean orders.
  • Telemetry:

    • TopTelemetryEvt: Telemetry events.
    • TopTelemetryOrd: Telemetry orders.
  • Time:

    • TimeEvt: Time events.
    • TimeOrd: Time orders.
  • Calendar:

    • TopCalEvt: Calendar events.
    • TopCalOrd: Calendar orders.
  • UI:

    • TopUIEvt: UI events.
    • TopUIOrd: UI orders.

Methods

Predefined methods are available in methods.go:

  • Device Methods:

    • DEV_ADD_NEW, DEV_ADD, DEV_REMOVE, etc.
  • Admin Methods:

    • App-core DFU: AD_INIT_UPDATE, AD_SEND_CHUNK, AD_UPDATE_FINISHED (0x00–0x02).
    • Network-core DFU (0x0B–0x0D): AD_INIT_UPDATE_NET, AD_SEND_CHUNK_NET, AD_UPDATE_FINISHED_NET — matches the firmware's multi-image net-core DFU.
    • AD_GET_INFO, AD_GET_STATUS, AD_RESET, AD_ALIVE, AD_BLE_COMFIRM, ESP-S3 OTA (AD_INIT_ESP_OTA/AD_SEND_ESP_OTA_CHUNK/AD_ESP_OTA_FINISHED).
    • AD_SET_ENTITY_ID (0x11), AD_FACTORY_RESET (0x12), AD_SET_ENOCEAN_SENDER_ID (0x13), AD_CHECK_ENTITY_ID_READY (0x14).
    • AD_ENTER_TEST_MODE (0x15): switches the bridge into factory test mode (persists test state + reboots into the test SM) so it can be re-provisioned with a fresh identity. Effective only on a firmware build with test support compiled in.

    Opcodes mirror the firmware AdminOrderType enum (the source of truth). AD_FACTORY_RESET is 0x12 — it was previously 0x0B, which collided with net-core DFU init; callers built against older mqttcomms must rebuild.

  • Time Methods:

    • TM_GET_TIME, TM_PUBLISH.
  • Calendar Methods:

    • CL_SET_ZONE_PLANNING, CL_GET_ZONE_EXCEPTION.
  • Telemetry Methods:

    • TELEMETRY.
  • UI Methods:

    • UI_ZONE_LIST: Request/send zone list.
    • UI_BUILDING_NAME: Request/send building name.
    • UI_FULL_INFO: Request/send full UI information.

Custom Protocol

The library supports encoding and decoding custom protocol messages with CRC validation. See mqttcomms.go for details.

Encode a Message

Use GenerateMsg to encode a message:

msg := &mqttcomms.Msg{
    Seq:    1,
    Op:     mqttcomms.REQRESP,
    Method: mqttcomms.DEV_ADD,
    Body:   []byte("payload"),
}
encoded, err := mqttcomms.GenerateMsg(msg)
if err != nil {
    fmt.Println("Error encoding message:", err)
}
Decode a Message

Use DecodeMsg to decode a message:

decoded, err := mqttcomms.DecodeMsg(encoded)
if err != nil {
    fmt.Println("Error decoding message:", err)
}
fmt.Println("Decoded message:", decoded)

License

This project is licensed under the GNU General Public License v3. See the LICENSE file for details.

Documentation

Index

Constants

View Source
const (
	// RenewalModeExpiracy is the mode where the client renews the connection on expiracy
	RenewalModeExpiracy = "expiracy"
	// RenewalModeSignal is the mode where the client renews the connection on SIGHUP
	RenewalModeSignal = "signal"
)
View Source
const (
	// Device methods
	DEV_ADD_NEW                      = 0x00
	DEV_ADD                          = 0x01
	DEV_REMOVE                       = 0x02
	DEV_GET_ACTUATOR                 = 0x03
	DEV_GET_SENSOR                   = 0x04
	DEV_UPDATE_ZONE                  = 0x05
	DEV_ADD_NEW_ERL                  = 0x06
	ERL_REMOVE                       = 0x07
	DEV_ADD_INTERNAL_TMP_SENSOR      = 0x08
	DEV_ADD_INTERNAL_HUM_SENSOR      = 0x09
	DEV_ADD_INTERNAL_COV_SENSOR      = 0x0A
	DEV_ADD_INTERNAL_NOX_SENSOR      = 0x0B
	DEV_UPDATE_ZONE_INTERNAL_SENSORS = 0x0C
	DEV_REMOVE_INTERNAL_SENSORS      = 0x0E

	// Admin methods
	AD_INIT_UPDATE        = 0x00
	AD_SEND_CHUNK         = 0x01
	AD_UPDATE_FINISHED    = 0x02
	AD_GET_INFO           = 0x03
	AD_GET_STATUS         = 0x04
	AD_RESET              = 0x05
	AD_ALIVE              = 0x06
	AD_BLE_COMFIRM        = 0x07
	AD_INIT_ESP_OTA       = 0x08
	AD_SEND_ESP_OTA_CHUNK = 0x09
	AD_ESP_OTA_FINISHED   = 0x0A
	// Network-core DFU (multi-image) — matches firmware init_dfu_net/dfu_pkt_net/fin_dfu_net.
	AD_INIT_UPDATE_NET     = 0x0B
	AD_SEND_CHUNK_NET      = 0x0C
	AD_UPDATE_FINISHED_NET = 0x0D

	AD_SET_ENTITY_ID = 0x11
	// NOTE: factory_reset is 0x12 (firmware bumped it when net-core DFU took 0x0B-0x0D).
	// It was previously (incorrectly) 0x0B here, colliding with net-core DFU init.
	AD_FACTORY_RESET         = 0x12
	AD_SET_ENOCEAN_SENDER_ID = 0x13
	AD_CHECK_ENTITY_ID_READY = 0x14
	AD_ENTER_TEST_MODE       = 0x15

	// ERL OTA over Thread — ADR 0007 step 4. The bridge PULLS: the cloud offers an
	// image with BEGIN, the bridge asks for each 512 B slice by offset as its 2x512 B
	// window drains, and reports the outcome with END. One transfer per bridge at a
	// time; a second BEGIN while one is in flight is refused.
	//
	// Bodies are big-endian, like every other body on this channel. EUI-64 travels in
	// CANONICAL (display) order, not the little-endian form the container embeds — the
	// cloud reverses it when personalising, per D4.
	//
	//	BEGIN     eui64[8] fileVersion[4] fileSize[4] channel[1]
	//	SLICE_REQ offset[4] length[2]
	//	SLICE     offset[4] data[<=512]
	//	END       status[1] fileVersion[4] reason[...]  (reason is UTF-8, may be empty)
	AD_ERL_OTA_BEGIN     = 0x16
	AD_ERL_OTA_SLICE_REQ = 0x17
	AD_ERL_OTA_SLICE     = 0x18
	AD_ERL_OTA_END       = 0x19

	AD_GOODBYE = 0xFF

	// Time methods
	TM_GET_TIME = 0x00
	TM_PUBLISH  = 0x01

	// Calendar methods
	CL_SET_ZONE_PLANNING                  = 0x00 // Weekly setpoints + optional exceptions for one zone
	CL_SET_ZONE_EXCEPTION                 = 0x01 // Exception-only update for one zone
	CL_GET_ZONE_PLANNING                  = 0x02 // Bridge requests schedule (inbound)
	CL_GET_ZONE_EXCEPTION                 = 0x03 // Bridge requests exceptions (inbound)
	CL_SEND_PLANNING_GROUP_EVT            = 0x06 // Full group metadata with embedded plannings (UI)
	CL_PLANNING_GROUP_ACTIVATE_RECEIVED   = 0x08 // User activated group on ESP (inbound)
	CL_PLANNING_EXCEPTION_EVT_RECEIVED    = 0x09 // User created exception on ESP (inbound)
	CL_PLANNING_GROUP_DEACTIVATE_RECEIVED = 0x0A // User deactivated group on ESP (inbound)
	CL_CLEAR_ALL_PLANNINGS                = 0x0B // Clear all zone plannings + exceptions (optional hold targets in body)
	CL_SYNC_GROUPS_HASH                   = 0x0C // Bridge sends CRC32 hash of group list for sync check

	// Telemetry methods
	TELEMETRY = 0x00

	// UI methods
	UI_ZONE_LIST     = 0x00
	UI_BUILDING_NAME = 0x01
	UI_FULL_INFO     = 0x02
	UI_WEATHER       = 0x03
	UI_SUN_TIMES     = 0x04
)
View Source
const (
	REQACK  = 0x01
	NOACK   = 0x02
	ISACK   = 0x03
	REQRESP = 0x04
	ISRESP  = 0x05
)
View Source
const (
	STATUS_OK = 0x0
	STATUS_KO = 0x1
)
View Source
const (
	TopAdminEvt     = "AdminEvents"
	TopAdminOrd     = "AdminOrders"
	TopDevEvt       = "DeviceEvents"
	TopDevOrd       = "DeviceOrders"
	TopEnoEvt       = "EnoceanEvents"
	TopEnoOrd       = "EnoceanOrders"
	TopTelemetryEvt = "TelemetryEvents"
	TopTelemetryOrd = "TelemetryOrders"
	TimeEvt         = "TimeEvents"
	TimeOrd         = "TimeOrders"
	TopCalEvt       = "CalendarEvents"
	TopCalOrd       = "CalendarOrders"
	TopUIEvt        = "UIEvents"
	TopUIOrd        = "UIOrders"
	TopTermEvt      = "TerminalEvents"
	TopTermOrd      = "TerminalOrders"
)

Variables

This section is empty.

Functions

func GenerateMsg

func GenerateMsg(m *Msg) ([]byte, error)

Types

type Client added in v0.0.7

type Client struct {
	Log *logging.Logger

	IsConnected chan bool

	sync.Mutex
	// contains filtered or unexported fields
}

Client structure for mqtt client Client represents an MQTT client with configuration, logging, and synchronization capabilities. It includes the following fields: - client: The underlying MQTT client instance. - conf: Configuration settings for the client. - Log: Logger for logging client activities. - wg: WaitGroup to manage goroutines. - IsConnected: Channel to signal connection status. - sighup: Channel to handle OS signals. - Mutex: Embedded mutex for synchronization.

func (*Client) Connect added in v0.0.8

func (c *Client) Connect()

Connect establishes a connection to the MQTT broker using the client's configuration. It sets up TLS configuration, reads credentials from a file if specified, and configures the MQTT client options including username, password, broker URL, client ID, and handlers for connection events. The function attempts to connect to the broker and retries every 5 seconds until a successful connection is made.

func (*Client) InitMqtt added in v0.0.7

func (c *Client) InitMqtt(conf *Conf)

InitMqtt initializes the MQTT client with the provided configuration. It sets up channels for connection status and signal handling, and starts the appropriate renewal handling goroutine based on the configuration.

Parameters:

  • conf: A pointer to a Conf struct containing the client's configuration.

func (*Client) Subscribe added in v0.0.7

func (c *Client) Subscribe(topic string, callback MQTT.MessageHandler)

Subscribe to a topic, the messages of this topic will be passed through the method callback Subscribe subscribes the client to a given MQTT topic and registers a callback function to handle incoming messages on that topic.

Parameters:

  • topic: The MQTT topic to subscribe to.// - callback: A function of type MQTT.MessageHandler that will be called// data - The byte slice containing the data to be published. topic - The MQTT topic to which the data should be published.

Returns:

error - An error if the MQTT client is not instantiated or if the publish operation fails, otherwise nil.

func (*Client) SubscribeWait added in v0.2.10

func (c *Client) SubscribeWait(topic string, callback MQTT.MessageHandler, timeout time.Duration) error

SubscribeWait subscribes to a topic and waits for the subscription to be confirmed by the broker.

func (*Client) Unsubscribe added in v0.0.7

func (c *Client) Unsubscribe(topic string)

Unsubscribe unsubscribes the client from the specified MQTT topic. It takes a single parameter: - topic: the topic string from which the client should unsubscribe.

func (*Client) WriteMQTT added in v0.0.7

func (c *Client) WriteMQTT(data []byte, topic string) error

WriteMQTT send data to a topic WriteMQTT publishes data to a specified MQTT topic. It waits for any ongoing operations to complete, locks the client for exclusive access, and then attempts to publish the data. If the MQTT client is not instantiated, it logs a warning and returns an error. If the publish operation fails, it logs a warning and returns the error.

Parameters:

data  - The byte slice containing the data to be published.
topic - The MQTT topic to which the data should be published.

Returns:

error - An error if the MQTT client is not instantiated or if the publish operation fails, otherwise nil.

type Conf added in v0.0.7

type Conf struct {
	ClientID     string
	CredFromFile bool
	MqttUrl      string
	MqttUser     string
	MqttPass     string
	MqttCredPath string
	MqttCAPath   string
	MqttCertPath string
	MqttKeyPath  string
	UniqueID     string
	RenewalMode  string
}

Conf represents the configuration settings required for MQTT communication. It includes fields for client identification, credential sources, and MQTT connection details.

Fields: - ClientID: A unique identifier for the MQTT client. - CredFromFile: A boolean indicating whether credentials should be loaded from a file. - MqttUrl: The URL of the MQTT broker. - MqttUser: The username for MQTT authentication. - MqttPass: The password for MQTT authentication. - MqttCredPath: The file path to the MQTT credentials. - MqttCAPath: The file path to the Certificate Authority (CA) certificate. - MqttCertPath: The file path to the client certificate. - MqttKeyPath: The file path to the client key. - UniqueID: A unique identifier for the configuration instance. - RenewalMode: The mode for renewing the MQTT connection or credentials.

type Msg

type Msg struct {
	Seq    uint16
	Op     uint8
	Method uint8
	Len    uint16
	Body   []byte
	Crc    uint16
}

func DecodeMsg

func DecodeMsg(msg []byte) (Msg, error)

Jump to

Keyboard shortcuts

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