Exemple #1
0
/*
Forward message to MQTT server
*/
func ConnectToMQTTServer(MQTTServerAddress string) (*client.Client, error) {
	defer func() {
		if err := recover(); err != nil {
			utils.Log.Println(err)
			debug.PrintStack()
		}
	}()

	cli := client.New(&client.Options{
		ErrorHandler: func(err error) {
			utils.Log.Println("MQTT Client error:", err)
		},
	})

	var err error

	RandomID := utils.MakeRandomID()

	err = cli.Connect(&client.ConnectOptions{
		Network:         "tcp",
		Address:         MQTTServerAddress,
		ClientID:        []byte(RandomID),
		CleanSession:    true,
		PINGRESPTimeout: 5 * time.Second,
		KeepAlive:       5,
	})

	if err != nil {
		return nil, err
	}

	return cli, nil
}
Exemple #2
0
func newMqttEngine() (*mqttEngine, error) {

	murl, err := url.Parse(*mqttURL)

	if err != nil {
		return nil, err
	}

	mq := &mqttEngine{}

	// Create an MQTT Client.
	cli := client.New(&client.Options{
		ErrorHandler: mq.handleClientError,
	})

	mq.murl = murl
	mq.cli = cli

	mq.attemptConnect()

	//mq.publisher = publisher
	mq.pollTicker = time.NewTicker(time.Second * 1)
	mq.pubTicker = time.NewTicker(time.Second * 15)

	go poll(mq)
	go publish(mq, "Ready to publish")

	return mq, nil
}
Exemple #3
0
func Test_newCommandConn_ReadFileErr(t *testing.T) {
	cli := client.New(&client.Options{
		ErrorHandler: func(_ error) {},
	})

	defer quit(cli)

	if _, err := newCommandConn([]string{"-crt", "not_exist_file.crt"}, cli); err == nil {
		notNilErrorExpected(t)
	}
}
Exemple #4
0
func Test_newCommandConn(t *testing.T) {
	cli := client.New(&client.Options{
		ErrorHandler: func(_ error) {},
	})

	defer quit(cli)

	if _, err := newCommandConn([]string{"-crt", filepath.Join("test", "test.crt")}, cli); err != nil {
		nilErrorExpected(t, err)
	}
}
Exemple #5
0
func Test_newCommandPub_errCmdArgsParse(t *testing.T) {
	cli := client.New(&client.Options{
		ErrorHandler: func(_ error) {},
	})

	defer quit(cli)

	if _, err := newCommandPub([]string{"-not-exist-flag"}, cli); err != errCmdArgsParse {
		invalidError(t, err, errCmdArgsParse)
	}
}
Exemple #6
0
func Test_newCommandPub(t *testing.T) {
	cli := client.New(&client.Options{
		ErrorHandler: func(_ error) {},
	})

	defer quit(cli)

	if _, err := newCommandPub([]string{"-t", "topicName"}, cli); err != nil {
		nilErrorExpected(t, err)
	}
}
Exemple #7
0
func Test_newCommand_errInvalidCmdName(t *testing.T) {
	cli := client.New(&client.Options{
		ErrorHandler: func(_ error) {},
	})

	defer quit(cli)

	if _, err := newCommand("invalidCmdName", nil, cli); err != errInvalidCmdName {
		invalidError(t, err, errInvalidCmdName)
	}
}
Exemple #8
0
func Test_newCommandDisconn(t *testing.T) {
	cli := client.New(&client.Options{
		ErrorHandler: func(_ error) {},
	})

	defer quit(cli)

	if cmd := newCommandDisconn(cli); cmd == nil {
		t.Error("cmd => nil, want => not nil")
	}
}
Exemple #9
0
func Test_newCommandConn_errParseCrtFailure(t *testing.T) {
	cli := client.New(&client.Options{
		ErrorHandler: func(_ error) {},
	})

	defer quit(cli)

	if _, err := newCommandConn([]string{"-crt", filepath.Join("test", "error.crt")}, cli); err != errParseCrtFailure {
		invalidError(t, err, errParseCrtFailure)
	}
}
Exemple #10
0
func main() {
	// Set up channel on which to send signal notifications.
	sigc := make(chan os.Signal, 1)
	signal.Notify(sigc, os.Interrupt, os.Kill)

	// Print the version of GMQ Client and exit if "v" flag is true.
	if *flagV {
		printVersion()
		exit(0)
		return
	}

	// Create a Client.
	cli := client.New(&client.Options{
		ErrorHandler: errorHandler,
	})

	// Quit if signal notifications are sent.
	go func() {
		<-sigc
		quit(cli)
	}()

	// Create a scanner which reads lines from standard input.
	scanner := bufio.NewScanner(stdin)

	for printHeader(); scanner.Scan(); printHeader() {
		// Get the command name and the command arguments from
		// the scanner.
		cmdName, cmdArgs := cmdNameArgs(scanner.Text())

		// Skip the remaining processes if the command name is zero value.
		if cmdName == "" {
			continue
		}

		// Create a command.
		cmd, err := newCommand(cmdName, cmdArgs, cli)
		if err != nil {
			printError(err)
			continue
		}

		// Run the command.
		if err := cmd.run(); err != nil {
			printError(err)
			continue
		}

		// Print the successfule message.
		printSuccess(cmdName)
	}
}
Exemple #11
0
func Test_commandDisconn_run(t *testing.T) {
	cli := client.New(&client.Options{
		ErrorHandler: func(_ error) {},
	})

	defer quit(cli)

	cmd := &commandDisconn{cli: cli}

	if err := cmd.run(); err != client.ErrNotYetConnected {
		invalidError(t, err, client.ErrNotYetConnected)
	}
}
Exemple #12
0
func Test_commandQuit_run(t *testing.T) {
	cli := client.New(&client.Options{
		ErrorHandler: func(_ error) {},
	})

	cmd := commandQuit{
		cli: cli,
	}

	if err := cmd.run(); err != nil {
		nilErrorExpected(t, err)
	}
}
Exemple #13
0
func Test_commandPub_run(t *testing.T) {
	cli := client.New(&client.Options{
		ErrorHandler: func(_ error) {},
	})

	defer quit(cli)

	cmd, err := newCommandPub([]string{"-t", "topicName"}, cli)
	if err != nil {
		nilErrorExpected(t, err)
	}

	if err := cmd.run(); err != client.ErrNotYetConnected {
		invalidError(t, err, client.ErrNotYetConnected)
	}
}
Exemple #14
0
func Test_quit(t *testing.T) {
	cli := client.New(&client.Options{
		ErrorHandler: func(_ error) {},
	})

	err := cli.Connect(&client.ConnectOptions{
		Network:  "tcp",
		Address:  testAddress,
		ClientID: []byte("clientID"),
	})
	if err != nil {
		nilErrorExpected(t, err)
	}

	quit(cli)
}
Exemple #15
0
func Test_commandConn_run(t *testing.T) {
	cli := client.New(&client.Options{
		ErrorHandler: func(_ error) {},
	})

	defer quit(cli)

	cmd, err := newCommandConn(nil, cli)
	if err != nil {
		nilErrorExpected(t, err)
		return
	}

	if err := cmd.run(); err == nil {
		notNilErrorExpected(t)
	}
}
Exemple #16
0
func NewChat() (*Chat, error) {
	cli := client.New(&client.Options{
		ErrorHandler: func(err error) {
			log.Println(err)
		},
	})
	chat := Chat{MqttClient: cli, Rooms: make(map[string]*Room)}

	u, _ := uuid.NewV4()
	err := cli.Connect(&client.ConnectOptions{
		Network:  "tcp",
		Address:  getMqttMaster() + ":1883",
		ClientID: []byte(u.String()),
	})
	if err != nil {
		return nil, err
	}

	err = cli.Subscribe(&client.SubscribeOptions{
		SubReqs: []*client.SubReq{
			&client.SubReq{
				TopicFilter: []byte("rooms/#"),
				QoS:         mqtt.QoS0,
				Handler: func(topicName, message []byte) {
					s := strings.Split(string(topicName), "/")
					if len(s) < 2 {
						log.Printf("Unexpected topic: %s", string(topicName))
						return
					}
					room := chat.GetRoom(s[1])
					var msg Message
					json.Unmarshal(message, &msg)
					for e := room.Channels.Front(); e != nil; e = e.Next() {
						ch := e.Value.(chan Message)
						ch <- msg
					}
				},
			},
		},
	})
	if err != nil {
		panic(err)
	}
	return &chat, nil
}
Exemple #17
0
func Test_newCommand(t *testing.T) {
	cmdNames := []string{
		cmdNameConn,
		cmdNameDisconn,
		cmdNameHelp,
		cmdNamePub,
		cmdNameQuit,
		cmdNameSub,
		cmdNameUnsub,
	}

	cli := client.New(&client.Options{
		ErrorHandler: func(_ error) {},
	})

	defer quit(cli)

	for _, cmdName := range cmdNames {
		if _, err := newCommand(cmdName, nil, cli); err != nil {
			nilErrorExpected(t, err)
		}
	}
}
Exemple #18
0
func main() {
	r := gin.New()
	r.Use(gin.Recovery())

	r.GET("/ping", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message":  "pong",
			"lastseen": time.Now().String(),
		})
	})

	r.GET("/fgdata", func(c *gin.Context) {

		datamux.Lock()
		if fgdata != "" && strings.Contains(fgdata, "#") {
			s := strings.Split(fgdata, "#")

			curdata.Message = "OK"
			curdata.Lastseen = lastseen
			curdata.Lux = s[1]
			curdata.Temp = s[2]
			curdata.Lstate = s[0]
		}

		if light1 != "" {
			curdata.Light1 = light1
			curdata.Light1ls = light1ls
		} else {
			curdata.Light1 = "N/A"
			curdata.Light1ls = light1ls
		}
		datamux.Unlock()

		if fgdata != "" && strings.Contains(fgdata, "#") {
			//s := strings.Split(fgdata, "#")
			c.JSON(200, curdata)
			// c.JSON(200, gin.H{
			// 	"message":  "OK",
			// 	"lastseen": lastseen,
			// 	"lux":      s[1],
			// 	"temp":     s[2],
			// 	"lstate":   s[0],
			//})
		} else {
			c.JSON(200, gin.H{
				"message": "No data retreived. Check Network Connection",
			})
		}
	})

	r.GET("/", func(c *gin.Context) {
		c.Redirect(http.StatusMovedPermanently, "/static")
	})

	r.StaticFS("/static", http.Dir("./web"))

	//MQTT

	// Create an MQTT Client.
	cli := client.New(&client.Options{
		// Define the processing of the error handler.
		ErrorHandler: func(err error) {
			fmt.Println(err)
		},
	})

	// Terminate the Client.
	defer cli.Terminate()

	defer cli.Disconnect()

	// Connect to the MQTT Server.
	err := cli.Connect(&client.ConnectOptions{
		Network:  "tcp",
		Address:  "192.168.2.37:1883",
		ClientID: []byte("example-client"),
	})
	if err != nil {
		fmt.Println("Error on mqtt connect:", err)
		os.Exit(1)
	}

	go mqttWorker(cli)

	r.Run() // listen and server on 0.0.0.0:8080
}
Exemple #19
0
func main() {
	flag.Parse()

	if flag.NFlag() < 2 {
		fmt.Println("Too few arguments")
		Usage()
		os.Exit(0)
	}
	if (*message == "") || (*topic == "") {
		fmt.Println("Need a topic and message to publish")
		Usage()
		os.Exit(0)
	}

	fmt.Println("topic: ", *topic, "\tmessage: ", *message)

	// Set up channel on which to send signal notifications.
	sigc := make(chan os.Signal, 1)
	signal.Notify(sigc, os.Interrupt, os.Kill)

	// Create an MQTT Client.
	cli := client.New(&client.Options{
		// Define the processing of the error handler.
		ErrorHandler: func(err error) {
			fmt.Println(err)
		},
	})

	// Terminate the Client.
	defer cli.Terminate()

	s := []string{*host, *port}

	address := strings.Join(s, ":")
	fmt.Println("host info: ", address, "QoS option: ", *qos)

	var mQoS = mqtt.QoS0
	switch *qos {
	case "0":
		mQoS = mqtt.QoS0
	case "1":
		mQoS = mqtt.QoS1
	case "2":
		mQoS = mqtt.QoS2
	default:
		mQoS = mqtt.QoS0
	}

	// Connect to the MQTT Server.
	err := cli.Connect(&client.ConnectOptions{
		Network:  "tcp",
		Address:  address,
		ClientID: []byte("example-client"),
		//	CONNACKTimeout:  30,
		//	KeepAlive:       50,
	})
	if err != nil {
		panic(err)
	}

	err = cli.Publish(&client.PublishOptions{
		QoS:       mQoS,
		TopicName: []byte(*topic),
		Message:   []byte(*message),
	})
	if err != nil {
		panic(err)
	}

	// Wait for receiving a signal.
	// I cannot figure out why publish does not work without this command
	// <-sigc
	time.Sleep(time.Duration(*delay) * time.Millisecond)

	// Disconnect the Network Connection.
	if err := cli.Disconnect(); err != nil {
		panic(err)
	}
}