How KCloud-Platform-IoT Supports IoT Protocols Like MQTT and CoAP
KCloud-Platform-IoT implements MQTT through a Go-based Paho client wrapper with automatic reconnection capabilities, while CoAP is supported via a Java Spring Boot module using the Eclipse Californium library.
KCloud-Platform-IoT is an open-source IoT platform that provides native support for lightweight machine-to-machine communication through dedicated protocol adapters. The architecture splits implementation responsibilities across languages, using Go for MQTT client operations and Java for CoAP server functionality, enabling developers to choose the optimal tool for their specific device connectivity requirements.
MQTT Implementation in Go
The MQTT support resides in the Go service layer, specifically within KCloud-Platform-IoT-Go/service/iot/core/mqtt.go. This module wraps the Eclipse Paho MQTT client to provide robust connection management and message handling for IoT devices.
Connection Management and Auto-Reconnection
The MQTT struct encapsulates all connection parameters including username, password, client ID, host, port, topic, QoS level, and retained flag settings. The GetMqttClient() method constructs a configured client with automatic reconnection logic and connection event callbacks.
func (m *MQTT) GetMqttClient() mqtt.Client {
broker := fmt.Sprintf("tcp://%s:%s", m.Host, m.Port)
options := mqtt.NewClientOptions()
options.AddBroker(broker)
options.SetClientID(m.ClientId)
options.SetUsername(m.Username)
options.SetPassword(m.Password)
options.OnConnect = onConnect
options.SetAutoReconnect(true)
options.OnConnectionLost = onConnectLost
client := mqtt.NewClient(options)
if token := client.Connect(); token.Wait() && token.Error() != nil {
// retry on failure
time.Sleep(5 * time.Second)
return m.GetMqttClient()
}
return client
}
This implementation ensures that temporary network interruptions do not permanently disconnect devices, as the client automatically attempts to re-establish the connection with a five-second backoff.
Publishing and Subscribing Operations
The module exposes helper methods for core MQTT operations. PublishMQTT and DefaultPublishMQTT handle message transmission with configurable QoS levels and retention policies, while SubscribeMultiple enables simultaneous subscription to multiple topic filters. The DisConnectMQTT method ensures clean session termination when the client shuts down.
CoAP Implementation in Java
For Constrained Application Protocol support, KCloud-Platform-IoT leverages the laokou-common-coap Java module. This implementation uses the Eclipse Californium library to provide a lightweight, UDP-based communication layer suitable for constrained devices with limited processing power.
Spring-Managed CoAP Server Configuration
The CoapServerConfig class in laokou-common/laokou-common-coap/src/main/java/org/laokou/common/coap/config/CoapServerConfig.java defines a Spring bean that manages the server lifecycle. The configuration automatically starts the server when the Spring context initializes and gracefully stops it on shutdown.
@Configuration
public class CoapServerConfig {
@Bean(initMethod = "start", destroyMethod = "stop")
public CoapServer coapServer(SpringCoapServerProperties props) {
return new CoapServer(props.getPort());
}
}
Port Configuration and Properties
The server listens on a configurable port defined through SpringCoapServerProperties, allowing deployment flexibility across different network environments. Developers specify the port in their application.yml configuration, with the default CoAP port 5683 typically used for unsecured UDP communication.
Practical Code Examples
Connecting and Publishing via MQTT (Go)
The following example demonstrates establishing an MQTT connection and publishing sensor data using the core MQTT struct:
import (
"github.com/koushenhai/kcloud-platform-iot/KCloud-Platform-IoT-Go/service/iot/core"
"time"
)
func main() {
// Define connection parameters
cfg := core.MQTT{
Username: "user",
Password: "pass",
ClientId: "device-001",
Host: "broker.example.com",
Port: "1883",
Topic: "sensors/temperature",
Qos: 1,
Retained: false,
}
// Create client
client := cfg.GetMqttClient()
defer cfg.DisConnectMQTT(client)
// Publish payload
payload := []byte(`{"temp":23.5}`)
cfg.PublishMQTT(client, cfg.Topic, cfg.Qos, cfg.Retained, payload)
// Keep the client alive for a short while
time.Sleep(2 * time.Second)
}
Subscribing to Multiple Topics (Go)
To receive messages from multiple sensors simultaneously using topic filters:
func msgHandler(client mqtt.Client, msg mqtt.Message) {
fmt.Printf("Topic:%s Payload:%s\n", msg.Topic(), string(msg.Payload()))
}
func main() {
cfg := core.MQTT{
// ... (same as before)
Topic: "sensors/temperature,sensors/humidity",
Qos: 1,
}
client := cfg.GetMqttClient()
defer cfg.DisConnectMQTT(client)
cfg.SubscribeMultiple(client, msgHandler)
// Block forever (or use a context cancellation)
select {}
}
Starting a CoAP Server (Java)
Enable CoAP support by including the module and configuring the listening port:
@SpringBootApplication
public class CoapApp {
public static void main(String[] args) {
SpringApplication.run(CoapApp.class, args);
}
}
# src/main/resources/application.yml
spring:
coap:
port: 5683 # default CoAP port
The CoapServerConfig bean automatically instantiates and starts the server. You can extend CoapResource to implement custom resource handlers for device-specific endpoints, registering them with the server instance.
Summary
- Dual-language architecture: MQTT client functionality is implemented in Go using the Paho library, while CoAP server capabilities are provided through Java and Eclipse Californium.
- Resilient MQTT connections: The Go implementation includes automatic reconnection logic with configurable backoff strategies in
GetMqttClient(). - Spring Boot integration: The CoAP module provides seamless integration with Spring's lifecycle management through
CoapServerConfigandSpringCoapServerProperties. - Auxiliary HTTP support: The platform includes HTTP utilities in
KCloud-Platform-IoT-Go/service/iot/core/http.gofor RESTful device management alongside MQTT and CoAP. - Production-ready configuration: Both protocols support externalized configuration, allowing flexible deployment across development, staging, and production environments.
Frequently Asked Questions
Does KCloud-Platform-IoT support MQTT over WebSockets?
The current MQTT implementation in mqtt.go uses standard TCP connections via the Paho client. While the core implementation focuses on TCP, the underlying Paho library supports WebSocket transports, though this would require extending the current MQTT struct to accept WebSocket URLs instead of the standard tcp:// broker format.
Can the CoAP server handle both UDP and DTLS encrypted connections?
The basic CoapServerConfig implementation creates a standard UDP server on the configured port. For DTLS (Datagram Transport Layer Security) support, you would need to extend the configuration to instantiate a CoapEndpoint with a DTLSConnector from the Californium library, configuring cipher suites and certificate chains appropriately within the Spring configuration class.
How does the platform handle MQTT message QoS levels?
The Go MQTT struct exposes a Qos field that accepts integer values 0, 1, or 2, corresponding to MQTT's At Most Once, At Least Once, and Exactly Once delivery guarantees. These values are passed directly to the PublishMQTT method and underlying Paho client to ensure end-to-end quality of service enforcement between devices and the platform.
Is there a Java implementation of the MQTT client in KCloud-Platform-IoT?
The repository currently implements MQTT client functionality exclusively in Go within the KCloud-Platform-IoT-Go service module. Java-based services can communicate with MQTT brokers through the Go service layer or by implementing additional Java MQTT client modules using libraries like Eclipse Paho Java Client.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →