agi.iot.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. package agi
  2. import (
  3. "encoding/json"
  4. "log"
  5. "github.com/robertkrimen/otto"
  6. user "imuslab.com/arozos/mod/user"
  7. )
  8. /*
  9. AGI IoT Control Protocols
  10. This is a library for allowing AGI script to control / send commands to IoT devices
  11. Use with caution and prepare to handle errors. IoT devices are not always online / connectabe.
  12. Author: tobychui
  13. */
  14. func (g *Gateway) IoTLibRegister() {
  15. err := g.RegisterLib("iot", g.injectIoTFunctions)
  16. if err != nil {
  17. log.Fatal(err)
  18. }
  19. }
  20. func (g *Gateway) injectIoTFunctions(vm *otto.Otto, u *user.User) {
  21. vm.Set("_iot_scan", func(call otto.FunctionCall) otto.Value {
  22. scannedDevices := g.Option.IotManager.ScanDevices()
  23. js, _ := json.Marshal(scannedDevices)
  24. devList, err := vm.ToValue(string(js))
  25. if err != nil {
  26. return otto.FalseValue()
  27. }
  28. return devList
  29. })
  30. vm.Set("_iot_list", func(call otto.FunctionCall) otto.Value {
  31. devices := g.Option.IotManager.GetCachedDeviceList()
  32. js, _ := json.Marshal(devices)
  33. devList, err := vm.ToValue(string(js))
  34. if err != nil {
  35. return otto.FalseValue()
  36. }
  37. return devList
  38. })
  39. vm.Set("_iot_connect", func(call otto.FunctionCall) otto.Value {
  40. return otto.NullValue()
  41. })
  42. vm.Set("_iot_status", func(call otto.FunctionCall) otto.Value {
  43. return otto.NullValue()
  44. })
  45. vm.Set("_iot_exec", func(call otto.FunctionCall) otto.Value {
  46. return otto.NullValue()
  47. })
  48. vm.Set("_iot_disconnect", func(call otto.FunctionCall) otto.Value {
  49. return otto.NullValue()
  50. })
  51. vm.Set("_iot_iconTag", func(call otto.FunctionCall) otto.Value {
  52. return otto.NullValue()
  53. })
  54. vm.Set("_iot_ready", func(call otto.FunctionCall) otto.Value {
  55. if g.Option.IotManager == nil {
  56. return otto.FalseValue()
  57. } else {
  58. return otto.TrueValue()
  59. }
  60. })
  61. //Wrap all the native code function into an imagelib class
  62. _, err := vm.Run(`
  63. var iot = {
  64. "scan": function(){
  65. var devList = _iot_scan();
  66. return JSON.parse(devList);
  67. },
  68. "list": function(){
  69. var devList = _iot_list();
  70. return JSON.parse(devList);
  71. }
  72. };
  73. iot.ready = _iot_ready;
  74. iot.connect = _iot_connect;
  75. iot.status = _iot_status;
  76. iot.exec = _iot_exec;
  77. iot.disconnect = _iot_disconnect;
  78. iot.iconTag = _iot_iconTag;
  79. `)
  80. if err != nil {
  81. log.Println("*AGI* IoT Functions Injection Error", err.Error())
  82. }
  83. }