star-cloud/mqtt-gateway/internal/handler/mqtt_handler.go
sky121113 4b8436e6c2 [REFACTOR] 移除 MQTT $SYS 監聽機制並優化 CI/CD 流程
1. 移除 MQTT Gateway 對 $SYS 系統主題的訂閱與解析邏輯,改由遺囑 (Last Will) 統一處理上下線狀態。
2. 更新 EMQX ACL 設定,移除 Gateway 的系統主題存取權限。
3. 優化 CI/CD 流程 (deploy-demo.yaml):將 EMQX 重啟改為熱重載 (Reload),並新增 MQTT Worker 自動重啟。
2026-04-22 13:33:42 +08:00

57 lines
1.2 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package handler
import (
"encoding/json"
"log"
"star-cloud-gateway/internal/bridge"
"strings"
mqtt "github.com/eclipse/paho.mqtt.golang"
)
type MqttHandler struct {
pusher *bridge.RedisPusher
}
func NewMqttHandler(pusher *bridge.RedisPusher) *MqttHandler {
return &MqttHandler{pusher: pusher}
}
func (h *MqttHandler) HandleMessage(client mqtt.Client, msg mqtt.Message) {
topic := msg.Topic()
payload := msg.Payload()
log.Printf("Received message on topic: %s", topic)
// 業務主題格式:
// 3 層: machine/{serialNo}/{type} (如 heartbeat, error, transaction, status)
// 4 層: machine/{serialNo}/{type}/{subType} (如 command/ack)
parts := strings.Split(topic, "/")
if len(parts) < 3 {
return
}
serialNo := parts[1]
msgType := parts[2]
// 4 層 Topic將 type/subType 組合為 type_subType (如 command/ack → command_ack)
if len(parts) >= 4 {
msgType = parts[2] + "_" + parts[3]
}
var jsonPayload interface{}
err := json.Unmarshal(payload, &jsonPayload)
if err != nil {
// 如果不是有效的 JSON則視為純文字/數值 (Raw Value)
jsonPayload = string(payload)
}
bridgePayload := bridge.BridgePayload{
Type: msgType,
SerialNo: serialNo,
Payload: jsonPayload,
}
h.pusher.Push(bridgePayload)
}