Created
September 28, 2017 13:26
-
-
Save brutella/e5bb4be15f2c78e42050e3cf24b0504c to your computer and use it in GitHub Desktop.
HTTP server which turns a HomeKit switch on and off
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"github.com/brutella/hc" | |
"github.com/brutella/hc/accessory" | |
"github.com/brutella/hc/log" | |
"net/http" | |
) | |
func main() { | |
switchInfo := accessory.Info{ | |
Name: "Lamp", | |
} | |
acc := accessory.NewSwitch(switchInfo) | |
t, err := hc.NewIPTransport(hc.Config{}, acc.Accessory) | |
if err != nil { | |
log.Info.Panic(err) | |
} | |
mux := http.NewServeMux() | |
mux.HandleFunc("/turnOn", func(w http.ResponseWriter, req *http.Request) { | |
acc.Switch.On.SetValue(true) | |
log.Info.Println("Switch turned on") | |
w.Write([]byte("Switch turned on")) | |
}) | |
mux.HandleFunc("/turnOff", func(w http.ResponseWriter, req *http.Request) { | |
acc.Switch.On.SetValue(false) | |
log.Info.Println("Switch turned off") | |
w.Write([]byte("Switch turned off")) | |
}) | |
s := &http.Server{ | |
Addr: ":4321", | |
Handler: mux, | |
} | |
// Run server in new goroutine | |
go s.ListenAndServe() | |
hc.OnTermination(func() { | |
s.Close() | |
t.Stop() | |
}) | |
log.Info.Printf("http://localhost%s/turnOn turns the switch on\n", s.Addr) | |
log.Info.Printf("http://localhost%s/turnOff turns the switch off\n", s.Addr) | |
t.Start() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment