/*
2022/04/26 07:56:11 Failed Scan Resource Not Ready
2022/04/26 07:56:11 Scanning...69
2022/04/26 07:56:11 Failed Scan Resource Not Ready
2022/04/26 07:56:11 Scanning...70
2022/04/26 07:56:11 Scanned name M_IZAR_TEST MAC DF:5F:34:32:3A:44
2022/04/26 07:56:24 Failed Connect Software caused connection abort
2022/04/26 07:56:24 Scanned name M_IZAR_TEST MAC DF:5F:41:4C:9F:92
2022/04/26 07:56:54 SUCCESS Connect (false) /org/bluez/hci0/dev_DF_5F_41_4C_9F_92
2022/04/26 07:56:55 Discovering service...
Failed to discover the Nordic UART Service: timeout on DiscoverServices
2022/04/26 07:57:05 Scanning...71
2022/04/26 07:57:09 Scanned name M_IZAR_TEST MAC DF:5F:34:32:3A:44
2022/04/26 07:57:12 Failed Connect Software caused connection abort
2022/04/26 07:57:12 Scanned name M_IZAR_TEST MAC DF:5F:34:32:3A:44
2022/04/26 07:57:12 Failed Connect Properties.GetAll org.bluez.Device1: Message recipient disconnected from message bus without replying
程序截至在这里了?????
*/
package main
import (
"log"
"os"
"strings"
"time"
bluetooth "github.com/GKoSon/gobluetooth"
)
var (
serviceUUID = bluetooth.ServiceUUIDNordicUART
rxUUID = bluetooth.CharacteristicUUIDUARTRX
txUUID = bluetooth.CharacteristicUUIDUARTTX
)
var adapter = bluetooth.DefaultAdapter
var device *bluetooth.Device
const target_name = "M_IZAR_TEST"
var runCnt int64 = 0
var yesCnt int64 = 0
var failCnt int64 = 0
var rxdatacount int64 = 0
var rxdatanumber int64 = 0
func measureTime(funcName string) func() {
start := time.Now()
return func() {
log.Printf("Time taken by %s function is %v \n", funcName, time.Since(start))
}
}
func String_rm_char(a string, b string) string {
mac := ""
str := strings.Split(a, b)
for _, s := range str {
mac += s
}
return mac
}
func hciinit() bool {
if os.Args[1] == string("1") {
adapter.SetHciId("hci1")
} else if os.Args[1] == string("0") {
adapter.SetHciId("hci0")
} else {
log.Printf("please input 0 1 as hci")
return false
}
err := adapter.Enable()
if err != nil {
log.Printf("could not enable the BLE stack:%v", err.Error())
return false
}
return true
}
func oneloop() {
runCnt++
adapter.StopScan()
// Scan for NUS peripheral.
err := adapter.Scan(func(adapter *bluetooth.Adapter, result bluetooth.ScanResult) {
//defer measureTime("SCAN")()//一旦开启 LOG很多
start := time.Now()
if !result.AdvertisementPayload.HasServiceUUID(serviceUUID) {
return
}
/*加强停止Scan函数的限制条件*/
/*额外 条件1--从机必须有名字 而且符合约定*/
//log.Printf("Scanned MAC %s", result.Address.String())
if target_name != result.AdvertisementPayload.LocalName() {
//log.Printf("Failed name he is %s",result.AdvertisementPayload.LocalName())
return
}
log.Printf("Scanned name %s MAC %s", result.LocalName(), result.Address.String())
log.Printf("ScanedTarget %s", String_rm_char(result.Address.String(), ":"))
/*额外 条件2--从机连接成功*/
d, e := adapter.Connect(result.Address, bluetooth.ConnectionParams{})
if e != nil {
log.Printf("FailedConnect %v", e)
failCnt++
return
}
log.Printf("ConnectedTarget (%v) %s [%v]", d.IsConnected(), d.DevPath,time.Since(start))
device = d
// Stop the scan.真正的退出scan这个杜塞函数
err := adapter.StopScan()
if err != nil {
// Unlikely, but we can't recover from this.
log.Printf("Failed StopScan %v ", err.Error())
}
})
if err != nil {
log.Printf("Failed Scan %v ", err.Error())
log.Printf("===========END=========(%d)\r\n", failCnt)
failCnt = 0
return
}
// Connected. Look up the Nordic UART Service.
log.Printf("Discovering service...")
services, err := device.DiscoverServices([]bluetooth.UUID{serviceUUID})
if err != nil {
println("Failed to discover the Nordic UART Service:", err.Error())
log.Printf("===========END=========(%d)\r\n", failCnt)
failCnt = 0
return
}
service := services[0]
// Get the two characteristics present in this service.
chars, err := service.DiscoverCharacteristics([]bluetooth.UUID{rxUUID, txUUID})
if err != nil {
println("Failed to discover RX and TX characteristics:", err.Error())
log.Printf("===========END=========(%d)\r\n", failCnt)
failCnt = 0
return
}
var rx bluetooth.DeviceCharacteristic
var tx bluetooth.DeviceCharacteristic
if chars[0].UUID() == txUUID {
tx = chars[0]
rx = chars[1]
} else {
tx = chars[1]
rx = chars[0]
}
log.Printf("RX %v\r\n", rx)
//log.Printf("TX %v\r\n", tx)
//log.Printf("DiscoverCharacteristics:%+v\r\n", chars)
//Enable notifications to receive incoming data.
err = tx.EnableNotifications(func(value []byte) {
//log.Printf("PI recv %d bytes: %X\r\n", len(value), value)
log.Printf("PI recv %d \r\n", len(value))
rxdatacount++
rxdatanumber = rxdatanumber + int64(len(value))
})
if err != nil {
log.Printf("Failed EnableNotifications %+v\r\n", err.Error())
log.Printf("===========END=========(%d)\r\n", failCnt)
failCnt = 0
return
}
log.Printf("Connected.When NODE disconnect.This pid while Exit\r\n")
/*等待从机断开 PI从不发消息*/
for {
if !device.IsConnected() {
yesCnt++
log.Printf("TotalCount=%d,yes=%d,fail=%d,rxdatacount=%d,rxdatanumber=%d", runCnt, yesCnt, failCnt, rxdatacount, rxdatanumber)
log.Printf("===========END=========device GoodBye\r\n")
rxdatacount = 0
rxdatanumber = 0
return
}
time.Sleep(time.Microsecond * 200)
}
}
func loginit() {
logFile, logErr := os.OpenFile("pi_hci.log", os.O_CREATE|os.O_RDWR|os.O_APPEND, 0666)
if logErr != nil {
os.Exit(1)
}
log.Printf("log will write a file")
log.SetOutput(logFile)
log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
log.Printf("Server abort! Cause:%v \n", "test log file")
}
func main() {
//loginit()
if !hciinit() {
return
}
for {
oneloop()
}
}
|