Пример #1
0
 public void Publish(string path, JSC.JSValue value, INotMsg req) {
   var arr = new JSL.Array(3);
   arr[0] = 6;
   arr[1] = path;
   arr[2] = value;
   this.Send(new SioClient.Request(0, arr, req));
 }
Пример #2
0
 public void Request(string path, int mask, INotMsg req) {
   var arr = new JSL.Array(3);
   arr[0] = 4;
   arr[1] = path;
   arr[2] = mask;
   this.Send(new SioClient.Request(0, arr, req));
 }
Пример #3
0
        public void SendArr(JST.Array arr, bool rep = true)
        {
            var ms  = JsLib.Stringify(arr);
            int len = Encoding.UTF8.GetByteCount(ms);
            int st  = 1;
            int tmp = len;

            while (tmp > 0x7F)
            {
                tmp = tmp >> 7;
                st++;
            }
            var buf = new byte[len + st + 2];

            Encoding.UTF8.GetBytes(ms, 0, ms.Length, buf, st + 1);
            tmp    = len;
            buf[0] = 0;
            for (int i = st; i > 0; i--)
            {
                buf[i] = (byte)((tmp & 0x7F) | (i < st ? 0x80 : 0));
                tmp    = tmp >> 7;
            }
            buf[buf.Length - 1] = 0xFF;
            if (this._socket.Connected)
            {
                this._stream.Write(buf, 0, buf.Length);
                if (verbose && rep)
                {
                    Log.Debug("{0}.Send({1})", this.ToString(), ms);
                }
            }
        }
Пример #4
0
 public void Move(string pOld, string ppNew, string nName) {
   var arr = new JSL.Array(4);
   arr[0] = 12;
   arr[1] = pOld;
   arr[2] = ppNew;
   arr[3] = nName;
   this.Send(new SioClient.Request(-1, arr, null));
 }
Пример #5
0
        private static void ParseDir(string path)
        {
            Console.WriteLine("  {0}", path);
            string             indexFn = path + "/index.json", dirName, json;
            List <JSC.JSValue> lstN = new List <JSC.JSValue>();

            JSC.JSObject jc;
            SortedList <string, JSC.JSValue> olds = new SortedList <string, JSC.JSValue>();

            if (File.Exists(indexFn))
            {
                json = File.ReadAllText(indexFn, Encoding.UTF8);
                var jo = JSL.JSON.parse(json);
                foreach (var js in jo)
                {
                    if (js.Value["children"].ValueType == JSC.JSValueType.String && (dirName = js.Value["children"].Value as string) != null)
                    {
                        olds.Add(dirName, js.Value);
                    }
                }
            }
            foreach (var dp in Directory.EnumerateDirectories(path, "*", SearchOption.TopDirectoryOnly))
            {
                _dirs.Enqueue(dp);
                dirName = dp.Substring(path.Length + 1);
                if (olds.ContainsKey(dirName))
                {
                    lstN.Add(olds[dirName]);
                }
                else
                {
                    jc             = JSC.JSObject.CreateObject();
                    jc["name"]     = dirName;
                    jc["hint"]     = string.Empty;
                    jc["children"] = dirName;
                    lstN.Add(jc);
                }
            }
            foreach (var fn in Directory.EnumerateFiles(path, "*.xst", SearchOption.TopDirectoryOnly))
            {
                jc = Import(fn);
                if (jc != null)
                {
                    lstN.Add(jc);
                }
            }

            var arr = new JSL.Array(lstN.Count);

            for (int i = 0; i < lstN.Count; i++)
            {
                arr[i] = lstN[i];
            }
            json = JSL.JSON.stringify(arr, null, null, "");
            File.WriteAllText(indexFn, json, Encoding.UTF8);
        }
Пример #6
0
        public void ConvertJSArrayToNativeArrayTest()
        {
            var data     = new string[] { "1", "2", "3", "4" };
            var srcArray = new NiL.JS.BaseLibrary.Array(data);

            object res = ConvertJStoObj(srcArray, typeof(double[]), true);

            Assert.IsInstanceOfType(res, typeof(double[]));
            CollectionAssert.AreEqual(data.Select(double.Parse).ToArray(), (double[])res);
        }
Пример #7
0
 internal void Create(string path, string schemaName, JSC.JSValue value, INotMsg req) {
   JSL.Array arr;
   arr = new JSL.Array(value == null?3:4);
   arr[0] = 8;
   arr[1] = path;
   arr[2] = schemaName;
   if(value != null) {
     arr[3] = value;
   }
   this.Send(new SioClient.Request(0, arr, req));
 }
