Example #1
0
func main() {
	flag.Parse()

	d, err := dev.NewDevice(*device)
	if err != nil {
		log.Fatalf("can't new device : %s", err)
	}
	ble.SetDefaultDevice(d)

	// Default to search device with name of Gopher (or specified by user).
	filter := func(a ble.Advertisement) bool {
		return strings.ToUpper(a.LocalName()) == strings.ToUpper(*name)
	}

	// If addr is specified, search for addr instead.
	if len(*addr) != 0 {
		filter = func(a ble.Advertisement) bool {
			return strings.ToUpper(a.Address().String()) == strings.ToUpper(*addr)
		}
	}

	// Scan for specified durantion, or until interrupted by user.
	fmt.Printf("Scanning for %s...\n", *sd)
	ctx := ble.WithSigHandler(context.WithTimeout(context.Background(), *sd))
	cln, err := ble.Connect(ctx, filter)
	if err != nil {
		log.Fatalf("can't connect : %s", err)
	}

	go func() {
		cln.Disconnected()
		fmt.Printf("[ %s ] is disconnected \n", cln.Address())
	}()

	fmt.Printf("Discovering profile...\n")
	p, err := cln.DiscoverProfile(true)
	if err != nil {
		log.Fatalf("can't discover profile: %s", err)
	}

	// Start the exploration.
	explore(cln, p)

	// Disconnect the connection. (On OS X, this might take a while.)
	fmt.Printf("Disconnecting [ %s ]... (this might take up to few seconds on OS X)\n", cln.Address())
	cln.CancelConnection()
}
Example #2
0
func cmdConnect(c *cli.Context) error {
	curr.client = nil

	var cln ble.Client
	var err error

	ctx := ble.WithSigHandler(context.WithTimeout(context.Background(), c.Duration("tmo")))
	if c.String("addr") != "" {
		curr.addr = ble.NewAddr(c.String("addr"))
		fmt.Printf("Dialing to specified address: %s\n", curr.addr)
		cln, err = ble.Dial(ctx, curr.addr)
	} else if filter(c) != nil {
		fmt.Printf("Scanning with filter...\n")
		if cln, err = ble.Connect(ctx, filter(c)); err == nil {
			curr.addr = cln.Address()
			fmt.Printf("Connected to %s\n", curr.addr)

		}
	} else if curr.addr != nil {
		fmt.Printf("Dialing to implicit address: %s\n", curr.addr)
		cln, err = ble.Dial(ctx, curr.addr)
	} else {
		return fmt.Errorf("no filter specified, and cached peripheral address")
	}
	if err == nil {
		curr.client = cln
		curr.clients[cln.Address().String()] = cln
	}
	go func() {
		<-cln.Disconnected()
		delete(curr.clients, cln.Address().String())
		curr.client = nil
		fmt.Printf("\n%s disconnected\n", cln.Address().String())
	}()
	return err
}