初始化项目

This commit is contained in:
BBIT-Kai
2026-05-26 13:53:23 +08:00
commit 7e803e2cdb
27 changed files with 1820 additions and 0 deletions
+64
View File
@@ -0,0 +1,64 @@
package model
import (
"errors"
"strings"
)
type MqttTopic struct {
DeptId string
Domain string
DeviceType string
DeviceID string
Resource string
}
// 从字符串解析成 MqttTopic
func FromStringToMqttTopic(topic string) *MqttTopic {
parts := strings.Split(topic, "/")
// 补齐不足的部分
for len(parts) < 5 {
parts = append(parts, "")
}
return &MqttTopic{
DeptId: parts[0],
Domain: parts[1],
DeviceType: parts[2],
DeviceID: parts[3],
Resource: parts[4],
}
}
// 从结构体生成 topic 字符串,可用 "+" 表示通配符
func (m *MqttTopic) ToString() string {
toVal := func(s string) string {
if s == "" {
return "+"
}
return s
}
return strings.Join([]string{
toVal(m.DeptId),
toVal(m.Domain),
toVal(m.DeviceType),
toVal(m.DeviceID),
toVal(m.Resource),
}, "/")
}
// 严格生成 topic,不允许 "+" 或空
func (m *MqttTopic) Build() (string, error) {
parts := []string{m.DeptId, m.Domain, m.DeviceType, m.DeviceID, m.Resource}
for _, p := range parts {
if p == "" || p == "+" {
return "", errors.New("cannot build strict topic, wildcard exists")
}
}
return strings.Join(parts, "/"), nil
}
// 判断是否为通配符 topic
func (m *MqttTopic) IsWildcard() bool {
topic := m.ToString()
return strings.Contains(topic, "+") || strings.Contains(topic, "#")
}