From cfe0d71f41228eed24dac7035d0d2e6ee483a4e7 Mon Sep 17 00:00:00 2001 From: Adrian Zankich Date: Sun, 24 Nov 2013 14:41:36 -0800 Subject: [PATCH] Add api commands --- api.go | 18 +++++++++++------- device.go | 4 ++-- driver.go | 1 + utils.go | 5 ++--- 4 files changed, 16 insertions(+), 12 deletions(-) diff --git a/api.go b/api.go index 477685f29..7c08d2d75 100644 --- a/api.go +++ b/api.go @@ -25,19 +25,23 @@ func Api(bot *Gobot) { return toJson(bot.FindRobotDevice(params["robotname"], params["devicename"])) }) + m.Get("/robots/:robotname/devices/:devicename/commands", func(params martini.Params) string { + return toJson(bot.FindRobotDevice(params["robotname"], params["devicename"]).Commands()) + }) + 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"]) - p := make([]interface{}, len(response_hash)) - i := 0 - for _, v := range response_hash { - p[i] = v - i++ + 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}) + } } - Call(robot.Driver, params["command"], p...) - return "" + return toJson(map[string]interface{}{"results": "Unknown Command"}) }) go m.Run() diff --git a/device.go b/device.go index 6b268ac5c..c5f570617 100644 --- a/device.go +++ b/device.go @@ -29,6 +29,6 @@ func (d *Device) Start() { } } -func (d *Device) Command(method_name string, arguments []string) { - //dt.Driver.Command(method_name, arguments) +func (d *Device) Commands() interface{} { + return reflect.ValueOf(d.Driver).Elem().FieldByName("Commands").Interface() } diff --git a/driver.go b/driver.go index aca82e673..978c68955 100644 --- a/driver.go +++ b/driver.go @@ -7,6 +7,7 @@ type Driver struct { Pin string Name string Params map[string]string + Commands []string Events map[string]chan interface{} `json:"-"` } diff --git a/utils.go b/utils.go index f251d4184..8dfaa3c95 100644 --- a/utils.go +++ b/utils.go @@ -54,13 +54,12 @@ func ConnectTo(port string) net.Conn { return tcpPort } -func Call(thing interface{}, method string, params ...interface{}) (result []reflect.Value, err error) { +func Call(thing interface{}, method string, params ...interface{}) []reflect.Value { in := make([]reflect.Value, len(params)) for k, param := range params { in[k] = reflect.ValueOf(param) } - result = reflect.ValueOf(thing).MethodByName(method).Call(in) - return + return reflect.ValueOf(thing).MethodByName(method).Call(in) } func toJson(obj interface{}) string {