Пример #8
0
        public void SendReq(int cmd, INotMsg req, params JSC.JSValue[] arg)
        {
            int mid = Interlocked.Increment(ref _msgId);
            var arr = new JSL.Array(arg.Length + 2);

            arr[0] = cmd;
            arr[1] = mid;
            for (int i = 0; i < arg.Length; i++)
            {
                arr[i + 2] = arg[i] ?? JSC.JSValue.Undefined;
            }
            this.Send(new ClRequest(mid, arr, req));
        }
Пример #9
0
        public void SendCmd(int cmd, params JSC.JSValue[] arg)
        {
            var arr = new JSL.Array(arg.Length + 1);

            arr[0] = cmd;
            for (int i = 0; i < arg.Length; i++)
            {
                arr[i + 1] = arg[i] ?? JSC.JSValue.Undefined;
            }
            if (Status == ClientState.Ready)
            {
                _socket.SendArr(arr);
            }
        }
Пример #10
0
 private void Send(INotMsg msg) {
   lock(_connEvnt) {
     if(_st == State.Ready) {
       _sio.Send(msg);
     } else if(_st == State.BadAuth) {
       var arr = new JSL.Array(2);
       arr[0] = url.ToString();
       arr[1] = "Bad username or password";
       msg.Response(null, false, arr);
       DWorkspace.This.AddMsg(msg);
     } else {
       _connEvnt.Add(new WaitConnect(msg, this));
     }
   }
 }
Пример #11
0
        //private System.Collections.Concurrent.ConcurrentQueue<Tuple<byte[], byte[]>> _inBuf;

        public MsGUdp(MQTT_SNPl pl)
        {
            _pl       = pl;
            _scanBusy = 0;
            //_inBuf = new System.Collections.Concurrent.ConcurrentQueue<Tuple<byte[], byte[]>>();
            _udpT = Topic.root.Get("/$YS/MQTT-SN/udp");

            if (!_udpT.CheckAttribute(Topic.Attribute.Required) || _udpT.GetState().ValueType != JSC.JSValueType.Boolean)
            {
                _udpT.SetAttribute(Topic.Attribute.Required | Topic.Attribute.Config);
                var act = new JSL.Array(1);
                var r_a = JSC.JSObject.CreateObject();
                r_a["name"] = "MQTT_SN.RefreshNIC";
                r_a["text"] = "Refresh";
                act[0]      = r_a;
                _udpT.SetField("Action", act);
                _udpT.SetState(true);
            }
            else if (!(bool)_udpT.GetState())
            {
                return; // udp disabled
            }
            _scanBusy = 1;
            ScanNIC(false);

            try {
                _udp = new UdpClient(1883);
                _udp.EnableBroadcast = true;
                _udp.BeginReceive(new AsyncCallback(ReceiveCallback), null);
                _advTick = new Timer(SendAdv, null, 4500, 900000);
                Topic t;
                if (Topic.root.Exist("/$YS/MQTT-SN/radius", out t) && t.GetState().IsNumber)
                {
                    _gwRadius = (byte)(int)t.GetState();
                    if (_gwRadius < 1 || _gwRadius > 3)
                    {
                        _gwRadius = 0;
                    }
                }
                else
                {
                    _gwRadius = 1;
                }
            }
            catch (Exception ex) {
                Log.Error("MsGUdp.ctor() {0}", ex.Message);
            }
        }
Пример #12
0
        public static void Init(MQTT_SNPl pl)
        {
            _pl = pl;
            ThreadPool.RegisterWaitForSingleObject(_startScan, ScanSerialPorts, null, 289012, false);
            _portsTopic = Topic.root.Get("/$YS/MQTT-SN/ports");
            if (!_portsTopic.CheckAttribute(Topic.Attribute.Required) || _portsTopic.GetState().ValueType != JSC.JSValueType.Boolean)
            {
                var act = new JSL.Array(1);
                var r_a = JSC.JSObject.CreateObject();
                r_a["name"] = "MQTT_SN.RefreshPorts";
                r_a["text"] = "Refresh";
                act[0]      = r_a;
                _portsTopic.SetField("Action", act);
                _portsTopic.SetState(true);
                _portsTopic.SetAttribute(Topic.Attribute.Required | Topic.Attribute.Config);
                _scanBusy = 1;
            }
            _portValuesSR = _portsTopic.Subscribe(SubRec.SubMask.Chldren | SubRec.SubMask.Value, PortValuesChanged);

            _startScan.Set();
        }
Пример #13
0
 protected void Emit(params object[] args) {
   if(args==null || args.Length==0){
     return;
   }
   var r=new JSL.Array(args.Length);
   for(int i=0; i<args.Length; i++) {
     r[i]=JSC.JSValue.Marshal(args[i]);
   }
   string msg=JSL.JSON.stringify(r, null, null);
   this.Send("42"+msg);
   X13.Log.Debug("{0}\n  EMIT : {1}",this.ToString(), msg);
 }
