Skip to content

Commit

Permalink
Move resolution out of formats
Browse files Browse the repository at this point in the history
  • Loading branch information
pakerfeldt committed Aug 29, 2024
1 parent 5048c80 commit 1c067d1
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 43 deletions.
37 changes: 0 additions & 37 deletions knx/dpt/formats.go
Original file line number Diff line number Diff line change
Expand Up @@ -228,43 +228,6 @@ func unpackV16(data []byte, i *int16) error {
return nil
}

func packV32AsV16(i int32, resolution int32) []byte {
return packV16(int16(i / resolution))
}

func unpackV16AsV32(data []byte, i *int32, resolution int32) error {
if len(data) != 3 {
return ErrInvalidLength
}
var i16 int16
err := unpackV16(data, &i16)
if err != nil {
return err
}

*i = int32(i16) * resolution
return nil
}

func packFloat32AsV16(f float32, resolution float32) []byte {
return packV16(int16(math.Round(float64(f / resolution))))
}

func unpackV16AsFloat32(data []byte, f *float32, resolution float32) error {
if len(data) != 3 {
return ErrInvalidLength
}

var i int16
if err := unpackV16(data, &i); err != nil {
return err
}

*f = float32(i) * resolution

return nil
}

func packV32(i int32) []byte {
b := make([]byte, 5)

Expand Down
28 changes: 22 additions & 6 deletions knx/dpt/types_8.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package dpt

import (
"fmt"
"math"
)

// DPT_8001 represents DPT 8.001 / Counter.
Expand Down Expand Up @@ -49,11 +50,16 @@ func (d DPT_8002) String() string {
type DPT_8003 int32

func (d DPT_8003) Pack() []byte {
return packV32AsV16(int32(d), 10)
return packV16(int16(int32(d) / 10))
}

func (d *DPT_8003) Unpack(data []byte) error {
return unpackV16AsV32(data, (*int32)(d), 10)
var i int16
if err := unpackV16(data, &i); err != nil {
return nil
}
*d = DPT_8003(int32(i) * 10)
return nil
}

func (d DPT_8003) Unit() string {
Expand All @@ -68,11 +74,16 @@ func (d DPT_8003) String() string {
type DPT_8004 int32

func (d DPT_8004) Pack() []byte {
return packV32AsV16(int32(d), 100)
return packV16(int16(int32(d) / 100))
}

func (d *DPT_8004) Unpack(data []byte) error {
return unpackV16AsV32(data, (*int32)(d), 100)
var i int16
if err := unpackV16(data, &i); err != nil {
return nil
}
*d = DPT_8004(int32(i) * 100)
return nil
}

func (d DPT_8004) Unit() string {
Expand Down Expand Up @@ -144,11 +155,16 @@ func (d DPT_8007) String() string {
type DPT_8010 float32

func (d DPT_8010) Pack() []byte {
return packFloat32AsV16(float32(d), 0.01)
return packV16(int16(math.Round(float64(d) / 0.01)))
}

func (d *DPT_8010) Unpack(data []byte) error {
return unpackV16AsFloat32(data, (*float32)(d), 0.01)
var i int16
if err := unpackV16(data, &i); err != nil {
return nil
}
*d = DPT_8010(float32(i) * 0.01)
return nil
}

func (d DPT_8010) Unit() string {
Expand Down

0 comments on commit 1c067d1

Please sign in to comment.