package initialize import ( "confrontation-training/global" "confrontation-training/models/gateway" "github.com/robfig/cron" "strings" "time" "tinygo.org/x/bluetooth" ) var adapter = bluetooth.DefaultAdapter func FindGateway() { // Enable BLE interface. must("enable BLE stack", adapter.Enable()) global.GatewayList = make(map[string]gateway.GatewayInfo) // Start scanning. println("scanning...") global.Log4J.Info("开启网关扫描---") cron := cron.New() isScanning := false cron.AddFunc("0 */1 * * * *", func() { if !isScanning { isScanning = true err := adapter.Scan(func(adapter *bluetooth.Adapter, device bluetooth.ScanResult) { println("found device:", device.Address.String(), device.RSSI, device.LocalName()) mac := strings.ReplaceAll(device.Address.String(), ":", "") name := device.LocalName() if strings.HasSuffix(name, mac) { global.Log4J.Info("发现可能是网关的设备:mac="+mac, " name="+name) var gatewayInfo gateway.GatewayInfo gatewayInfo.Mac = mac gatewayInfo.Name = name global.GatewayList[mac] = gatewayInfo } time.Sleep(time.Millisecond * 100) }) must("start scan", err) } else { isScanning = false adapter.StopScan() } global.Log4J.Info("关闭网关扫描---") adapter.StopScan() time.Sleep(time.Millisecond * 10000) global.Log4J.Info("开启网关扫描---") }) cron.Start() select {} } func must(action string, err error) { if err != nil { global.Log4J.Info("failed to " + action + ": " + err.Error()) } }