|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "context" |
| 6 | + "encoding/json" |
| 7 | + "fmt" |
| 8 | + "io/ioutil" |
| 9 | + "log" |
| 10 | + "net/http" |
| 11 | + "os" |
| 12 | + "path/filepath" |
| 13 | + "time" |
| 14 | + |
| 15 | + "github.com/grandcat/zeroconf" |
| 16 | +) |
| 17 | + |
| 18 | +const elgatoAPIPath = "/elgato/lights" |
| 19 | + |
| 20 | +var ( |
| 21 | + version string |
| 22 | + commit string |
| 23 | + buildDate string |
| 24 | +) |
| 25 | + |
| 26 | +type LightState struct { |
| 27 | + Lights []struct { |
| 28 | + On int `json:"on"` |
| 29 | + } `json:"lights"` |
| 30 | +} |
| 31 | + |
| 32 | +// findElgatoLight discovers the first Elgato Light on the local network using mDNS. |
| 33 | +// It returns the IP address of the found light or an error if no light is found. |
| 34 | +func findElgatoLight() (string, error) { |
| 35 | + resolver, err := zeroconf.NewResolver(nil) |
| 36 | + if err != nil { |
| 37 | + return "", fmt.Errorf("failed to initialize resolver: %w", err) |
| 38 | + } |
| 39 | + |
| 40 | + entries := make(chan *zeroconf.ServiceEntry) |
| 41 | + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) |
| 42 | + defer cancel() |
| 43 | + |
| 44 | + go func() { |
| 45 | + if err := resolver.Browse(ctx, "_elg._tcp", "local.", entries); err != nil { |
| 46 | + log.Printf("failed to browse mDNS: %v", err) |
| 47 | + } |
| 48 | + }() |
| 49 | + |
| 50 | + for entry := range entries { |
| 51 | + if len(entry.AddrIPv4) > 0 { |
| 52 | + return entry.AddrIPv4[0].String(), nil |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + return "", fmt.Errorf("no Elgato light found") |
| 57 | +} |
| 58 | + |
| 59 | +// getCurrentState retrieves the current on/off state of the Elgato Light. |
| 60 | +// It returns 1 if the light is on, 0 if it is off, or an error if the state cannot be retrieved. |
| 61 | +func getCurrentState(ip string) (int, error) { |
| 62 | + url := fmt.Sprintf("http://%s:9123%s", ip, elgatoAPIPath) |
| 63 | + |
| 64 | + resp, err := http.Get(url) |
| 65 | + if err != nil { |
| 66 | + return 0, fmt.Errorf("failed to get current state: %w", err) |
| 67 | + } |
| 68 | + defer resp.Body.Close() |
| 69 | + |
| 70 | + if resp.StatusCode != http.StatusOK { |
| 71 | + return 0, fmt.Errorf("unexpected response: %s", resp.Status) |
| 72 | + } |
| 73 | + |
| 74 | + body, err := ioutil.ReadAll(resp.Body) |
| 75 | + if err != nil { |
| 76 | + return 0, fmt.Errorf("failed to read response body: %w", err) |
| 77 | + } |
| 78 | + |
| 79 | + var state LightState |
| 80 | + if err := json.Unmarshal(body, &state); err != nil { |
| 81 | + return 0, fmt.Errorf("failed to parse JSON: %w", err) |
| 82 | + } |
| 83 | + |
| 84 | + if len(state.Lights) > 0 { |
| 85 | + return state.Lights[0].On, nil |
| 86 | + } |
| 87 | + |
| 88 | + return 0, fmt.Errorf("no light state data available") |
| 89 | +} |
| 90 | + |
| 91 | +// toggleLight changes the Elgato Light's state from on to off or vice versa. |
| 92 | +// It fetches the current state, determines the opposite state, and sends a request to update it. |
| 93 | +func toggleLight(ip string) error { |
| 94 | + currentState, err := getCurrentState(ip) |
| 95 | + if err != nil { |
| 96 | + return fmt.Errorf("failed to get current state: %w", err) |
| 97 | + } |
| 98 | + |
| 99 | + newState := 1 - currentState |
| 100 | + |
| 101 | + url := fmt.Sprintf("http://%s:9123%s", ip, elgatoAPIPath) |
| 102 | + payload := LightState{ |
| 103 | + Lights: []struct { |
| 104 | + On int `json:"on"` |
| 105 | + }{ |
| 106 | + {On: newState}, |
| 107 | + }, |
| 108 | + } |
| 109 | + |
| 110 | + body, err := json.Marshal(payload) |
| 111 | + if err != nil { |
| 112 | + return fmt.Errorf("failed to marshal JSON: %w", err) |
| 113 | + } |
| 114 | + |
| 115 | + req, err := http.NewRequest("PUT", url, bytes.NewBuffer(body)) |
| 116 | + if err != nil { |
| 117 | + return fmt.Errorf("failed to create request: %w", err) |
| 118 | + } |
| 119 | + req.Header.Set("Content-Type", "application/json") |
| 120 | + |
| 121 | + client := &http.Client{Timeout: 3 * time.Second} |
| 122 | + resp, err := client.Do(req) |
| 123 | + if err != nil { |
| 124 | + return fmt.Errorf("failed to send request: %w", err) |
| 125 | + } |
| 126 | + defer resp.Body.Close() |
| 127 | + |
| 128 | + if resp.StatusCode != http.StatusOK { |
| 129 | + return fmt.Errorf("unexpected response: %s", resp.Status) |
| 130 | + } |
| 131 | + |
| 132 | + fmt.Printf("Light toggled to %s\n", map[int]string{0: "off", 1: "on"}[newState]) |
| 133 | + return nil |
| 134 | +} |
| 135 | + |
| 136 | +// printHelp displays the usage instructions for the program. |
| 137 | +func printHelp(programName string) { |
| 138 | + fmt.Printf(`Usage: %s [option] |
| 139 | +
|
| 140 | +This program finds the first Elgato Light on your network and toggles its state. |
| 141 | +
|
| 142 | +Options: |
| 143 | + --help Show this help message. |
| 144 | + --version Show program version. |
| 145 | +
|
| 146 | +Example usage: |
| 147 | + %s Toggles the light on or off |
| 148 | + %s --help Shows this message |
| 149 | +`, programName, programName, programName) |
| 150 | +} |
| 151 | + |
| 152 | +// main is the entry point of the program. It detects Elgato Lights and toggles their state. |
| 153 | +func main() { |
| 154 | + programName := filepath.Base(os.Args[0]) |
| 155 | + |
| 156 | + if len(os.Args) > 1 { |
| 157 | + switch os.Args[1] { |
| 158 | + case "--help": |
| 159 | + printHelp(programName) |
| 160 | + return |
| 161 | + case "--version": |
| 162 | + fmt.Printf("Version: %s\nCommit: %s\nBuild Date: %s\n", version, commit, buildDate) |
| 163 | + return |
| 164 | + } |
| 165 | + } |
| 166 | + |
| 167 | + ip, err := findElgatoLight() |
| 168 | + if err != nil { |
| 169 | + log.Fatalf("Error: %v", err) |
| 170 | + } |
| 171 | + |
| 172 | + if err := toggleLight(ip); err != nil { |
| 173 | + log.Fatalf("Failed to toggle light: %v", err) |
| 174 | + } |
| 175 | +} |
0 commit comments