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