first
This commit is contained in:
94
internal/devices/webswitch/webswitch.go
Normal file
94
internal/devices/webswitch/webswitch.go
Normal file
@@ -0,0 +1,94 @@
|
||||
package webswitch
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
host string
|
||||
httpClient *http.Client
|
||||
}
|
||||
|
||||
type Status struct {
|
||||
Relays []RelayState `json:"relays"`
|
||||
}
|
||||
|
||||
type RelayState struct {
|
||||
Number int `json:"number"`
|
||||
State bool `json:"state"`
|
||||
}
|
||||
|
||||
func New(host string) *Client {
|
||||
return &Client{
|
||||
host: host,
|
||||
httpClient: &http.Client{
|
||||
Timeout: 5 * time.Second,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) SetRelay(relay int, state bool) error {
|
||||
if relay < 1 || relay > 5 {
|
||||
return fmt.Errorf("relay number must be between 1 and 5")
|
||||
}
|
||||
|
||||
action := "off"
|
||||
if state {
|
||||
action = "on"
|
||||
}
|
||||
|
||||
url := fmt.Sprintf("http://%s/relaycontrol/%s/%d", c.host, action, relay)
|
||||
|
||||
resp, err := c.httpClient.Get(url)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to control relay: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
return fmt.Errorf("unexpected status code %d: %s", resp.StatusCode, string(body))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) TurnOn(relay int) error {
|
||||
return c.SetRelay(relay, true)
|
||||
}
|
||||
|
||||
func (c *Client) TurnOff(relay int) error {
|
||||
return c.SetRelay(relay, false)
|
||||
}
|
||||
|
||||
func (c *Client) AllOn() error {
|
||||
for i := 1; i <= 5; i++ {
|
||||
if err := c.TurnOn(i); err != nil {
|
||||
return fmt.Errorf("failed to turn on relay %d: %w", i, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) AllOff() error {
|
||||
for i := 1; i <= 5; i++ {
|
||||
if err := c.TurnOff(i); err != nil {
|
||||
return fmt.Errorf("failed to turn off relay %d: %w", i, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Ping checks if the device is reachable
|
||||
func (c *Client) Ping() error {
|
||||
url := fmt.Sprintf("http://%s/", c.host)
|
||||
resp, err := c.httpClient.Get(url)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user