code.pfad.fr/gohmekit@v0.2.1/hapip/characteristic/service/accessory/accessory.go (about)

     1  package accessory
     2  
     3  import (
     4  	"net/http"
     5  
     6  	"code.pfad.fr/gohmekit/hapip"
     7  	"code.pfad.fr/gohmekit/hapip/characteristic"
     8  	"code.pfad.fr/gohmekit/hapip/characteristic/service"
     9  )
    10  
    11  // Basic implements a basic accessory.
    12  type Basic struct {
    13  	// required
    14  	Identify func(bool) error
    15  	// required
    16  	Manufacturer, Model, Name, SerialNumber, FirmwareRevision string
    17  
    18  	// optional
    19  	HardwareRevision string
    20  	AccessoryFlags   *characteristic.Updatable[uint32]
    21  
    22  	// HAPProtocolVersion will be added as "HAP Protocol Information" service to the services if not empty
    23  	HAPProtocolVersion string
    24  
    25  	// Additional services provided by this accessory
    26  	AdditionalServices []hapip.Service
    27  }
    28  
    29  func (i Basic) Services() []hapip.Service {
    30  	s := []hapip.Service{i.Service()}
    31  	if i.HAPProtocolVersion != "" {
    32  		s = append(s, service.HAPProtocolInformation(characteristic.Version(i.HAPProtocolVersion)))
    33  	}
    34  	s = append(s, i.AdditionalServices...)
    35  	return s
    36  }
    37  
    38  func (i Basic) Service() characteristic.Service {
    39  	var optional []hapip.Characteristic
    40  	if i.HardwareRevision != "" {
    41  		optional = append(optional, characteristic.HardwareRevision(i.HardwareRevision))
    42  	}
    43  	if i.AccessoryFlags != nil {
    44  		optional = append(optional, i.AccessoryFlags)
    45  	}
    46  	return service.AccessoryInformation(
    47  		characteristic.Identify(i.Identify),
    48  		characteristic.Manufacturer(notEmpty(i.Manufacturer, "-")),
    49  		characteristic.Model(notEmpty(i.Model, "-")),
    50  		characteristic.Name(notEmpty(i.Name, "-")),
    51  		characteristic.SerialNumber(notEmpty(i.SerialNumber, "-")),
    52  		characteristic.FirmwareRevision(notEmpty(i.FirmwareRevision, "-")),
    53  		optional...,
    54  	)
    55  }
    56  
    57  func notEmpty(s, fallback string) string { //nolint:unparam
    58  	if s == "" {
    59  		return fallback
    60  	}
    61  	return s
    62  }
    63  
    64  func (i Basic) WithResourceHandler(handler func(rw http.ResponseWriter, typ string, width, height int) error) WithResource {
    65  	return WithResource{
    66  		Basic:           i,
    67  		ResourceHandler: handler,
    68  	}
    69  }
    70  
    71  // WithResource implements an accessory with a /resource handler.
    72  type WithResource struct {
    73  	Basic
    74  
    75  	ResourceHandler func(rw http.ResponseWriter, typ string, width, height int) error
    76  }
    77  
    78  func (i WithResource) Resource(rw http.ResponseWriter, typ string, width, height int) error {
    79  	return i.ResourceHandler(rw, typ, width, height)
    80  }