コード例 #1
0
ファイル: fugimqtt.go プロジェクト: tunebird/fugidaire-server
// 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)
}
コード例 #2
0
ファイル: main.go プロジェクト: vermoudakias/mgpsrv
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)
}
コード例 #3
0
ファイル: parser.go プロジェクト: geoffholden/gowx
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)
	}
}
コード例 #4
0
ファイル: custom_store.go プロジェクト: lg0491986/pando-cloud
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)
}
コード例 #5
0
ファイル: will_test.go プロジェクト: chansuke/fuji
// 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("")
}
コード例 #6
0
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)
}
コード例 #7
0
ファイル: simple.go プロジェクト: aun-signage/aun-receiver
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)
}
コード例 #8
0
ファイル: ssl.go プロジェクト: aun-signage/aun-receiver
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)
}
コード例 #9
0
ファイル: controller.go プロジェクト: else/pinpad-controller
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()
}
コード例 #10
0
ファイル: retain_test.go プロジェクト: taoyonggang/fuji
// 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("")
}
コード例 #11
0
ファイル: device.go プロジェクト: lg0491986/pando-cloud
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
}
コード例 #12
0
ファイル: ssl.go プロジェクト: lg0491986/pando-cloud
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)
}
コード例 #13
0
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)
	}
}
コード例 #14
0
ファイル: broker.go プロジェクト: chansuke/fuji
// 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
}
コード例 #15
0
ファイル: main.go プロジェクト: aun-signage/aun-receiver
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
}
コード例 #16
0
ファイル: simple.go プロジェクト: lg0491986/pando-cloud
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)
}
コード例 #17
0
ファイル: ir.go プロジェクト: gordyf/golirc
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 {}
}
コード例 #18
0
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)
}
コード例 #19
0
ファイル: sango.go プロジェクト: rzagabe/telegraf
func main() {
	opts := MQTT.NewClientOptions().AddBroker("tcp://lite.mqtt.shiguredo.jp:1883")
	opts.SetDefaultPublishHandler(f)
	opts.SetOnConnectHandler(onConnect)
	opts.SetCleanSession(true)

	opts.SetUsername("shirou@github")
	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 := "shirou@github/log"
	token := c.Publish(topic, byte(qos), retain, payload)
	//	token.Wait()
	fmt.Println("%v", token.Error())

	for {
		time.Sleep(1 * time.Second)
	}
}
コード例 #20
0
ファイル: main.go プロジェクト: tht/avr-structparser
// 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
}
コード例 #21
0
ファイル: mqtt-bench.go プロジェクト: RouGang/mqtt-bench
// 指定されたBrokerへ接続し、そのMQTTクライアントを返す。
// 接続に失敗した場合は nil を返す。
func Connect(id int, execOpts ExecOptions) *MQTT.Client {

	// 複数プロセスで、ClientIDが重複すると、Broker側で問題となるため、
	// プロセスIDを利用して、IDを割り振る。
	// mqttbench<プロセスIDの16進数値>-<クライアントの連番>
	pid := strconv.FormatInt(int64(os.Getpid()), 16)
	clientId := fmt.Sprintf("mqttbench%s-%d", pid, id)

	opts := MQTT.NewClientOptions()
	opts.AddBroker(execOpts.Broker)
	opts.SetClientID(clientId)

	if execOpts.Username != "" {
		opts.SetUsername(execOpts.Username)
	}
	if execOpts.Password != "" {
		opts.SetPassword(execOpts.Password)
	}

	// TLSの設定
	certConfig := execOpts.CertConfig
	switch c := certConfig.(type) {
	case ServerCertConfig:
		tlsConfig := CreateServerTlsConfig(c.ServerCertFile)
		opts.SetTLSConfig(tlsConfig)
	case ClientCertConfig:
		tlsConfig := CreateClientTlsConfig(c.RootCAFile, c.ClientCertFile, c.ClientKeyFile)
		opts.SetTLSConfig(tlsConfig)
	default:
		// do nothing.
	}

	if execOpts.UseDefaultHandler == true {
		// Apollo(1.7.1利用)の場合、DefaultPublishHandlerを指定しないと、Subscribeできない。
		// ただし、指定した場合でもretainされたメッセージは最初の1度しか取得されず、2回目以降のアクセスでは空になる点に注意。
		var result *SubscribeResult = &SubscribeResult{}
		result.Count = 0

		var handler MQTT.MessageHandler = func(client *MQTT.Client, msg MQTT.Message) {
			result.Count++
			if Debug {
				fmt.Printf("Received at defaultHandler : topic=%s, message=%s\n", msg.Topic(), msg.Payload())
			}
		}
		opts.SetDefaultPublishHandler(handler)

		DefaultHandlerResults[id] = result
	}

	client := MQTT.NewClient(opts)
	token := client.Connect()

	if token.Wait() && token.Error() != nil {
		fmt.Printf("Connected error: %s\n", token.Error())
		return nil
	}

	return client
}
コード例 #22
0
func StartMqttConnection() (*MQTT.MqttClient, *MQTT.ClientOptions, error) {
	opts := MQTT.NewClientOptions().AddBroker("tcp://test.mosquitto.org:1883").SetClientId("GolangWeatherStation")
	opts.SetOnConnectionLost(onMqttConnLost)
	c := MQTT.NewClient(opts)
	_, err := c.Start()
	mqttConnected = true
	return c, opts, err
}
コード例 #23
0
ファイル: gomqtt.go プロジェクト: Hades32/gomqtt
func createMqttOptsFromFlags() *mqtt.ClientOptions {
	opts := mqtt.NewClientOptions()
	opts.AddBroker(serverURL)
	opts.TLSConfig.InsecureSkipVerify = insecure
	if clientID != "" {
		opts.SetClientID(clientID)
	}
	return opts
}
コード例 #24
0
func main() {
	opts := MQTT.NewClientOptions().SetBroker("tcp://test.mosquitto.org:1883").SetClientId("router-sample")
	opts.SetTraceLevel(MQTT.Off)
	opts.SetCleanSession(true)

	c := MQTT.NewClient(opts)
	_, err := c.Start()
	if err != nil {
		panic(err)
	}

	loadFilter, _ := MQTT.NewTopicFilter("$SYS/broker/load/#", 0)
	if receipt, err := c.StartSubscription(brokerLoadHandler, loadFilter); err != nil {
		fmt.Println(err)
		os.Exit(1)
	} else {
		<-receipt
	}

	connectionFilter, _ := MQTT.NewTopicFilter("$SYS/broker/connection/#", 0)
	if receipt, err := c.StartSubscription(brokerConnectionHandler, connectionFilter); err != nil {
		fmt.Println(err)
		os.Exit(1)
	} else {
		<-receipt
	}

	clientsFilter, _ := MQTT.NewTopicFilter("$SYS/broker/clients/#", 0)
	if receipt, err := c.StartSubscription(brokerClientsHandler, clientsFilter); err != nil {
		fmt.Println(err)
		os.Exit(1)
	} else {
		<-receipt
	}

	num_bload := 0
	num_bconns := 0
	num_bclients := 0

	for i := 0; i < 100; i++ {
		select {
		case <-broker_load:
			num_bload++
		case <-broker_connection:
			num_bconns++
		case <-broker_clients:
			num_bclients++
		}
	}

	fmt.Printf("Received %3d Broker Load messages\n", num_bload)
	fmt.Printf("Received %3d Broker Connection messages\n", num_bconns)
	fmt.Printf("Received %3d Broker Clients messages\n", num_bclients)

	c.Disconnect(250)
}
コード例 #25
0
ファイル: bug-ping.go プロジェクト: rzagabe/telegraf
func main() {
	opts := MQTT.NewClientOptions().AddBroker("tcp://localhost:1883")
	c := MQTT.NewClient(opts)
	if token := c.Connect(); token.Wait() && token.Error() != nil {
		panic(token.Error())
	}
	for {
		time.Sleep(1 * time.Second)
	}
}
コード例 #26
0
ファイル: main.go プロジェクト: nablaone/golang-sandbox
func client(s string) *MQTT.Client {
	connOpts := MQTT.NewClientOptions().AddBroker(server).SetClientID(topic + s)

	client := MQTT.NewClient(connOpts)
	if t := client.Connect(); t.Wait() && t.Error() != nil {
		panic(t.Error())
	}
	return client

}
コード例 #27
0
ファイル: mqtt.go プロジェクト: wolfeidau/mqforward
//
// with Connects connect to the MQTT broker with Options.
func NewMqttClient(conf MqttConf, mqttChan chan Message, commandChan chan string) (*MqttClient, error) {
	opts := MQTT.NewClientOptions()

	port := conf.Port
	if port == 0 {
		port = 1883
	}
	scheme := "tcp"
	if port == 8883 {
		scheme = "ssl"
	}
	brokerUri := fmt.Sprintf("%s://%s:%d", scheme, conf.Hostname, port)
	log.Infof("Broker URI: %s", brokerUri)
	opts.AddBroker(brokerUri)

	if conf.Username != "" {
		opts.SetUsername(conf.Username)
	}
	if conf.Password != "" {
		opts.SetPassword(conf.Password)
	}

	clientId := getRandomClientId()
	opts.SetClientID(clientId)
	opts.SetAutoReconnect(true)

	topic := conf.Topic
	if strings.HasSuffix(topic, "#") == false {
		topic = topic + "#"
	}
	subscribed := map[string]byte{
		topic: byte(0),
	}

	ret := &MqttClient{
		Config:      conf,
		Subscribed:  subscribed,
		lock:        new(sync.Mutex),
		mqttChan:    mqttChan,
		commandChan: commandChan,
	}
	opts.SetOnConnectHandler(ret.SubscribeOnConnect)
	opts.SetConnectionLostHandler(ret.ConnectionLost)

	ret.Opts = opts

	client, err := ret.Connect(conf, opts, subscribed)
	if err != nil {
		return nil, err
	}
	ret.Client = client

	return ret, nil
}
コード例 #28
0
ファイル: client.go プロジェクト: RouGang/mqtt-benchmark
func (c *Client) pubMessages(in, out chan *Message, doneGen, donePub chan bool) {
	onConnected := func(client *mqtt.Client) {
		log.Printf("CLIENT %v is connected to the broker %v\n", c.ID, c.BrokerURL)
		ctr := 0
		for {
			select {
			case m := <-in:
				m.Sent = time.Now()
				token := client.Publish(m.Topic, m.QoS, false, m.Payload)
				token.Wait()
				if token.Error() != nil {
					log.Printf("CLIENT %v Error sending message: %v\n", c.ID, token.Error())
					m.Error = true
				} else {
					m.Delivered = time.Now()
					m.Error = false
				}
				out <- m

				if ctr > 0 && ctr%100 == 0 {
					log.Printf("CLIENT %v published %v messages and keeps publishing...\n", c.ID, ctr)
				}
				ctr++
			case <-doneGen:
				donePub <- true
				log.Printf("CLIENT %v is done publishing\n", c.ID)
				return
			}
		}
	}

	opts := mqtt.NewClientOptions().
		AddBroker(c.BrokerURL).
		SetClientID(fmt.Sprintf("mqtt-benchmark-%v-%v", time.Now(), c.ID)).
		SetCleanSession(true).
		SetAutoReconnect(true).
		SetOnConnectHandler(onConnected).
		SetConnectionLostHandler(func(client *mqtt.Client, reason error) {
			log.Printf("CLIENT %v lost connection to the broker: %v. Will reconnect...\n", c.ID, reason.Error())
		})
	if c.BrokerUser != "" && c.BrokerPass != "" {
		opts.SetUsername(c.BrokerUser)
		opts.SetPassword(c.BrokerPass)
	}
	client := mqtt.NewClient(opts)
	token := client.Connect()
	token.Wait()

	if token.Error() != nil {
		log.Printf("CLIENT %v had error connecting to the broker: %v\n", c.ID, token.Error())
	}
}
コード例 #29
0
ファイル: mqtt.go プロジェクト: sqrls/jolie
func ConnectPaho() (PacketHandler, error) {
	uri := os.Getenv("MQTT_BROKER")
	opts := MQTT.NewClientOptions().AddBroker(uri)
	opts.SetClientID("jolie")

	c := MQTT.NewClient(opts)
	if token := c.Connect(); token.Wait() && token.Error() != nil {
		return nil, token.Error()
	}
	log.Printf("Connected to %s", uri)

	return &MqttConsumer{c}, nil
}
コード例 #30
0
ファイル: aggregator.go プロジェクト: geoffholden/gowx
func aggregator(cmd *cobra.Command, args []string) {
	if verbose {
		jww.SetStdoutThreshold(jww.LevelTrace)
	}
	db, err := data.OpenDatabase()
	if err != nil {
		jww.FATAL.Println(err)
		panic(err)
	}

	dataChannel := make(chan data.SensorData)

	topic := "/gowx/sample"
	opts := MQTT.NewClientOptions().AddBroker(viper.GetString("broker")).SetClientID("aggregator").SetCleanSession(true)

	opts.OnConnect = func(c *MQTT.Client) {
		if token := c.Subscribe(topic, 0, func(client *MQTT.Client, msg MQTT.Message) {
			r := bytes.NewReader(msg.Payload())
			decoder := json.NewDecoder(r)
			var data data.SensorData
			err := decoder.Decode(&data)
			if err != nil {
				jww.ERROR.Println(err)
				return
			}
			dataChannel <- data
		}); token.Wait() && token.Error() != nil {
			jww.FATAL.Println(token.Error())
			panic(token.Error())
		}
	}

	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)

	ticker := time.NewTicker(time.Duration(viper.GetInt("interval")) * time.Second)

	thedata := make(map[mapKey][]float64)
	for {
		select {
		case <-ticker.C:
			sumData(&thedata, db)
		case d := <-dataChannel:
			addData(&thedata, d)
		}
	}
}