This commit is contained in:
Nicolas Duhamel 2022-10-28 19:20:04 +02:00
parent 11b3622abe
commit 6837a07beb
6 changed files with 1171 additions and 1194 deletions

50
main.go
View File

@ -1,18 +1,19 @@
package main package main
import ( import (
"citadel/heater/pkg/device"
"citadel/heater/mqtt" "citadel/heater/mqtt"
mqttpaho "github.com/eclipse/paho.mqtt.golang" "citadel/heater/pkg/device"
"context" "context"
"encoding/json" "encoding/json"
"flag"
"os" "os"
"os/signal" "os/signal"
"strings"
"syscall" "syscall"
"time" "time"
"strings"
mqttpaho "github.com/eclipse/paho.mqtt.golang"
"github.com/rs/zerolog" "github.com/rs/zerolog"
"flag"
) )
type Config struct { type Config struct {
@ -115,9 +116,13 @@ func (app *App) onSettingsMessage(ctx context.Context, msg mqttpaho.Message) {
Str("device", device_name). Str("device", device_name).
Logger() Logger()
logger.Debug().Str("topic", msg.Topic()).Str("payload", string(msg.Payload())).Msg("")
ctx = logger.WithContext(ctx) ctx = logger.WithContext(ctx)
logger.Debug().
Str("topic", msg.Topic()).
Str("payload", string(msg.Payload())).
Msg("")
var device_settings device.DeviceSettings var device_settings device.DeviceSettings
if err := json.Unmarshal(msg.Payload(), &device_settings); err != nil { if err := json.Unmarshal(msg.Payload(), &device_settings); err != nil {
logger.Error().Err(err).Msg("Parsing payload") logger.Error().Err(err).Msg("Parsing payload")
@ -129,21 +134,19 @@ func (app *App) onSettingsMessage(ctx context.Context, msg mqttpaho.Message) {
} }
if _, ok := app.DeviceManager.Get(device_name); !ok { if _, ok := app.DeviceManager.Get(device_name); !ok {
err := app.DeviceManager.Add(tvr) if err := app.DeviceManager.Add(tvr); err != nil {
if err != nil { logger.Error().Err(err).Msg("unexpected, abord")
logger.Error().Err(err).Msg("Unexpected")
return return
} }
} else { } else {
err := app.DeviceManager.SetSettings(device_name, device_settings) if err := app.DeviceManager.
if err != nil { SetSettings(device_name, device_settings); err != nil {
logger.Error().Err(err).Msg("Unexpected") logger.Error().Err(err).Msg("unexpected, abord")
return return
} }
} }
err := app.DeviceManager.Check(ctx, device_name) if err := app.DeviceManager.Check(ctx, device_name); err != nil {
if err != nil {
logger.Error().Err(err).Msg("During device `Check`") logger.Error().Err(err).Msg("During device `Check`")
} }
} }
@ -159,28 +162,23 @@ func (app *App) onSetStateMessage(ctx context.Context, msg mqttpaho.Message) {
Logger() Logger()
ctx = logger.WithContext(ctx) ctx = logger.WithContext(ctx)
var state device.DeviceState var state device.DeviceState
if err := json.Unmarshal(msg.Payload(), &state); err != nil { if err := json.Unmarshal(msg.Payload(), &state); err != nil {
logger.Error().Err(err).Msg("Error while parsing payload") logger.Error().Err(err).Msg("Error while parsing payload")
}
logger.Info().Interface("state", state).Msg("new state")
device, ok := app.DeviceManager.Get(device_name)
if !ok {
logger.Error().Msg("Device not found, abord")
return return
} }
logger.Debug().Interface("state", state).Msg("new state")
if device, ok := app.DeviceManager.Get(device_name); ok {
if err := device.SetState(&logger, state, app.PubChan); err != nil { if err := device.SetState(&logger, state, app.PubChan); err != nil {
logger.Error().Err(err).Msg("") logger.Error().Err(err).Msg("unexpected")
return return
} }
} else {
logger.Error().Msg("Device not found, abord")
}
} }
func (app *App) Run() { func (app *App) Run() {
ctx, ctxCancel := context.WithCancel(context.Background()) ctx, ctxCancel := context.WithCancel(context.Background())
@ -191,7 +189,6 @@ func (app *App) Run() {
ctx = log.WithContext(ctx) ctx = log.WithContext(ctx)
defer ctxCancel() defer ctxCancel()
if err := app.mqtt_hub.Connect(ctx); err != nil { if err := app.mqtt_hub.Connect(ctx); err != nil {
@ -271,4 +268,3 @@ func main() {
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM) signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit <-quit
} }

View File

@ -1,13 +1,14 @@
package device package device
import ( import (
"github.com/eclipse/paho.mqtt.golang" "context"
"github.com/ohler55/ojg/jp" "encoding/json"
"github.com/ohler55/ojg/oj"
"fmt" "fmt"
"time" "time"
"encoding/json"
"context" mqtt "github.com/eclipse/paho.mqtt.golang"
"github.com/ohler55/ojg/jp"
"github.com/ohler55/ojg/oj"
"github.com/rs/zerolog" "github.com/rs/zerolog"
// "reflect" // "reflect"
) )
@ -16,10 +17,9 @@ var timeNow = func() time.Time {
return time.Now() return time.Now()
} }
type Error string type Error string
func (e Error) Error() string { return string(e) }
func (e Error) Error() string { return string(e) }
type DeviceState struct { type DeviceState struct {
Mode string `json:"mode"` Mode string `json:"mode"`
@ -62,7 +62,6 @@ func (s *DeviceState) Equivalent(state DeviceState) bool {
return true return true
} }
// Internal state // Internal state
type Device struct { type Device struct {
Name string Name string
@ -71,7 +70,6 @@ type Device struct {
State DeviceState State DeviceState
} }
func (d *Device) StateTopic() string { func (d *Device) StateTopic() string {
return fmt.Sprintf("heater/%s/state", d.Name) return fmt.Sprintf("heater/%s/state", d.Name)
} }
@ -80,7 +78,6 @@ func (d Device) ListenTopic() (string, error) {
return d.Settings.TVR.FormatTopicState(d.Name) return d.Settings.TVR.FormatTopicState(d.Name)
} }
func (d *Device) Program() (WeekProgram, error) { func (d *Device) Program() (WeekProgram, error) {
// return current device program if specified or default one // return current device program if specified or default one
prog_name := "default" prog_name := "default"
@ -96,8 +93,7 @@ func (d *Device) Program() (WeekProgram, error) {
return program, nil return program, nil
} }
func (d *Device) ProgramName() string {
func (d *Device) ProgramName() (string) {
prog_name := "default" prog_name := "default"
if d.State.Program_name != "" { if d.State.Program_name != "" {
prog_name = d.State.Program_name prog_name = d.State.Program_name
@ -105,7 +101,6 @@ func (d *Device) ProgramName() (string) {
return prog_name return prog_name
} }
func (d *Device) publishState(pubchan chan Message) error { func (d *Device) publishState(pubchan chan Message) error {
payload, err := json.Marshal(d.State) payload, err := json.Marshal(d.State)
@ -122,7 +117,6 @@ func (d *Device) publishState(pubchan chan Message) error {
return nil return nil
} }
func (d *Device) SetSetpoint(value int, pubchan chan Message) error { func (d *Device) SetSetpoint(value int, pubchan chan Message) error {
topic, err := d.Settings.TVR.FormatTopic(d.Name) topic, err := d.Settings.TVR.FormatTopic(d.Name)
if err != nil { if err != nil {
@ -142,7 +136,6 @@ func (d *Device) SetSetpoint(value int, pubchan chan Message) error {
return nil return nil
} }
func (d *Device) SetState(log *zerolog.Logger, state DeviceState, pubchan chan Message) error { func (d *Device) SetState(log *zerolog.Logger, state DeviceState, pubchan chan Message) error {
// If same state do nothing // If same state do nothing
// else use checksetpoint for changing state // else use checksetpoint for changing state
@ -166,7 +159,6 @@ func (d *Device) SetState(log *zerolog.Logger, state DeviceState, pubchan chan M
return nil return nil
} }
func (d *Device) CheckSetpoint(log *zerolog.Logger, pubchan chan Message) error { func (d *Device) CheckSetpoint(log *zerolog.Logger, pubchan chan Message) error {
change, err := d.update(log, pubchan) change, err := d.update(log, pubchan)
if err != nil { if err != nil {
@ -182,7 +174,6 @@ func (d *Device) CheckSetpoint(log *zerolog.Logger, pubchan chan Message) error
return nil return nil
} }
func (d *Device) update(log *zerolog.Logger, pubchan chan Message) (bool, error) { func (d *Device) update(log *zerolog.Logger, pubchan chan Message) (bool, error) {
// Handle all the update setpoint logic // Handle all the update setpoint logic
// push in pubChan a Message if setpoint need to be update // push in pubChan a Message if setpoint need to be update
@ -193,7 +184,7 @@ func (d *Device) update(log *zerolog.Logger, pubchan chan Message) (bool, error)
Int("State.Setpoint", d.State.Setpoint). Int("State.Setpoint", d.State.Setpoint).
Str("State.Program_name", d.State.Program_name). Str("State.Program_name", d.State.Program_name).
Logger() Logger()
log.Info().Msg("Check if setpoint need an update") log.Debug().Msg("check if setpoint need an update")
switch d.State.Mode { switch d.State.Mode {
case "always": case "always":
@ -213,7 +204,6 @@ func (d *Device) update(log *zerolog.Logger, pubchan chan Message) (bool, error)
} }
func (d *Device) onMessage(ctx context.Context, msg mqtt.Message) { func (d *Device) onMessage(ctx context.Context, msg mqtt.Message) {
log := zerolog.Ctx(ctx).With(). log := zerolog.Ctx(ctx).With().
Str("action", "device state receive"). Str("action", "device state receive").
@ -247,7 +237,6 @@ func (d *Device) onMessage(ctx context.Context, msg mqtt.Message) {
} }
func (d *Device) handle_reset_state(log *zerolog.Logger, pubchan chan Message) (bool, error) { func (d *Device) handle_reset_state(log *zerolog.Logger, pubchan chan Message) (bool, error) {
// called when need to fallback to program mode previous or default // called when need to fallback to program mode previous or default
program, err := d.Program() program, err := d.Program()
@ -280,7 +269,6 @@ func (d *Device) handle_reset_state(log *zerolog.Logger, pubchan chan Message) (
return true, nil return true, nil
} }
func (d *Device) handle_always(log *zerolog.Logger, pubchan chan Message) (bool, error) { func (d *Device) handle_always(log *zerolog.Logger, pubchan chan Message) (bool, error) {
// return true if change made // return true if change made

View File

@ -1,9 +1,10 @@
package device package device
import ( import (
"fmt"
"context" "context"
"github.com/eclipse/paho.mqtt.golang" "fmt"
mqtt "github.com/eclipse/paho.mqtt.golang"
"github.com/rs/zerolog" "github.com/rs/zerolog"
) )

View File

@ -1,18 +1,18 @@
package device package device
import ( import (
"fmt"
"io/ioutil"
"reflect"
"testing" "testing"
"time" "time"
"fmt"
"reflect"
"github.com/rs/zerolog" "github.com/rs/zerolog"
"io/ioutil"
) )
// monday // monday
var test_time = time.Date(2022, time.October, 24, 0, 0, 0, 0, time.Local) var test_time = time.Date(2022, time.October, 24, 0, 0, 0, 0, time.Local)
var test_presets = []Preset{ var test_presets = []Preset{
{Label: "default", Value: 17, Color: "#012a36"}, {Label: "default", Value: 17, Color: "#012a36"},
{Label: "normal", Value: 19, Color: "#b6244f"}, {Label: "normal", Value: 19, Color: "#b6244f"},
@ -241,7 +241,6 @@ func TestStateEquivalent(t *testing.T) {
} }
} }
func TestStateTopic(t *testing.T) { func TestStateTopic(t *testing.T) {
topic := test_device.StateTopic() topic := test_device.StateTopic()
if topic != "heater/valid/state" { if topic != "heater/valid/state" {
@ -310,7 +309,6 @@ func TestProgram(t *testing.T) {
} }
} }
func TestUpdate(t *testing.T) { func TestUpdate(t *testing.T) {
// device 1: currentSetpoint 0 program, not specified expect default // device 1: currentSetpoint 0 program, not specified expect default
// device 2: currentSetpoint 0 program, unknown one, expect error // device 2: currentSetpoint 0 program, unknown one, expect error
@ -319,7 +317,6 @@ func TestUpdate(t *testing.T) {
// device 5: currentSetpoint 17 indem 4 but fixed timeNow-2h // device 5: currentSetpoint 17 indem 4 but fixed timeNow-2h
// device 6: currentSetpoint 17, until_next set a timeNow, test time time now +1h : no change // device 6: currentSetpoint 17, until_next set a timeNow, test time time now +1h : no change
timeNow = func() time.Time { timeNow = func() time.Time {
return test_time return test_time
} }
@ -373,7 +370,6 @@ func TestUpdate(t *testing.T) {
Time: timeNow(), Time: timeNow(),
} }
var tests = []struct { var tests = []struct {
getTime func() time.Time getTime func() time.Time
device Device device Device
@ -382,7 +378,7 @@ func TestUpdate(t *testing.T) {
err error err error
}{ }{
{timeNow, device1, []Message{ {timeNow, device1, []Message{
Message{ {
Payload: []byte("{\"current_heating_setpoint\": 17}"), Payload: []byte("{\"current_heating_setpoint\": 17}"),
Topic: "zigbee2mqtt/TVR/1/set", Topic: "zigbee2mqtt/TVR/1/set",
Retain: false, Retain: false,
@ -390,7 +386,7 @@ func TestUpdate(t *testing.T) {
}, true, nil}, }, true, nil},
{timeNow, device2, []Message{}, false, Error("device 2 don't have unknown program")}, {timeNow, device2, []Message{}, false, Error("device 2 don't have unknown program")},
{timeNow, device3, []Message{ {timeNow, device3, []Message{
Message{ {
Payload: []byte("{\"current_heating_setpoint\": 22}"), Payload: []byte("{\"current_heating_setpoint\": 22}"),
Topic: "zigbee2mqtt/TVR/3/set", Topic: "zigbee2mqtt/TVR/3/set",
Retain: false, Retain: false,
@ -400,7 +396,7 @@ func TestUpdate(t *testing.T) {
{timeNow, device5, []Message{}, true, nil}, {timeNow, device5, []Message{}, true, nil},
{timeNow, device6, []Message{}, false, nil}, {timeNow, device6, []Message{}, false, nil},
{func() time.Time { return test_time.Add(7*time.Hour + 30*time.Minute) }, device6, []Message{ {func() time.Time { return test_time.Add(7*time.Hour + 30*time.Minute) }, device6, []Message{
Message{ {
Payload: []byte("{\"current_heating_setpoint\": 19}"), Payload: []byte("{\"current_heating_setpoint\": 19}"),
Topic: "zigbee2mqtt/TVR/6/set", Topic: "zigbee2mqtt/TVR/6/set",
Retain: false, Retain: false,

View File

@ -1,10 +1,10 @@
package device package device
import ( import (
"time"
"bytes" "bytes"
"text/template"
"fmt" "fmt"
"text/template"
"time"
) )
type DayOfWeek int type DayOfWeek int
@ -25,7 +25,7 @@ func (d DayOfWeek) Previous() DayOfWeek {
func (d DayOfWeek) DaysBetween(n DayOfWeek) int { func (d DayOfWeek) DaysBetween(n DayOfWeek) int {
var between int var between int
if (n < d) { if n < d {
between = 7 - int(d-n) between = 7 - int(d-n)
} else { } else {
between = int(n - d) between = int(n - d)
@ -83,7 +83,6 @@ func (s Setpoint) Value(presets []Preset) (int, error) {
return presets[s.Preset_id].Value, nil return presets[s.Preset_id].Value, nil
} }
type WeekProgram map[DayOfWeek][]Setpoint type WeekProgram map[DayOfWeek][]Setpoint
func (p WeekProgram) Current() Setpoint { func (p WeekProgram) Current() Setpoint {
@ -135,7 +134,7 @@ func (p WeekProgram) NextTime(t time.Time) (time.Time, error) {
weekday = weekday.Next() weekday = weekday.Next()
daytime = 0 daytime = 0
if weekday == startweekday { if weekday == startweekday {
return time.Time{}, fmt.Errorf("Shouldn't happen no setpoint found over the week") return time.Time{}, Error("shouldn't happen no setpoint found over the week")
} }
} }

View File

@ -1,9 +1,9 @@
package device package device
import ( import (
"fmt"
"testing" "testing"
"time" "time"
"fmt"
) )
func TestDaysBetween(t *testing.T) { func TestDaysBetween(t *testing.T) {
@ -29,7 +29,6 @@ func TestDaysBetween(t *testing.T) {
} }
} }
func TestNextTime(t *testing.T) { func TestNextTime(t *testing.T) {
defaultSetpoints := []Setpoint{ defaultSetpoints := []Setpoint{
@ -43,7 +42,6 @@ func TestNextTime(t *testing.T) {
{Start: 0, Preset_id: 0}, {Start: 0, Preset_id: 0},
} }
default_program := WeekProgram{ default_program := WeekProgram{
Monday: defaultSetpoints, Monday: defaultSetpoints,
Thuesday: defaultSetpoints, Thuesday: defaultSetpoints,
@ -64,7 +62,6 @@ func TestNextTime(t *testing.T) {
Sunday: zeroSetpoints, Sunday: zeroSetpoints,
} }
var tests = []struct { var tests = []struct {
prog WeekProgram prog WeekProgram
time time.Time time time.Time