hybridgroup.gobot/api.go

49 lines
1.5 KiB
Go
Raw Normal View History

2013-11-24 02:36:08 +08:00
package gobot
2013-11-24 08:19:11 +08:00
import (
"encoding/json"
"github.com/codegangsta/martini"
"net/http"
)
2013-11-24 02:36:08 +08:00
func Api(bot *Gobot) {
m := martini.Classic()
m.Get("/robots", func() string {
return toJson(bot.Robots)
})
m.Get("/robots/:robotname", func(params martini.Params) string {
return toJson(bot.FindRobot(params["robotname"]))
})
m.Get("/robots/:robotname/devices", func(params martini.Params) string {
return toJson(bot.FindRobot(params["robotname"]).GetDevices())
})
m.Get("/robots/:robotname/devices/:devicename", func(params martini.Params) string {
return toJson(bot.FindRobotDevice(params["robotname"], params["devicename"]))
})
2013-11-25 06:41:36 +08:00
m.Get("/robots/:robotname/devices/:devicename/commands", func(params martini.Params) string {
return toJson(bot.FindRobotDevice(params["robotname"], params["devicename"]).Commands())
})
2013-11-24 08:19:11 +08:00
m.Post("/robots/:robotname/devices/:devicename/commands/:command", func(params martini.Params, res http.ResponseWriter, req *http.Request) string {
decoder := json.NewDecoder(req.Body)
var response_hash map[string]interface{}
decoder.Decode(&response_hash)
robot := bot.FindRobotDevice(params["robotname"], params["devicename"])
2013-11-25 06:41:36 +08:00
commands := robot.Commands().([]string)
for command := range commands {
if commands[command] == params["command"] {
ret := Call(robot.Driver, params["command"], response_hash)
return toJson(map[string]interface{}{"results": ret})
}
2013-11-24 08:19:11 +08:00
}
2013-11-25 06:41:36 +08:00
return toJson(map[string]interface{}{"results": "Unknown Command"})
2013-11-24 08:19:11 +08:00
})
2013-11-24 02:36:08 +08:00
go m.Run()
}