package agi import ( "encoding/json" "log" "github.com/robertkrimen/otto" user "imuslab.com/arozos/mod/user" ) /* AGI IoT Control Protocols This is a library for allowing AGI script to control / send commands to IoT devices Use with caution and prepare to handle errors. IoT devices are not always online / connectabe. Author: tobychui */ func (g *Gateway) IoTLibRegister() { err := g.RegisterLib("iot", g.injectIoTFunctions) if err != nil { log.Fatal(err) } } func (g *Gateway) injectIoTFunctions(vm *otto.Otto, u *user.User) { vm.Set("_iot_scan", func(call otto.FunctionCall) otto.Value { scannedDevices := g.Option.IotManager.ScanDevices() js, _ := json.Marshal(scannedDevices) devList, err := vm.ToValue(string(js)) if err != nil { return otto.FalseValue() } return devList }) vm.Set("_iot_list", func(call otto.FunctionCall) otto.Value { devices := g.Option.IotManager.GetCachedDeviceList() js, _ := json.Marshal(devices) devList, err := vm.ToValue(string(js)) if err != nil { return otto.FalseValue() } return devList }) vm.Set("_iot_connect", func(call otto.FunctionCall) otto.Value { return otto.NullValue() }) vm.Set("_iot_status", func(call otto.FunctionCall) otto.Value { return otto.NullValue() }) vm.Set("_iot_exec", func(call otto.FunctionCall) otto.Value { return otto.NullValue() }) vm.Set("_iot_disconnect", func(call otto.FunctionCall) otto.Value { return otto.NullValue() }) vm.Set("_iot_iconTag", func(call otto.FunctionCall) otto.Value { return otto.NullValue() }) vm.Set("_iot_ready", func(call otto.FunctionCall) otto.Value { if g.Option.IotManager == nil { return otto.FalseValue() } else { return otto.TrueValue() } }) //Wrap all the native code function into an imagelib class _, err := vm.Run(` var iot = { "scan": function(){ var devList = _iot_scan(); return JSON.parse(devList); }, "list": function(){ var devList = _iot_list(); return JSON.parse(devList); } }; iot.ready = _iot_ready; iot.connect = _iot_connect; iot.status = _iot_status; iot.exec = _iot_exec; iot.disconnect = _iot_disconnect; iot.iconTag = _iot_iconTag; `) if err != nil { log.Println("*AGI* IoT Functions Injection Error", err.Error()) } }