问题:树莓派做蓝牙主机 去连接从机时候 容易失败
连接失败 就重现开始扫描 在连接
希望在失败以后做一个复位蓝牙的动作
如何复位一次hci接口?
func Reset(adapterID string) error {
err := Down(adapterID)
if err != nil {
log.Warnf("Down failed: %s", err)
}
return Up(adapterID)
}
怎么找到的?
\muka\hw\linux\linux.go
\muka\examples\hci_updown\hci_updown.go
在tigo全局找 hci 都是.H文件里面才有
所以根本就没有使用!
那还是自己去搬运吧
log "github.com/sirupsen/logrus"
log.Warnf("Down failed: %s", err)
方式1 台湾
func parse_MAC(result bluetooth.ScanResult) string {
mac := ""
str := strings.Split(result.Address.String(), ":")
for _, s := range str {
mac += s
}
return mac
}
func hci_disconnect(result bluetooth.ScanResult) {
cmd := exec.Command("hcitool", "con")
stdout, err := cmd.Output()
if err != nil {
log.Printf("[BLE][%s] Use hcitool to disconnect ble: %v\r\n", parse_MAC(result), err)
return
}
log.Printf("[BLE][%s] hcitool raw output:%s\r\n", parse_MAC(result), stdout)
index := strings.Index(string(stdout), strings.ToUpper(result.Address.String()))
if index == -1 {
log.Printf("[BLE][%s] BLE already disconnected\r\n", parse_MAC(result))
return
}
cmd_out := string(stdout)[index:]
log.Printf("[BLE][%s] hcitool con output : %s\r\n", parse_MAC(result), cmd_out)
s_format := strings.ToUpper(result.Address.String()) + " handle %d %s"
// log.Printf("[BLE][%s] sscanf format : %s\r\n", parse_MAC(result), s_format)
var handle int
var temp string
fmt.Sscanf(cmd_out, s_format, &handle, &temp)
log.Printf("[BLE][%s] hcitool ledc %d\r\n", parse_MAC(result), handle)
cmd = exec.Command("hcitool", "ledc", fmt.Sprint(handle))
cmd.Output()
}
方式2
用源码 example修改一下
package main
import (
"fmt"
"strconv"
"strings"
"time"
"github.com/muka/go-bluetooth/hw/linux/hci"
log "github.com/sirupsen/logrus"
)
//HciUpDownExample hciconfig up / down
func Run(rawAdapterID string) error {
log.Info("Turn down")
adapterID, err := strconv.Atoi(strings.Replace(rawAdapterID, "hci", "", 1))
if err != nil {
return err
}
err = hci.Down(adapterID)
if err != nil {
return fmt.Errorf("Failed to stop device hci%d: %s", adapterID, err.Error())
}
time.Sleep(time.Second * 5) //此时终端hciconfig去看hci0的状态显示是down
log.Info("Turn on")
err = hci.Up(adapterID)
if err != nil {
return fmt.Errorf("Failed to start device hci%d: %s", adapterID, err.Error())
}
log.Info("Done.")
return nil
}
func main() {
Run("hci0")
for {
}
}