design and impl BaseServiceRequest

This commit is contained in:
Sam Lewis
2022-10-12 01:14:32 -04:00
parent 4cf16d0d41
commit 7f9e346d34
6 changed files with 54 additions and 11 deletions

View File

@@ -3,9 +3,30 @@ package services
import (
"context"
"github.com/saml-dev/gome-assistant/internal/http"
"nhooyr.io/websocket"
)
func BuildService[T Light | HomeAssistant](conn *websocket.Conn, ctx context.Context) *T {
return &T{conn: conn, ctx: ctx}
func BuildService[T Light | HomeAssistant](conn *websocket.Conn, ctx context.Context, httpClient *http.HttpClient) *T {
return &T{conn: conn, ctx: ctx, httpClient: httpClient}
}
type BaseServiceRequest struct {
Id int `json:"id"`
RequestType string `json:"type"` // hardcoded "call_service"
Domain string `json:"domain"`
Service string `json:"service"`
ServiceData map[string]any `json:"service_data,omitempty"`
Target struct {
EntityId string `json:"entity_id"`
} `json:"target"`
}
func NewBaseServiceRequest(entityId string) BaseServiceRequest {
bsr := BaseServiceRequest{
Id: 10,
RequestType: "call_service",
}
bsr.Target.EntityId = entityId
return bsr
}

View File

@@ -4,6 +4,7 @@ import (
"context"
"github.com/saml-dev/gome-assistant/internal/http"
ws "github.com/saml-dev/gome-assistant/internal/websocket"
"nhooyr.io/websocket"
)
@@ -13,6 +14,26 @@ type HomeAssistant struct {
httpClient *http.HttpClient
}
// TODO: design how much reuse I can get between request types. E.g.
// only difference between light.turnon and homeassistant.turnon is
// domain and extra data
func (ha *HomeAssistant) TurnOn(entityId string) {
req := NewBaseServiceRequest(entityId)
req.Domain = "homeassistant"
req.Service = "turn_on"
ws.WriteMessage(req, ha.conn, ha.ctx)
}
func (ha *HomeAssistant) TurnOff(entityId string) {
req := NewBaseServiceRequest(entityId)
req.Domain = "homeassistant"
req.Service = "turn_off"
ws.WriteMessage(req, ha.conn, ha.ctx)
}
func (ha *HomeAssistant) Toggle(entityId string) {
req := NewBaseServiceRequest(entityId)
req.Domain = "homeassistant"
req.Service = "toggle"
ws.WriteMessage(req, ha.conn, ha.ctx)
}