| 1 |
package gatt |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"encoding/binary" |
| 6 |
"errors" |
| 7 |
"fmt" |
| 8 |
"log" |
| 9 |
"sync" |
| 10 |
"time" |
| 11 |
|
| 12 |
"github.com/paypal/gatt/xpc" |
| 13 |
) |
| 14 |
|
| 15 |
const ( |
| 16 |
peripheralDiscovered = 37 |
| 17 |
peripheralConnected = 38 |
| 18 |
peripheralDisconnected = 40 |
| 19 |
|
| 20 |
rssiRead = 55 |
| 21 |
includedServicesDiscovered = 63 |
| 22 |
serviceDiscovered = 56 |
| 23 |
characteristicsDiscovered = 64 |
| 24 |
characteristicRead = 71 |
| 25 |
characteristicWritten = 72 |
| 26 |
notificationValueSet = 74 |
| 27 |
descriptorsDiscovered = 76 |
| 28 |
descriptorRead = 79 |
| 29 |
descriptorWritten = 80 |
| 30 |
) |
| 31 |
|
| 32 |
type device struct { |
| 33 |
deviceHandler |
| 34 |
|
| 35 |
conn xpc.XPC |
| 36 |
|
| 37 |
role int |
| 38 |
|
| 39 |
reqc chan message |
| 40 |
rspc chan message |
| 41 |
|
| 42 |
|
| 43 |
plist map[string]*peripheral |
| 44 |
plistmu *sync.Mutex |
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
attrN int |
| 49 |
attrs map[int]*attr |
| 50 |
|
| 51 |
subscribers map[string]*central |
| 52 |
} |
| 53 |
|
| 54 |
func NewDevice(opts ...Option) (Device, error) { |
| 55 |
d := &device{ |
| 56 |
reqc: make(chan message), |
| 57 |
rspc: make(chan message), |
| 58 |
plist: map[string]*peripheral{}, |
| 59 |
plistmu: &sync.Mutex{}, |
| 60 |
|
| 61 |
attrN: 1, |
| 62 |
attrs: make(map[int]*attr), |
| 63 |
|
| 64 |
subscribers: make(map[string]*central), |
| 65 |
} |
| 66 |
d.Option(opts...) |
| 67 |
d.conn = xpc.XpcConnect("com.apple.blued", d) |
| 68 |
return d, nil |
| 69 |
} |
| 70 |
|
| 71 |
func (d *device) Init(f func(Device, State)) error { |
| 72 |
go d.loop() |
| 73 |
rsp := d.sendReq(1, xpc.Dict{ |
| 74 |
"kCBMsgArgName": fmt.Sprintf("gopher-%v", time.Now().Unix()), |
| 75 |
"kCBMsgArgOptions": xpc.Dict{"kCBInitOptionShowPowerAlert": 1}, |
| 76 |
"kCBMsgArgType": d.role, |
| 77 |
}) |
| 78 |
d.stateChanged = f |
| 79 |
go d.stateChanged(d, State(rsp.MustGetInt("kCBMsgArgState"))) |
| 80 |
return nil |
| 81 |
} |
| 82 |
|
| 83 |
func (d *device) Advertise(a *AdvPacket) error { |
| 84 |
rsp := d.sendReq(8, xpc.Dict{ |
| 85 |
"kCBAdvDataAppleMfgData": a.b, |
| 86 |
}) |
| 87 |
|
| 88 |
if res := rsp.MustGetInt("kCBMsgArgResult"); res != 0 { |
| 89 |
return errors.New("FIXME: Advertise error") |
| 90 |
} |
| 91 |
return nil |
| 92 |
} |
| 93 |
|
| 94 |
func (d *device) AdvertiseNameAndServices(name string, ss []UUID) error { |
| 95 |
us := uuidSlice(ss) |
| 96 |
rsp := d.sendReq(8, xpc.Dict{ |
| 97 |
"kCBAdvDataLocalName": name, |
| 98 |
"kCBAdvDataServiceUUIDs": us}, |
| 99 |
) |
| 100 |
if res := rsp.MustGetInt("kCBMsgArgResult"); res != 0 { |
| 101 |
return errors.New("FIXME: Advertise error") |
| 102 |
} |
| 103 |
return nil |
| 104 |
} |
| 105 |
|
| 106 |
func (d *device) AdvertiseIBeaconData(data []byte) error { |
| 107 |
var utsname xpc.Utsname |
| 108 |
xpc.Uname(&utsname) |
| 109 |
|
| 110 |
var rsp xpc.Dict |
| 111 |
|
| 112 |
if utsname.Release >= "14." { |
| 113 |
l := len(data) |
| 114 |
buf := bytes.NewBuffer([]byte{byte(l + 5), 0xFF, 0x4C, 0x00, 0x02, byte(l)}) |
| 115 |
buf.Write(data) |
| 116 |
rsp = d.sendReq(8, xpc.Dict{"kCBAdvDataAppleMfgData": buf.Bytes()}) |
| 117 |
} else { |
| 118 |
rsp = d.sendReq(8, xpc.Dict{"kCBAdvDataAppleBeaconKey": data}) |
| 119 |
} |
| 120 |
|
| 121 |
if res := rsp.MustGetInt("kCBMsgArgResult"); res != 0 { |
| 122 |
return errors.New("FIXME: Advertise error") |
| 123 |
} |
| 124 |
|
| 125 |
return nil |
| 126 |
} |
| 127 |
|
| 128 |
func (d *device) AdvertiseIBeacon(u UUID, major, minor uint16, pwr int8) error { |
| 129 |
b := make([]byte, 21) |
| 130 |
copy(b, reverse(u.b)) |
| 131 |
binary.BigEndian.PutUint16(b[16:], major) |
| 132 |
binary.BigEndian.PutUint16(b[18:], minor) |
| 133 |
b[20] = uint8(pwr) |
| 134 |
return d.AdvertiseIBeaconData(b) |
| 135 |
} |
| 136 |
|
| 137 |
func (d *device) StopAdvertising() error { |
| 138 |
rsp := d.sendReq(9, nil) |
| 139 |
if res := rsp.MustGetInt("kCBMsgArgResult"); res != 0 { |
| 140 |
return errors.New("FIXME: Stop Advertise error") |
| 141 |
} |
| 142 |
return nil |
| 143 |
} |
| 144 |
|
| 145 |
func (d *device) RemoveAllServices() error { |
| 146 |
d.sendCmd(12, nil) |
| 147 |
return nil |
| 148 |
} |
| 149 |
|
| 150 |
func (d *device) AddService(s *Service) error { |
| 151 |
if s.uuid.Equal(attrGAPUUID) || s.uuid.Equal(attrGATTUUID) { |
| 152 |
|
| 153 |
return nil |
| 154 |
} |
| 155 |
|
| 156 |
xs := xpc.Dict{ |
| 157 |
"kCBMsgArgAttributeID": d.attrN, |
| 158 |
"kCBMsgArgAttributeIDs": []int{}, |
| 159 |
"kCBMsgArgCharacteristics": nil, |
| 160 |
"kCBMsgArgType": 1, |
| 161 |
"kCBMsgArgUUID": reverse(s.uuid.b), |
| 162 |
} |
| 163 |
d.attrN++ |
| 164 |
|
| 165 |
xcs := xpc.Array{} |
| 166 |
for _, c := range s.Characteristics() { |
| 167 |
props := 0 |
| 168 |
perm := 0 |
| 169 |
if c.props&CharRead != 0 { |
| 170 |
props |= 0x02 |
| 171 |
if CharRead&c.secure != 0 { |
| 172 |
perm |= 0x04 |
| 173 |
} else { |
| 174 |
perm |= 0x01 |
| 175 |
} |
| 176 |
} |
| 177 |
if c.props&CharWriteNR != 0 { |
| 178 |
props |= 0x04 |
| 179 |
if c.secure&CharWriteNR != 0 { |
| 180 |
perm |= 0x08 |
| 181 |
} else { |
| 182 |
perm |= 0x02 |
| 183 |
} |
| 184 |
} |
| 185 |
if c.props&CharWrite != 0 { |
| 186 |
props |= 0x08 |
| 187 |
if c.secure&CharWrite != 0 { |
| 188 |
perm |= 0x08 |
| 189 |
} else { |
| 190 |
perm |= 0x02 |
| 191 |
} |
| 192 |
} |
| 193 |
if c.props&CharNotify != 0 { |
| 194 |
if c.secure&CharNotify != 0 { |
| 195 |
props |= 0x100 |
| 196 |
} else { |
| 197 |
props |= 0x10 |
| 198 |
} |
| 199 |
} |
| 200 |
if c.props&CharIndicate != 0 { |
| 201 |
if c.secure&CharIndicate != 0 { |
| 202 |
props |= 0x200 |
| 203 |
} else { |
| 204 |
props |= 0x20 |
| 205 |
} |
| 206 |
} |
| 207 |
|
| 208 |
xc := xpc.Dict{ |
| 209 |
"kCBMsgArgAttributeID": d.attrN, |
| 210 |
"kCBMsgArgUUID": reverse(c.uuid.b), |
| 211 |
"kCBMsgArgAttributePermissions": perm, |
| 212 |
"kCBMsgArgCharacteristicProperties": props, |
| 213 |
"kCBMsgArgData": c.value, |
| 214 |
} |
| 215 |
d.attrs[d.attrN] = &attr{h: uint16(d.attrN), value: c.value, pvt: c} |
| 216 |
d.attrN++ |
| 217 |
|
| 218 |
xds := xpc.Array{} |
| 219 |
for _, d := range c.Descriptors() { |
| 220 |
if d.uuid.Equal(attrClientCharacteristicConfigUUID) { |
| 221 |
|
| 222 |
continue |
| 223 |
} |
| 224 |
xd := xpc.Dict{ |
| 225 |
"kCBMsgArgData": d.value, |
| 226 |
"kCBMsgArgUUID": reverse(d.uuid.b), |
| 227 |
} |
| 228 |
xds = append(xds, xd) |
| 229 |
} |
| 230 |
xc["kCBMsgArgDescriptors"] = xds |
| 231 |
xcs = append(xcs, xc) |
| 232 |
} |
| 233 |
xs["kCBMsgArgCharacteristics"] = xcs |
| 234 |
|
| 235 |
rsp := d.sendReq(10, xs) |
| 236 |
if res := rsp.MustGetInt("kCBMsgArgResult"); res != 0 { |
| 237 |
return errors.New("FIXME: Add Srvice error") |
| 238 |
} |
| 239 |
return nil |
| 240 |
} |
| 241 |
|
| 242 |
func (d *device) SetServices(ss []*Service) error { |
| 243 |
d.RemoveAllServices() |
| 244 |
for _, s := range ss { |
| 245 |
d.AddService(s) |
| 246 |
} |
| 247 |
return nil |
| 248 |
} |
| 249 |
|
| 250 |
func (d *device) Scan(ss []UUID, dup bool) { |
| 251 |
args := xpc.Dict{ |
| 252 |
"kCBMsgArgUUIDs": uuidSlice(ss), |
| 253 |
"kCBMsgArgOptions": xpc.Dict{ |
| 254 |
"kCBScanOptionAllowDuplicates": map[bool]int{true: 1, false: 0}[dup], |
| 255 |
}, |
| 256 |
} |
| 257 |
d.sendCmd(29, args) |
| 258 |
} |
| 259 |
|
| 260 |
func (d *device) StopScanning() { |
| 261 |
d.sendCmd(30, nil) |
| 262 |
} |
| 263 |
|
| 264 |
func (d *device) Connect(p Peripheral) { |
| 265 |
pp := p.(*peripheral) |
| 266 |
d.plist[pp.id.String()] = pp |
| 267 |
d.sendCmd(31, |
| 268 |
xpc.Dict{ |
| 269 |
"kCBMsgArgDeviceUUID": pp.id, |
| 270 |
"kCBMsgArgOptions": xpc.Dict{ |
| 271 |
"kCBConnectOptionNotifyOnDisconnection": 1, |
| 272 |
}, |
| 273 |
}) |
| 274 |
} |
| 275 |
|
| 276 |
func (d *device) respondToRequest(id int, args xpc.Dict) { |
| 277 |
|
| 278 |
switch id { |
| 279 |
case 19: |
| 280 |
u := UUID{args.MustGetUUID("kCBMsgArgDeviceUUID")} |
| 281 |
t := args.MustGetInt("kCBMsgArgTransactionID") |
| 282 |
a := args.MustGetInt("kCBMsgArgAttributeID") |
| 283 |
o := args.MustGetInt("kCBMsgArgOffset") |
| 284 |
|
| 285 |
attr := d.attrs[a] |
| 286 |
v := attr.value |
| 287 |
if v == nil { |
| 288 |
c := newCentral(d, u) |
| 289 |
req := &ReadRequest{ |
| 290 |
Request: Request{Central: c}, |
| 291 |
Cap: int(c.mtu - 1), |
| 292 |
Offset: o, |
| 293 |
} |
| 294 |
rsp := newResponseWriter(int(c.mtu - 1)) |
| 295 |
if c, ok := attr.pvt.(*Characteristic); ok { |
| 296 |
c.rhandler.ServeRead(rsp, req) |
| 297 |
v = rsp.bytes() |
| 298 |
} |
| 299 |
} |
| 300 |
|
| 301 |
d.sendCmd(13, xpc.Dict{ |
| 302 |
"kCBMsgArgAttributeID": a, |
| 303 |
"kCBMsgArgData": v, |
| 304 |
"kCBMsgArgTransactionID": t, |
| 305 |
"kCBMsgArgResult": 0, |
| 306 |
}) |
| 307 |
|
| 308 |
case 20: |
| 309 |
u := UUID{args.MustGetUUID("kCBMsgArgDeviceUUID")} |
| 310 |
t := args.MustGetInt("kCBMsgArgTransactionID") |
| 311 |
a := 0 |
| 312 |
noRsp := false |
| 313 |
xxws := args.MustGetArray("kCBMsgArgATTWrites") |
| 314 |
for _, xxw := range xxws { |
| 315 |
xw := xxw.(xpc.Dict) |
| 316 |
if a == 0 { |
| 317 |
a = xw.MustGetInt("kCBMsgArgAttributeID") |
| 318 |
} |
| 319 |
o := xw.MustGetInt("kCBMsgArgOffset") |
| 320 |
i := xw.MustGetInt("kCBMsgArgIgnoreResponse") |
| 321 |
b := xw.MustGetBytes("kCBMsgArgData") |
| 322 |
_ = o |
| 323 |
attr := d.attrs[a] |
| 324 |
c := newCentral(d, u) |
| 325 |
r := Request{Central: c} |
| 326 |
attr.pvt.(*Characteristic).whandler.ServeWrite(r, b) |
| 327 |
if i == 1 { |
| 328 |
noRsp = true |
| 329 |
} |
| 330 |
|
| 331 |
} |
| 332 |
if noRsp { |
| 333 |
break |
| 334 |
} |
| 335 |
d.sendCmd(13, xpc.Dict{ |
| 336 |
"kCBMsgArgAttributeID": a, |
| 337 |
"kCBMsgArgData": nil, |
| 338 |
"kCBMsgArgTransactionID": t, |
| 339 |
"kCBMsgArgResult": 0, |
| 340 |
}) |
| 341 |
|
| 342 |
case 21: |
| 343 |
u := UUID{args.MustGetUUID("kCBMsgArgDeviceUUID")} |
| 344 |
a := args.MustGetInt("kCBMsgArgAttributeID") |
| 345 |
attr := d.attrs[a] |
| 346 |
c := newCentral(d, u) |
| 347 |
d.subscribers[u.String()] = c |
| 348 |
c.startNotify(attr, c.mtu) |
| 349 |
|
| 350 |
case 22: |
| 351 |
u := UUID{args.MustGetUUID("kCBMsgArgDeviceUUID")} |
| 352 |
a := args.MustGetInt("kCBMsgArgAttributeID") |
| 353 |
attr := d.attrs[a] |
| 354 |
if c := d.subscribers[u.String()]; c != nil { |
| 355 |
c.stopNotify(attr) |
| 356 |
} |
| 357 |
|
| 358 |
case 23: |
| 359 |
} |
| 360 |
} |
| 361 |
|
| 362 |
func (d *device) CancelConnection(p Peripheral) { |
| 363 |
d.sendCmd(32, xpc.Dict{"kCBMsgArgDeviceUUID": p.(*peripheral).id}) |
| 364 |
} |
| 365 |
|
| 366 |
|
| 367 |
|
| 368 |
func (d *device) HandleXpcEvent(event xpc.Dict, err error) { |
| 369 |
if err != nil { |
| 370 |
log.Println("error:", err) |
| 371 |
return |
| 372 |
} |
| 373 |
|
| 374 |
id := event.MustGetInt("kCBMsgId") |
| 375 |
args := event.MustGetDict("kCBMsgArgs") |
| 376 |
|
| 377 |
|
| 378 |
switch id { |
| 379 |
case |
| 380 |
6, |
| 381 |
16, |
| 382 |
17, |
| 383 |
18: |
| 384 |
d.rspc <- message{id: id, args: args} |
| 385 |
|
| 386 |
case |
| 387 |
19, |
| 388 |
20, |
| 389 |
21, |
| 390 |
22, |
| 391 |
23: |
| 392 |
d.respondToRequest(id, args) |
| 393 |
|
| 394 |
case peripheralDiscovered: |
| 395 |
xa := args.MustGetDict("kCBMsgArgAdvertisementData") |
| 396 |
if len(xa) == 0 { |
| 397 |
return |
| 398 |
} |
| 399 |
u := UUID{args.MustGetUUID("kCBMsgArgDeviceUUID")} |
| 400 |
a := &Advertisement{ |
| 401 |
LocalName: xa.GetString("kCBAdvDataLocalName", args.GetString("kCBMsgArgName", "")), |
| 402 |
TxPowerLevel: xa.GetInt("kCBAdvDataTxPowerLevel", 0), |
| 403 |
ManufacturerData: xa.GetBytes("kCBAdvDataManufacturerData", nil), |
| 404 |
} |
| 405 |
|
| 406 |
rssi := args.MustGetInt("kCBMsgArgRssi") |
| 407 |
|
| 408 |
if xu, ok := xa["kCBAdvDataServiceUUIDs"]; ok { |
| 409 |
for _, xs := range xu.(xpc.Array) { |
| 410 |
s := UUID{reverse(xs.([]byte))} |
| 411 |
a.Services = append(a.Services, s) |
| 412 |
} |
| 413 |
} |
| 414 |
if xsds, ok := xa["kCBAdvDataServiceData"]; ok { |
| 415 |
xsd := xsds.(xpc.Array) |
| 416 |
for i := 0; i < len(xsd); i += 2 { |
| 417 |
sd := ServiceData{ |
| 418 |
UUID: UUID{xsd[i].([]byte)}, |
| 419 |
Data: xsd[i+1].([]byte), |
| 420 |
} |
| 421 |
a.ServiceData = append(a.ServiceData, sd) |
| 422 |
} |
| 423 |
} |
| 424 |
if d.peripheralDiscovered != nil { |
| 425 |
go d.peripheralDiscovered(&peripheral{id: xpc.UUID(u.b), d: d}, a, rssi) |
| 426 |
} |
| 427 |
|
| 428 |
case peripheralConnected: |
| 429 |
u := UUID{args.MustGetUUID("kCBMsgArgDeviceUUID")} |
| 430 |
p := &peripheral{ |
| 431 |
id: xpc.UUID(u.b), |
| 432 |
d: d, |
| 433 |
reqc: make(chan message), |
| 434 |
rspc: make(chan message), |
| 435 |
quitc: make(chan struct{}), |
| 436 |
sub: newSubscriber(), |
| 437 |
} |
| 438 |
d.plistmu.Lock() |
| 439 |
d.plist[u.String()] = p |
| 440 |
d.plistmu.Unlock() |
| 441 |
go p.loop() |
| 442 |
|
| 443 |
if d.peripheralConnected != nil { |
| 444 |
go d.peripheralConnected(p, nil) |
| 445 |
} |
| 446 |
|
| 447 |
case peripheralDisconnected: |
| 448 |
u := UUID{args.MustGetUUID("kCBMsgArgDeviceUUID")} |
| 449 |
d.plistmu.Lock() |
| 450 |
p := d.plist[u.String()] |
| 451 |
delete(d.plist, u.String()) |
| 452 |
d.plistmu.Unlock() |
| 453 |
if d.peripheralDisconnected != nil { |
| 454 |
d.peripheralDisconnected(p, nil) |
| 455 |
} |
| 456 |
close(p.quitc) |
| 457 |
|
| 458 |
case |
| 459 |
rssiRead, |
| 460 |
serviceDiscovered, |
| 461 |
includedServicesDiscovered, |
| 462 |
characteristicsDiscovered, |
| 463 |
characteristicRead, |
| 464 |
characteristicWritten, |
| 465 |
notificationValueSet, |
| 466 |
descriptorsDiscovered, |
| 467 |
descriptorRead, |
| 468 |
descriptorWritten: |
| 469 |
|
| 470 |
u := UUID{args.MustGetUUID("kCBMsgArgDeviceUUID")} |
| 471 |
d.plistmu.Lock() |
| 472 |
p := d.plist[u.String()] |
| 473 |
d.plistmu.Unlock() |
| 474 |
p.rspc <- message{id: id, args: args} |
| 475 |
|
| 476 |
default: |
| 477 |
log.Printf("Unhandled event: %#v", event) |
| 478 |
} |
| 479 |
} |
| 480 |
|
| 481 |
func (d *device) sendReq(id int, args xpc.Dict) xpc.Dict { |
| 482 |
m := message{id: id, args: args, rspc: make(chan xpc.Dict)} |
| 483 |
d.reqc <- m |
| 484 |
return <-m.rspc |
| 485 |
} |
| 486 |
|
| 487 |
func (d *device) sendCmd(id int, args xpc.Dict) { |
| 488 |
d.reqc <- message{id: id, args: args} |
| 489 |
} |
| 490 |
|
| 491 |
func (d *device) loop() { |
| 492 |
for req := range d.reqc { |
| 493 |
d.sendCBMsg(req.id, req.args) |
| 494 |
if req.rspc == nil { |
| 495 |
continue |
| 496 |
} |
| 497 |
m := <-d.rspc |
| 498 |
req.rspc <- m.args |
| 499 |
} |
| 500 |
} |
| 501 |
|
| 502 |
func (d *device) sendCBMsg(id int, args xpc.Dict) { |
| 503 |
|
| 504 |
d.conn.Send(xpc.Dict{"kCBMsgId": id, "kCBMsgArgs": args}, false) |
| 505 |
} |