本文整理汇总了Golang中git/eclipse/org/gitroot/paho/org/eclipse/paho/mqtt/golang/git.NewClient函数的典型用法代码示例。如果您正苦于以下问题:Golang NewClient函数的具体用法?Golang NewClient怎么用?Golang NewClient使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewClient函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: test_pub
func test_pub() {
//create a ClientOptions struct setting the broker address, clientid, turn
//off trace output
opts := MQTT.NewClientOptions().AddBroker(*uri)
opts.SetCleanSession(false)
opts.SetDefaultPublishHandler(default_msg_handler)
opts.SetClientID(*cid)
//create and start a client using the above ClientOptions
c := MQTT.NewClient(opts)
if token := c.Connect(); token.Wait() && token.Error() != nil {
panic(token.Error())
}
//Publish messages to topic at qos and wait for the receipt
//from the server after sending each message
for i := 0; i < *count; i++ {
text := fmt.Sprintf("%s #%d", *msg, i)
token := c.Publish(*topic, byte(*qos), false, text)
if token == nil {
fmt.Printf("Publish failed\n")
} else {
token.Wait()
fmt.Printf("Published msg qos[%d] topic[%s] payload[%s]\n",
*qos, *topic, text)
}
}
// Publish the end-of-test message
token := c.Publish(*topic, byte(*qos), false, end_of_test)
if token != nil {
token.Wait()
}
c.Disconnect(250)
}
开发者ID:vermoudakias,项目名称:mgpsrv,代码行数:35,代码来源:main.go
示例2: setupMQTT
// SetupMQTT : connect to server and register callbacks
func setupMQTT(config Config) {
fmt.Printf("username : %s", config.MQTT.Username)
if pass := config.MQTT.Password; pass == "" {
fmt.Println("No password given")
} else {
fmt.Printf("password: %s\n", config.MQTT.Password)
}
var server = fmt.Sprintf("tcp://%s:%s", config.MQTT.Host, config.MQTT.Port)
opts := MQTT.NewClientOptions().AddBroker(server)
opts.SetUsername(config.MQTT.Username)
opts.SetPassword(config.MQTT.Password)
opts.SetClientID(config.MQTT.ClientID)
c = MQTT.NewClient(opts)
if token := c.Connect(); token.Wait() && token.Error() != nil {
panic(token.Error())
} else {
fmt.Printf("connected to %s\n", server)
}
//defer c.Disconnect(250)
if token := c.Subscribe(config.MQTT.Topic, 0, f); token.Wait() && token.Error() != nil {
fmt.Println(token.Error())
os.Exit(1)
}
text := fmt.Sprintf("Hello from %s who just connected!", config.MQTT.ClientID)
token := c.Publish(config.MQTT.Topic, 0, false, text)
token.Wait()
time.Sleep(2 * time.Second)
}
开发者ID:tunebird,项目名称:fugidaire-server,代码行数:33,代码来源:fugimqtt.go
示例3: main
func main() {
//create a ClientOptions struct setting the broker address, clientid, turn
//off trace output and set the default message handler
opts := MQTT.NewClientOptions().AddBroker("tcp://nava.work:1883")
opts.SetClientID("go-simple")
opts.SetDefaultPublishHandler(f)
//create and start a client using the above ClientOptions
c := MQTT.NewClient(opts)
if token := c.Connect(); token.Wait() && token.Error() != nil {
panic(token.Error())
}
//subscribe to the topic /go-mqtt/sample and request messages to be delivered
//at a maximum qos of zero, wait for the receipt to confirm the subscription
//if token := c.Subscribe("go-mqtt/sample", 0, nil); token.Wait() && token.Error() != nil {
//fmt.Println(token.Error())
//os.Exit(1)
//}
//Publish 5 messages to /go-mqtt/sample at qos 1 and wait for the receipt
//from the server after sending each message
type payload struct {
Vendorid int
Value int
Jobid int
Siteid int
Cardid int
Timestamp string
}
for {
p := payload{
Cardid: rand.Intn(100),
Jobid: rand.Intn(5),
Siteid: rand.Intn(100),
Value: rand.Intn(100) * 10,
Vendorid: rand.Intn(2000),
Timestamp: time.Now().Format(time.RFC3339),
}
ret, _ := json.Marshal(p)
val := string(ret)
text := val
fmt.Println(text)
token := c.Publish("paybox", 0, false, text)
token.Wait()
//os.Exit(0)
time.Sleep(10 * time.Second)
}
//unsubscribe from /go-mqtt/sample
c.Disconnect(250)
}
开发者ID:satit13,项目名称:mqtt_pub_auto,代码行数:60,代码来源:mqtt_pub_forever.go
示例4: parser
func parser(cmd *cobra.Command, args []string) {
if verbose {
jww.SetStdoutThreshold(jww.LevelTrace)
}
opts := MQTT.NewClientOptions().AddBroker(viper.GetString("broker")).SetClientID("parser").SetCleanSession(true)
client := MQTT.NewClient(opts)
if token := client.Connect(); token.Wait() && token.Error() != nil {
jww.FATAL.Println(token.Error())
panic(token.Error())
}
defer client.Disconnect(0)
fi, err := os.Stat(viper.GetString("port"))
if err != nil {
jww.FATAL.Println(err)
panic(err)
}
if fi.Mode()&os.ModeType != 0 {
serialLoop(client)
} else {
file, err := os.Open(viper.GetString("port"))
if err != nil {
jww.FATAL.Println(err)
panic(err)
}
defer file.Close()
loop(file, client)
}
}
开发者ID:geoffholden,项目名称:gowx,代码行数:30,代码来源:parser.go
示例5: main
func main() {
opts := MQTT.NewClientOptions().AddBroker("tcp://test.mosquitto.org:1883").SetClientId("trivial")
opts.SetDefaultPublishHandler(f)
c := MQTT.NewClient(opts)
_, err := c.Start()
if err != nil {
panic(err)
}
filter, _ := MQTT.NewTopicFilter("/go-mqtt/sample", 0)
if receipt, err := c.StartSubscription(nil, filter); err != nil {
fmt.Println(err)
os.Exit(1)
} else {
<-receipt
}
for i := 0; i < 5; i++ {
text := fmt.Sprintf("this is msg #%d!", i)
receipt := c.Publish(MQTT.QOS_ONE, "/go-mqtt/sample", []byte(text))
<-receipt
}
time.Sleep(3 * time.Second)
if receipt, err := c.EndSubscription("/go-mqtt/sample"); err != nil {
fmt.Println(err)
os.Exit(1)
} else {
<-receipt
}
c.Disconnect(250)
}
开发者ID:aun-signage,项目名称:aun-receiver,代码行数:35,代码来源:simple.go
示例6: setupWillSubscriber
// setupWillSubscriber start subscriber process and returnes a channel witch can receive will message.
func setupWillSubscriber(gw *gateway.Gateway, broker *broker.Broker) (chan MQTT.Message, inidef.Error) {
// Setup MQTT pub/sub client to confirm published content.
//
messageOutputChannel := make(chan MQTT.Message)
opts := MQTT.NewClientOptions()
brokerUrl := fmt.Sprintf("tcp://%s:%d", broker.Host, broker.Port)
opts.AddBroker(brokerUrl)
opts.SetClientID(gw.Name + "testSubscriber") // to distinguish MQTT client from publisher
opts.SetCleanSession(false)
opts.SetDefaultPublishHandler(func(client *MQTT.Client, msg MQTT.Message) {
messageOutputChannel <- msg
})
client := MQTT.NewClient(opts)
if client == nil {
return nil, inidef.Error("NewClient failed")
}
if token := client.Connect(); token.Wait() && token.Error() != nil {
return nil, inidef.Error(fmt.Sprintf("NewClient Start failed %q", token.Error()))
}
qos := 0
// assume topicPrefix == ""
willTopic := fmt.Sprintf("/%s/will", gw.Name)
client.Subscribe(willTopic, byte(qos), func(client *MQTT.Client, msg MQTT.Message) {
messageOutputChannel <- msg
})
return messageOutputChannel, inidef.Error("")
}
开发者ID:chansuke,项目名称:fuji,代码行数:32,代码来源:will_test.go
示例7: MQTTConnect
// MQTTConnect returns MQTTClient with options.
func MQTTConnect(gwName string, b *Broker) (*MQTT.Client, error) {
opts := MQTT.NewClientOptions()
defaulturl := fmt.Sprintf("tcp://%s:%d", b.Host, b.Port)
if b.Tls {
defaulturl := fmt.Sprintf("ssl://%s:%d", b.Host, b.Port)
opts.AddBroker(defaulturl)
opts.SetClientID(gwName)
opts.SetTLSConfig(b.TLSConfig)
} else {
opts.AddBroker(defaulturl)
opts.SetClientID(gwName)
}
log.Infof("broker connecting to: %v", defaulturl)
opts.SetUsername(b.Username)
opts.SetPassword(b.Password)
if !inidef.IsNil(b.WillMessage) {
willTopic := strings.Join([]string{b.TopicPrefix, gwName, "will"}, "/")
willQoS := 0
opts.SetBinaryWill(willTopic, b.WillMessage, byte(willQoS), true)
}
opts.SetOnConnectHandler(b.SubscribeOnConnect)
opts.SetConnectionLostHandler(b.onConnectionLost)
client := MQTT.NewClient(opts)
return client, nil
}
开发者ID:chansuke,项目名称:fuji,代码行数:29,代码来源:broker.go
示例8: publishMqtt
func publishMqtt() {
opts := mqtt.NewClientOptions()
opts.SetBroker(*broker)
opts.SetClientId("pinpad-main")
opts.SetCleanSession(true)
opts.SetTraceLevel(mqtt.Off)
opts.SetOnConnectionLost(func(client *mqtt.MqttClient, err error) {
fmt.Printf("lost mqtt connection, trying to reconnect: %s\n", err)
client.Start()
})
client := mqtt.NewClient(opts)
_, err := client.Start()
if err != nil {
fmt.Printf("could not connect to mqtt broker: %s\n", err)
return
}
var msg string
if newStatus.Open {
msg = "\"open\""
} else {
msg = "\"closed\""
}
mqttMsg := mqtt.NewMessage([]byte(msg))
mqttMsg.SetQoS(mqtt.QOS_ONE)
mqttMsg.SetRetainedFlag(true)
r := client.PublishMessage(*topic, mqttMsg)
<-r
lastPublishedStatus = newStatus
client.ForceDisconnect()
}
开发者ID:else,项目名称:pinpad-controller,代码行数:35,代码来源:controller.go
示例9: main
func main() {
config := &serial.Config{Name: "/dev/tty.usbmodem1411", Baud: 57600}
s, err := serial.OpenPort(config)
if err != nil {
panic(err)
}
opts := MQTT.NewClientOptions().AddBroker("tcp://46.101.145.61:1883")
opts.SetClientID("meteo-studio")
// Connect MQTT client
c := MQTT.NewClient(opts)
if token := c.Connect(); token.Wait() && token.Error() != nil {
panic(token.Error())
}
// Loop over serial port lines
scanner := bufio.NewScanner(s)
for scanner.Scan() {
parts := strings.Split(scanner.Text(), "|")
if parts[0] == "6" {
// if command is "6" (meteo data payload), push it to the broker
token := c.Publish("studio/meteo", 0, false, parts[1])
token.Wait()
}
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "reading standard input:", err)
}
}
开发者ID:jvelo,项目名称:go-serial-to-mqtt,代码行数:30,代码来源:serial-to-mqtt.go
示例10: setupRetainSubscriber
// setupRetainSubscriber returnes channel in order to read messages with retained flag
func setupRetainSubscriber(gw *gateway.Gateway, broker *broker.Broker, dummyDevice *device.DummyDevice) (chan [2]string, inidef.Error) {
// Setup MQTT pub/sub client to confirm published content.
//
messageOutputChannel := make(chan [2]string)
opts := MQTT.NewClientOptions()
brokerUrl := fmt.Sprintf("tcp://%s:%d", broker.Host, broker.Port)
opts.AddBroker(brokerUrl)
opts.SetClientID(gw.Name + "testSubscriber") // to distinguish MQTT client from publisher
opts.SetCleanSession(false)
opts.SetDefaultPublishHandler(func(client *MQTT.Client, msg MQTT.Message) {
messageOutputChannel <- [2]string{msg.Topic(), string(msg.Payload())}
})
client := MQTT.NewClient(opts)
if client == nil {
return nil, inidef.Error("NewClient failed")
}
if token := client.Connect(); token.Wait() && token.Error() != nil {
return nil, inidef.Error(fmt.Sprintf("NewClient Start failed %q", token.Error()))
}
qos := 0
retainedTopic := fmt.Sprintf("%s/%s/%s/%s", broker.TopicPrefix, gw.Name, dummyDevice.Name, dummyDevice.Type)
client.Subscribe(retainedTopic, byte(qos), func(client *MQTT.Client, msg MQTT.Message) {
})
return messageOutputChannel, inidef.Error("")
}
开发者ID:taoyonggang,项目名称:fuji,代码行数:30,代码来源:retain_test.go
示例11: DoAccess
func (d *Device) DoAccess() error {
logger := log.New(os.Stdout, "", log.LstdFlags)
MQTT.ERROR = logger
MQTT.CRITICAL = logger
MQTT.WARN = logger
MQTT.DEBUG = logger
//create a ClientOptions struct setting the broker address, clientid, turn
//off trace output and set the default message handler
opts := MQTT.NewClientOptions().AddBroker("tls://" + d.access)
clientid := fmt.Sprintf("%x", d.id)
opts.SetClientID(clientid)
opts.SetUsername(clientid) // clientid as username
opts.SetPassword(hex.EncodeToString(d.token))
opts.SetKeepAlive(30 * time.Second)
opts.SetDefaultPublishHandler(d.messageHandler)
opts.SetTLSConfig(&tls.Config{Certificates: nil, InsecureSkipVerify: true})
//create and start a client using the above ClientOptions
c := MQTT.NewClient(opts)
if token := c.Connect(); token.Wait() && token.Error() != nil {
return token.Error()
}
// beigin report event test
go d.reportEvent(c)
// we just pause here to wait for messages
<-make(chan int)
defer c.Disconnect(250)
return nil
}
开发者ID:lg0491986,项目名称:pando-cloud,代码行数:34,代码来源:device.go
示例12: main
func main() {
tlsconfig := NewTlsConfig()
opts := MQTT.NewClientOptions()
opts.AddBroker("ssl://hushbox.net:17004")
opts.SetClientId("ssl-sample").SetTlsConfig(tlsconfig)
opts.SetDefaultPublishHandler(f)
// Start the connection
c := MQTT.NewClient(opts)
_, err := c.Start()
if err != nil {
panic(err)
}
filter, _ := MQTT.NewTopicFilter("/go-mqtt/sample", 0)
c.StartSubscription(nil, filter)
i := 0
for _ = range time.Tick(time.Duration(1) * time.Second) {
if i == 5 {
break
}
text := fmt.Sprintf("this is msg #%d!", i)
c.Publish(MQTT.QOS_ZERO, "/go-mqtt/sample", []byte(text))
i++
}
c.Disconnect(250)
}
开发者ID:aun-signage,项目名称:aun-receiver,代码行数:30,代码来源:ssl.go
示例13: mqttClient
func mqttClient(mqttUrl string) (*MQTT.MqttClient, error) {
opts := MQTT.NewClientOptions()
opts.AddBroker(mqttUrl)
opts.SetCleanSession(true)
opts.SetClientId(clientId())
opts.SetOnConnectionLost(func(client *MQTT.MqttClient, reason error) {
log.Fatal("MQTT CONNECTION LOST", reason) // TODO reconnect
})
parsed, err := url.Parse(mqttUrl)
if err != nil {
return nil, err
}
if user := parsed.User; user != nil {
if username := user.Username(); username != "" {
opts.SetUsername(username)
}
if password, set := user.Password(); set {
opts.SetPassword(password)
}
}
client := MQTT.NewClient(opts)
_, err = client.Start()
if err != nil {
return nil, err
}
return client, nil
}
开发者ID:aun-signage,项目名称:aun-receiver,代码行数:31,代码来源:main.go
示例14: main
func main() {
myNoOpStore := &NoOpStore{}
opts := MQTT.NewClientOptions()
opts.AddBroker("tcp://iot.eclipse.org:1883")
opts.SetClientID("custom-store")
opts.SetStore(myNoOpStore)
var callback MQTT.MessageHandler = func(client *MQTT.Client, msg MQTT.Message) {
fmt.Printf("TOPIC: %s\n", msg.Topic())
fmt.Printf("MSG: %s\n", msg.Payload())
}
c := MQTT.NewClient(opts)
if token := c.Connect(); token.Wait() && token.Error() != nil {
panic(token.Error())
}
c.Subscribe("/go-mqtt/sample", 0, callback)
for i := 0; i < 5; i++ {
text := fmt.Sprintf("this is msg #%d!", i)
token := c.Publish("/go-mqtt/sample", 0, false, text)
token.Wait()
}
for i := 1; i < 5; i++ {
time.Sleep(1 * time.Second)
}
c.Disconnect(250)
}
开发者ID:lg0491986,项目名称:pando-cloud,代码行数:32,代码来源:custom_store.go
示例15: main
func main() {
/*
* MQTT setup
*/
opts := MQTT.NewClientOptions().AddBroker("tcp://localhost:1883")
opts.SetClientID("golirc")
mc := MQTT.NewClient(opts)
if token := mc.Connect(); token.Wait() && token.Error() != nil {
panic(token.Error())
}
/*
* LIRC setup
*/
ir, err := lirc.Init("/var/run/lirc/lircd")
if err != nil {
panic(err)
}
ir.Handle("", "BTN_0", makeHandler(mc, "0"))
ir.Handle("", "BTN_1", makeHandler(mc, "1"))
ir.Handle("", "BTN_2", makeHandler(mc, "2"))
ir.Handle("", "BTN_3", makeHandler(mc, "3"))
go ir.Run()
select {}
}
开发者ID:gordyf,项目名称:golirc,代码行数:31,代码来源:ir.go
示例16: main
func main() {
opts := MQTT.NewClientOptions().AddBroker("tcp://iot.eclipse.org:1883").SetClientID("gotrivial")
opts.SetDefaultPublishHandler(f)
c := MQTT.NewClient(opts)
if token := c.Connect(); token.Wait() && token.Error() != nil {
panic(token.Error())
}
if token := c.Subscribe("/go-mqtt/sample", 0, nil); token.Wait() && token.Error() != nil {
fmt.Println(token.Error())
os.Exit(1)
}
for i := 0; i < 5; i++ {
text := fmt.Sprintf("this is msg #%d!", i)
token := c.Publish("/go-mqtt/sample", 0, false, text)
token.Wait()
}
time.Sleep(3 * time.Second)
if token := c.Unsubscribe("/go-mqtt/sample"); token.Wait() && token.Error() != nil {
fmt.Println(token.Error())
os.Exit(1)
}
c.Disconnect(250)
}
开发者ID:lg0491986,项目名称:pando-cloud,代码行数:29,代码来源:simple.go
示例17: main
func main() {
myNoOpStore := &NoOpStore{}
opts := MQTT.NewClientOptions()
opts.AddBroker("tcp://test.mosquitto.org:1883")
opts.SetClientId("custom-store")
opts.SetStore(myNoOpStore)
var callback MQTT.MessageHandler = func(client *MQTT.MqttClient, msg MQTT.Message) {
fmt.Printf("TOPIC: %s\n", msg.Topic())
fmt.Printf("MSG: %s\n", msg.Payload())
}
c := MQTT.NewClient(opts)
_, err := c.Start()
if err != nil {
panic(err)
}
filter, _ := MQTT.NewTopicFilter("/go-mqtt/sample", 0)
c.StartSubscription(callback, filter)
for i := 0; i < 5; i++ {
text := fmt.Sprintf("this is msg #%d!", i)
c.Publish(MQTT.QOS_ONE, "/go-mqtt/sample", []byte(text))
}
for i := 1; i < 5; i++ {
time.Sleep(1 * time.Second)
}
c.Disconnect(250)
}
开发者ID:aun-signage,项目名称:aun-receiver,代码行数:33,代码来源:custom_store.go
示例18: main
func main() {
opts := MQTT.NewClientOptions().AddBroker("tcp://lite.mqtt.shiguredo.jp:1883")
opts.SetDefaultPublishHandler(f)
opts.SetOnConnectHandler(onConnect)
opts.SetCleanSession(true)
opts.SetUsername("[email protected]")
opts.SetPassword("8Ub6F68kfYlr7RoV")
c := MQTT.NewClient(opts)
if token := c.Connect(); token.Wait() && token.Error() != nil {
panic(token.Error())
}
qos := 0
retain := false
payload := "sanple"
topic := "[email protected]/log"
token := c.Publish(topic, byte(qos), retain, payload)
// token.Wait()
fmt.Println("%v", token.Error())
for {
time.Sleep(1 * time.Second)
}
}
开发者ID:rzagabe,项目名称:telegraf,代码行数:26,代码来源:sango.go
示例19: main
func main() {
tlsconfig := NewTLSConfig()
opts := MQTT.NewClientOptions()
opts.AddBroker("ssl://iot.eclipse.org:8883")
opts.SetClientID("ssl-sample").SetTLSConfig(tlsconfig)
opts.SetDefaultPublishHandler(f)
// Start the connection
c := MQTT.NewClient(opts)
if token := c.Connect(); token.Wait() && token.Error() != nil {
panic(token.Error())
}
c.Subscribe("/go-mqtt/sample", 0, nil)
i := 0
for _ = range time.Tick(time.Duration(1) * time.Second) {
if i == 5 {
break
}
text := fmt.Sprintf("this is msg #%d!", i)
c.Publish("/go-mqtt/sample", 0, false, text)
i++
}
c.Disconnect(250)
}
开发者ID:lg0491986,项目名称:pando-cloud,代码行数:28,代码来源:ssl.go
示例20: connectToHub
// connectToHub sets up an MQTT client and registers as a "jet/..." client.
// Uses last-will to automatically unregister on disconnect. This returns a
// "topic notifier" channel to allow updating the registered status value.
func connectToHub(clientName, port string, retain bool) chan<- interface{} {
// add a "fairly random" 6-digit suffix to make the client name unique
nanos := time.Now().UnixNano()
clientID := fmt.Sprintf("%s/%06d", clientName, nanos%1e6)
options := mqtt.NewClientOptions()
options.AddBroker(port)
options.SetClientID(clientID)
options.SetKeepAlive(10)
options.SetBinaryWill(clientName+"/"+clientID, nil, 1, retain)
hub = mqtt.NewClient(options)
if t := hub.Connect(); t.Wait() && t.Error() != nil {
log.Fatal(t.Error())
}
if retain {
log.Println("connected as", clientID, "to", port)
}
// register as jet client, cleared on disconnect by the will
feed := topicNotifier("jet/"+clientID, retain)
feed <- 0 // start off with state "0" to indicate connection
// return a topic feed to allow publishing hub status changes
return feed
}
开发者ID:tht,项目名称:avr-structparser,代码行数:30,代码来源:main.go
注:本文中的git/eclipse/org/gitroot/paho/org/eclipse/paho/mqtt/golang/git.NewClient函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论