1
0
mirror of https://github.com/hybridgroup/gobot.git synced 2025-04-27 13:48:56 +08:00

250 lines
7.6 KiB
Go
Raw Normal View History

2014-04-29 13:20:32 -07:00
package api
2013-11-23 10:36:08 -08:00
2013-11-23 16:19:11 -08:00
import (
"crypto/subtle"
"encoding/base64"
2013-11-23 16:19:11 -08:00
"encoding/json"
"github.com/bmizerany/pat"
"github.com/hybridgroup/gobot"
2014-04-15 17:59:44 -07:00
"io/ioutil"
2014-04-22 20:48:08 -07:00
"log"
2013-11-23 16:19:11 -08:00
"net/http"
2013-11-27 20:05:45 -08:00
"reflect"
2013-11-23 16:19:11 -08:00
)
2013-11-23 10:36:08 -08:00
2014-04-29 13:20:32 -07:00
// Optional restful API through Gobot has access
2014-04-26 10:13:33 -06:00
// all the robots.
type api struct {
2014-04-29 13:20:32 -07:00
gobot *gobot.Gobot
server *pat.PatternServeMux
2014-04-29 13:20:32 -07:00
Host string
Port string
Username string
Password string
Cert string
Key string
Debug bool
2014-04-29 13:20:32 -07:00
start func(*api)
}
2014-06-10 15:16:11 -07:00
func NewAPI(g *gobot.Gobot) *api {
2014-04-29 13:20:32 -07:00
return &api{
2014-05-15 11:50:45 -07:00
gobot: g,
start: func(a *api) {
2014-04-29 13:20:32 -07:00
if a == nil {
return
}
port := a.Port
if port == "" {
port = "3000"
}
host := a.Host
cert := a.Cert
key := a.Key
log.Println("Initializing API on " + host + ":" + port + "...")
http.Handle("/", a.server)
2014-04-29 13:20:32 -07:00
go func() {
if cert != "" && key != "" {
http.ListenAndServeTLS(host+":"+port, cert, key, nil)
2014-04-29 13:20:32 -07:00
} else {
log.Println("WARNING: API using insecure connection. We recommend using an SSL certificate with Gobot.")
http.ListenAndServe(host+":"+port, nil)
2014-04-29 13:20:32 -07:00
}
}()
},
}
2014-04-26 10:13:33 -06:00
}
// start starts the api using the start function
// sets on the API on initialization.
2014-04-29 13:20:32 -07:00
func (a *api) Start() {
a.server = pat.New()
2013-11-27 20:05:45 -08:00
commandRoute := "/robots/:robot/devices/:device/commands/:command"
robotCommandRoute := "/robots/:robot/commands/:command"
2013-11-27 20:05:45 -08:00
a.server.Get("/", http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
http.Redirect(res, req, "/robots", 301)
}))
a.server.Get("/robots", a.setHeaders(a.robots))
a.server.Get("/robots/:robot", a.setHeaders(a.robot))
a.server.Get("/robots/:robot/commands", a.setHeaders(a.robotCommands))
a.server.Get(robotCommandRoute, a.setHeaders(a.executeRobotCommand))
a.server.Post(robotCommandRoute, a.setHeaders(a.executeRobotCommand))
a.server.Get("/robots/:robot/devices", a.setHeaders(a.robotDevices))
a.server.Get("/robots/:robot/devices/:device", a.setHeaders(a.robotDevice))
a.server.Get("/robots/:robot/devices/:device/commands", a.setHeaders(a.robotDeviceCommands))
a.server.Get(commandRoute, a.setHeaders(a.executeCommand))
a.server.Post(commandRoute, a.setHeaders(a.executeCommand))
a.server.Get("/robots/:robot/connections", a.setHeaders(a.robotConnections))
a.server.Get("/robots/:robot/connections/:connection", a.setHeaders(a.robotConnection))
2013-11-23 16:19:11 -08:00
a.start(a)
}
2014-04-18 22:44:50 -07:00
// basic auth inspired by https://github.com/codegangsta/martini-contrib/blob/master/auth/
func (a *api) basicAuth(res http.ResponseWriter, req *http.Request) bool {
auth := req.Header.Get("Authorization")
if !a.secureCompare(auth, "Basic "+base64.StdEncoding.EncodeToString([]byte(a.Username+":"+a.Password))) {
res.Header().Set("WWW-Authenticate", "Basic realm=\"Authorization Required\"")
http.Error(res, "Not Authorized", http.StatusUnauthorized)
return false
}
return true
}
func (a *api) secureCompare(given string, actual string) bool {
if subtle.ConstantTimeEq(int32(len(given)), int32(len(actual))) == 1 {
return subtle.ConstantTimeCompare([]byte(given), []byte(actual)) == 1
}
/* Securely compare actual to itself to keep constant time, but always return false */
return subtle.ConstantTimeCompare([]byte(actual), []byte(actual)) == 1 && false
}
2014-04-18 22:44:50 -07:00
func (a *api) setHeaders(f func(http.ResponseWriter, *http.Request)) http.HandlerFunc {
return func(res http.ResponseWriter, req *http.Request) {
if a.Debug {
log.Println(req)
}
if a.Username != "" {
if !a.basicAuth(res, req) {
return
}
}
f(res, req)
}
2014-04-15 17:59:44 -07:00
}
2014-05-15 11:50:45 -07:00
func (a *api) robots(res http.ResponseWriter, req *http.Request) {
2014-06-10 15:16:11 -07:00
jsonRobots := []*gobot.JSONRobot{}
2014-05-15 11:50:45 -07:00
for _, robot := range a.gobot.Robots {
2014-06-10 15:16:11 -07:00
jsonRobots = append(jsonRobots, robot.ToJSON())
2014-04-15 17:59:44 -07:00
}
data, _ := json.Marshal(jsonRobots)
res.Header().Set("Content-Type", "application/json; charset=utf-8")
res.Write(data)
}
func (a *api) robot(res http.ResponseWriter, req *http.Request) {
robot := req.URL.Query().Get(":robot")
data, _ := json.Marshal(a.gobot.Robot(robot).ToJSON())
2014-04-15 17:59:44 -07:00
res.Header().Set("Content-Type", "application/json; charset=utf-8")
res.Write(data)
}
func (a *api) robotCommands(res http.ResponseWriter, req *http.Request) {
robot := req.URL.Query().Get(":robot")
data, _ := json.Marshal(a.gobot.Robot(robot).RobotCommands)
2014-04-15 17:59:44 -07:00
res.Header().Set("Content-Type", "application/json; charset=utf-8")
res.Write(data)
}
func (a *api) robotDevices(res http.ResponseWriter, req *http.Request) {
robot := req.URL.Query().Get(":robot")
devices := a.gobot.Robot(robot).Devices()
2014-06-10 15:16:11 -07:00
jsonDevices := []*gobot.JSONDevice{}
2014-04-15 17:59:44 -07:00
for _, device := range devices {
2014-06-10 15:16:11 -07:00
jsonDevices = append(jsonDevices, device.ToJSON())
2014-04-15 17:59:44 -07:00
}
data, _ := json.Marshal(jsonDevices)
res.Header().Set("Content-Type", "application/json; charset=utf-8")
res.Write(data)
}
func (a *api) robotDevice(res http.ResponseWriter, req *http.Request) {
robot := req.URL.Query().Get(":robot")
device := req.URL.Query().Get(":device")
2014-06-10 15:16:11 -07:00
data, _ := json.Marshal(a.gobot.Robot(robot).Device(device).ToJSON())
2014-04-15 17:59:44 -07:00
res.Header().Set("Content-Type", "application/json; charset=utf-8")
res.Write(data)
}
func (a *api) robotDeviceCommands(res http.ResponseWriter, req *http.Request) {
robot := req.URL.Query().Get(":robot")
device := req.URL.Query().Get(":device")
2014-05-15 11:50:45 -07:00
data, _ := json.Marshal(a.gobot.Robot(robot).Device(device).Commands())
2014-04-15 17:59:44 -07:00
res.Header().Set("Content-Type", "application/json; charset=utf-8")
res.Write(data)
2013-11-23 10:36:08 -08:00
}
2013-11-24 15:47:48 -08:00
func (a *api) robotConnections(res http.ResponseWriter, req *http.Request) {
robot := req.URL.Query().Get(":robot")
connections := a.gobot.Robot(robot).Connections()
2014-06-10 15:16:11 -07:00
jsonConnections := []*gobot.JSONConnection{}
2014-04-18 22:44:50 -07:00
for _, connection := range connections {
2014-06-10 15:16:11 -07:00
jsonConnections = append(jsonConnections, connection.ToJSON())
2014-04-18 22:44:50 -07:00
}
data, _ := json.Marshal(jsonConnections)
res.Header().Set("Content-Type", "application/json; charset=utf-8")
res.Write(data)
}
func (a *api) robotConnection(res http.ResponseWriter, req *http.Request) {
robot := req.URL.Query().Get(":robot")
connection := req.URL.Query().Get(":connection")
2014-06-10 15:16:11 -07:00
data, _ := json.Marshal(a.gobot.Robot(robot).Connection(connection).ToJSON())
2014-04-18 22:44:50 -07:00
res.Header().Set("Content-Type", "application/json; charset=utf-8")
res.Write(data)
}
func (a *api) executeCommand(res http.ResponseWriter, req *http.Request) {
robot := req.URL.Query().Get(":robot")
device := req.URL.Query().Get(":device")
command := req.URL.Query().Get(":command")
2014-04-15 17:59:44 -07:00
data, _ := ioutil.ReadAll(req.Body)
2013-11-24 15:47:48 -08:00
var body map[string]interface{}
2014-04-15 17:59:44 -07:00
json.Unmarshal(data, &body)
d := a.gobot.Robot(robot).Device(device)
commands := d.Commands().([]string)
for c := range commands {
if commands[c] == command {
2014-06-10 15:16:11 -07:00
ret := []interface{}{}
for _, v := range gobot.Call(d.Driver, command, body) {
ret = append(ret, v.Interface())
}
data, _ = json.Marshal(ret)
2014-04-15 17:59:44 -07:00
res.Header().Set("Content-Type", "application/json; charset=utf-8")
res.Write(data)
return
2013-11-24 15:47:48 -08:00
}
}
data, _ = json.Marshal([]interface{}{"Unknown Command"})
2014-04-15 17:59:44 -07:00
res.Header().Set("Content-Type", "application/json; charset=utf-8")
res.Write(data)
2013-11-24 15:47:48 -08:00
}
2013-11-27 20:05:45 -08:00
func (a *api) executeRobotCommand(res http.ResponseWriter, req *http.Request) {
robot := req.URL.Query().Get(":robot")
command := req.URL.Query().Get(":command")
2014-04-15 19:19:14 -07:00
data, _ := ioutil.ReadAll(req.Body)
2014-04-22 20:48:08 -07:00
body := make(map[string]interface{})
2014-04-15 19:19:14 -07:00
json.Unmarshal(data, &body)
r := a.gobot.Robot(robot)
2014-04-15 19:19:14 -07:00
in := make([]reflect.Value, 1)
body["robot"] = robot
2014-04-15 19:19:14 -07:00
in[0] = reflect.ValueOf(body)
c := r.Commands[command]
if c != nil {
2014-06-10 15:16:11 -07:00
ret := []interface{}{}
for _, v := range reflect.ValueOf(c).Call(in) {
ret = append(ret, v.Interface())
}
data, _ = json.Marshal(ret)
2014-04-15 19:19:14 -07:00
} else {
data, _ = json.Marshal([]interface{}{"Unknown Command"})
2013-11-27 20:05:45 -08:00
}
2014-04-15 19:19:14 -07:00
res.Header().Set("Content-Type", "application/json; charset=utf-8")
res.Write(data)
2013-11-27 20:05:45 -08:00
}