forked from thomascriley/ble
/
main.go
55 lines (45 loc) · 1.23 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package main
import (
"flag"
"fmt"
"log"
"time"
"github.com/pkg/errors"
"golang.org/x/net/context"
"github.com/thomascriley/ble"
"github.com/thomascriley/ble/examples/lib"
"github.com/thomascriley/ble/examples/lib/dev"
)
var (
device = flag.String("device", "default", "implementation of ble")
du = flag.Duration("du", 5*time.Second, "advertising duration, 0 for indefinitely")
)
func main() {
flag.Parse()
d, err := dev.NewDevice(*device)
if err != nil {
log.Fatalf("can't new device : %s", err)
}
ble.SetDefaultDevice(d)
testSvc := ble.NewService(lib.TestSvcUUID)
testSvc.AddCharacteristic(lib.NewCountChar())
testSvc.AddCharacteristic(lib.NewEchoChar())
if err := ble.AddService(testSvc); err != nil {
log.Fatalf("can't add service: %s", err)
}
// Advertise for specified durantion, or until interrupted by user.
fmt.Printf("Advertising for %s...\n", *du)
ctx := ble.WithSigHandler(context.WithTimeout(context.Background(), *du))
chkErr(ble.AdvertiseNameAndServices(ctx, "Gopher", testSvc.UUID))
}
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())
}
}