Пример #14
0
        public override JSObject Invoke(JSObject thisOverride, Arguments argsObj)
        {
            bool bynew = false;
            if (thisOverride != null)
                bynew = thisOverride.oValue == typeof(Expressions.New) as object;
            try
            {
                if (!bynew && proxy.hostedType == typeof(Date))
                    return new Date().ToString();
                object obj;
                if (proxy.hostedType == typeof(NiL.JS.BaseLibrary.Array))
                {
                    if (argsObj == null)
                        obj = new NiL.JS.BaseLibrary.Array();
                    else switch (argsObj.length)
                        {
                            case 0:
                                obj = new NiL.JS.BaseLibrary.Array();
                                break;
                            case 1:
                                {
                                    switch (argsObj.a0.valueType)
                                    {
                                        case JSObjectType.Int:
                                            obj = new NiL.JS.BaseLibrary.Array(argsObj.a0.iValue);
                                            break;
                                        case JSObjectType.Double:
                                            obj = new NiL.JS.BaseLibrary.Array(argsObj.a0.dValue);
                                            break;
                                        default:
                                            obj = new NiL.JS.BaseLibrary.Array(argsObj);
                                            break;
                                    }
                                    break;
                                }
                            default:
                                obj = new NiL.JS.BaseLibrary.Array(argsObj);
                                break;
                        }
                }
                else
                {
                    if ((argsObj == null || argsObj.length == 0)
#if PORTABLE
 && proxy.hostedType.GetTypeInfo().IsValueType)
#else
 && proxy.hostedType.IsValueType)
#endif
                        obj = Activator.CreateInstance(proxy.hostedType);
                    else
                    {
                        object[] args = null;
                        MethodProxy constructor = findConstructor(argsObj, ref args);
                        if (constructor == null)
                            throw new JSException((new TypeError(proxy.hostedType.Name + " can't be created.")));
                        obj = constructor.InvokeImpl(null, args, argsObj == null ? constructor.parameters.Length != 0 ? new Arguments() : null : argsObj);
                    }
                }
                JSObject res = null;
                if (bynew)
                {
                    // Здесь нельзя возвращать контейнер с ValueType < Object, иначе из New выйдет служебный экземпляр NewMarker
                    res = obj as JSObject;
                    if (res != null)
                    {
                        // Для Number, Boolean и String
                        if (res.valueType < JSObjectType.Object)
                        {
                            res = new ObjectContainer(obj, res.__proto__);
                        }
                        else if (res.oValue is JSObject)
                        {
                            res.oValue = res;
                            // На той стороне понять, по new или нет вызван конструктор не удастся,
                            // поэтому по соглашению такие типы себя настраивают так, как будто они по new,
                            // а в oValue пишут экземпляр аргумента на тот случай, если вызван конструктор типа как функция
                            // с передачей в качестве аргумента существующего экземпляра
                        }
                    }
                    else
                    {
                        res = new ObjectContainer(obj, TypeProxy.GetPrototype(proxy.hostedType));
                        //if (res.fields == null)
                        //    res.fields = createFields();
                        // из-за того, что GetMember сам дотягивается до объекта, можно попробовать убрать создание филдов
                        res.attributes |= proxy.hostedType.IsDefined(typeof(ImmutableAttribute), false) ? JSObjectAttributesInternal.Immutable : JSObjectAttributesInternal.None;
                        if (obj is Date)
                            res.valueType = JSObjectType.Date;
                    }
                }
                else
                {
                    if (proxy.hostedType == typeof(JSObject))
                    {
                        if (((obj as JSObject).oValue is JSObject) && ((obj as JSObject).oValue as JSObject).valueType >= JSObjectType.Object)
                            return (obj as JSObject).oValue as JSObject;
                    }
                    res = obj as JSObject ?? new ObjectContainer(obj)
                    {
                        attributes = JSObjectAttributesInternal.SystemObject | (proxy.hostedType.IsDefined(typeof(ImmutableAttribute), false) ? JSObjectAttributesInternal.Immutable : JSObjectAttributesInternal.None)
                    };
                }
                return res;
            }
            catch (TargetInvocationException e)
            {
#if !PORTABLE
                if (System.Diagnostics.Debugger.IsAttached)
                    System.Diagnostics.Debugger.Log(10, "Exception", e.Message);
#endif
                throw e.InnerException;
            }
        }
Пример #15
0
 public void Delete(string path) {
   var arr = new JSL.Array(2);
   arr[0] = 10;
   arr[1] = path;
   this.Send(new SioClient.Request(-1, arr, null));
 }
