2023-07-10 09:02:17 +00:00
|
|
|
package connection
|
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2024-05-20 11:21:21 +00:00
|
|
|
type Connectable interface {
|
|
|
|
SetIsConnected(bool)
|
|
|
|
IsConnected() bool
|
|
|
|
}
|
|
|
|
|
2023-09-22 13:18:42 +00:00
|
|
|
type StateChangeCb func(State)
|
|
|
|
|
2023-07-10 09:02:17 +00:00
|
|
|
type Status struct {
|
2023-09-22 13:18:42 +00:00
|
|
|
stateChangeCb StateChangeCb
|
|
|
|
state State
|
|
|
|
stateLock sync.RWMutex
|
2023-07-10 09:02:17 +00:00
|
|
|
}
|
|
|
|
|
2023-09-22 13:18:42 +00:00
|
|
|
func NewStatus() *Status {
|
2023-07-10 09:02:17 +00:00
|
|
|
return &Status{
|
2023-09-22 13:18:42 +00:00
|
|
|
state: NewState(),
|
2023-07-10 09:02:17 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-09-22 13:18:42 +00:00
|
|
|
func (c *Status) SetStateChangeCb(stateChangeCb StateChangeCb) {
|
|
|
|
c.stateChangeCb = stateChangeCb
|
|
|
|
}
|
|
|
|
|
2023-07-10 09:02:17 +00:00
|
|
|
func (c *Status) SetIsConnected(value bool) {
|
2023-09-22 13:18:42 +00:00
|
|
|
now := time.Now().Unix()
|
|
|
|
|
|
|
|
state := c.GetState()
|
|
|
|
state.LastCheckedAt = now
|
|
|
|
if value {
|
|
|
|
state.LastSuccessAt = now
|
2023-07-10 09:02:17 +00:00
|
|
|
}
|
2023-09-22 13:18:42 +00:00
|
|
|
if value {
|
|
|
|
state.Value = StateValueConnected
|
|
|
|
} else {
|
|
|
|
state.Value = StateValueDisconnected
|
|
|
|
}
|
|
|
|
|
|
|
|
c.SetState(state)
|
2023-07-10 09:02:17 +00:00
|
|
|
}
|
|
|
|
|
2023-09-22 13:18:42 +00:00
|
|
|
func (c *Status) ResetStateValue() {
|
|
|
|
state := c.GetState()
|
|
|
|
state.Value = StateValueUnknown
|
|
|
|
c.SetState(state)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Status) GetState() State {
|
|
|
|
c.stateLock.RLock()
|
|
|
|
defer c.stateLock.RUnlock()
|
2023-07-10 09:02:17 +00:00
|
|
|
|
2023-09-22 13:18:42 +00:00
|
|
|
return c.state
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Status) SetState(state State) {
|
|
|
|
c.stateLock.Lock()
|
|
|
|
isStateChange := c.state.Value != state.Value
|
|
|
|
c.state = state
|
|
|
|
c.stateLock.Unlock()
|
|
|
|
|
|
|
|
if isStateChange && c.stateChangeCb != nil {
|
|
|
|
c.stateChangeCb(state)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Status) GetStateValue() StateValue {
|
|
|
|
return c.GetState().Value
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Status) IsConnected() bool {
|
|
|
|
return c.GetStateValue() == StateValueConnected
|
2023-07-10 09:02:17 +00:00
|
|
|
}
|