From ac3bb1ebe94714cebfa746bd5e1b634af33def9d Mon Sep 17 00:00:00 2001 From: Siegfried Siegert Date: Wed, 2 Sep 2020 09:02:30 +0200 Subject: [PATCH] Write data in database table --- Config/Config.go | 32 -------------------------------- config/config.go | 39 +++++++++++++++++++++++++++++++++++++++ env/env.go | 31 +++++++++++++++++++++++++++++++ go.mod | 2 ++ main.go | 35 ++++++++++------------------------- models/devices.go | 9 ++++++++- mqtt/mqtt.go | 32 ++++++++++++++++---------------- 7 files changed, 106 insertions(+), 74 deletions(-) delete mode 100644 Config/Config.go create mode 100644 config/config.go create mode 100644 env/env.go diff --git a/Config/Config.go b/Config/Config.go deleted file mode 100644 index 58456e7..0000000 --- a/Config/Config.go +++ /dev/null @@ -1,32 +0,0 @@ -package Config - -import ( - //"fmt" - "log" - - "github.com/pelletier/go-toml" -) - -var BrokerAddress = "" -var BrokerPort int64 = 8883 -var BrokerClientId = "go_client" -var BrokerUsername = "" -var BrokerPassword = "" -var EnableTLS = true - -func ReadConfig() { - config, err := toml.LoadFile("config.toml") - - if err != nil { - //fmt.Println("Error ", err.Error()) - log.Fatal(err.Error()) - } else { - // retrieve data directly - BrokerAddress = config.Get("BROKER.Address").(string) - BrokerPort = config.Get("BROKER.Port").(int64) - BrokerClientId = config.Get("BROKER.ClientId").(string) - BrokerUsername = config.Get("BROKER.Username").(string) - BrokerPassword = config.Get("BROKER.Password").(string) - EnableTLS = config.Get("BROKER.EnableTLS").(bool) - } -} diff --git a/config/config.go b/config/config.go new file mode 100644 index 0000000..4d4247b --- /dev/null +++ b/config/config.go @@ -0,0 +1,39 @@ +package config + +import ( + //"fmt" + "log" + + "github.com/pelletier/go-toml" +) + +type Config struct { + BrokerAddress string + BrokerPort int64 + BrokerClientID string + BrokerUsername string + BrokerPassword string + EnableTLS bool +} + +func NewConfig(configFilename string) (*Config, error) { + tomlData, err := toml.LoadFile(configFilename) + + conf := Config{"", 8883, "go_client", "", "", true} + + if err != nil { + //fmt.Println("Error ", err.Error()) + log.Printf("ERROR: NewConfig(): %s", err.Error()) + return nil, err + } else { + // retrieve data directly + conf.BrokerAddress = tomlData.Get("BROKER.Address").(string) + conf.BrokerPort = tomlData.Get("BROKER.Port").(int64) + conf.BrokerClientID = tomlData.Get("BROKER.ClientId").(string) + conf.BrokerUsername = tomlData.Get("BROKER.Username").(string) + conf.BrokerPassword = tomlData.Get("BROKER.Password").(string) + conf.EnableTLS = tomlData.Get("BROKER.EnableTLS").(bool) + } + + return &conf, nil +} diff --git a/env/env.go b/env/env.go new file mode 100644 index 0000000..921ecdb --- /dev/null +++ b/env/env.go @@ -0,0 +1,31 @@ +package env + +import ( + "mqttListener/config" + "mqttListener/models" + + "fmt" + //"log" + + "net/http" +) + +type Env struct { + DB models.Datastore + Config *config.Config +} + +func (env *Env) DevicesIndex(w http.ResponseWriter, r *http.Request) { + if r.Method != "GET" { + http.Error(w, http.StatusText(405), 405) + return + } + devices, err := env.DB.AllDevices() + if err != nil { + http.Error(w, http.StatusText(500), 500) + return + } + for _, device := range devices { + fmt.Fprintf(w, "%s, %s, %s, £%.2f\n", device.ID, device.MAC, device.SN, device.LastMsg) + } +} diff --git a/go.mod b/go.mod index f08de5c..c247699 100644 --- a/go.mod +++ b/go.mod @@ -8,4 +8,6 @@ require ( github.com/mmcdole/gofeed v1.0.0 github.com/pelletier/go-toml v1.2.0 github.com/spf13/cobra v1.0.0 + golang.org/x/lint v0.0.0-20200302205851-738671d3881b // indirect + golang.org/x/tools v0.0.0-20200831203904-5a2aa26beb65 // indirect ) diff --git a/main.go b/main.go index 4966e50..5dfcd80 100644 --- a/main.go +++ b/main.go @@ -1,7 +1,8 @@ package main import ( - "mqttListener/Config" + "mqttListener/config" + "mqttListener/env" "mqttListener/models" "mqttListener/mqtt" @@ -15,32 +16,31 @@ import ( "net/http" ) -type Env struct { - db models.Datastore -} - func main() { c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt, syscall.SIGTERM) - Config.ReadConfig() + config, err := config.NewConfig("config.toml") + if err != nil { + log.Panic(err) + } // DEBUG Config - // fmt.Println("BrokerAddress = ", Config.BrokerAddress) + fmt.Println("BrokerAddress = ", config.BrokerAddress) db, err := models.NewDB("simple.sqlite") if err != nil { log.Panic(err) } - env := &Env{db} + env := &env.Env{db, config} - mqtt.Setup() + mqtt.Setup(env) mqtt.Connect() go mqtt.Listen() - http.HandleFunc("/devices", env.devicesIndex) + http.HandleFunc("/devices", env.DevicesIndex) go http.ListenAndServe(":3000", nil) fmt.Println("awaiting signal") @@ -49,18 +49,3 @@ func main() { mqtt.Disconnect() } - -func (env *Env) devicesIndex(w http.ResponseWriter, r *http.Request) { - if r.Method != "GET" { - http.Error(w, http.StatusText(405), 405) - return - } - devices, err := env.db.AllDevices() - if err != nil { - http.Error(w, http.StatusText(500), 500) - return - } - for _, device := range devices { - fmt.Fprintf(w, "%s, %s, %s, £%.2f\n", device.ID, device.MAC, device.SN, device.LastMsg) - } -} diff --git a/models/devices.go b/models/devices.go index 3678fc8..a391be8 100644 --- a/models/devices.go +++ b/models/devices.go @@ -1,5 +1,9 @@ package models +import ( + "fmt" +) + type Device struct { ID string MAC string @@ -30,12 +34,15 @@ func (db *DB) AllDevices() ([]*Device, error) { } func (db *DB) InsertDevice(device *Device) error { - sqlStmt := `INSERT OR REPLACE INTO table (id, mac, sn, lastMsg) + sqlStmt := `INSERT OR REPLACE INTO devices (id, mac, sn, lastMsg) VALUES($1, $2, $3, $4);` _, err := db.Exec(sqlStmt, device.ID, device.MAC, device.SN, device.LastMsg) if err != nil { return err } + // DEBUG + fmt.Printf("Sucessfully inserted device with ID %s to database\n", device.ID) + return err } diff --git a/mqtt/mqtt.go b/mqtt/mqtt.go index 940f784..41c4562 100644 --- a/mqtt/mqtt.go +++ b/mqtt/mqtt.go @@ -8,7 +8,7 @@ import ( "strconv" "strings" - "mqttListener/Config" + "mqttListener/env" "mqttListener/models" "regexp" "time" @@ -22,18 +22,11 @@ import ( URI = mqtt://:@: */ -/* TODO: This options are just a suggestion -Options: - [-help] Display help - [-customer] Customer- or project number - [-device] Device number - [-uri ] Broker URI -*/ - var client MQTT.Client var opts *MQTT.ClientOptions var topic string var uri url.URL +var ev *env.Env func Connect() { client = MQTT.NewClient(opts) @@ -64,17 +57,19 @@ func Listen() { */ } -func Setup() { +func Setup(environment *env.Env) { + + ev = environment scheme := "tcp://" - if Config.EnableTLS { + if ev.Config.EnableTLS { scheme = "ssl://" } urlString := scheme - urlString += Config.BrokerUsername + ":" + Config.BrokerPassword + "@" - urlString += Config.BrokerAddress + ":" - urlString += strconv.FormatInt(Config.BrokerPort, 10) + urlString += ev.Config.BrokerUsername + ":" + ev.Config.BrokerPassword + "@" + urlString += ev.Config.BrokerAddress + ":" + urlString += strconv.FormatInt(ev.Config.BrokerPort, 10) fmt.Println("broker urlString: ", urlString) @@ -89,7 +84,7 @@ func Setup() { topic = "/ATB/#" - opts = createClientOptions(Config.BrokerClientId, uri) + opts = createClientOptions(ev.Config.BrokerClientID, uri) } @@ -101,7 +96,7 @@ func createClientOptions(ClientID string, uri *url.URL) *MQTT.ClientOptions { opts.SetPassword(password) opts.SetClientID(ClientID) opts.SetDefaultPublishHandler(f) - if Config.EnableTLS { + if ev.Config.EnableTLS { tlsConfig := &tls.Config{InsecureSkipVerify: true, ClientAuth: tls.NoClientCert} opts.SetTLSConfig(tlsConfig) } @@ -180,4 +175,9 @@ var subscriptionHandler = func(client MQTT.Client, msg MQTT.Message) { fmt.Printf("Device SN = %s\n", device.SN) // TODO: store this device in database + err = ev.DB.InsertDevice(&device) + if err != nil { + fmt.Println(err.Error()) + return + } }