agi.iot.go 6.9 KB

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