package main import ( "log" "dim13.org/anki" "github.com/currantlabs/gatt" ) func onStateChange(d gatt.Device, s gatt.State) { sid := gatt.MustParseUUID(anki.ServiceUUID) log.Println("State", s) switch s { case gatt.StatePoweredOn: log.Println("Scan...") d.Scan([]gatt.UUID{sid}, false) default: d.StopScanning() } } func onDiscover(p gatt.Peripheral, a *gatt.Advertisement, rssi int) { //defer p.Device().StopScanning() sid := gatt.MustParseUUID(anki.ServiceUUID) for _, s := range a.Services { log.Println("Found", p.ID()) if s.Equal(sid) { log.Println("Connect", p.ID()) p.Device().Connect(p) } } } func onRead(w gatt.ResponseWriter, r *gatt.ReadRequest) { log.Println("READ", r) } func onConnect(p gatt.Peripheral, err error) { ss, err := p.DiscoverServices(nil) if err != nil { log.Println(err) return } for _, s := range ss { log.Println("Service", s.UUID()) cs, err := p.DiscoverCharacteristics(nil, s) if err != nil { log.Println("Discover Service", err) return } for _, c := range cs { log.Println("Characteristic", c.UUID()) ds, err := p.DiscoverDescriptors(nil, c) if err != nil { log.Println("Discover Descriptors", err) return } for _, d := range ds { log.Println("Descriptor", d.UUID()) } log.Println("Properties", c.Properties()) if (c.Properties() & (gatt.CharNotify | gatt.CharIndicate)) != 0 { if err := p.SetNotifyValue(c, onNotify); err != nil { log.Println("Set notify", err) return } } if (c.Properties() & gatt.CharWrite) != 0 { //c.HandleReadFunc(onRead) //log.Println("Send") //c.SetValue([]byte{0x01, 0x18}) p.WriteCharacteristic(c, []byte{0x01, 0x90}, false) // sdk p.WriteCharacteristic(c, []byte{0x01, 0x16}, true) // ping p.WriteCharacteristic(c, []byte{0x01, 0x18}, true) // version p.WriteCharacteristic(c, []byte{0x01, 0x1a}, true) // battery p.WriteCharacteristic(c, []byte{0x02, 0x1d, 0xff}, true) // lights } } } } func onNotify(c *gatt.Characteristic, b []byte, err error) { log.Printf("notify: % X | %q\n", b, b) id, payload := anki.SplitMsg(b) log.Printf("ID: %v | % X\n", id, payload) } func onDisconnect(p gatt.Peripheral, err error) { log.Println("Disconnect", p.ID()) p.Device().CancelConnection(p) } func main() { d, err := gatt.NewDevice() if err != nil { log.Fatal(err) } d.Handle( gatt.PeripheralDiscovered(onDiscover), gatt.PeripheralConnected(onConnect), gatt.PeripheralDisconnected(onDisconnect), ) d.Init(onStateChange) select {} }