Ejemplo n.º 1
0
func reconnectMqttBroker(client *MQTT.MqttClient, opts *MQTT.ClientOptions) {
	if mqttConnected == false {
		//log.Println("Attempting reconnect . . .")
		// Always reconnect with cleansession false
		opts.SetCleanSession(false)
		_, err := client.Start()
		if err != nil {
			time.Sleep(1 * time.Second)
		} else {
			log.Info("Reconnected")
			mqttConnected = true
		}
	}
}
Ejemplo n.º 2
0
Archivo: main.go Proyecto: kgbu/mqttcli
// connects MQTT broker
func connect(c *cli.Context, opts *MQTT.ClientOptions) (*MQTTClient, error) {
	log.Info("Connecting...")

	willPayload := c.String("will-payload")
	willQoS := c.Int("will-qos")
	willRetain := c.Bool("will-retain")
	willTopic := c.String("will-topic")
	if willPayload != "" && willTopic != "" {
		opts.SetWill(willTopic, willPayload, MQTT.QoS(willQoS), willRetain)
	}

	client := &MQTTClient{Opts: opts}
	_, err := client.Connect()
	if err != nil {
		return nil, err
	}
	log.Info("Connected")

	return client, nil
}
Ejemplo n.º 3
0
func getSettingsFromFile(p string, opts *MQTT.ClientOptions) error {
	confPath := ""
	home := UserHomeDir()
	// replace home to ~ in order to match
	p = strings.Replace(p, home, "~", 1)
	if p == "~/.mqttcli.cfg" || p == "" {
		confPath = path.Join(home, DefaultConfigFile)
		_, err := os.Stat(confPath)
		if os.IsNotExist(err) {
			return err
		}
	} else {
		confPath = p
	}

	ret, err := readFromConfigFile(confPath)
	if err != nil {
		log.Error(err)
		return err
	}

	tlsConfig, ok, err := makeTlsConfig(ret.CaCert, ret.ClientCert, ret.PrivateKey, false)
	if err != nil {
		return err
	}
	if ok {
		opts.SetTLSConfig(tlsConfig)
	}

	if ret.Host != "" {
		if ret.Port == 0 {
			ret.Port = 1883
		}
		scheme := "tcp"
		if ret.Port == 8883 {
			scheme = "ssl"
		}
		brokerUri := fmt.Sprintf("%s://%s:%d", scheme, ret.Host, ret.Port)
		log.Infof("Broker URI: %s", brokerUri)
		opts.AddBroker(brokerUri)
	}

	if ret.UserName != "" {
		opts.SetUsername(ret.UserName)
	}
	if ret.Password != "" {
		opts.SetPassword(ret.Password)
	}
	return nil
}
Ejemplo n.º 4
0
func getSettingsFromFile(p string, opts *MQTT.ClientOptions) error {
	confPath := ""

	if p == "~/.mqtt.cfg" || p == "" {
		home := UserHomeDir()
		confPath = path.Join(home, DefaultConfigFile)

		_, err := os.Stat(confPath)
		if os.IsNotExist(err) {
			return err
		}
	} else {
		confPath = p
	}

	ret, err := readFromConfigFile(confPath)
	if err != nil {
		return err
	}
	if ret.Host != "" {
		if ret.Port == "" {
			ret.Port = "1883"
		}
		scheme := "tcp" // FIXME:
		brokerUri := fmt.Sprintf("%s://%s:%s", scheme, ret.Host, ret.Port)
		log.Infof("Broker URI: %s", brokerUri)
		opts.AddBroker(brokerUri)
	}

	if ret.UserName != "" {
		opts.SetUsername(ret.UserName)
	}
	if ret.Password != "" {
		opts.SetPassword(ret.Password)
	}

	return nil
}