Skip to content

Commit

Permalink
Added tick checking
Browse files Browse the repository at this point in the history
  • Loading branch information
virtualzone committed Mar 26, 2024
1 parent 4ea027e commit 1499e6c
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
34 changes: 34 additions & 0 deletions node/charge-controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@ import (
"fmt"
"log"
"math"
"slices"
"sort"
"strings"
"sync"
"time"
)

Expand All @@ -19,13 +21,16 @@ type ChargeController struct {
Time Time
Async bool
ChargeStartFailCount int
inTick []string
inTickMutex sync.Mutex
}

func NewChargeController() *ChargeController {
return &ChargeController{
Time: new(RealTime),
Async: true,
ChargeStartFailCount: 0,
inTick: []string{},
}
}

Expand Down Expand Up @@ -55,6 +60,27 @@ func (c *ChargeController) OnTick() {
}
}

func (c *ChargeController) setInTick(vin string) {
c.inTickMutex.Lock()
defer c.inTickMutex.Unlock()
if !slices.Contains(c.inTick, vin) {
c.inTick = append(c.inTick, vin)
}
}

func (c *ChargeController) unsetInTick(vin string) {
c.inTickMutex.Lock()
defer c.inTickMutex.Unlock()
idx := slices.Index(c.inTick, vin)
if idx > -1 {
c.inTick = slices.Delete(c.inTick, idx, 1)
}
}

func (c *ChargeController) isInTick(vin string) bool {
return slices.Contains(c.inTick, vin)
}

func (c *ChargeController) processVehicle(vehicle *Vehicle) {
state := GetDB().GetVehicleState(vehicle.VIN)
if state == nil {
Expand All @@ -72,6 +98,14 @@ func (c *ChargeController) processVehicle(vehicle *Vehicle) {
return
}

if c.isInTick(vehicle.VIN) {
// skip this round if vehicle is still processing
return
}

c.setInTick(vehicle.VIN)
defer c.unsetInTick(vehicle.VIN)

if !vehicle.Enabled && state.Charging != ChargeStateNotCharging {
// Stop charging if vehicle is still charging but not enabled anymore
c.stopCharging(vehicle, state)
Expand Down
16 changes: 16 additions & 0 deletions node/charge-controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1331,3 +1331,19 @@ func TestChargeControl_getActualSurplus_oldRecords(t *testing.T) {
assert.NotNil(t, surplus)
assert.Equal(t, 3000, surplus)
}

func TestChargeControl_setInTick(t *testing.T) {
t.Cleanup(ResetTestDB)

cc := NewTestChargeController()
assert.False(t, cc.isInTick("123"))

cc.setInTick("123")
cc.setInTick("123")
assert.True(t, cc.isInTick("123"))
assert.Equal(t, 1, len(cc.inTick))
assert.Equal(t, "123", cc.inTick[0])

cc.unsetInTick("123")
assert.False(t, cc.isInTick("123"))
}

0 comments on commit 1499e6c

Please sign in to comment.