ble_recon_events.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // +build !windows
  2. package ble
  3. import (
  4. "github.com/bettercap/gatt"
  5. )
  6. func (mod *BLERecon) onStateChanged(dev gatt.Device, s gatt.State) {
  7. mod.Debug("state changed to %v", s)
  8. switch s {
  9. case gatt.StatePoweredOn:
  10. if mod.currDevice == nil {
  11. mod.Debug("starting discovery ...")
  12. dev.Scan([]gatt.UUID{}, true)
  13. } else {
  14. mod.Debug("current device was not cleaned: %v", mod.currDevice)
  15. }
  16. case gatt.StatePoweredOff:
  17. mod.Debug("resetting device instance")
  18. mod.gattDevice.StopScanning()
  19. mod.setCurrentDevice(nil)
  20. mod.gattDevice = nil
  21. default:
  22. mod.Warning("unexpected state: %v", s)
  23. }
  24. }
  25. func (mod *BLERecon) onPeriphDiscovered(p gatt.Peripheral, a *gatt.Advertisement, rssi int) {
  26. mod.Session.BLE.AddIfNew(p.ID(), p, a, rssi)
  27. }
  28. func (mod *BLERecon) onPeriphDisconnected(p gatt.Peripheral, err error) {
  29. mod.Session.Events.Add("ble.device.disconnected", mod.currDevice)
  30. mod.setCurrentDevice(nil)
  31. if mod.Running() {
  32. mod.Debug("device disconnected, restoring discovery.")
  33. mod.gattDevice.Scan([]gatt.UUID{}, true)
  34. }
  35. }
  36. func (mod *BLERecon) onPeriphConnected(p gatt.Peripheral, err error) {
  37. if err != nil {
  38. mod.Warning("connected to %s but with error: %s", p.ID(), err)
  39. return
  40. } else if mod.currDevice == nil {
  41. mod.Warning("connected to %s but after the timeout :(", p.ID())
  42. return
  43. }
  44. mod.connected = true
  45. defer func(per gatt.Peripheral) {
  46. mod.Debug("disconnecting from %s ...", per.ID())
  47. per.Device().CancelConnection(per)
  48. mod.setCurrentDevice(nil)
  49. }(p)
  50. mod.Session.Events.Add("ble.device.connected", mod.currDevice)
  51. if err := p.SetMTU(500); err != nil {
  52. mod.Warning("failed to set MTU: %s", err)
  53. }
  54. mod.Debug("connected, enumerating all the things for %s!", p.ID())
  55. services, err := p.DiscoverServices(nil)
  56. // https://github.com/bettercap/bettercap/issues/498
  57. if err != nil && err.Error() != "success" {
  58. mod.Error("error discovering services: %s", err)
  59. return
  60. }
  61. mod.showServices(p, services)
  62. }