Ejemplo n.º 1
0
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)
}
Ejemplo n.º 2
0
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)
}
Ejemplo n.º 3
0
func StartRecording(c *cli.Context) {
	url := createUrl(c.GlobalString("url"), c.GlobalInt("port"))
	file, err := os.Create(c.GlobalString("record"))
	if err != nil {
		log.Fatal(err)
	}
	topic := c.GlobalString("topic")

	opts := MQTT.NewClientOptions()
	opts.AddBroker(url)

	receiver := MQTT.NewClient(opts)
	if token := receiver.Connect(); token.Wait() && token.Error() != nil {
		log.Fatal(token.Error())
	}
	exitSignalCh := make(chan os.Signal)
	signal.Notify(exitSignalCh, os.Interrupt)
	signal.Notify(exitSignalCh, syscall.SIGTERM)

	recoderCh := newRecoder(file, exitSignalCh)
	f := func(receiver MQTT.Client, msg MQTT.Message) {
		recoderCh <- msg
	}

	if token := receiver.Subscribe(topic, 1, f); token.Wait() && token.Error() != nil {
		log.Fatal(token.Error())
	}

	for {
	}

}
Ejemplo n.º 4
0
func createClientOptions(clientID, raw, username, password string) *paho.ClientOptions {
	opts := paho.NewClientOptions()
	opts.AddBroker(raw)
	opts.SetClientID(clientID)
	if username != "" && password != "" {
		opts.SetPassword(password)
		opts.SetUsername(username)
	}
	opts.AutoReconnect = false
	return opts
}
Ejemplo n.º 5
0
func main() {
	opts := MQTT.NewClientOptions().AddBroker("tcp://localhost:1883")
	opts.SetClientID("backend")
	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())
	}
	defer c.Disconnect(250)

	subscribeBackend(c, "GamerDisconnect")
	subscribeBackend(c, "GamerJoined")

	// Setup Game
	game = initGame()
	//playerJoinedEvent = make(chan string)
	lock = sync.RWMutex{}
	/*
		go func() {
			for {
				time.Sleep(time.Second)
				fmt.Println(game.gamerStatus)
			}
		}()*/

	generateGamerId := func(w http.ResponseWriter, r *http.Request) {
		lock.Lock()
		defer lock.Unlock()

		for slot, status := range game.gamerStatus {
			if status == Unassigned {
				fmt.Fprintf(w, "%s", game.colors[slot])
				game.gamerStatus[slot] = WaitForJoin
				go joinGamer(slot)
				return
			}
		}

		fmt.Fprintf(w, "%d", -1) // no open slot
	}
	http.HandleFunc("/requestjoin", generateGamerId)

	log.Println("Starting Web Server")
	http.Handle("/", http.FileServer(http.Dir("./static")))
	go func() {
		time.Sleep(time.Second * 2)
		openSystemBrowser("http://localhost")
	}()
	log.Fatal(http.ListenAndServe(":80", nil))
}
Ejemplo n.º 6
0
// NewClient creates a new DefaultClient
func NewClient(ctx log.Interface, id, username, password string, brokers ...string) Client {
	if ctx == nil {
		ctx = log.Get()
	}

	mqttOpts := MQTT.NewClientOptions()

	for _, broker := range brokers {
		mqttOpts.AddBroker(broker)
	}

	mqttOpts.SetClientID(fmt.Sprintf("%s-%s", id, random.String(16)))
	mqttOpts.SetUsername(username)
	mqttOpts.SetPassword(password)

	// TODO: Some tuning of these values probably won't hurt:
	mqttOpts.SetKeepAlive(30 * time.Second)
	mqttOpts.SetPingTimeout(10 * time.Second)

	mqttOpts.SetCleanSession(true)

	mqttOpts.SetDefaultPublishHandler(func(client MQTT.Client, msg MQTT.Message) {
		ctx.Warnf("Received unhandled message: %v", msg)
	})

	var reconnecting bool

	mqttOpts.SetConnectionLostHandler(func(client MQTT.Client, err error) {
		ctx.Warnf("Disconnected (%s). Reconnecting...", err.Error())
		reconnecting = true
	})

	ttnClient := &DefaultClient{
		ctx:           ctx,
		subscriptions: make(map[string]MQTT.MessageHandler),
	}

	mqttOpts.SetOnConnectHandler(func(client MQTT.Client) {
		ctx.Info("Connected to MQTT")
		if reconnecting {
			for topic, handler := range ttnClient.subscriptions {
				ctx.Infof("Re-subscribing to topic: %s", topic)
				ttnClient.subscribe(topic, handler)
			}
			reconnecting = false
		}
	})

	ttnClient.mqtt = MQTT.NewClient(mqttOpts)

	return ttnClient
}
Ejemplo n.º 7
0
func NewPahoClient(options ClientOptions) Client {
	pahoOptions := paho.NewClientOptions()

	pahoOptions.AddBroker(options.Broker)
	pahoOptions.SetClientID(options.ClientId)
	pahoOptions.SetUsername(options.Username)
	pahoOptions.SetPassword(options.Password)

	pahoOptions.SetConnectionLostHandler(func(client paho.Client, err error) {
		options.OnConnectionLost(err)
	})

	newClient := paho.NewClient(pahoOptions)

	return &pahoClient{client: &newClient}
}
Ejemplo n.º 8
0
// newOption returns ClientOptions via parsing command line options.
func newOption(c *cli.Context) (*MQTT.ClientOptions, error) {
	opts := MQTT.NewClientOptions()

	host := c.String("host")
	port := c.Int("p")

	opts.SetClientID(getRandomClientId())

	scheme := "tcp"
	brokerUri := fmt.Sprintf("%s://%s:%d", scheme, host, port)
	log.Infof("Broker URI: %s", brokerUri)
	opts.AddBroker(brokerUri)

	opts.SetAutoReconnect(true)
	return opts, nil
}
Ejemplo n.º 9
0
func main() {
	opts := MQTT.NewClientOptions().AddBroker("tcp://iot.eclipse.org:1883").SetClientID("router-sample")
	opts.SetCleanSession(true)

	c := MQTT.NewClient(opts)
	if token := c.Connect(); token.Wait() && token.Error() != nil {
		panic(token.Error())
	}

	if token := c.Subscribe("$SYS/broker/load/#", 0, brokerLoadHandler); token.Wait() && token.Error() != nil {
		fmt.Println(token.Error())
		os.Exit(1)
	}

	if token := c.Subscribe("$SYS/broker/connection/#", 0, brokerConnectionHandler); token.Wait() && token.Error() != nil {
		fmt.Println(token.Error())
		os.Exit(1)
	}

	if token := c.Subscribe("$SYS/broker/clients/#", 0, brokerClientsHandler); token.Wait() && token.Error() != nil {
		fmt.Println(token.Error())
		os.Exit(1)
	}

	loadCount := 0
	connectionCount := 0
	clientsCount := 0

	for i := 0; i < 100; i++ {
		select {
		case <-brokerLoad:
			loadCount++
		case <-brokerConnection:
			connectionCount++
		case <-brokerClients:
			clientsCount++
		}
	}

	fmt.Printf("Received %3d Broker Load messages\n", loadCount)
	fmt.Printf("Received %3d Broker Connection messages\n", connectionCount)
	fmt.Printf("Received %3d Broker Clients messages\n", clientsCount)

	c.Disconnect(250)
}
Ejemplo n.º 10
0
// createPahoClient creates a new paho client
func createPahoClient(host string, clientID string, username string, password string) paho.Client {
	opts := paho.NewClientOptions().AddBroker(host).SetClientID(clientID)
	opts.SetKeepAlive(300 * time.Second)
	opts.SetPingTimeout(20 * time.Second)
	opts.SetAutoReconnect(true)
	opts.SetConnectionLostHandler(func(client paho.Client, err error) {
		connectionLostHandler(client, err, host)
	})
	opts.SetOnConnectHandler(func(client paho.Client) {
		connectHandler(client, host)
	})

	if len(username) > 0 && len(password) > 0 {
		opts.SetUsername(username)
		opts.SetPassword(password)
	}

	return paho.NewClient(opts)
}
Ejemplo n.º 11
0
func PlayBack(c *cli.Context) {
	url := createUrl(c.GlobalString("url"), c.GlobalInt("port"))

	opts := MQTT.NewClientOptions()
	opts.AddBroker(url)

	sender := MQTT.NewClient(opts)
	if token := sender.Connect(); token.Wait() && token.Error() != nil {
		log.Fatal(token.Error())
	}
	playLoop := c.Bool("loop")
	loopCount := 0
	for playLoop || loopCount == 0 {
		loopCount++
		file, err := os.Open(c.GlobalString("record"))
		if err != nil {
			log.Fatal(err)
		}
		reader := bufio.NewScanner(file)
		fastForward := c.Bool("ff")
		var message message
		var previousTime time.Time
		firstRound := true
		for reader.Scan() {
			json.Unmarshal([]byte(reader.Text()), &message)
			if !fastForward {
				if !firstRound {
					toWait := message.Time.Sub(previousTime)
					previousTime = message.Time
					time.Sleep(toWait)
				} else {
					firstRound = false
					previousTime = message.Time
				}
			}
			fmt.Println(message.Payload)
			if token := sender.Publish(message.Topic, 1, false, message.Payload); token.Wait() && token.Error() != nil {
				fmt.Println(token.Error())
			}
		}
	}

}
Ejemplo n.º 12
0
func main() {
	//MQTT.DEBUG = log.New(os.Stdout, "", 0)
	//MQTT.ERROR = log.New(os.Stdout, "", 0)
	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)
		}
	}
	tlsConfig := &tls.Config{InsecureSkipVerify: true, ClientAuth: tls.NoClientCert}
	connOpts.SetTLSConfig(tlsConfig)

	client := MQTT.NewClient(connOpts)
	if token := client.Connect(); token.Wait() && token.Error() != nil {
		fmt.Println(token.Error())
		return
	}
	fmt.Printf("Connected to %s\n", *server)

	for {
		message, err := stdin.ReadString('\n')
		if err == io.EOF {
			os.Exit(0)
		}
		client.Publish(*topic, byte(*qos), *retained, message)
	}
}
Ejemplo n.º 13
0
func (m *MQTT) createOpts() (*paho.ClientOptions, error) {
	opts := paho.NewClientOptions()

	opts.SetClientID("Telegraf-Output-" + internal.RandomString(5))

	tlsCfg, err := internal.GetTLSConfig(
		m.SSLCert, m.SSLKey, m.SSLCA, m.InsecureSkipVerify)
	if err != nil {
		return nil, err
	}

	scheme := "tcp"
	if tlsCfg != nil {
		scheme = "ssl"
		opts.SetTLSConfig(tlsCfg)
	}

	user := m.Username
	if user != "" {
		opts.SetUsername(user)
	}
	password := m.Password
	if password != "" {
		opts.SetPassword(password)
	}

	if len(m.Servers) == 0 {
		return opts, fmt.Errorf("could not get host infomations")
	}
	for _, host := range m.Servers {
		server := fmt.Sprintf("%s://%s", scheme, host)

		opts.AddBroker(server)
	}
	opts.SetAutoReconnect(true)
	return opts, nil
}
Ejemplo n.º 14
0
func main() {
	topic := flag.String("topic", "", "The topic name to/from which to publish/subscribe")
	broker := flag.String("broker", "tcp://iot.eclipse.org:1883", "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", "testgoid", "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 *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)
		if token := client.Connect(); token.Wait() && token.Error() != nil {
			panic(token.Error())
		}
		fmt.Println("Sample Publisher Started")
		for i := 0; i < *num; i++ {
			fmt.Println("---- doing publish ----")
			token := client.Publish(*topic, byte(*qos), false, *payload)
			token.Wait()
		}

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

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

		client := MQTT.NewClient(opts)
		if token := client.Connect(); token.Wait() && token.Error() != nil {
			panic(token.Error())
		}

		if token := client.Subscribe(*topic, byte(*qos), nil); token.Wait() && token.Error() != nil {
			fmt.Println(token.Error())
			os.Exit(1)
		}

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

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