Exemplo n.º 1
0
func Create(setting *Setting) *MqttClient {
	uri, err := url.Parse(setting.URL)
	if err != nil {
		log.Errorf("Faild to parse mqtt-url: %v", err)
		return nil
	}
	opts := mqtt.NewClientOptions()

	// tcp://iot.eclipse.org:1883 - connect to iot.eclipse.org on port 1883 using plain TCP
	// ws://iot.eclipse.org:1883  - connect to iot.eclipse.org on port 1883 using WebSockets
	// tls://iot.eclipse.org:8883 - connect to iot.eclipse.org on port 8883 using TLS (ssl:// and tcps:// are synonyms for tls://)
	//opts.AddBroker(fmt.Sprintf("tcps://%s", uri.Host))
	//opts.AddBroker(fmt.Sprintf("tls://%s", uri.Host))
	opts.AddBroker(fmt.Sprintf("tls://%s", uri.Host))

	if uri.User != nil {
		username := uri.User.Username()
		password, _ := uri.User.Password()
		opts.SetUsername(username)
		opts.SetPassword(password)
	}
	opts.SetClientID(setting.ClientId)
	opts.AutoReconnect = true
	opts.ProtocolVersion = 4
	opts.CleanSession = true

	if false {
		certPool, err := GetCertPool("/vagrant/goapp/src/github.com/fltmtoda/golibs-examples/mosquitto.org.crt")
		if err != nil {
			panic(err)
		}
		opts.SetTLSConfig(
			&tls.Config{
				RootCAs: certPool,
			},
		)
	}

	opts.OnConnectionLost = func(c *mqtt.Client, err error) {
		if err != nil {
			log.Errorf("Failed to disconnect mqtt-server: %v [%v]", opts.Servers, err)
			return
		} else {
			log.Infof("Disonnect mqtt-server: %v", opts.Servers)
		}
	}

	return &MqttClient{
		internalClient: mqtt.NewClient(opts),
		setting:        setting,
	}
}
Exemplo n.º 2
0
func (t *TimestampType) Set(value interface{}) {
	if value != nil {
		switch v := value.(type) {
		case time.Time:
			t.valid, t.val = true, v
		default:
			sTime := util.ToString(v)
			if sTime != util.BLANK && sTime != "null" {
				sTime = strings.Replace(sTime, "T", " ", -1)
				if len(sTime) > 26 {
					sTime = sTime[0:26]
				}
				sTime = strings.TrimSpace(sTime)
				parseTime, err := time.Parse("2006-01-02 15:04:05.999999", sTime)
				if err != nil {
					log.Errorf("Time parse error: %v", err)
					break
				}
				t.valid, t.val = true, parseTime.Local()
			}
		}
	}
	if !t.valid {
		t.val = emptyTime
	}
}
Exemplo n.º 3
0
func (c *MqttClient) Subscribe(topic string, qos QoS, callback SubscribeMessageHandler) error {
	token := c.internalClient.Subscribe(
		topic,
		byte(qos),
		func(c *mqtt.Client, msg mqtt.Message) {
			if msg == nil {
				log.Warn("Subscribe message is nil")
				return
			}
			if err := callback(msg); err != nil {
				log.Errorf("Failed to subscript mqtt-server: %v", err)
				return
			}
		},
	)
	if qos != QOS_ZERO {
		token.Wait()
	}
	if token.Error() != nil {
		return fmt.Errorf("Failed to subscript mqtt-server: %v", token.Error())
	}
	return nil
}