ble_device.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. // +build !windows
  2. package network
  3. import (
  4. "encoding/json"
  5. "time"
  6. "github.com/bettercap/gatt"
  7. )
  8. type BLECharacteristic struct {
  9. UUID string `json:"uuid"`
  10. Name string `json:"name"`
  11. Handle uint16 `json:"handle"`
  12. Properties []string `json:"properties"`
  13. Data interface{} `json:"data"`
  14. }
  15. type BLEService struct {
  16. UUID string `json:"uuid"`
  17. Name string `json:"name"`
  18. Handle uint16 `json:"handle"`
  19. EndHandle uint16 `json:"end_handle"`
  20. Characteristics []BLECharacteristic `json:"characteristics"`
  21. }
  22. type BLEDevice struct {
  23. Alias string
  24. LastSeen time.Time
  25. DeviceName string
  26. Vendor string
  27. RSSI int
  28. Device gatt.Peripheral
  29. Advertisement *gatt.Advertisement
  30. Services []BLEService
  31. }
  32. type bleDeviceJSON struct {
  33. LastSeen time.Time `json:"last_seen"`
  34. Name string `json:"name"`
  35. MAC string `json:"mac"`
  36. Alias string `json:"alias"`
  37. Vendor string `json:"vendor"`
  38. RSSI int `json:"rssi"`
  39. Connectable bool `json:"connectable"`
  40. Flags string `json:"flags"`
  41. Services []BLEService `json:"services"`
  42. }
  43. func NewBLEDevice(p gatt.Peripheral, a *gatt.Advertisement, rssi int) *BLEDevice {
  44. vendor := ManufLookup(NormalizeMac(p.ID()))
  45. if vendor == "" && a != nil {
  46. vendor = a.Company
  47. }
  48. return &BLEDevice{
  49. LastSeen: time.Now(),
  50. Device: p,
  51. Vendor: vendor,
  52. Advertisement: a,
  53. RSSI: rssi,
  54. Services: make([]BLEService, 0),
  55. }
  56. }
  57. func (d *BLEDevice) Name() string {
  58. // get the name if it's being set during services enumeration via 'Device Name'
  59. name := d.DeviceName
  60. if name == "" {
  61. // get the name from the device
  62. name = d.Device.Name()
  63. if name == "" && d.Advertisement != nil {
  64. // get the name from the advertisement data
  65. name = d.Advertisement.LocalName
  66. }
  67. }
  68. return name
  69. }
  70. func (d *BLEDevice) MarshalJSON() ([]byte, error) {
  71. doc := bleDeviceJSON{
  72. LastSeen: d.LastSeen,
  73. Name: d.Name(),
  74. MAC: d.Device.ID(),
  75. Alias: d.Alias,
  76. Vendor: d.Vendor,
  77. RSSI: d.RSSI,
  78. Connectable: d.Advertisement.Connectable,
  79. Flags: d.Advertisement.Flags.String(),
  80. Services: d.Services,
  81. }
  82. return json.Marshal(doc)
  83. }