aboutsummaryrefslogtreecommitdiff
path: root/example.go
diff options
context:
space:
mode:
Diffstat (limited to 'example.go')
-rw-r--r--example.go78
1 files changed, 42 insertions, 36 deletions
diff --git a/example.go b/example.go
index 8e10090..440b4ee 100644
--- a/example.go
+++ b/example.go
@@ -1,49 +1,55 @@
1package main 1package main
2 2
3import ( 3import (
4 "encoding/json" 4 "github.com/brutella/hc"
5 "fmt" 5 "github.com/brutella/hc/accessory"
6 "github.com/mcrute/go-inform/inform" 6
7 "io/ioutil" 7 "log"
8 "os" 8 "time"
9) 9)
10 10
11func main() { 11func main() {
12 fp, err := os.Open("data/test_files/1.bin") 12 switchInfo := accessory.Info{
13 if err != nil { 13 Name: "Lamp",
14 fmt.Println("Error loading file") 14 SerialNumber: "051AC-23AAM1",
15 return 15 Manufacturer: "Foobar",
16 } 16 Model: "AB",
17 defer fp.Close()
18
19 kp, err := os.Open("data/device_keys.json")
20 if err != nil {
21 fmt.Println("Error loading key file")
22 return
23 } 17 }
24 defer kp.Close() 18 acc := accessory.NewSwitch(switchInfo)
25 19
26 var keys map[string]string 20 config := hc.Config{Pin: "12344321", Port: "12345", StoragePath: "./db"}
27 kd, _ := ioutil.ReadAll(kp) 21 t, err := hc.NewIPTransport(config, acc.Accessory)
28 json.Unmarshal(kd, &keys)
29 22
30 codec := &inform.Codec{keys}
31
32 msg, err := codec.Unmarshal(fp)
33 if err != nil { 23 if err != nil {
34 fmt.Println(err.Error()) 24 log.Fatal(err)
35 return
36 } 25 }
37 26
38 fmt.Printf("%s", msg) 27 // Log to console when client (e.g. iOS app) changes the value of the on characteristic
39 28 acc.Switch.On.OnValueRemoteUpdate(func(on bool) {
40 out, _ := os.Create("test.out") 29 if on == true {
41 defer out.Close() 30 log.Println("[INFO] Client changed switch to on")
42 31 } else {
43 pkt, err := codec.Marshal(msg) 32 log.Println("[INFO] Client changed switch to off")
44 if err != nil { 33 }
45 fmt.Println(err.Error()) 34 })
46 return 35
47 } 36 // Periodically toggle the switch's on characteristic
48 out.Write(pkt) 37 go func() {
38 for {
39 on := !acc.Switch.On.GetValue()
40 if on == true {
41 log.Println("[INFO] Switch is on")
42 } else {
43 log.Println("[INFO] Switch is off")
44 }
45 acc.Switch.On.SetValue(on)
46 time.Sleep(5 * time.Second)
47 }
48 }()
49
50 hc.OnTermination(func() {
51 t.Stop()
52 })
53
54 t.Start()
49} 55}