homecontroller/device.go

126 lines
3.0 KiB
Go

package main
import (
"crypto/rand"
"encoding/binary"
"errors"
)
func getNewID(clients []StoredClient) uint32 {
newID := uint32(0)
for _, client := range clients {
if client.ID >= newID {
newID = client.ID + 1
}
}
return newID
}
func addDevice(name string, deviceType uint8, clients []StoredClient) (key []byte, usedID uint32) {
key = make([]byte, 64)
_, err := rand.Read(key)
if err != nil {
panic(err)
}
usedID = getNewID(clients)
storedClients = append(storedClients, StoredClient{
Key: key,
Name: name,
ID: usedID,
Type: deviceType,
Privileges: 0,
})
return key, usedID
}
func addController(name string, clients []StoredClient) (key []byte, usedID uint32) {
key = make([]byte, 64)
_, err := rand.Read(key)
if err != nil {
panic(err)
}
usedID = getNewID(clients)
storedClients = append(storedClients, StoredClient{
Key: key,
Name: name,
ID: usedID,
Type: 0,
Privileges: 1,
})
return key, usedID
}
func (client *Device) setChannel(id uint8, value uint8) error {
if client.channels == nil || uint8(len(client.channels)) >= id {
return errors.New("channel impossible to set")
}
var outBuffer []byte
outBuffer = append(outBuffer, id)
outBuffer = append(outBuffer, value)
return client.client.sendPacket(2, outBuffer)
}
func (client *Device) getDeviceChannelResponse(targetDeviceID uint32, id uint8) error {
if clients == nil || uint32(len(clients)) >= targetDeviceID {
return errors.New("target device is nonexistent")
}
clientDevice := clients[targetDeviceID]
if clientDevice.channels == nil || uint8(len(clientDevice.channels)) >= id {
return errors.New("channel impossible to get")
}
var outBuffer []byte
var deviceID []byte
binary.LittleEndian.PutUint32(deviceID, targetDeviceID)
outBuffer = append(outBuffer, deviceID...)
outBuffer = append(outBuffer, id)
outBuffer = append(outBuffer, clientDevice.channels[id])
return client.client.sendPacket(4, outBuffer)
}
func (client *Device) readChannel(id uint8) error {
if client.channels == nil || uint8(len(client.channels)) >= id {
return errors.New("channel impossible to get")
}
var outBuffer []byte
outBuffer = append(outBuffer, id)
return client.client.sendPacket(3, outBuffer)
}
func (client *Device) readChannels() error {
if client.channels == nil || uint8(len(client.channels)) == 0 {
return errors.New("channels impossible to get")
}
var err error
for channelID := range client.channels {
err = client.readChannel(uint8(channelID))
if err != nil {
return err
}
}
return nil
}
func (client *Device) receiveChannel(data []byte) error {
if len(data) < 1 {
return errors.New("channel data too short")
}
id := data[0]
if client.channels == nil || uint8(len(client.channels)) >= id {
return errors.New("channel impossible to get")
}
value := data[4:5][0]
client.channels[id] = value
return nil
}
var deviceChannelCount = []uint8{0, 1, 1, 2}
//0: phone
//1: switch
//2: dimmer
//3: gate