示例#1
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 {
	}

}
示例#2
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)
}
示例#3
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)
}
示例#4
0
// Connect returns true if connection to mqtt is established
func (a *Adaptor) Connect() (err error) {
	a.client = paho.NewClient(createClientOptions(a.clientID, a.Host, a.username, a.password))
	if token := a.client.Connect(); token.Wait() && token.Error() != nil {
		err = multierror.Append(err, token.Error())
	}

	return
}
示例#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))
}
示例#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
}
示例#7
0
func main() {
	//MQTT.DEBUG = log.New(os.Stdout, "", 0)
	//MQTT.ERROR = log.New(os.Stdout, "", 0)
	c := make(chan os.Signal, 1)
	i = 0
	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")
	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.ClientOptions{
		ClientID:             *clientid,
		CleanSession:         true,
		Username:             *username,
		Password:             *password,
		MaxReconnectInterval: 1 * time.Second,
		KeepAlive:            30 * time.Second,
		TLSConfig:            tls.Config{InsecureSkipVerify: true, ClientAuth: tls.NoClientCert},
	}
	connOpts.AddBroker(*server)
	connOpts.OnConnect = func(c MQTT.Client) {
		if token := c.Subscribe(*topic, byte(*qos), onMessageReceived); token.Wait() && token.Error() != nil {
			panic(token.Error())
		}
	}

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

	for {
		time.Sleep(1 * time.Second)
	}
}
示例#8
0
// connects MQTT broker
func connect(opts *MQTT.ClientOptions) (MQTT.Client, error) {

	opts.SetOnConnectHandler(SubscribeOnConnect)
	opts.SetConnectionLostHandler(ConnectionLost)

	m := MQTT.NewClient(opts)

	log.Info("connecting...")

	if token := m.Connect(); token.Wait() && token.Error() != nil {
		return m, token.Error()
	}

	return m, nil
}
示例#9
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}
}
示例#10
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)
}
示例#11
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)
}
示例#12
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())
			}
		}
	}

}
示例#13
0
文件: mqtt.go 项目: jeichorn/telegraf
func (m *MQTT) Connect() error {
	var err error
	m.Lock()
	defer m.Unlock()
	if m.QoS > 2 || m.QoS < 0 {
		return fmt.Errorf("MQTT Output, invalid QoS value: %d", m.QoS)
	}

	m.opts, err = m.createOpts()
	if err != nil {
		return err
	}

	m.client = paho.NewClient(m.opts)
	if token := m.client.Connect(); token.Wait() && token.Error() != nil {
		return token.Error()
	}

	return nil
}
示例#14
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)
	}
}
示例#15
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")
	}
}