Ejemplo n.º 1
0
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)
}
Ejemplo n.º 2
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)
}
Ejemplo n.º 3
0
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)
}
Ejemplo n.º 4
0
func main() {
	opts := MQTT.NewClientOptions().AddBroker("tcp://test.mosquitto.org:1883").SetClientId("router-sample")
	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)
}
Ejemplo n.º 5
0
func (p *MQTTPublisher) configureMqttConnection() {
	connOpts := MQTT.NewClientOptions().
		AddBroker(p.config.URL).
		SetClientId(p.clientId).
		SetCleanSession(true).
		SetOnConnectionLost(p.onConnectionLost)

	// Username/password authentication
	if p.config.Username != "" && p.config.Password != "" {
		connOpts.SetUsername(p.config.Username)
		connOpts.SetPassword(p.config.Password)
	}

	// SSL/TLS
	if strings.HasPrefix(p.config.URL, "ssl") {
		tlsConfig := &tls.Config{}
		// Custom CA to auth broker with a self-signed certificate
		if p.config.CaFile != "" {
			caFile, err := ioutil.ReadFile(p.config.CaFile)
			if err != nil {
				logger.Printf("MQTTPublisher.configureMqttConnection() ERROR: failed to read CA file %s:%s\n", p.config.CaFile, err.Error())
			} else {
				tlsConfig.RootCAs = x509.NewCertPool()
				ok := tlsConfig.RootCAs.AppendCertsFromPEM(caFile)
				if !ok {
					logger.Printf("MQTTPublisher.configureMqttConnection() ERROR: failed to parse CA certificate %s\n", p.config.CaFile)
				}
			}
		}
		// Certificate-based client authentication
		if p.config.CertFile != "" && p.config.KeyFile != "" {
			cert, err := tls.LoadX509KeyPair(p.config.CertFile, p.config.KeyFile)
			if err != nil {
				logger.Printf("MQTTPublisher.configureMqttConnection() ERROR: failed to load client TLS credentials: %s\n",
					err.Error())
			} else {
				tlsConfig.Certificates = []tls.Certificate{cert}
			}
		}

		connOpts.SetTlsConfig(tlsConfig)
	}

	p.client = MQTT.NewClient(connOpts)
}
Ejemplo n.º 6
0
func main() {
	stdin := bufio.NewReader(os.Stdin)
	hostname, _ := os.Hostname()

	server := flag.String("server", "tcp://127.0.0.1:1883", "The full URL of the MQTT server to connect to")
	topic := flag.String("topic", hostname, "Topic to publish the messages on")
	qos := flag.Int("qos", 0, "The QoS to send the messages at")
	//retained := flag.Bool("retained", false, "Are the messages sent with the retained flag")
	clientid := flag.String("clientid", hostname+strconv.Itoa(time.Now().Second()), "A clientid for the connection")
	username := flag.String("username", "", "A username to authenticate to the MQTT server")
	password := flag.String("password", "", "Password to match username")
	flag.Parse()

	connOpts := MQTT.NewClientOptions().AddBroker(*server).SetClientId(*clientid).SetCleanSession(true)
	if *username != "" {
		connOpts.SetUsername(*username)
		if *password != "" {
			connOpts.SetPassword(*password)
		}
	}

	client := MQTT.NewClient(connOpts)
	_, err := client.Start()
	if err != nil {
		panic(err)
	} else {
		fmt.Printf("Connected to %s\n", *server)
	}

	for {
		message, err := stdin.ReadString('\n')
		if err == io.EOF {
			os.Exit(0)
		}
		r := client.Publish(MQTT.QoS(*qos), *topic, []byte(strings.TrimSpace(message)))
		<-r
		fmt.Println("Message Sent")
	}
}
Ejemplo n.º 7
0
func main() {
	topic := flag.String("topic", "", "The topic name to/from which to publish/subscribe")
	broker := flag.String("broker", "", "The broker URI. ex: tcp://10.10.1.1:1883")
	password := flag.String("password", "", "The password (optional)")
	user := flag.String("user", "", "The User (optional)")
	id := flag.String("id", "", "The ClientID (optional)")
	cleansess := flag.Bool("clean", false, "Set Clean Session (default false)")
	qos := flag.Int("qos", 0, "The Quality of Service 0,1,2 (default 0)")
	num := flag.Int("num", 1, "The number of messages to publish or subscribe (default 1)")
	payload := flag.String("message", "", "The message text to publish (default empty)")
	action := flag.String("action", "", "Action publish or subscribe (required)")
	store := flag.String("store", ":memory:", "The Store Directory (default use memory store)")
	flag.Parse()

	if *broker == "" {
		fmt.Println("Invalid setting for -broker")
		return
	}

	if *action != "pub" && *action != "sub" {
		fmt.Println("Invalid setting for -action, must be pub or sub")
		return
	}

	if *topic == "" {
		fmt.Println("Invalid setting for -topic, must not be empty")
		return
	}

	fmt.Printf("Sample Info:\n")
	fmt.Printf("\taction:    %s\n", *action)
	fmt.Printf("\tbroker:    %s\n", *broker)
	fmt.Printf("\tclientid:  %s\n", *id)
	fmt.Printf("\tuser:      %s\n", *user)
	fmt.Printf("\tpassword:  %s\n", *password)
	fmt.Printf("\ttopic:     %s\n", *topic)
	fmt.Printf("\tmessage:   %s\n", *payload)
	fmt.Printf("\tqos:       %d\n", *qos)
	fmt.Printf("\tcleansess: %v\n", *cleansess)
	fmt.Printf("\tnum:       %d\n", *num)
	fmt.Printf("\tstore:     %s\n", *store)

	opts := MQTT.NewClientOptions()
	opts.AddBroker(*broker)
	opts.SetClientId(*id)
	opts.SetUsername(*user)
	opts.SetPassword(*password)
	opts.SetCleanSession(*cleansess)
	if *store != ":memory:" {
		opts.SetStore(MQTT.NewFileStore(*store))
	}

	if *action == "pub" {
		client := MQTT.NewClient(opts)
		_, err := client.Start()
		gotareceipt := make(chan bool)
		if err != nil {
			panic(err)
		}
		fmt.Println("Sample Publisher Started")
		for i := 0; i < *num; i++ {
			fmt.Println("---- doing publish ----")
			receipt := client.Publish(MQTT.QoS(*qos), *topic, []byte(*payload))

			go func() {
				<-receipt
				fmt.Println("  message delivered!")
				gotareceipt <- true
			}()
		}

		for i := 0; i < *num; i++ {
			<-gotareceipt
		}

		client.Disconnect(250)
		fmt.Println("Sample Publisher Disconnected")
	} else {
		num_received := 0
		choke := make(chan [2]string)

		opts.SetDefaultPublishHandler(func(client *MQTT.MqttClient, msg MQTT.Message) {
			choke <- [2]string{msg.Topic(), string(msg.Payload())}
		})

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

		filter, e := MQTT.NewTopicFilter(*topic, byte(*qos))
		if e != nil {
			fmt.Println(e)
			os.Exit(1)
		}

		client.StartSubscription(nil, filter)

		for num_received < *num {
			incoming := <-choke
			fmt.Printf("RECEIVED TOPIC: %s MESSAGE: %s\n", incoming[0], incoming[1])
			num_received++
		}

		client.Disconnect(250)
		fmt.Println("Sample Subscriber Disconnected")
	}
}