code.pfad.fr/gohmekit@v0.2.1/hapip/handle_resource.go (about)

     1  package hapip
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"net/http"
     7  )
     8  
     9  func (h Handler) postResource(rw http.ResponseWriter, req *http.Request) error {
    10  	var resource struct {
    11  		AID    uint16 `json:"aid"`
    12  		Type   string `json:"resource-type"`
    13  		Width  int    `json:"image-width"`
    14  		Height int    `json:"image-height"`
    15  	}
    16  	err := json.NewDecoder(req.Body).Decode(&resource)
    17  	if err != nil {
    18  		rw.WriteHeader(http.StatusBadRequest)
    19  		return err
    20  	}
    21  	aid := resource.AID
    22  	if aid == 0 {
    23  		aid = 1
    24  	}
    25  	acc := h.Accessories[aid]
    26  	if acc == nil {
    27  		rw.WriteHeader(http.StatusBadRequest)
    28  		return fmt.Errorf("unknown accessory: %d", resource.AID)
    29  	}
    30  	accr, ok := acc.(AccessoryResource)
    31  	if !ok {
    32  		rw.WriteHeader(http.StatusBadRequest)
    33  		return fmt.Errorf("accessory[%d] does not support Resource()", resource.AID)
    34  	}
    35  	h.Logger.Log("resource", resource.Type, "w", resource.Width, "h", resource.Height)
    36  	return accr.Resource(rw, resource.Type, resource.Width, resource.Height)
    37  }