Skip to content

Commit

Permalink
hci: implement Characteristic WriteHandler
Browse files Browse the repository at this point in the history
Signed-off-by: deadprogram <[email protected]>
  • Loading branch information
deadprogram committed Jan 27, 2024
1 parent eac6f2d commit a896c7a
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
21 changes: 21 additions & 0 deletions adapter_hci.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ type hciAdapter struct {

connectedDevices []Device
notificationsStarted bool
charWriteHandlers []charWriteHandler
}

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

return Device{}
}

// charWriteHandler contains a handler->callback mapping for characteristic
// writes.
type charWriteHandler struct {
handle uint16
callback func(connection Connection, offset int, value []byte)
}

// getCharWriteHandler returns a characteristic write handler if one matches the
// handle, or nil otherwise.
func (a *Adapter) getCharWriteHandler(handle uint16) *charWriteHandler {
for i := range a.charWriteHandlers {
h := &a.charWriteHandlers[i]
if h.handle == handle {
return h
}
}

return nil
}
19 changes: 17 additions & 2 deletions gatts_hci.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,16 @@ func (a *Adapter) AddService(service *Service) error {
service.Characteristics[i].Handle.value = service.Characteristics[i].Value
}

if (service.Characteristics[i].Flags.Write() ||
service.Characteristics[i].Flags.WriteWithoutResponse()) &&
service.Characteristics[i].WriteEvent != nil {
handlers := append(a.charWriteHandlers, charWriteHandler{
handle: valueHandle,
callback: service.Characteristics[i].WriteEvent,
})
a.charWriteHandlers = handlers
}

if debug {
println("added characteristic", charHandle, valueHandle, service.Characteristics[i].UUID.String())
}
Expand All @@ -71,8 +81,13 @@ func (a *Adapter) AddService(service *Service) error {

// Write replaces the characteristic value with a new value.
func (c *Characteristic) Write(p []byte) (n int, err error) {
if !c.permissions.Notify() {
return 0, errNoNotify
if !(c.permissions.Write() || c.permissions.WriteWithoutResponse()) {
return 0, errNoWrite
}

hdl := c.adapter.getCharWriteHandler(c.handle)
if hdl != nil {
hdl.callback(Connection(c.handle), 0, p)
}

c.value = append([]byte{}, p...)
Expand Down

0 comments on commit a896c7a

Please sign in to comment.