-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmanager.go
77 lines (62 loc) · 1.48 KB
/
manager.go
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
package main
import (
"net/http"
"log"
"strings"
"strconv"
"fmt"
)
type Manager struct {
leftMotor Motor
rightMotor Motor
frontSensor Sensor
backSensor Sensor
bindPort string
}
var (
requestNumber = 0
)
func (m *Manager) SensorHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Handling request", requestNumber, r.URL.String())
requestNumber++
fmt.Fprintf(w, "{\"front\":\"%f\",\"back\":\"%f\"}", m.frontSensor.GetValue(), m.backSensor.GetValue())
}
func (m *Manager) MotorHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Handling request", requestNumber, r.URL.String())
requestNumber++
arr := strings.Split(r.URL.String(), "/")
if len(arr) < 4 {
log.Println("Incorrect request", r.URL.String())
w.WriteHeader(500)
return
}
left, err := strconv.Atoi(arr[2])
if err != nil {
log.Println("Incorrect request", r.URL.String())
w.WriteHeader(500)
return
}
right, err := strconv.Atoi(arr[3])
if err != nil {
log.Println("Incorrect request", r.URL.String())
w.WriteHeader(500)
return
}
if requestNumber % 2 == 0 {
m.leftMotor.SetDirection(left)
m.rightMotor.SetDirection(right)
} else {
m.rightMotor.SetDirection(right)
m.leftMotor.SetDirection(left)
}
w.Write([]byte("OK"))
}
func (m *Manager) Run() {
go m.rightMotor.Run()
go m.leftMotor.Run()
go m.backSensor.Run()
go m.frontSensor.Run()
http.HandleFunc("/", m.SensorHandler)
http.HandleFunc("/motors/", m.MotorHandler)
http.ListenAndServe(":"+ m.bindPort, nil)
}