agi.iot.go 6.9 KB

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