Added lots of services and fixed bug with ID for websocket calls

This commit is contained in:
Sam Lewis
2022-10-13 02:17:36 -04:00
parent 7f9e346d34
commit b99c1e5925
13 changed files with 379 additions and 59 deletions

View File

@@ -3,54 +3,48 @@ package services
import (
"context"
"github.com/saml-dev/gome-assistant/internal/http"
ws "github.com/saml-dev/gome-assistant/internal/websocket"
"nhooyr.io/websocket"
)
type Light struct {
conn *websocket.Conn
ctx context.Context
httpClient *http.HttpClient
}
/* Structs */
type LightRequest struct {
Id int `json:"id"`
Type string `json:"type"`
Domain string `json:"domain"`
Service string `json:"service"`
Target struct {
EntityId string `json:"entity_id"`
} `json:"target"`
type Light struct {
conn *websocket.Conn
ctx context.Context
}
/* Public API */
func (l Light) TurnOn(entityId string) {
req := newLightOnRequest(entityId)
// TurnOn a light entity. Takes an entityId and an optional
// map that is translated into service_data.
func (l Light) TurnOn(entityId string, serviceData ...map[string]any) {
req := NewBaseServiceRequest(entityId)
req.Domain = "light"
req.Service = "turn_on"
if len(serviceData) != 0 {
req.ServiceData = serviceData[0]
}
ws.WriteMessage(req, l.conn, l.ctx)
}
// Toggle a light entity. Takes an entityId and an optional
// map that is translated into service_data.
func (l Light) Toggle(entityId string, serviceData ...map[string]any) {
req := NewBaseServiceRequest(entityId)
req.Domain = "light"
req.Service = "toggle"
if len(serviceData) != 0 {
req.ServiceData = serviceData[0]
}
ws.WriteMessage(req, l.conn, l.ctx)
}
func (l Light) TurnOff(entityId string) {
req := newLightOffRequest(entityId)
req := NewBaseServiceRequest(entityId)
req.Domain = "light"
req.Service = "turn_off"
ws.WriteMessage(req, l.conn, l.ctx)
}
/* Internal */
func newLightOnRequest(entityId string) LightRequest {
req := LightRequest{
Id: 5,
Type: "call_service",
Domain: "light",
Service: "turn_on",
}
req.Target.EntityId = entityId
return req
}
func newLightOffRequest(entityId string) LightRequest {
req := newLightOnRequest(entityId)
req.Service = "turn_off"
return req
}