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)
}
Exemple #2
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)
}
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)
}
Exemple #4
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)
}
Exemple #5
0
func Subscribe(client *MQTT.MqttClient, topic string) {
	filter, _ := MQTT.NewTopicFilter(topic, byte(MQTT.QOS_ZERO))
	if receipt, err := client.StartSubscription(f, filter); err != nil {
		fmt.Println(err)
		os.Exit(1)
	} else {
		<-receipt
	}
}
Exemple #6
0
func (b *Bus) listen() {
	b.log.Infof("connecting to the bus")

	opts := mqtt.NewClientOptions().AddBroker(b.conf.LocalUrl).SetClientId("mqtt-bridgeify-bus")

	b.client = mqtt.NewClient(opts)

	_, err := b.client.Start()
	if err != nil {
		b.log.Errorf("Can't start connection: %s", err)
	} else {
		b.log.Infof("Connected as %s\n", b.conf.LocalUrl)
	}

	topicFilter, _ := mqtt.NewTopicFilter(connectTopic, 0)
	if receipt, err := b.client.StartSubscription(b.handleConnect, topicFilter); err != nil {
		b.log.Errorf("Subscription Failed: %s", err)
		panic(err)
	} else {
		<-receipt
		b.log.Infof("Subscribed to: %+v", topicFilter)
	}

	topicFilter, _ = mqtt.NewTopicFilter(disconnectTopic, 0)
	if receipt, err := b.client.StartSubscription(b.handleDisconnect, topicFilter); err != nil {
		b.log.Errorf("Subscription Failed: %s", err)
		panic(err)
	} else {
		<-receipt
		b.log.Infof("Subscribed to: %+v", topicFilter)
	}

	ev := &statusEvent{Status: "started"}

	b.client.PublishMessage(statusTopic, b.encodeRequest(ev))

	b.setupBackgroundJob()

}
Exemple #7
0
func (m *MQTTClient) Subscribe(topic string, qos int) error {
	topicFilter, err := MQTT.NewTopicFilter(topic, byte(qos))
	if err != nil {
		return err
	}
	_, err = m.Client.StartSubscription(onMessageReceived, topicFilter)
	if err != nil {
		return err
	}

	for {
		time.Sleep(1 * time.Second)
	}
	return nil
}
func main() {
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt, syscall.SIGTERM)
	go func() {
		<-c
		fmt.Println("signal received, exiting")
		os.Exit(0)
	}()

	hostname, _ := os.Hostname()

	server := flag.String("server", "tcp://127.0.0.1:1883", "The full url of the MQTT server to connect to ex: tcp://127.0.0.1:1883")
	topic := flag.String("topic", "#", "Topic to subscribe to")
	qos := flag.Int("qos", 0, "The QoS to subscribe to 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().SetBroker(*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)
	}

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

	for {
		time.Sleep(1 * time.Second)
	}
}
func readFromMqttChannel(t *testing.T, wg *sync.WaitGroup) {
	log.Println("try to connect to MQTT for getting data")
	opts := MQTT.NewClientOptions().AddBroker("tcp://localhost:1883").SetClientId("myReader")

	c := MQTT.NewClient(opts)
	_, err := c.Start()
	log.Println("client connected")
	if err != nil {
		panic(err)
	}

	filter, _ := MQTT.NewTopicFilter("/mackristof/weather-mtp/davis1", 1)
	_, err = c.StartSubscription(onMessageReceived, filter)
	assert.Nil(t, err)
	for {
		time.Sleep(2 * time.Second)
		log.Println("sleeping for 2 sec")
	}
	c.Disconnect(250)
	wg.Done()
}
Exemple #10
0
func Subscribe(client *MQTT.MqttClient, topic string) error {
	topicName := config.user + "/" + topic
	// 無料枠はQoS 0のみ
	qos := 0

	// Subscribeするtopicを設定します
	topicFilter, err := MQTT.NewTopicFilter(topicName, byte(qos))
	if err != nil {
		return err
	}

	// Subscribeします
	// onMessageReceived はメッセージが届いたら呼び出されるコールバックです
	_, err = client.StartSubscription(onMessageReceived, topicFilter)
	if err != nil {
		return err
	}

	// そのままではプロセスが終わってしまいますので、待ち受けます
	for {
		time.Sleep(1 * time.Second)
	}
}
Exemple #11
0
func (self *Subscriber) addChannel(filter eventFilter, topics []string) eventChannel {
	// subscribe topics not yet subscribed to
	for _, topic := range topics {
		_, exists := self.topicCount[topic]
		if !exists {
			filter, _ := MQTT.NewTopicFilter(topicName(topic), 1)
			// fmt.Printf("StartSubscription: %+v\n", filter)
			// nil = all messages go to the default handler
			self.broker.client.StartSubscription(nil, filter)
		}
		self.topicCount[topic] += 1
	}

	ch := eventChannel{
		C:      make(chan *pubsub.Event, 16),
		filter: filter,
		topics: topics,
	}
	self.channelsLock.Lock()
	self.channels = append(self.channels, ch)
	self.channelsLock.Unlock()
	return ch
}
Exemple #12
0
// mainLoop initiates all ports and handles the traffic
func mainLoop() {
	openPorts()
	defer closePorts()

	waitCh := make(chan bool)
	go func() {
		total := 0
		for {
			v := <-outCh
			if !v {
				log.Println("An OUT port is closed. Interrupting execution")
				exitCh <- syscall.SIGTERM
				break
			} else {
				total++
			}
			// At least one output ports are opened
			if total >= 1 && waitCh != nil {
				waitCh <- true
			}
		}
	}()

	log.Println("Waiting for options to arrive...")
	var (
		ip            [][]byte
		clientOptions *mqtt.ClientOptions
		client        *mqtt.MqttClient
		defaultTopic  string
		qos           mqtt.QoS
	)

	// Setup socket poll items
	poller := zmq.NewPoller()
	poller.Add(optsPort, zmq.POLLIN)
	poller.Add(tmplPort, zmq.POLLIN)

	for {
		sockets, err := poller.Poll(-1)
		if err != nil {
			log.Println("Error polling ports:", err.Error())
			continue
		}
		for _, socket := range sockets {
			if socket.Socket == nil {
				log.Println("ERROR: could not find socket in polling items array")
				continue
			}
			ip, err = socket.Socket.RecvMessageBytes(0)
			if err != nil {
				log.Println("Error receiving message:", err.Error())
				continue
			}
			if !runtime.IsValidIP(ip) || !runtime.IsPacket(ip) {
				log.Println("Invalid IP:", ip)
				continue
			}
			switch socket.Socket {
			case optsPort:
				err = json.Unmarshal(ip[1], &options)
				if err != nil {
					log.Println("ERROR: failed to unmarshal options:", err.Error())
					continue
				}
				clientOptions, defaultTopic, qos, err = helper.ParseOptionsURI(options.OptionsURI)
				if err != nil {
					log.Printf("Failed to parse connection uri. Error: %s", err.Error())
					continue
				}
				log.Println("Options specified:", options)
			case tmplPort:
				err = json.Unmarshal(ip[1], &propTemplate)
				if err != nil {
					log.Println("ERROR: failed to unmarshal template:", err.Error())
					continue
				}
				log.Printf("Template specified: %+v", propTemplate)

			default:
				log.Println("ERROR: IP from unhandled socket received!")
				continue
			}

			if defaultTopic != "" && clientOptions != nil && propTemplate != nil {
				log.Println("Component configured. Moving on...")
				break
			}
		}

		client = mqtt.NewClient(clientOptions)
		if _, err = client.Start(); err != nil {
			log.Printf("Failed to create MQTT client. Error: %s", err.Error())
			continue
		}

		defer client.Disconnect(1e6)

		optsPort.Close()
		tmplPort.Close()
		break
	}

	log.Println("Started...")
	topicFilter, err := mqtt.NewTopicFilter(defaultTopic, byte(qos))
	utils.AssertError(err)
	_, err = client.StartSubscription(messageHandler, topicFilter)
	utils.AssertError(err)

	ticker := time.Tick(1 * time.Second)
	for _ = range ticker {
	}
}
Exemple #13
0
func TestPahoGoClient(t *testing.T) {
	var wg sync.WaitGroup

	ready1 := make(chan struct{})
	ready2 := make(chan struct{})

	uri := "tcp://127.0.0.1:1883"
	u, err := url.Parse(uri)
	require.NoError(t, err, "Error parsing URL")

	// Start listener
	wg.Add(1)
	go startServiceN(t, u, &wg, ready1, ready2, 1)

	<-ready1

	opts := MQTT.NewClientOptions().AddBroker("tcp://localhost:1883").SetClientId("trivial")
	opts.SetDefaultPublishHandler(f)

	c := MQTT.NewClient(opts)
	_, err = c.Start()
	require.NoError(t, err)

	filter, _ := MQTT.NewTopicFilter("/go-mqtt/sample", 0)
	receipt, err := c.StartSubscription(nil, filter)
	require.NoError(t, err)

	select {
	case <-receipt:

	case <-time.After(time.Millisecond * 100):
		require.FailNow(t, "Test timed out")
	}

	for i := 0; i < 100; i++ {
		text := fmt.Sprintf("this is msg #%d!", i)
		receipt := c.Publish(MQTT.QOS_ONE, "/go-mqtt/sample", []byte(text))

		select {
		case <-receipt:

		case <-time.After(time.Millisecond * 100):
			require.FailNow(t, "Test timed out")
		}
	}

	time.Sleep(3 * time.Second)

	receipt, err = c.EndSubscription("/go-mqtt/sample")
	require.NoError(t, err)

	select {
	case <-receipt:

	case <-time.After(time.Millisecond * 100):
		require.FailNow(t, "Test timed out")
	}

	c.Disconnect(250)

	close(ready2)

	wg.Wait()
}
Exemple #14
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")
	}
}