Skip to content

Commit

Permalink
feat(logs): adding log
Browse files Browse the repository at this point in the history
  • Loading branch information
atbore-phx committed Mar 2, 2024
1 parent 0f17e4e commit aeceb77
Show file tree
Hide file tree
Showing 14 changed files with 92 additions and 70 deletions.
12 changes: 6 additions & 6 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ go 1.22.0

require (
github.com/spf13/cobra v1.8.0
github.com/stretchr/testify v1.8.4
github.com/stretchr/testify v1.9.0
)

require (
Expand All @@ -14,18 +14,17 @@ require (
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/magiconair/properties v1.8.7 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/pelletier/go-toml/v2 v2.1.0 // indirect
github.com/pelletier/go-toml/v2 v2.1.1 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/sagikazarmark/locafero v0.4.0 // indirect
github.com/sagikazarmark/slog-shim v0.1.0 // indirect
github.com/sourcegraph/conc v0.3.0 // indirect
github.com/spf13/afero v1.11.0 // indirect
github.com/spf13/cast v1.6.0 // indirect
github.com/subosito/gotenv v1.6.0 // indirect
go.uber.org/atomic v1.9.0 // indirect
go.uber.org/multierr v1.9.0 // indirect
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 // indirect
golang.org/x/sys v0.16.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
golang.org/x/exp v0.0.0-20240222234643-814bf88cf225 // indirect
golang.org/x/sys v0.17.0 // indirect
golang.org/x/text v0.14.0 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
Expand All @@ -36,4 +35,5 @@ require (
github.com/simonvetter/modbus v1.6.0
github.com/spf13/pflag v1.0.5 // indirect
github.com/spf13/viper v1.18.2
go.uber.org/zap v1.27.0
)
26 changes: 14 additions & 12 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0V
github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0=
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/pelletier/go-toml/v2 v2.1.0 h1:FnwAJ4oYMvbT/34k9zzHuZNrhlz48GB3/s6at6/MHO4=
github.com/pelletier/go-toml/v2 v2.1.0/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc=
github.com/pelletier/go-toml/v2 v2.1.1 h1:LWAJwfNvjQZCFIDKWYQaM62NcYeYViCmWIwmOStowAI=
github.com/pelletier/go-toml/v2 v2.1.1/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
Expand Down Expand Up @@ -52,21 +52,23 @@ github.com/spf13/viper v1.18.2/go.mod h1:EKmWIqdnk5lOcmR72yw6hS+8OPYcwD0jteitLMV
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE=
go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
go.uber.org/multierr v1.9.0 h1:7fIwc/ZtS0q++VgcfqFDxSBZVv/Xo49/SYnDFupUwlI=
go.uber.org/multierr v1.9.0/go.mod h1:X2jQV1h+kxSjClGpnseKVIxpmcjrj7MNnI0bnlfKTVQ=
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 h1:GoHiUyI/Tp2nVkLI2mCxVkOjsbSXD66ic0XW0js0R9g=
golang.org/x/exp v0.0.0-20230905200255-921286631fa9/go.mod h1:S2oDrQGGwySpoQPVqRShND87VCbxmc6bL1Yd2oYrm6k=
golang.org/x/sys v0.16.0 h1:xWw16ngr6ZMtmxDyKyIgsE93KNKz5HKmMa3b8ALHidU=
golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8=
go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
golang.org/x/exp v0.0.0-20240222234643-814bf88cf225 h1:LfspQV/FYTatPTr/3HzIcmiUFH7PGP+OQ6mgDYo3yuQ=
golang.org/x/exp v0.0.0-20240222234643-814bf88cf225/go.mod h1:CxmFvTBINI24O/j8iY7H1xHzx2i4OsyguNBmN/uPtqc=
golang.org/x/sys v0.17.0 h1:25cE3gD+tdBA7lp7QfhuV+rJiE9YXTcS3VG1SqssI/Y=
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
Expand Down
1 change: 1 addition & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
)

func main() {

cmd.Execute()

}
3 changes: 0 additions & 3 deletions pkg/cmd/configure.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"fmt"
"ha-fronius-bm/pkg/fronius"
"strings"
"time"

"github.com/spf13/cobra"
"github.com/spf13/viper"
Expand All @@ -15,8 +14,6 @@ var cfgCmd = &cobra.Command{
Short: "Configure Battery Storage Charge",
Long: `connect via modbus to the fronius inverter and set charging`,
Run: func(cmd *cobra.Command, args []string) {
now := time.Now()
fmt.Println(now.Format("2006-01-02 15:04:05"))
fronius_ip := viper.GetString("fronius_ip")
if len(strings.TrimSpace(fronius_ip)) == 0 {
fmt.Println("The --fronius_ip flag must be set")
Expand Down
9 changes: 2 additions & 7 deletions pkg/cmd/estimate.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"ha-fronius-bm/pkg/power"
"ha-fronius-bm/pkg/storage"
"strings"
"time"

"github.com/spf13/cobra"
"github.com/spf13/viper"
Expand All @@ -16,8 +15,6 @@ var estCmd = &cobra.Command{
Short: "Estimate Forecast Solar Power",
Long: `Print the solar forecast and the battery storage power`,
Run: func(cmd *cobra.Command, args []string) {
now := time.Now()
fmt.Println(now.Format("2006-01-02 15:04:05"))
url := viper.GetString("url")
apiKey := viper.GetString("apikey")
fronius_ip := viper.GetString("fronius_ip")
Expand All @@ -33,18 +30,16 @@ var estCmd = &cobra.Command{
}

pwr := power.New()
solarPowerProduction, err := pwr.Handler(apiKey, url)
_, err := pwr.Handler(apiKey, url)
if err != nil {
panic(err)
}
fmt.Println("Forecast Solar Power:", solarPowerProduction)

str := storage.New()
capacity2charge, err := str.Handler(fronius_ip)
_, err = str.Handler(fronius_ip)
if err != nil {
panic(err)
}
fmt.Println("Battery Capacity to charge:", capacity2charge)
},
}

Expand Down
18 changes: 5 additions & 13 deletions pkg/cmd/schedule.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import (
"ha-fronius-bm/pkg/fronius"
"ha-fronius-bm/pkg/power"
"ha-fronius-bm/pkg/storage"
u "ha-fronius-bm/src/utils"
"strings"
"time"

"github.com/spf13/cobra"
"github.com/spf13/viper"
Expand All @@ -17,8 +17,6 @@ var scdCmd = &cobra.Command{
Short: "Schedule Battery Storage Charge",
Long: `Workflow to Check Forecast and Battery residual Capacity and decide if it has to be charged in a definited time range`,
Run: func(cmd *cobra.Command, args []string) {
now := time.Now()
fmt.Println(now.Format("2006-01-02 15:04:05"))
url := viper.GetString("url")
apiKey := viper.GetString("apikey")
fronius_ip := viper.GetString("fronius_ip")
Expand All @@ -43,25 +41,19 @@ var scdCmd = &cobra.Command{
if err != nil {
panic(err)
}
fmt.Printf("Forecast Solar Power:%d W\n", int(solarPowerProduction))

str := storage.New()
capacity2charge, err := str.Handler(fronius_ip)
if err != nil {
panic(err)
}
fmt.Printf("Battery Capacity to charge: %d W\n", int(capacity2charge))
fmt.Printf("your Daily consumption is:%d W\n", int(pw_consumption))
u.Log.Infof("your Daily consumption is:%d W", int(pw_consumption))

scd := fronius.New()
charge_pc, _ := scd.Handler(solarPowerProduction, capacity2charge, pw_consumption, max_charge, start_hr, end_hr, fronius_ip)

if charge_pc != 0 {
fmt.Printf("Set Charging at: %dW\n", charge_pc*100)
} else {
fmt.Println("Disabling Charging and setting to defaults")
_, err = scd.Handler(solarPowerProduction, capacity2charge, pw_consumption, max_charge, start_hr, end_hr, fronius_ip)
if err != nil {
panic(err)
}

},
}

Expand Down
19 changes: 12 additions & 7 deletions pkg/fronius/configure.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package fronius
import (
"fmt"

u "ha-fronius-bm/src/utils"

"github.com/simonvetter/modbus"
)

Expand All @@ -27,9 +29,10 @@ var mdsc = map[uint16]int16{
func WriteFroniusModbusRegisters(modbusStorageCfg map[uint16]int16) error {

for r, v := range modbusStorageCfg {
u.Log.Infof("Writing register: %d ; value: %v", r, uint16(v))
err = modbusClient.WriteRegister(r-1, uint16(v))
if err != nil {
fmt.Printf("Something goes wrong writing the register: %d, value: %d\n", r, v)
u.Log.Errorf("Something goes wrong writing the register: %d, value: %d", r, v)
panic(err)
}
}
Expand All @@ -40,9 +43,9 @@ func ReadFroniusModbusRegisters(modbusStorageCfg map[uint16]int16) ([]int16, err
values := []int16{}
for r, v := range modbusStorageCfg {
value, err := modbusClient.ReadRegister(r-1, modbus.HOLDING_REGISTER)
// fmt.Printf("register: %d ; value: %v\n", r, value)
u.Log.Infof("Reading register: %d ; value: %v", r, value)
if err != nil {
fmt.Printf("Something goes wrong reading the register: %d, value: %d\n", r, v)
u.Log.Errorf("Something goes wrong reading the register: %d, value: %d", r, v)
panic(err)
}
values = append(values, int16(value))
Expand All @@ -52,28 +55,29 @@ func ReadFroniusModbusRegisters(modbusStorageCfg map[uint16]int16) ([]int16, err

func ReadFroniusModbusRegister(address uint16) (int16, error) {
value, err := modbusClient.ReadRegister(address-1, modbus.HOLDING_REGISTER)
// fmt.Printf("register: %d ; value: %v\n", address, value)
u.Log.Infof("Reading register: %d ; value: %v", address, value)
if err != nil {
fmt.Printf("Something goes wrong reading the register: %d, value: %d\n", address, value)
u.Log.Errorf("Something goes wrong reading the register: %d, value: %d", address, value)
panic(err)
}
return int16(value), nil
}

func Setdefaults(modbus_ip string) error {
u.Log.Info("Setting Fronius Storage Defaults start...")
regList := mdsc

OpenModbusClient(modbus_ip)

WriteFroniusModbusRegisters(regList)
ReadFroniusModbusRegisters(regList)

ClosemodbusClient()

u.Log.Info("Setting Fronius Modbus Defaults done.")
return nil
}

func ForceCharge(modbus_ip string, power_prc int16) error {
u.Log.Infof("Setting Fronius Storage Force Charge at %d% start...", power_prc)
if power_prc > 0 {
regList := mdsc

Expand All @@ -91,5 +95,6 @@ func ForceCharge(modbus_ip string, power_prc int16) error {
} else {
panic(fmt.Errorf("someting goes wrong when force charging, percent of charging is negative: %d", power_prc))
}
u.Log.Info("Setting Fronius Storage Force Charge done.")
return nil
}
10 changes: 5 additions & 5 deletions pkg/fronius/modbus.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package fronius

import (
"fmt"
u "ha-fronius-bm/src/utils"
"time"

"github.com/simonvetter/modbus"
Expand All @@ -17,17 +17,17 @@ func OpenModbusClient(url string) error {
Timeout: 1 * time.Second,
})
if err != nil {
fmt.Print("Someting goes wrong configuring Modbus Client")
u.Log.Error("Someting goes wrong configuring Modbus Client")
panic(err)
}
err = modbusClient.Open()
if err != nil {
fmt.Print("Someting goes wrong opening Modbus Client")
u.Log.Error("Someting goes wrong opening Modbus Client")
panic(err)
}
err = modbusClient.SetUnitId(1)
if err != nil {
fmt.Print("Someting goes wrong setting Modbus Client SlaveID")
u.Log.Error("Someting goes wrong setting Modbus Client SlaveID")
panic(err)
}

Expand All @@ -38,7 +38,7 @@ func OpenModbusClient(url string) error {
func ClosemodbusClient() error {
modbusClient.Close()
if err != nil {
fmt.Print("Someting goes wrong closing Modbus Client")
u.Log.Error("Someting goes wrong closing Modbus Client")
panic(err)
}

Expand Down
15 changes: 10 additions & 5 deletions pkg/fronius/schedule.go
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
package fronius

import (
"fmt"
u "ha-fronius-bm/src/utils"
"time"
)

func SetFroniusChargeBatteryMode(pw_forecast float64, pw_batt2charge float64, pw_consumption float64, max_charge int, start_hr string, end_hr string, fronius_ip string) (int16, error) {
var ch_pc int16 = 0
time, _ := CheckTimeRange(start_hr, end_hr)

if !time || pw_batt2charge == 0 { // out of the time range or battery 100% => do not charge
fmt.Printf("Out time range start_time: %s - end_time: %s\n", start_hr, end_hr)
if !time { // out of the time range => do not charge
u.Log.Infof("Out time range start_time: %s - end_time: %s", start_hr, end_hr)
Setdefaults(fronius_ip)
} else if pw_batt2charge == 0 { // battery 100% => do not charge
u.Log.Infof("Battery to charge: %f%", pw_batt2charge)
Setdefaults(fronius_ip)
} else { // in the time range
pw_pv_net := pw_forecast - pw_consumption
Expand All @@ -19,9 +22,11 @@ func SetFroniusChargeBatteryMode(pw_forecast float64, pw_batt2charge float64, pw
pw_max, _ := ReadFroniusModbusRegister(WChaMax)
ClosemodbusClient()
if pw_pv_net <= 0 { // net pv power is not enough => charge the diff
u.Log.Infof("Net Forecast Power is not enough: %f W", pw_pv_net)
ch_pc = SetChargePower(float64(pw_max), -1*pw_pv_net, float64(max_charge))
ForceCharge(fronius_ip, ch_pc)
} else { // there is pv power available
u.Log.Infof("Net Forecast Power is enough: %f W", pw_pv_net)
pw_grid := pw_batt2charge - pw_pv_net
if pw_grid > 0 { // it's less than the battery's capacity to charge => charge the the diff
ch_pc = SetChargePower(float64(pw_max), pw_grid, float64(max_charge))
Expand All @@ -46,13 +51,13 @@ func CheckTimeRange(start_hr string, end_hr string) (bool, error) {
layout := "15:04"
startTime, err := time.Parse(layout, start_hr)
if err != nil {
fmt.Print("Something goes wrong parsing start time")
u.Log.Error("Something goes wrong parsing start time")
panic(err)
}

endTime, err := time.Parse(layout, end_hr)
if err != nil {
fmt.Print("Something goes wrong parsing end time")
u.Log.Error("Something goes wrong parsing end time")
panic(err)
}

Expand Down
9 changes: 5 additions & 4 deletions pkg/power/estimate.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package power

import (
"encoding/json"
"fmt"
u "ha-fronius-bm/src/utils"
"net/http"
"time"
)
Expand All @@ -26,7 +26,6 @@ func GetForecast(apiKey string, url string) (Forecasts, error) {
if err != nil {
return Forecasts{}, err
}

return forecasts, nil
}

Expand All @@ -35,7 +34,7 @@ func GetTotalDayPowerEstimate(forecasts Forecasts, day time.Time) (float64, erro
for _, forecast := range forecasts.Forecasts {
periodEnd, err := time.Parse(time.RFC3339, forecast.PeriodEnd)
if err != nil {
fmt.Println("Error parsing time:", err)
u.Log.Errorln("Error parsing time:", err)
return totalPower, err
}
if periodEnd.Year() == day.Year() && periodEnd.YearDay() == day.YearDay() {
Expand All @@ -44,7 +43,9 @@ func GetTotalDayPowerEstimate(forecasts Forecasts, day time.Time) (float64, erro
}

// The calculated totalPower is in Wh
return totalPower * 1000, nil
totalPower = totalPower * 1000
u.Log.Infof("Forecast Solar Power: %d W", int(totalPower))
return totalPower, nil
}

func checkMidnight(now time.Time) time.Time {
Expand Down
Loading

0 comments on commit aeceb77

Please sign in to comment.