code.pfad.fr/gohmekit@v0.2.1/hapip/characteristic/write_only.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.CharacteristicWriter = WriteOnly[string]{}
    11  
    12  type WriteOnly[Format format] struct {
    13  	Metadata[Format]
    14  	write func(val Format) error
    15  }
    16  
    17  func (w WriteOnly[Format]) Write(ctx context.Context, buf json.RawMessage) error {
    18  	var val Format
    19  	if err := unmarshal(buf, &val); err != nil {
    20  		return err
    21  	}
    22  	return w.write(val)
    23  }
    24  
    25  func unmarshal[Format format](buf json.RawMessage, v *Format) error {
    26  	switch any(v).(type) { //nolint:gocritic
    27  	case *bool:
    28  		switch string(buf) {
    29  		case "1":
    30  			buf = []byte("true")
    31  		case "0":
    32  			buf = []byte("false")
    33  		}
    34  	}
    35  	return json.Unmarshal(buf, v)
    36  }