package main import ( "encoding/json" "fmt" "os" "time" mqtt "github.com/eclipse/paho.mqtt.golang" ) func main() { broker := "wss://broker.emqx.io:8084/mqtt" clientID := "Mqttx_07c4e9ed" username := "1" password := "1" topic := "$dp" opts := mqtt.NewClientOptions() opts.AddBroker(broker) opts.SetClientID(clientID) opts.SetUsername(username) opts.SetPassword(password) opts.SetProtocolVersion(4) opts.SetKeepAlive(60 * time.Second) opts.SetAutoReconnect(true) opts.SetCleanSession(true) c := mqtt.NewClient(opts) if t := c.Connect(); t.Wait() && t.Error() != nil { fmt.Printf("connect error: %v\n", t.Error()) os.Exit(1) } defer c.Disconnect(250) // 构造所需数据格式(仅设备与时间变更) payload := map[string]any{ "type": "hws", "device": "Z866", "Dm": 0.0001, "Pa": 976.7, "Rc": 0, "Sm": 0.0001, "Ta": 39, "Ua": 26.6, "time": time.Now().UnixMilli(), } b, _ := json.Marshal(payload) if t := c.Publish(topic, 1, false, b); t.Wait() && t.Error() != nil { fmt.Printf("publish error: %v\n", t.Error()) os.Exit(2) } fmt.Println("published to", topic) }