func mqttWorker(c *client.Client) { // Subscribe to topics. err := c.Subscribe(&client.SubscribeOptions{ SubReqs: []*client.SubReq{ &client.SubReq{ TopicFilter: []byte("fgdata"), QoS: mqtt.QoS0, // Define the processing of the message handler. Handler: func(topicName, message []byte) { wmux.Lock() fgdata = string(message) lastseen = time.Now().String() wmux.Unlock() }, }, &client.SubReq{ TopicFilter: []byte("light1"), QoS: mqtt.QoS0, // Define the processing of the message handler. Handler: func(topicName, message []byte) { wmux.Lock() light1 = string(message) light1ls = time.Now().String() wmux.Unlock() }, }, }, }) if err != nil { fmt.Println("Error", err) } }
func StartMQTTSender(MQTTServerAddress string, MQTTSendChan chan *lib.PostMessage, channel_name string) chan bool { close_chan := make(chan bool) go func() { defer func() { if err := recover(); err != nil { utils.Log.Println(err) debug.PrintStack() } }() var post_message *lib.PostMessage var cli *client.Client var err error cli, err = ConnectToMQTTServer(MQTTServerAddress) if err != nil { utils.Log.Println("Connect to MQTT Server failed:", err) return } for { select { case <-close_chan: close_chan <- true utils.Log.Printf("Quit MQTT Sender worker.") return case post_message = <-MQTTSendChan: message_json_buffer, err := ffjson.Marshal(post_message) if err != nil { utils.Log.Println() } err = cli.Publish(&client.PublishOptions{ QoS: mqtt.QoS0, TopicName: []byte(channel_name), Message: []byte(message_json_buffer), }) if err != nil { utils.Log.Println("Publish to MQTT Failed:", err) utils.Log.Println("Try to connect MQTT Server.") cli, err = ConnectToMQTTServer(MQTTServerAddress) if err != nil { utils.Log.Println("Connect to MQTT Server failed:", err) } } utils.Log.Printf("Send message to MQTT Server: %s, Length: %d\n", MQTTServerAddress, len(message_json_buffer)) ffjson.Pool(message_json_buffer) } } }() return close_chan }
// quit quits this process. func quit(cli *client.Client) { // Disconnect the Network Connection. cli.Disconnect() // Terminate the Client. cli.Terminate() // Exit. exit(0) }