-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
executable file
·78 lines (54 loc) · 1.67 KB
/
server.go
File metadata and controls
executable file
·78 lines (54 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package main
import (
"time"
"github.com/julienschmidt/httprouter"
"net/http"
"log"
"regexp"
"github.com/hybridgroup/gobot"
"github.com/hybridgroup/gobot/platforms/gpio"
"github.com/hybridgroup/gobot/platforms/raspi"
"html/template"
)
var validPath = regexp.MustCompile("^(open|close|status)$")
var templates = template.Must(template.ParseFiles("web/button.html"))
func indexHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
templates.Execute(w, r)
}
func initGobot() (*gobot.Gobot, httprouter.Handle) {
_gobot := gobot.NewGobot()
raspiAdapter := raspi.NewRaspiAdaptor("raspi")
remoteButton := gpio.NewRelayDriver(raspiAdapter, "remoteButton", "26")
robot := gobot.NewRobot("remoteButtonBot",
[]gobot.Connection{raspiAdapter},
[]gobot.Device{remoteButton},
)
_gobot.AddRobot(robot)
gobotHandler := func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
command := ps.ByName("command")
m := validPath.FindStringSubmatch(command)
if m == nil {
http.Error(w, "Invalid command: "+command, http.StatusBadRequest)
return
}
log.Printf("Command [%s] accepted.", command)
if (command=="open" || command=="close") {
remoteButton.On();
time.Sleep(2000 * time.Millisecond)
log.Println("[+] Relay going LOW")
remoteButton.Off();
log.Printf("state: %v",remoteButton.State())
}
templates.Execute(w, r)
}
return _gobot, gobotHandler;
}
func main() {
_gobot, gobotHandler := initGobot()
router := httprouter.New()
router.GET("/garer", indexHandler)
router.GET("/garer/v1/cmd/:command", gobotHandler)
log.Printf("Blown will a port:8080")
log.Fatal(http.ListenAndServe(":8080", router))
_gobot.Start()
}