1
0
Fork 0
go-satel/get_name.go

83 lines
2.4 KiB
Go

package satel
import (
"errors"
"strings"
"golang.org/x/text/encoding/charmap"
)
type DeviceType byte
const (
DeviceType_Partition DeviceType = 0
DeviceType_Zone DeviceType = 1
DeviceType_User DeviceType = 2
DeviceType_ExpanderOrLCD DeviceType = 3
DeviceType_Output DeviceType = 4
DeviceType_ZoneWithPartitionAssignment DeviceType = 5
DeviceType_Timer DeviceType = 6
DeviceType_Telephone DeviceType = 7
DeviceType_Object DeviceType = 15
DeviceType_PartitionWithObjectAssignment DeviceType = 16
DeviceType_OutputWithDurationTime DeviceType = 17
DeviceType_PartitionWithObjectAssignmentAndOptions DeviceType = 18
)
type NameEvent struct {
DevType DeviceType
DevNumber byte
DevTypeFunction byte
DevName string
}
func makeNameEvent(bytes []byte) (*NameEvent, error) {
if len(bytes) < 19 {
return nil, errors.New("Received data too short")
}
cp1250dec := charmap.Windows1250.NewDecoder()
name, err := cp1250dec.String(string(bytes[3:19]))
if err != nil {
return nil, err
}
return &NameEvent{
DevType: DeviceType(bytes[0]),
DevNumber: bytes[1],
DevTypeFunction: bytes[2],
DevName: strings.TrimSpace(name),
}, nil
}
type getNameResult struct {
ev *NameEvent
err error
}
func (s *Satel) GetName(devType DeviceType, devIndex byte) (*NameEvent, error) {
resultChan := make(chan getNameResult)
s.commandQueue <- func() {
err := s.sendCmd(0xEE, byte(devType), devIndex)
if err != nil {
resultChan <- getNameResult{nil, errors.New("Could not send Satel read device name")}
}
var bytes = <-s.rawEvents
if len(bytes) < (1 + 19 + 2) {
resultChan <- getNameResult{nil, errors.New("Received data too short")}
}
cmd := bytes[0]
bytes = bytes[1 : len(bytes)-2]
if cmd == 0xEF {
resultChan <- getNameResult{nil, errors.New("Did not receive a name")}
} else if cmd == 0xEE {
name, err := makeNameEvent(bytes)
resultChan <- getNameResult{name, err}
} else {
resultChan <- getNameResult{nil, errors.New("Received unexpected result instead of a name")}
}
}
nameResult := <-resultChan
return nameResult.ev, nameResult.err
}