Пример #16
0
        private JSC.JSValue Bs2Js(BsonValue val)
        {
            if (val == null)
            {
                return(JSC.JSValue.Undefined);
            }
            switch (val.Type) //-V3002
            {
            case BsonType.ObjectId: {
                var p = Id2Topic(val.AsObjectId);
                if (p != null)
                {
                    return(new JSL.String("¤TR" + p));
                }
                else
                {
                    throw new ArgumentException("Unknown ObjectId: " + val.AsObjectId.ToString());
                }
            }

            case BsonType.Array: {
                var arr = val.AsArray;
                var r   = new JSL.Array(arr.Count);
                for (int i = 0; i < arr.Count; i++)
                {
                    if (!arr[i].IsNull)
                    {
                        r[i] = Bs2Js(arr[i]);
                    }
                }
                return(r);
            }

            case BsonType.Boolean:
                return(new JSL.Boolean(val.AsBoolean));

            case BsonType.DateTime:
                return(JSC.JSValue.Marshal(val.AsDateTime.ToLocalTime()));

            case BsonType.Binary:
                return(new ByteArray(val.AsBinary));

            case BsonType.Document: {
                var r = JSC.JSObject.CreateObject();
                var o = val.AsDocument;
                foreach (var i in o)
                {
                    r[UnescapFieldName(i.Key)] = Bs2Js(i.Value);
                }
                return(r);
            }

            case BsonType.Double: {
                return(new JSL.Number(val.AsDouble));
            }

            case BsonType.Int32:
                return(new JSL.Number(val.AsInt32));

            case BsonType.Int64:
                return(new JSL.Number(val.AsInt64));

            case BsonType.Null:
                return(JSC.JSValue.Null);

            case BsonType.String:
                return(new JSL.String(val.AsString));
            }
            throw new NotImplementedException("Bs2Js(" + val.Type.ToString() + ")");
        }
Пример #17
0
 public Request(long msgId, JSL.Array jo, INotMsg req) {
   this.msgId = msgId;
   this.data = jo;
   this._req = req;
 }
Пример #18
0
 private EventArguments(SIO_Connection conn, long msgId, JSL.Array req) {
   this._conn=conn;
   this._msgId=msgId;
   this._request=req;
   this.Count=req.Count();
 }
Пример #19
0
 public ClRequest(int msgId, JSL.Array jo, INotMsg req)
 {
     this.msgId = msgId;
     this.data  = jo;
     this._req  = req;
 }
Пример #20
0
        public MqSite(MQTTPl pl, MqClient client, Topic owner, Uri uUri)
        {
            this.Client = client;
            this.Owner  = owner;
            this._pl    = pl;
            this._uri   = uUri;

            _subEn      = ReadFlag("MQTT.subscribe", true);
            _pubEn      = ReadFlag("MQTT.publish", true);
            _retainedEn = ReadFlag("MQTT.retained", false);

            remotePath = _uri.PathAndQuery + _uri.Fragment;
            var sl = remotePath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);

            remotePrefix = string.Empty;
            _mask        = SubRec.SubMask.Value;
            for (int i = 0; i < sl.Length; i++)
            {
                if (sl[i] == "+")
                {
                    _mask |= SubRec.SubMask.Chldren;
                    break;
                }
                if (sl[i] == "#")
                {
                    _mask |= SubRec.SubMask.All;
                    break;
                }
                remotePrefix = remotePrefix + "/" + sl[i];
            }
            Client.Sites.Add(this);
            if (Client.status == MqClient.Status.Connected)
            {
                this.Connected();
            }
            var act = this.Owner.GetField("Action");

            JSC.JSValue txt;
            if (act == null || !act.Any(z => z.Value.ValueType == JSC.JSValueType.Object && (txt = z.Value["name"]).ValueType == JSC.JSValueType.String && (txt.Value as string) == "MQTT.Reconnect"))
            {
                int       i;
                JSL.Array act_n;
                if (act == null)
                {
                    act_n = new JSL.Array(1);
                    i     = 0;
                }
                else
                {
                    int j = act.Count();
                    act_n = new JSL.Array(j + 1);
                    for (i = 0; i < j; i++)
                    {
                        act_n[i] = act[i.ToString()];
                    }
                }
                var r_a = JSC.JSObject.CreateObject();
                r_a["name"] = "MQTT.Reconnect";
                r_a["text"] = "Reconnect MQTT connection";
                act_n[i]    = r_a;
                this.Owner.SetField("Action", act_n);
            }
        }
Пример #21
0
 public void Response(params object[] args) {
   _response=new JSL.Array(args.Length);
   for(int i=0; i<args.Length; i++) {
     _response[i] = JSC.JSValue.Marshal(args[i]);
   }
   _error=false;
 }
Пример #22
0
 public EsMessage(EsSocket conn, JST.Array req)
 {
     this._conn    = conn;
     this._request = req;
     this.Count    = req.Count();
 }