From 9e2ef6177283ddc15cd78ca5cecb3e5e932efae0 Mon Sep 17 00:00:00 2001 From: Paolo Asperti Date: Wed, 23 Dec 2020 15:32:05 +0100 Subject: [PATCH] Update config.go, display.go, and 7 more files... --- src/config.go | 8 +- src/display.go | 13 +++ src/main.go | 15 ++-- src/mqtt.go | 91 ++++++++++++++++----- src/mqtt_ui.go | 56 +++++++++++++ src/webui.go | 6 ++ templates/common/sidebar-menu.html | 27 +++++-- templates/mqtt.html | 123 +++++++++++++++++++++++++++++ templates/settings/mqtt.html | 0 9 files changed, 299 insertions(+), 40 deletions(-) create mode 100644 src/mqtt_ui.go create mode 100644 templates/mqtt.html delete mode 100644 templates/settings/mqtt.html diff --git a/src/config.go b/src/config.go index e15b9a1..47a3e76 100644 --- a/src/config.go +++ b/src/config.go @@ -7,14 +7,12 @@ import ( ) func readConfig() { - viper.SetConfigName("openpdu.yaml") // name of config file (without extension) + viper.SetConfigName("openpdu") // name of config file (without extension) viper.SetConfigType("yaml") - viper.AddConfigPath("/etc/openpdu/") // path to look for the config file in viper.AddConfigPath(".") // optionally look for config in the working directory + viper.AddConfigPath("/etc/openpdu/") // path to look for the config file in err := viper.ReadInConfig() // Find and read the config file if err != nil { // Handle errors reading the config file - log.Printf("Fatal error config file: %s \n", err) + log.Printf("Can't read config file: %s \n", err) } - - viper.SetDefault("hostname", "openpdu") } diff --git a/src/display.go b/src/display.go index d1c85f1..378c30a 100644 --- a/src/display.go +++ b/src/display.go @@ -6,6 +6,7 @@ import ( "log" "net" + "github.com/spf13/viper" "golang.org/x/image/font" "golang.org/x/image/font/basicfont" "golang.org/x/image/math/fixed" @@ -14,6 +15,18 @@ import ( "periph.io/x/periph/devices/ssd1306" ) +func init() { + viper.SetDefault("DisplayType", "none") + displayLoop() +} + +func displayLoop() { + if viper.GetString("DisplayType") == "ssd1306" { + initI2C() + go disp() + } +} + func addLabel(img *image.RGBA, x, y int, label string) { col := color.RGBA{200, 100, 0, 255} point := fixed.Point26_6{fixed.Int26_6(x * 64), fixed.Int26_6(y * 64)} diff --git a/src/main.go b/src/main.go index 8e7fb4b..0a103d7 100644 --- a/src/main.go +++ b/src/main.go @@ -12,17 +12,14 @@ import ( // Dictionary aaa type Dictionary map[string]interface{} +func init() { + viper.SetDefault("hostname", "openpdu") +} + func main() { - readConfig() - - nam := viper.Get("hostname") - log.Printf("hostname: %v\n", nam) - - initI2C() - - go disp() - + go mqttLoop() + log.Printf("hostname: %v\n", viper.Get("hostname")) startServer() } diff --git a/src/mqtt.go b/src/mqtt.go index c8c8613..3aa4025 100644 --- a/src/mqtt.go +++ b/src/mqtt.go @@ -2,32 +2,85 @@ package main import ( "fmt" - "os" + "time" MQTT "github.com/eclipse/paho.mqtt.golang" + "github.com/spf13/viper" ) +var MQTTclient MQTT.Client + func init() { - // set the protocol, ip and port of the broker. - opts := MQTT.NewClientOptions().AddBroker("tcp://localhost:1883") + viper.SetDefault("MqttCliendID", "OpenPDU") // max 23 chars + viper.SetDefault("MqttPrefix", "openpdu") // max 23 chars + viper.SetDefault("MqttSchema", "tcp") + viper.SetDefault("MqttHost", "localhost") + viper.SetDefault("MqttPort", "1883") + viper.SetDefault("MqttUsername", "") + viper.SetDefault("MqttPassword", "") - // set the id to the client. - opts.SetClientID("Device-pub") + // MQTT.ERROR = log.New(os.Stdout, "[ERROR] ", 0) + // MQTT.CRITICAL = log.New(os.Stdout, "[CRIT] ", 0) + // MQTT.WARN = log.New(os.Stdout, "[WARN] ", 0) + // MQTT.DEBUG = log.New(os.Stdout, "[DEBUG] ", 0) - // create a new client. - c := MQTT.NewClient(opts) - token := c.Connect() - token.Wait() - if token.Error() != nil { - fmt.Println(token.Error()) - os.Exit(1) - } - - message := "hello this is the trial message" - c.Publish("some_topic", 0, false, message) - - //c.Subscribe("some_topic", 0, nil); - c.Disconnect(250) + //MQTTclient.Subscribe("some_topic", 0, nil); + //MQTTclient.Disconnect(250) } // https://girishjoshi.io/post/golang-paho-mqtt/ + +func mqttLoop() { + uri := viper.GetString("MqttSchema") + "://" + viper.GetString("MqttHost") + ":" + viper.GetString("MqttPort") + opts := MQTT.NewClientOptions().AddBroker(uri) + + opts.SetClientID(viper.GetString("MqttCliendID")) + + if username := viper.GetString("MqttUsername"); username != "" { + opts.SetUsername(username) + } + + if password := viper.GetString("MqttPassword"); password != "" { + opts.SetPassword(password) + } + + opts.SetAutoReconnect(true) + opts.SetConnectRetryInterval(5 * time.Second) + opts.SetConnectTimeout(5 * time.Second) + + opts.SetConnectionLostHandler(func(c MQTT.Client, err error) { + fmt.Printf("!!!!!! mqtt connection lost error: %s\n" + err.Error()) + }) + opts.SetReconnectingHandler(func(c MQTT.Client, options *MQTT.ClientOptions) { + fmt.Println("...... mqtt reconnecting ......") + }) + opts.SetOnConnectHandler(func(c MQTT.Client) { + fmt.Println("...... mqtt connected ......") + // MQTTclient.Publish("openpdu/status", 0, false, "connected") + }) + + MQTTclient = MQTT.NewClient(opts) + + for { + token := MQTTclient.Connect() + token.Wait() + if MQTTclient.IsConnected() { + break + } + time.Sleep(5 * time.Second) + } + +} + +func MQTTreconfigure() { + if MQTTclient.IsConnected() { + MQTTclient.Disconnect(250) + } + go mqttLoop() +} + +func MQTTpublish(topic string, value string) { + if MQTTclient.IsConnected() { + MQTTclient.Publish(viper.GetString("MqttPrefix")+"/"+topic, 0, false, value) + } +} diff --git a/src/mqtt_ui.go b/src/mqtt_ui.go new file mode 100644 index 0000000..cb5c511 --- /dev/null +++ b/src/mqtt_ui.go @@ -0,0 +1,56 @@ +package main + +import ( + "strings" + + "github.com/spf13/viper" + "gopkg.in/macaron.v1" +) + +func mqttPage(ctx *macaron.Context) { + ctx.Data["schema"] = viper.GetString("MqttSchema") + ctx.Data["host"] = viper.GetString("MqttHost") + ctx.Data["port"] = viper.GetString("MqttPort") + ctx.Data["clientid"] = viper.GetString("MqttCliendID") + ctx.Data["prefix"] = viper.GetString("MqttPrefix") + ctx.Data["username"] = viper.GetString("MqttUsername") + ctx.Data["password"] = viper.GetString("MqttPassword") + + ctx.Data["schemas"] = []string{"tcp", "ssl", "ws"} + ctx.HTML(200, "mqtt") +} + +type MQTTPostForm struct { + Schema string `form:"schema" binding:"Required"` + Host string `form:"host" binding:"Required"` + Port string `form:"port" binding:"Required"` + Prefix string `form:"prefix" binding:"Required"` + ClientID string `form:"clientid" binding:"Required"` + Username string `form:"username"` + Password string `form:"password"` +} + +func mqttPost(ctx *macaron.Context, f MQTTPostForm) { + schema := strings.ToLower(strings.TrimSpace(f.Schema)) + switch schema { + case + "tcp", + "ssl", + "ws": + viper.Set("MqttSchema", schema) + default: + mqttPage(ctx) + return + } + + viper.Set("MqttHost", strings.ToLower(strings.TrimSpace(f.Host))) + viper.Set("MqttPort", strings.ToLower(strings.TrimSpace(f.Port))) + viper.Set("MqttCliendID", strings.TrimSpace(f.ClientID)) + viper.Set("MqttPrefix", strings.TrimSpace(f.Prefix)) + viper.Set("MqttUsername", strings.TrimSpace(f.Username)) + viper.Set("MqttPassword", f.Password) + + viper.WriteConfig() + + mqttPage(ctx) +} diff --git a/src/webui.go b/src/webui.go index 403bd1e..0e31e0a 100644 --- a/src/webui.go +++ b/src/webui.go @@ -6,6 +6,7 @@ import ( "net/http" "strconv" + "github.com/go-macaron/binding" "github.com/go-macaron/pongo2" "gopkg.in/macaron.v1" ) @@ -25,6 +26,7 @@ func statusPage(ctx *macaron.Context) { } func jsonStatus(ctx *macaron.Context) { + MQTTpublish("openpdu/status", "asdss") p0, err := MyBoard.channelStatus(0) if err != nil { @@ -85,10 +87,12 @@ func jsonOutletToggle(ctx *macaron.Context) { if err != nil { log.Fatal(err) } + MQTTpublish("openpdu/toggolo1", string(id)) err = MyBoard.channelToggle(uint(id)) if err != nil { log.Fatal(err) } + MQTTpublish("openpdu/toggolo2", string(id)) ctx.JSON(http.StatusOK, Dictionary{ "data": "ok", }) @@ -101,6 +105,8 @@ func startServer() { // m.Get("/", myHandler) m.Get("/", statusPage) + m.Get("/mqtt", mqttPage) + m.Post("/mqtt", binding.Bind(MQTTPostForm{}), mqttPost) m.Get("/json/status", jsonStatus) m.Post("/json/outlet/:id/toggle", jsonOutletToggle) diff --git a/templates/common/sidebar-menu.html b/templates/common/sidebar-menu.html index 158f130..3518600 100644 --- a/templates/common/sidebar-menu.html +++ b/templates/common/sidebar-menu.html @@ -26,20 +26,33 @@ -
  • + {% if pageselected in "lan mqtt ups syslog backup restore" %} +
  • + {% endif %} + Settings +
  • diff --git a/templates/mqtt.html b/templates/mqtt.html new file mode 100644 index 0000000..6f1c16a --- /dev/null +++ b/templates/mqtt.html @@ -0,0 +1,123 @@ + + + + {% include "common/common-head.html" %} + + +
    + + {% include "common/page-header.html" %} + {% with pageselected="mqtt" %} + {% include "common/sidebar-menu.html" %} + {% endwith %} + + +
    + + + + +
    + + +
    +
    + + +
    +
    +

    MQTT configuration

    +
    + + +
    +
    + +
    + +
    + +
    +
    + +
    + +
    + +
    +
    + +
    + +
    + +
    +
    + +
    + +
    + +
    +
    + +
    + +
    + +
    +
    + +
    + +
    + +
    +
    + +
    + +
    + +
    +
    + + +
    + + + + +
    +
    + +
    + +
    + + +
    + +
    + + + {% include "common/footer.html" %} + +
    + + + {% include "common/common-js.html" %} + + + + \ No newline at end of file diff --git a/templates/settings/mqtt.html b/templates/settings/mqtt.html deleted file mode 100644 index e69de29..0000000