开源项目 currantlabs/ble
使用教程
ble项目地址:https://gitcode.com/gh_mirrors/ble1/ble
1. 项目的目录结构及介绍
currantlabs/ble
├── cmd
│ ├── ble-scanner
│ │ └── main.go
│ ├── ble-service
│ │ └── main.go
│ └── ble-tester
│ └── main.go
├── examples
│ ├── battery
│ │ └── main.go
│ ├── heartrate
│ │ └── main.go
│ └── thermometer
│ └── main.go
├── pkg
│ ├── ble
│ │ ├── adapter.go
│ │ ├── characteristic.go
│ │ ├── device.go
│ │ ├── service.go
│ │ └── utils.go
│ └── linux
│ ├── adapter_linux.go
│ ├── characteristic_linux.go
│ ├── device_linux.go
│ └── service_linux.go
└── README.md
目录结构说明
cmd
: 包含项目的命令行工具,每个子目录对应一个可执行文件。ble-scanner
: 蓝牙扫描工具。ble-service
: 蓝牙服务工具。ble-tester
: 蓝牙测试工具。
examples
: 包含项目的示例代码,展示了如何使用蓝牙功能。battery
: 电池服务示例。heartrate
: 心率服务示例。thermometer
: 温度计服务示例。
pkg
: 包含项目的核心包,提供了蓝牙功能的实现。ble
: 蓝牙核心功能包。linux
: 针对Linux平台的实现。
README.md
: 项目说明文档。
2. 项目的启动文件介绍
cmd/ble-scanner/main.go
package main
import (
"log"
"github.com/currantlabs/ble"
"github.com/currantlabs/ble/linux"
)
func main() {
d, err := linux.NewDevice()
if err != nil {
log.Fatalf("Failed to create new device, err: %s", err)
}
ble.SetDefaultDevice(d)
// Scan for specified durantion, or until interrupted by user.
log.Println("Scanning for 5 seconds...")
ctx := ble.WithSigHandler(context.WithTimeout(context.Background(), 5*time.Second))
ch := ble.Discover(ctx, false)
for dev := range ch {
log.Printf("Found device: %s", dev.Addr().String())
}
}
cmd/ble-service/main.go
package main
import (
"log"
"github.com/currantlabs/ble"
"github.com/currantlabs/ble/linux"
)
func main() {
d, err := linux.NewDevice()
if err != nil {
log.Fatalf("Failed to create new device, err: %s", err)
}
ble.SetDefaultDevice(d)
// Advertise for specified duration, or until interrupted by user.
log.Println("Advertising for 5 seconds...")
ctx := ble.WithSigHandler(context.WithTimeout(context.Background(), 5*time.Second))
err = d.AdvertiseNameAndServices(ctx, "MyBLEService", ble.NewService(ble.MustParse("180F")))
if err != nil {
log.Fatalf("Failed to advertise, err: %s", err)
}
}
cmd/ble-tester/main.go
package main
import (
"log"
"github.com/currantlabs/ble"
"github.com/currantlabs/ble/linux"
)
func main() {
d, err := linux.NewDevice()
if err != nil {
log.Fatalf("Failed to create new device, err: %s", err)
}
ble.SetDefaultDevice(d)
// Perform a series of tests
log.Println("Starting BLE tests...")
// Test code here...
}