findGateway.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package initialize
  2. import (
  3. "confrontation-training/global"
  4. "confrontation-training/models/gateway"
  5. "github.com/robfig/cron"
  6. "strings"
  7. "time"
  8. "tinygo.org/x/bluetooth"
  9. )
  10. var adapter = bluetooth.DefaultAdapter
  11. func FindGateway() {
  12. // Enable BLE interface.
  13. must("enable BLE stack", adapter.Enable())
  14. global.GatewayList = make(map[string]gateway.GatewayInfo)
  15. // Start scanning.
  16. println("scanning...")
  17. global.Log4J.Info("开启网关扫描---")
  18. cron := cron.New()
  19. isScanning := false
  20. cron.AddFunc("0 */1 * * * *", func() {
  21. if !isScanning {
  22. isScanning = true
  23. err := adapter.Scan(func(adapter *bluetooth.Adapter, device bluetooth.ScanResult) {
  24. println("found device:", device.Address.String(), device.RSSI, device.LocalName())
  25. mac := strings.ReplaceAll(device.Address.String(), ":", "")
  26. name := device.LocalName()
  27. if strings.HasSuffix(name, mac) {
  28. global.Log4J.Info("发现可能是网关的设备:mac="+mac, " name="+name)
  29. var gatewayInfo gateway.GatewayInfo
  30. gatewayInfo.Mac = mac
  31. gatewayInfo.Name = name
  32. global.GatewayList[mac] = gatewayInfo
  33. }
  34. time.Sleep(time.Millisecond * 100)
  35. })
  36. must("start scan", err)
  37. } else {
  38. isScanning = false
  39. adapter.StopScan()
  40. }
  41. global.Log4J.Info("关闭网关扫描---")
  42. adapter.StopScan()
  43. time.Sleep(time.Millisecond * 10000)
  44. global.Log4J.Info("开启网关扫描---")
  45. })
  46. cron.Start()
  47. select {}
  48. }
  49. func must(action string, err error) {
  50. if err != nil {
  51. global.Log4J.Info("failed to " + action + ": " + err.Error())
  52. }
  53. }