123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 |
- 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())
- }
- }
|