code.pfad.fr/gohmekit@v0.2.1/hapip/characteristic/writable.go (about) 1 package characteristic 2 3 import ( 4 "context" 5 "encoding/json" 6 7 "code.pfad.fr/gohmekit/hapip" 8 ) 9 10 var _ hapip.CharacteristicNotifier = &Writable[string]{} 11 var _ hapip.CharacteristicWriter = &Writable[string]{} 12 13 // Writable is a writable characteristic, which value can be updated by the remote controller or 14 // by the software. 15 // 16 // When the updated (or written) value is different from the last value, all listeners will be notified. 17 type Writable[Format format] struct { 18 Updatable[Format] 19 write func(val Format) error 20 } 21 22 // Write fullfils the hapip.CharacteristicWriter interface (for use by hapip.Handler). 23 func (u *Writable[Format]) Write(ctx context.Context, buf json.RawMessage) error { 24 var val Format 25 if err := unmarshal(buf, &val); err != nil { 26 return err 27 } 28 err := u.write(val) 29 if err != nil { 30 return err 31 } 32 u.update(ctx, val) 33 return nil 34 } 35 36 // WithRemoteRead updates the characteristic (and returns itself), so that it gets its 37 // value from the given read function on Read. 38 // Must be called before any Read happens. 39 func (u *Writable[Format]) WithRemoteRead(read func(ctx context.Context) (Format, error)) *Writable[Format] { 40 u.read = read 41 return u 42 }