Closed schollz closed 6 years ago
package main
import (
"context"
"fmt"
"log"
"strings"
"time"
"github.com/go-ble/ble"
"github.com/go-ble/ble/examples/lib/dev"
)
func main() {
fmt.Println(scan())
fmt.Println("done")
}
func scan() (devices map[string]interface{}, err error) {
devices = make(map[string]interface{})
d, err := dev.NewDevice("default")
if err != nil {
log.Println("can't new device : %s", err)
return
}
defer d.Stop()
ble.SetDefaultDevice(d)
// Default to search device with name of Gopher (or specified by user).
filter := func(a ble.Advertisement) {
log.Println(a.Addr(), a.RSSI())
devices[a.Addr().String()] = a.RSSI()
}
sd := 5 * time.Second
// Scan for specified durantion, or until interrupted by user.
log.Println("Scanning for %s...", sd.String())
ctx := ble.WithSigHandler(context.WithTimeout(context.Background(), sd))
errFinish := ble.Scan(ctx, false, filter, nil)
if errFinish != nil {
if !strings.Contains(errFinish.Error(), "context deadline") {
err = errFinish
}
}
return
}
package main
import (
"context"
"flag"
"fmt"
"log"
"time"
"github.com/go-ble/ble"
"github.com/go-ble/ble/examples/lib/dev"
"github.com/pkg/errors"
)
var (
device = flag.String("device", "default", "implementation of ble")
du = flag.Duration("du", 1*time.Second, "scanning duration")
dup = flag.Bool("dup", true, "allow duplicate reported")
)
func main() {
flag.Parse()
d, err := dev.NewDevice(*device)
if err != nil {
log.Fatalf("can't new device : %s", err)
}
ble.SetDefaultDevice(d)
// Scan for specified durantion, or until interrupted by user.
fmt.Printf("Scanning for %s...\n", *du)
ctx := ble.WithSigHandler(context.WithTimeout(context.Background(), *du))
devices := make(map[string][]int)
advHandler := func(a ble.Advertisement) {
fmt.Printf("[%s] %3d\n", a.Addr(), a.RSSI())
if _, ok := devices[a.Addr().String()]; !ok {
devices[a.Addr().String()] = []int{}
}
devices[a.Addr().String()] = append(devices[a.Addr().String()], a.RSSI())
}
chkErr(ble.Scan(ctx, *dup, advHandler, nil))
fmt.Println(devices)
}
func chkErr(err error) {
switch errors.Cause(err) {
case nil:
case context.DeadlineExceeded:
fmt.Printf("done\n")
case context.Canceled:
fmt.Printf("canceled\n")
default:
log.Fatalf(err.Error())
}
}
package main
import (
"fmt"
"log"
"time"
"github.com/paypal/gatt"
)
func onStateChanged(d gatt.Device, s gatt.State) {
fmt.Println("State:", s)
switch s {
case gatt.StatePoweredOn:
fmt.Println("scanning...")
d.Scan([]gatt.UUID{}, false)
return
default:
d.StopScanning()
}
}
func onPeriphDiscovered(p gatt.Peripheral, a *gatt.Advertisement, rssi int) {
fmt.Printf("\nPeripheral ID: %s %d\n", p.ID(), rssi)
}
func main() {
d, err := gatt.NewDevice()
if err != nil {
log.Fatalf("Failed to open device, err: %s\n", err)
return
}
// Register handlers.
d.Handle(gatt.PeripheralDiscovered(onPeriphDiscovered))
d.Init(onStateChanged)
select {
case <-time.After(2 * time.Second):
log.Println("times up")
}
log.Println("done")
}