Skip to content

Commit 370c3a5

Browse files
committed
start creating API
1 parent 432bd15 commit 370c3a5

File tree

4 files changed

+50
-1
lines changed

4 files changed

+50
-1
lines changed

api/client.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -332,6 +332,8 @@ func (c *Client) SendAction(ctx context.Context, actionName string) (*Message, e
332332

333333
// SendEvent sends an event containing value to the cell.
334334
//
335+
// This is a more specific variant of SendAction.
336+
//
335337
// Events are named "Xevents" in F&Home's terminology.
336338
func (c *Client) SendEvent(ctx context.Context, cellID int, value string) error {
337339
actionName := ActionEvent

cmd/fhome/commands.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,7 @@ var configCommand = cli.Command{
140140
log.Println()
141141
}
142142
} else if cmd.Bool("glance") {
143-
// We want to see real values of the system resources.
143+
// We want to see the real values of the system resources.
144144
// To do that, we need to send the "statustouches" action and
145145
// wait for its response.
146146

cmd/fhomed/webserver/api.go

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package webserver
2+
3+
import (
4+
"github.com/bartekpacia/fhome/api"
5+
"net/http"
6+
)
7+
8+
type Api struct {
9+
fhomeClient *api.Client
10+
}
11+
12+
func NewApi() *Api {
13+
return &Api{}
14+
}
15+
16+
func (a *Api) Mux() http.Handler {
17+
mux := http.NewServeMux()
18+
19+
mux.HandleFunc("GET /devices", a.getDevices)
20+
mux.HandleFunc("POST /devices/{id}", a.toggleDevice)
21+
22+
authMux := withPassphrase(mux, "my-passphrase")
23+
return authMux
24+
}
25+
26+
func (a *Api) getDevices(w http.ResponseWriter, r *http.Request) {
27+
a.fhomeClient.SendEvent()
28+
29+
w.Header().Set("Content-Type", "application/json")
30+
}
31+
32+
func (a *Api) toggleDevice(w http.ResponseWriter, r *http.Request) {
33+
34+
}
35+
36+
func withPassphrase(next http.Handler, passphrase string) http.Handler {
37+
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
38+
if r.Header.Get("Authorization") != "Passphrase: "+passphrase {
39+
http.Error(w, "Unauthorized", http.StatusUnauthorized)
40+
return
41+
}
42+
43+
next.ServeHTTP(w, r)
44+
})
45+
}

cmd/fhomed/webserver/webserver.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,8 @@ func Run(ctx context.Context, client *api.Client, homeConfig *api.Config, email
5454
})
5555

5656
mux.Handle("GET /public", http.StripPrefix("/public/", http.FileServer(http.FS(assets))))
57+
58+
mux.Handle("/api/", http.StripPrefix("/api", api.Mux()))
5759
addr := fmt.Sprint("0.0.0.0:", port)
5860
httpServer := http.Server{Addr: addr, Handler: mux}
5961

0 commit comments

Comments
 (0)