github.com/stampzilla/stampzilla-go@v2.0.0-rc9+incompatible/nodes/stampzilla-knx/main.go (about) 1 package main 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "strings" 7 8 "github.com/sirupsen/logrus" 9 "github.com/stampzilla/stampzilla-go/nodes/stampzilla-server/models/devices" 10 "github.com/stampzilla/stampzilla-go/pkg/node" 11 ) 12 13 func main() { 14 node := node.New("knx") 15 16 tunnel := newTunnel(node) 17 tunnel.OnConnect = func() { 18 for _, dev := range node.Devices.All() { 19 dev.Online = true 20 } 21 node.SyncDevices() 22 } 23 tunnel.OnDisconnect = func() { 24 for _, dev := range node.Devices.All() { 25 dev.Online = false 26 } 27 node.SyncDevices() 28 } 29 30 config := &config{} 31 32 node.OnConfig(updatedConfig(node, tunnel, config)) 33 node.OnRequestStateChange(func(state devices.State, device *devices.Device) error { 34 id := strings.SplitN(device.ID.ID, ".", 2) 35 36 switch id[0] { 37 case "light": 38 config.Lock() 39 defer config.Unlock() 40 41 for _, light := range config.Lights { 42 if light.ID != id[1] { 43 continue 44 } 45 46 for stateKey, newState := range state { 47 switch stateKey { 48 case "on": 49 diff, value, err := boolDiff(newState, device.State[stateKey]) 50 if err != nil { 51 return err 52 } 53 54 if diff { 55 err := light.Switch(tunnel, value) 56 if err != nil { 57 return err 58 } 59 } 60 case "brightness": 61 diff, value, err := scalingDiff(newState, device.State[stateKey]) 62 if err != nil { 63 return err 64 } 65 66 if diff { 67 err := light.Brightness(tunnel, value*100) 68 if err != nil { 69 return err 70 } 71 } 72 } 73 74 } 75 } 76 default: 77 return fmt.Errorf("Unknown device type \"%s\"", id[0]) 78 } 79 return nil 80 }) 81 82 node.OnShutdown(func() { 83 tunnel.Close() 84 }) 85 86 err := node.Connect() 87 if err != nil { 88 logrus.Error(err) 89 return 90 } 91 92 logrus.SetFormatter(&logrus.TextFormatter{ 93 ForceColors: true, 94 }) 95 logrus.SetReportCaller(false) 96 97 node.Wait() 98 node.Client.Wait() 99 } 100 101 func updatedConfig(node *node.Node, tunnel *tunnel, config *config) func(data json.RawMessage) error { 102 return func(data json.RawMessage) error { 103 config.Lock() 104 defer config.Unlock() 105 err := json.Unmarshal(data, config) 106 if err != nil { 107 return err 108 } 109 110 go tunnel.SetAddress(config.Gateway.Address) 111 112 tunnel.ClearAllLinks() 113 for _, light := range config.Lights { 114 setupLight(node, tunnel, light) 115 } 116 117 for _, sensor := range config.Sensors { 118 setupSensor(node, tunnel, sensor) 119 } 120 121 return nil 122 } 123 }