85 lines
2.1 KiB
Go
85 lines
2.1 KiB
Go
|
package main
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
"io/ioutil"
|
||
|
"time"
|
||
|
|
||
|
"github.com/goburrow/serial"
|
||
|
"github.com/sirupsen/logrus"
|
||
|
"gopkg.in/yaml.v2"
|
||
|
)
|
||
|
|
||
|
type SerialConfig struct {
|
||
|
Address string `yaml:"address"`
|
||
|
BaudRate int `yaml:"baudrate"`
|
||
|
DataBits int `yaml:"databits"`
|
||
|
StopBits int `yaml:"stopbits"`
|
||
|
Parity string `yaml:"parity"`
|
||
|
}
|
||
|
|
||
|
type ClientConfig struct {
|
||
|
Serial SerialConfig `yaml:"serial_config"`
|
||
|
Paranoid bool `yaml:"paranoid"`
|
||
|
Debug bool `yaml:"debug"`
|
||
|
GNUPGBinary string `yaml:"gnupg_bin"`
|
||
|
OpenSSLBinary string `yaml:"openssl_bin"`
|
||
|
MySQLDSN string `yaml:"mysql_dsn"`
|
||
|
}
|
||
|
|
||
|
var defaultConfig = ClientConfig{
|
||
|
Serial: SerialConfig{
|
||
|
Address: "/dev/ttyUSB0",
|
||
|
BaudRate: 115200,
|
||
|
DataBits: 8,
|
||
|
StopBits: 1,
|
||
|
Parity: "N",
|
||
|
},
|
||
|
Paranoid: false,
|
||
|
Debug: false,
|
||
|
OpenSSLBinary: "/usr/bin/openssl",
|
||
|
GNUPGBinary: "/usr/bin/gpg",
|
||
|
MySQLDSN: "<username>:<password>@/database?parseTime=true",
|
||
|
}
|
||
|
|
||
|
func generateExampleConfig(configFile string) (config *ClientConfig, err error) {
|
||
|
config = &defaultConfig
|
||
|
configBytes, err := yaml.Marshal(config)
|
||
|
if err != nil {
|
||
|
logrus.Errorf("could not generate configuration data")
|
||
|
return
|
||
|
}
|
||
|
|
||
|
logrus.Infof("example data for %s:\n\n---\n%s\n", configFile, configBytes)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
func readConfig(configFile string) (config *ClientConfig, err error) {
|
||
|
source, err := ioutil.ReadFile(configFile)
|
||
|
if err != nil {
|
||
|
logrus.Errorf("opening configuration file failed: %v", err)
|
||
|
if exampleConfig, err := generateExampleConfig(configFile); err != nil {
|
||
|
return nil, err
|
||
|
} else {
|
||
|
logrus.Info("starting with default config")
|
||
|
return exampleConfig, nil
|
||
|
}
|
||
|
}
|
||
|
if err := yaml.Unmarshal(source, &config); err != nil {
|
||
|
return nil, fmt.Errorf("loading configuration file failed: %v", err)
|
||
|
}
|
||
|
|
||
|
return config, nil
|
||
|
}
|
||
|
|
||
|
func fillSerialConfig(clientConfig *ClientConfig) *serial.Config {
|
||
|
return &serial.Config{
|
||
|
Address: clientConfig.Serial.Address,
|
||
|
BaudRate: clientConfig.Serial.BaudRate,
|
||
|
DataBits: clientConfig.Serial.DataBits,
|
||
|
StopBits: clientConfig.Serial.StopBits,
|
||
|
Parity: clientConfig.Serial.Parity,
|
||
|
Timeout: 30 * time.Second,
|
||
|
}
|
||
|
}
|