Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Move token handling to identity #4

Merged
merged 8 commits into from
Dec 23, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Move token handling to identity
  • Loading branch information
andig committed Dec 21, 2024
commit eca372093992a66426ca88968ad170b722d88bd8
52 changes: 10 additions & 42 deletions connection.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,15 @@ import (
"fmt"
"log"
"net/http"
"time"

"net/url"
"time"

"golang.org/x/oauth2"
)

// Connection is the Sensonet connection
type Connection struct {
client *Helper
identity *Identity
homesAndSystemsCache Cacheable[HomesAndSystems]
cache time.Duration
currentQuickmode string
Expand All @@ -25,56 +23,27 @@ type Connection struct {
}

// NewConnection creates a new Sensonet device connection.
func NewConnection(client *http.Client, credentials *CredentialsStruct, token *oauth2.Token) (*Connection, *oauth2.Token, error) {
helper := NewHelper(client)
identity, err := NewIdentity(helper, credentials)
if err != nil {
log.Fatal(err)
}
var ts oauth2.TokenSource
if token == nil {
log.Println("No token provided. Calling login")
token, err = identity.Login()
if err != nil {
log.Fatal(err)
}
}

ts, err = identity.TokenSource(token)
if err != nil {
log.Println("Error generating token source from provied token. Calling login")
token, err = identity.Login()
if err != nil {
log.Fatal(err)
}
ts, err = identity.TokenSource(token)
if err != nil {
log.Fatal(err)
}
log.Println("Generating new token source successful")
}

func NewConnection(client *http.Client, ts oauth2.TokenSource) (*Connection, error) {
client.Transport = &oauth2.Transport{
Source: ts,
Base: client.Transport,
}

conn := &Connection{
client: helper,
identity: identity,
client: NewHelper(client),
cache: 90 * time.Second,
currentQuickmode: "", // assuming that no quick mode is active
quickmodeStarted: time.Now(),
quickmodeStopped: time.Now().Add(-2 * time.Minute), //time stamp is set in the past so that first call of refreshCurrentQuickMode() changes currentQuickmode if necessary
quickmodeStopped: time.Now().Add(-2 * time.Minute), // time stamp is set in the past so that first call of refreshCurrentQuickMode() changes currentQuickmode if necessary
}
token, _ = ts.Token()

conn.homesAndSystemsCache = ResettableCached(func() (HomesAndSystems, error) {
var res HomesAndSystems
err := conn.getHomesAndSystems(&res)
return res, err
}, conn.cache)

return conn, token, nil
return conn, nil
}

func (c *Connection) GetCurrentQuickMode() string {
Expand All @@ -99,7 +68,7 @@ func (c *Connection) getHomesAndSystems(res *HomesAndSystems) error {
req, _ := http.NewRequest("GET", uri, nil)
req.Header = c.getSensonetHttpHeader()

//var res Homes
// var res Homes
if err := c.client.DoJSON(req, &res.Homes); err != nil {
return fmt.Errorf("error getting homes: %w", err)
}
Expand All @@ -124,7 +93,6 @@ func (c *Connection) getHomesAndSystems(res *HomesAndSystems) error {
systemAndId.SystemDevices = systemDevices
if len(res.Systems) <= i {
res.Systems = append(res.Systems, systemAndId)

} else {
res.Systems[i] = systemAndId
}
Expand Down Expand Up @@ -351,14 +319,14 @@ func (c *Connection) StartStrategybased(systemId string, strategy int, heatingPa
}
default:
if c.currentQuickmode == QUICKMODE_HOTWATER {
//if hotwater boost active, then stop it
// if hotwater boost active, then stop it
err = c.StopHotWaterBoost(systemId, hotwaterPar.Index)
if err == nil {
log.Println("Stopping Hotwater Boost")
}
}
if c.currentQuickmode == QUICKMODE_HEATING {
//if zone quick veto active, then stop it
// if zone quick veto active, then stop it
err = c.StopZoneQuickVeto(systemId, heatingPar.ZoneIndex)
if err == nil {
log.Println("Stopping Zone Quick Veto")
Expand Down Expand Up @@ -416,7 +384,7 @@ func (c *Connection) StopStrategybased(systemId string, strategy int, heatingPar
// and returns, which quick mode should be started, when evcc sends an "Enable"
func (c *Connection) WhichQuickMode(dhwData *DhwData, zoneData *ZoneData, strategy int, heatingPar *HeatingParStruct, hotwater *HotwaterParStruct) int {
log.Println("Strategy = ", strategy)
//log.Printf("Checking if hot water boost possible. Operation Mode = %s, temperature setpoint= %02.2f, live temperature= %02.2f", res.Hotwater.OperationMode, res.Hotwater.HotwaterTemperatureSetpoint, res.Hotwater.HotwaterLiveTemperature)
// log.Printf("Checking if hot water boost possible. Operation Mode = %s, temperature setpoint= %02.2f, live temperature= %02.2f", res.Hotwater.OperationMode, res.Hotwater.HotwaterTemperatureSetpoint, res.Hotwater.HotwaterLiveTemperature)
// For strategy=STRATEGY_HOTWATER, a hotwater boost is possible when hotwater storage temperature is less than the temperature setpoint.
// For other strategies, a hotwater boost is possible when hotwater storage temperature is less than the temperature setpoint minus 5°C
addOn := -5.0
Expand Down
11 changes: 5 additions & 6 deletions identity.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,11 @@ import (
"net/http/cookiejar"
"net/url"
"strings"
"sync"
"time"

"github.com/coreos/go-oidc/v3/oidc"

"sync"

"dario.cat/mergo"
"golang.org/x/oauth2"
)
Expand All @@ -39,13 +38,13 @@ func Oauth2ConfigForRealm(realm string) *oauth2.Config {

type Identity struct {
client *Helper
trclient *Helper //seperate client for token refresh
trclient *Helper // seperate client for token refresh
user string
password string
realm string
}

func NewIdentity(client *Helper, credentials *CredentialsStruct) (*Identity, error) {
func NewIdentity(client *http.Client, credentials *CredentialsStruct) (*Identity, error) {
client.Jar, _ = cookiejar.New(nil)
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
Expand All @@ -57,7 +56,7 @@ func NewIdentity(client *Helper, credentials *CredentialsStruct) (*Identity, err
}

v := &Identity{
client: client,
client: NewHelper(client),
trclient: trclient,
user: credentials.User,
password: credentials.Password,
Expand All @@ -75,7 +74,7 @@ func NewIdentity(client *Helper, credentials *CredentialsStruct) (*Identity, err
func newClient() *http.Client {
return &http.Client{
Timeout: timeout,
//Transport: httplogger.NewLoggedTransport(http.DefaultTransport, newLogger(log)),
// Transport: httplogger.NewLoggedTransport(http.DefaultTransport, newLogger(log)),
}
}

Expand Down