Skip to content

Commit 9a53d2a

Browse files
deadprogrambgould
authored andcommitted
hci: implement Characteristic WriteHandler
Signed-off-by: deadprogram <[email protected]>
1 parent 3e90718 commit 9a53d2a

File tree

2 files changed

+40
-3
lines changed

2 files changed

+40
-3
lines changed

adapter_hci.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ type hciAdapter struct {
2222

2323
connectedDevices []Device
2424
notificationsStarted bool
25+
charWriteHandlers []charWriteHandler
2526
}
2627

2728
func (a *hciAdapter) enable() error {
@@ -174,3 +175,23 @@ func (a *hciAdapter) findConnection(handle uint16) Device {
174175

175176
return Device{}
176177
}
178+
179+
// charWriteHandler contains a handler->callback mapping for characteristic
180+
// writes.
181+
type charWriteHandler struct {
182+
handle uint16
183+
callback func(connection Connection, offset int, value []byte)
184+
}
185+
186+
// getCharWriteHandler returns a characteristic write handler if one matches the
187+
// handle, or nil otherwise.
188+
func (a *Adapter) getCharWriteHandler(handle uint16) *charWriteHandler {
189+
for i := range a.charWriteHandlers {
190+
h := &a.charWriteHandlers[i]
191+
if h.handle == handle {
192+
return h
193+
}
194+
}
195+
196+
return nil
197+
}

gatts_hci.go

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,16 @@ func (a *Adapter) AddService(service *Service) error {
5353
service.Characteristics[i].Handle.value = service.Characteristics[i].Value
5454
}
5555

56+
if (service.Characteristics[i].Flags.Write() ||
57+
service.Characteristics[i].Flags.WriteWithoutResponse()) &&
58+
service.Characteristics[i].WriteEvent != nil {
59+
handlers := append(a.charWriteHandlers, charWriteHandler{
60+
handle: valueHandle,
61+
callback: service.Characteristics[i].WriteEvent,
62+
})
63+
a.charWriteHandlers = handlers
64+
}
65+
5666
if debug {
5767
println("added characteristic", charHandle, valueHandle, service.Characteristics[i].UUID.String())
5868
}
@@ -71,11 +81,17 @@ func (a *Adapter) AddService(service *Service) error {
7181

7282
// Write replaces the characteristic value with a new value.
7383
func (c *Characteristic) Write(p []byte) (n int, err error) {
74-
if !c.permissions.Notify() {
75-
return 0, errNoNotify
84+
if !(c.permissions.Write() || c.permissions.WriteWithoutResponse() ||
85+
c.permissions.Notify() || c.permissions.Indicate()) {
86+
return 0, errNoWrite
87+
}
88+
89+
hdl := c.adapter.getCharWriteHandler(c.handle)
90+
if hdl != nil {
91+
hdl.callback(Connection(c.handle), 0, p)
7692
}
7793

78-
c.value = append([]byte{}, p...)
94+
copy(c.value, p)
7995

8096
if c.cccd&0x01 != 0 {
8197
// send notification

0 commit comments

Comments
 (0)