agi.iot.go 6.5 KB

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