1
0
mirror of https://github.com/shirou/mqttcli.git synced 2025-04-28 13:48:50 +08:00
mqttcli/config.go
2014-11-07 12:57:06 +09:00

92 lines
1.7 KiB
Go

package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path"
"runtime"
"strings"
MQTT "git.eclipse.org/gitroot/paho/org.eclipse.paho.mqtt.golang.git"
log "github.com/Sirupsen/logrus"
)
const DefaultConfigFile = ".mqttcli.cfg" // Under HOME
type Config struct {
Host string `json:"host"`
Port int `json:"port"`
UserName string `json:"username"`
Password string `json:"password"`
}
func readFromConfigFile(path string) (Config, error) {
ret := Config{}
b, err := ioutil.ReadFile(path)
if err != nil {
return ret, err
}
err = json.Unmarshal(b, &ret)
if err != nil {
return ret, err
}
return ret, nil
}
func UserHomeDir() string {
if runtime.GOOS == "windows" {
home := os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
if home == "" {
home = os.Getenv("USERPROFILE")
}
return home
}
return os.Getenv("HOME")
}
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
}
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
}