agi.iot.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. package agi
  2. import (
  3. "encoding/json"
  4. "log"
  5. "net/http"
  6. "github.com/robertkrimen/otto"
  7. "imuslab.com/arozos/mod/filesystem"
  8. "imuslab.com/arozos/mod/iot"
  9. user "imuslab.com/arozos/mod/user"
  10. )
  11. /*
  12. AGI IoT Control Protocols
  13. This is a library for allowing AGI script to control / send commands to IoT devices
  14. Use with caution and prepare to handle errors. IoT devices are not always online / connectabe.
  15. Author: tobychui
  16. */
  17. func (g *Gateway) IoTLibRegister() {
  18. err := g.RegisterLib("iot", g.injectIoTFunctions)
  19. if err != nil {
  20. log.Fatal(err)
  21. }
  22. }
  23. func (g *Gateway) injectIoTFunctions(vm *otto.Otto, u *user.User, scriptFsh *filesystem.FileSystemHandler, scriptPath string, w http.ResponseWriter, r *http.Request) {
  24. //Scan and return the latest iot device list
  25. vm.Set("_iot_scan", func(call otto.FunctionCall) otto.Value {
  26. scannedDevices := g.Option.IotManager.ScanDevices()
  27. js, _ := json.Marshal(scannedDevices)
  28. devList, err := vm.ToValue(string(js))
  29. if err != nil {
  30. return otto.FalseValue()
  31. }
  32. return devList
  33. })
  34. //List the current scanned device list from cache
  35. vm.Set("_iot_list", func(call otto.FunctionCall) otto.Value {
  36. devices := g.Option.IotManager.GetCachedDeviceList()
  37. js, _ := json.Marshal(devices)
  38. devList, err := vm.ToValue(string(js))
  39. if err != nil {
  40. return otto.FalseValue()
  41. }
  42. return devList
  43. })
  44. //Conenct an iot device. Return true if the device is connected or the device do not require connection before command exec
  45. vm.Set("_iot_connect", func(call otto.FunctionCall) otto.Value {
  46. //Get device ID from paratmer
  47. devID, err := call.Argument(0).ToString()
  48. if err != nil {
  49. return otto.FalseValue()
  50. }
  51. //Get the auth info from paramters
  52. username, err := call.Argument(1).ToString()
  53. if err != nil {
  54. username = ""
  55. }
  56. password, err := call.Argument(2).ToString()
  57. if err != nil {
  58. password = ""
  59. }
  60. token, err := call.Argument(3).ToString()
  61. if err != nil {
  62. token = ""
  63. }
  64. //Get device by id
  65. dev := g.Option.IotManager.GetDeviceByID(devID)
  66. if dev == nil {
  67. //No device with that ID found
  68. return otto.FalseValue()
  69. }
  70. if dev.RequireConnect == true {
  71. //Build the auto info
  72. autoInfo := iot.AuthInfo{
  73. Username: username,
  74. Password: password,
  75. Token: token,
  76. }
  77. //Connect the device
  78. dev.Handler.Connect(dev, &autoInfo)
  79. }
  80. //Return true
  81. return otto.TrueValue()
  82. })
  83. //Get the status of the given device
  84. vm.Set("_iot_status", func(call otto.FunctionCall) otto.Value {
  85. //Get device ID from paratmer
  86. devID, err := call.Argument(0).ToString()
  87. if err != nil {
  88. return otto.FalseValue()
  89. }
  90. dev := g.Option.IotManager.GetDeviceByID(devID)
  91. if dev == nil {
  92. return otto.FalseValue()
  93. }
  94. //We have no idea what is the structure of the dev status.
  95. //Just leave it to the front end to handle :P
  96. devStatus, err := dev.Handler.Status(dev)
  97. if err != nil {
  98. log.Println("*AGI IoT* " + err.Error())
  99. return otto.FalseValue()
  100. }
  101. js, _ := json.Marshal(devStatus)
  102. results, _ := vm.ToValue(string(js))
  103. return results
  104. })
  105. vm.Set("_iot_exec", func(call otto.FunctionCall) otto.Value {
  106. //Get device ID from paratmer
  107. devID, err := call.Argument(0).ToString()
  108. if err != nil {
  109. return otto.FalseValue()
  110. }
  111. //Get endpoint name
  112. epname, err := call.Argument(1).ToString()
  113. if err != nil {
  114. return otto.FalseValue()
  115. }
  116. //Get payload if any
  117. payload, err := call.Argument(2).ToString()
  118. if err != nil {
  119. payload = ""
  120. }
  121. //Get device by id
  122. dev := g.Option.IotManager.GetDeviceByID(devID)
  123. if dev == nil {
  124. //Device not found
  125. log.Println("*AGI IoT* Given device ID do not match any IoT devices")
  126. return otto.FalseValue()
  127. }
  128. //Get the endpoint from name
  129. var targetEp *iot.Endpoint
  130. for _, ep := range dev.ControlEndpoints {
  131. if ep.Name == epname {
  132. //This is the target endpoint
  133. thisEp := ep
  134. targetEp = thisEp
  135. }
  136. }
  137. if targetEp == nil {
  138. //Endpoint not found
  139. log.Println("*AGI IoT* Failed to get endpoint by name in this device")
  140. return otto.FalseValue()
  141. }
  142. var results interface{}
  143. //Try to convert it into a string map
  144. if payload != "" {
  145. payloadMap := map[string]interface{}{}
  146. err = json.Unmarshal([]byte(payload), &payloadMap)
  147. if err != nil {
  148. log.Println("*AGI IoT* Failed to parse input payload: " + err.Error())
  149. return otto.FalseValue()
  150. }
  151. //Execute the request
  152. results, err = dev.Handler.Execute(dev, targetEp, payloadMap)
  153. } else {
  154. //Execute the request without payload
  155. results, err = dev.Handler.Execute(dev, targetEp, nil)
  156. }
  157. if err != nil {
  158. log.Println("*AGI IoT* Failed to execute request to device: " + err.Error())
  159. return otto.FalseValue()
  160. }
  161. js, _ := json.Marshal(results)
  162. reply, _ := vm.ToValue(string(js))
  163. return reply
  164. })
  165. //Disconnect a given iot device using the device UUID
  166. vm.Set("_iot_disconnect", func(call otto.FunctionCall) otto.Value {
  167. //Get device ID from paratmer
  168. devID, err := call.Argument(0).ToString()
  169. if err != nil {
  170. return otto.FalseValue()
  171. }
  172. dev := g.Option.IotManager.GetDeviceByID(devID)
  173. if dev == nil {
  174. return otto.FalseValue()
  175. }
  176. if dev.RequireConnect == true {
  177. err = dev.Handler.Disconnect(dev)
  178. if err != nil {
  179. return otto.FalseValue()
  180. }
  181. }
  182. return otto.TrueValue()
  183. })
  184. //Return the icon tag for this device
  185. vm.Set("_iot_iconTag", func(call otto.FunctionCall) otto.Value {
  186. //Get device ID from paratmer
  187. devID, err := call.Argument(0).ToString()
  188. if err != nil {
  189. return otto.FalseValue()
  190. }
  191. dev := g.Option.IotManager.GetDeviceByID(devID)
  192. if dev == nil {
  193. //device not found
  194. return otto.NullValue()
  195. }
  196. deviceIconTag := dev.Handler.Icon(dev)
  197. it, _ := vm.ToValue(deviceIconTag)
  198. return it
  199. })
  200. vm.Set("_iot_ready", func(call otto.FunctionCall) otto.Value {
  201. if g.Option.IotManager == nil {
  202. return otto.FalseValue()
  203. } else {
  204. return otto.TrueValue()
  205. }
  206. })
  207. //Wrap all the native code function into an imagelib class
  208. _, err := vm.Run(`
  209. var iot = {
  210. "scan": function(){
  211. var devList = _iot_scan();
  212. return JSON.parse(devList);
  213. },
  214. "list": function(){
  215. var devList = _iot_list();
  216. return JSON.parse(devList);
  217. },
  218. "status": function(devid){
  219. var devStatus = _iot_status(devid);
  220. return JSON.parse(devStatus);
  221. },
  222. "exec": function(devid, epname, payload){
  223. payload = payload || "";
  224. payload = JSON.stringify(payload);
  225. var resp = _iot_exec(devid, epname, payload);
  226. if (resp == false){
  227. return false;
  228. }else{
  229. return JSON.parse(resp);
  230. }
  231. }
  232. };
  233. iot.ready = _iot_ready;
  234. iot.connect = _iot_connect;
  235. iot.disconnect = _iot_disconnect;
  236. iot.iconTag = _iot_iconTag;
  237. `)
  238. if err != nil {
  239. log.Println("*AGI* IoT Functions Injection Error", err.Error())
  240. }
  241. }