public void PubSub_Should_NotCrash_IfNo_Thread_Sleep()
        {
            using (var pub = new PublisherSocket())
            {
                using (var sub = new SubscriberSocket())
                {
                    int freePort = TcpPortFree();
                    pub.Bind("tcp://127.0.0.1:" + freePort);
                    sub.Connect("tcp://127.0.0.1:" + freePort);

                    sub.Subscribe("*");

                    Stopwatch sw = Stopwatch.StartNew();
                    {
                        for (int i = 0; i < 50; i++)
                        {
                            pub.SendFrame("*");                             // Ping.

                            Console.Write("*");
                            string topic;
                            var    gotTopic = sub.TryReceiveFrameString(TimeSpan.FromMilliseconds(100), out topic);
                            string ping;
                            var    gotPing = sub.TryReceiveFrameString(TimeSpan.FromMilliseconds(100), out ping);
                            if (gotTopic == true)
                            {
                                Console.Write("\n");
                                break;
                            }
                        }
                    }
                    Console.WriteLine("Connected in {0} ms.", sw.ElapsedMilliseconds);
                }
            }
        }
Example #2
0
    // Update is called once per frame
    private void Update()
    {
        _timeSinceLastPub += Time.deltaTime;
        if (_timeSinceLastPub >= 1 / ZmqPubRate)
        {
            var pubMsg   = new Msg();
            var position = _hip.position;
            var velocity = _hip.velocity;
            var msgData  = new MsgData
            {
                Position = new[] { position.x, position.y, position.z },
                Velocity = new[] { velocity.x, velocity.y, velocity.z },
                ID       = id
            };
            var pubMsgPayload = Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(msgData));
            pubMsg.InitGC(pubMsgPayload, pubMsgPayload.Length);
            _pub.Send(ref pubMsg, false);
            _timeSinceLastPub = 0;
        }

        //string recvStr;
        if (_sub.TryReceiveFrameString(out recvStr))
        {
            Debug.Log(recvStr);
            var recvJson = JsonConvert.DeserializeObject <Dictionary <string, string> >(recvStr);
            //if (int.Parse(recvJson["ID"]) != id) return;
            var forceX = float.Parse(recvJson["force_x"]);
            var forceY = float.Parse(recvJson["force_y"]);
            var forceZ = float.Parse(recvJson["force_z"]);
            _hip.AddRelativeForce(forceX, forceY, -(forceZ * 2));    //negative z because conversion from right-hand to left-hand coordinates
        }
    }
Example #3
0
        /// <summary>
        ///     进入系统侦听
        /// </summary>
        public static void RunMonitor()
        {
            var timeout = new TimeSpan(0, 0, 1);

            try
            {
                StationProgram.WriteLine("System Monitor Runing...");
                var subscriber = new SubscriberSocket();
                subscriber.Options.Identity          = StationProgram.Config.StationName.ToAsciiBytes();
                subscriber.Options.ReconnectInterval = new TimeSpan(0, 0, 0, 0, 200);
                subscriber.Connect(StationProgram.ZeroMonitorAddress);
                subscriber.Subscribe("");

                while (StationProgram.State == StationState.Run)
                {
                    if (!subscriber.TryReceiveFrameString(timeout, out var result))
                    {
                        continue;
                    }
                    OnMessagePush(result);
                }
            }
            catch (Exception e)
            {
                StationProgram.WriteLine(e.Message);
                LogRecorder.Exception(e);
            }
            if (StationProgram.State == StationState.Run)
            {
                Task.Factory.StartNew(RunMonitor);
            }
        }
Example #4
0
    private void nameGetterWork()
    {
        AsyncIO.ForceDotNet.Force();
        using (var subSocket = new SubscriberSocket())
        {
            subSocket.Options.ReceiveHighWatermark = 1;
            subSocket.Connect(_serverIP);
            subSocket.Subscribe("");

            while (!_nameGetterCancelled)
            {
                if (!subSocket.TryReceiveFrameString(out _newJsonString))
                {
                    continue;
                }

                if (!_newJsonString.Equals(_jsonString))
                {
                    _jsonString = _newJsonString;
                    _messageDelegate(_jsonString);
                }
            }
            subSocket.Close();
        }
        NetMQConfig.Cleanup();
    }
Example #5
0
 void Run()
 {
     while (_running)
     {
         try
         {
             string topic;
             if (_subSocket.TryReceiveFrameString(TimeSpan.FromMilliseconds(100), out topic))
             {
                 var eventName       = _subSocket.ReceiveFrameString();
                 var messageReceived = _subSocket.ReceiveFrameBytes();
                 try
                 {
                     MessaggioRicevuto(eventName, messageReceived);
                 }
                 catch
                 {
                 }
             }
         }
         catch (Exception ex)
         {
             if (_running)
             {
                 Console.WriteLine(this.GetType().Name + " : " + ex.Message);
             }
         }
     }
 }
Example #6
0
    // Update is called once per frame
    private void Update()
    {
        _timeSinceLastPub += Time.deltaTime;
        if (_timeSinceLastPub >= 1 / ZmqPubRate)
        {
            var pubMsg   = new Msg();
            var position = _hip.position;
            var velocity = _hip.velocity;
            var msgData  = new MsgData
            {
                Position = new[] { position.x, position.y, position.z },
                Velocity = new[] { velocity.x, velocity.y, velocity.z },
                ID       = id
            };
            var pubMsgPayload = Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(msgData));
            pubMsg.InitGC(pubMsgPayload, pubMsgPayload.Length);
            _pub.Send(ref pubMsg, false);
            _timeSinceLastPub = 0;
        }

        string recvStr;

        if (_sub.TryReceiveFrameString(out recvStr))
        {
            Debug.Log(recvStr);
        }
    }
    private void ListenerWork(string ip, string port)
    {
        AsyncIO.ForceDotNet.Force();
        using (var subSocket = new SubscriberSocket())
        {
            subSocket.Options.ReceiveHighWatermark = 1000;
            subSocket.Connect($"tcp://{ip}:{port}");
            subSocket.Subscribe("");
            Debug.Log($"Proctor has successfully connected to client1 via tcp://{ip}:{port}");
            while (!_listenerCancelled)
            {
                string frameString;

                if (!subSocket.TryReceiveFrameString(out frameString))
                {
                    continue;
                }
                var value = Int32.Parse(frameString);
                Debug.Log($"value is {value}");
                _messageQueue.Enqueue(frameString);
            }
            subSocket.Close();
        }
        NetMQConfig.Cleanup();
    }
    /**
     * Performs actual task of connecting to server and attempting to retreive JSON information about connections
     */
    private void nameGetterWork()
    {
        AsyncIO.ForceDotNet.Force();

        //Subscriber socket, connect to server and listen
        using (var subSocket = new SubscriberSocket())
        {
            subSocket.Options.ReceiveHighWatermark = 1;
            subSocket.Connect(_serverIP);
            subSocket.Subscribe("");

            //While still running
            while (!_nameGetterCancelled)
            {
                //Attempt to grab a string from server
                if (!subSocket.TryReceiveFrameString(out _newJsonString))
                {
                    continue;
                }

                //If the string is not equal to the previous string, we have an update
                if (!_newJsonString.Equals(_jsonString))
                {
                    //Assign the new string as our current string, then forward our message to the messageDelegate function
                    Debug.Log("New JSON is " + _newJsonString);
                    _jsonString = _newJsonString;
                    _messageDelegate(_jsonString);
                }
            }
            //Close socket
            subSocket.Close();
        }
        //Cleanup
        NetMQConfig.Cleanup();
    }
Example #9
0
        /// <summary>
        /// 命令轮询
        /// </summary>
        /// <returns></returns>
        private void PollTask()
        {
            StationProgram.WriteLine($"【{StationName}】poll start");
            var timeout = new TimeSpan(0, 0, 5);

            _inPoll = true;
            while (RunState == StationState.Run)
            {
                try
                {
                    if (!_socket.TryReceiveFrameString(timeout, out var title, out var more) || !more)
                    {
                        continue;
                    }
                    if (!_socket.TryReceiveFrameBytes(out var description, out more) || !more)
                    {
                        continue;
                    }
                    PublishItem item = new PublishItem
                    {
                        Title = title
                    };
                    int idx = 1;
                    while (more)
                    {
                        if (!_socket.TryReceiveFrameString(out var val, out more))
                        {
                            continue;
                        }
                        switch (description[idx++])
                        {
                        case ZeroHelper.zero_pub_sub:
                            item.SubTitle = val;
                            break;

                        case ZeroHelper.zero_pub_publisher:
                            item.Station = val;
                            break;

                        case ZeroHelper.zero_arg:
                            item.Content = val;
                            break;
                        }
                    }
                    _items.Push(item);
                }
                catch (Exception e)
                {
                    StationProgram.WriteLine($"【{StationName}】poll error{e.Message}...");
                    LogRecorder.Exception(e);
                    RunState = StationState.Failed;
                }
            }
            _inPoll = false;
            StationProgram.WriteLine($"【{StationName}】poll stop");
            _items.Save(CacheFileName);
            CloseSocket();
        }
        public void Test_Two_Subscribers()
        {
            NUnitUtils.PrintTestName();
            var sw = Stopwatch.StartNew();

            using (var pub = new PublisherSocket())
            {
                using (var sub1 = new SubscriberSocket())
                {
                    using (var sub2 = new SubscriberSocket())
                    {
                        var freePort = NUnitUtils.TcpPortFree();
                        pub.Bind("tcp://127.0.0.1:" + freePort);
                        sub1.Connect("tcp://127.0.0.1:" + freePort);
                        sub1.Subscribe("A");
                        sub2.Connect("tcp://127.0.0.1:" + freePort);
                        sub2.Subscribe("B");

                        Thread.Sleep(500);

                        var swInner = Stopwatch.StartNew();
                        {
                            pub.SendFrame("A\n"); // Ping.
                            {
                                string topic;
                                var    pass1 = sub1.TryReceiveFrameString(TimeSpan.FromMilliseconds(250), out topic);
                                if (pass1)
                                {
                                    Console.Write(topic);
                                }
                                else
                                {
                                    Assert.Fail();
                                }
                            }
                            pub.SendFrame("B\n"); // Ping.
                            {
                                string topic;
                                var    pass2 = sub2.TryReceiveFrameString(TimeSpan.FromMilliseconds(250), out topic);
                                if (pass2)
                                {
                                    Console.Write(topic);
                                }
                                else
                                {
                                    Assert.Fail();
                                }
                            }
                        }
                        Console.WriteLine("Connected in {0} ms.", swInner.ElapsedMilliseconds);
                    }
                }
            }

            NUnitUtils.PrintElapsedTime(sw.Elapsed);
        }
Example #11
0
        private void SubscribeEntry(object n)
        {
            string name = (string)n;

            using (SubscriberSocket subscriber = new SubscriberSocket())
            {
                if (!SubRM.ContainsKey(name))
                {
                    Logging.logger.Error("do not have the sub name, return");
                    return;
                }

                string endpoint = "tcp://" + SubRM[name].point.ip + ":" + SubRM[name].point.port;


                try
                {
                    subscriber.Connect(endpoint);
                }
                catch (Exception err)
                {
                    Logging.logger.Error("connect to DataSubscribe faild " + endpoint + " " + err.Message);
                    throw (err);
                }

                subscriber.Subscribe("");
                SubRM[name].subsock = subscriber;
                SubRM[name].Working = true;
                while (SubRM[name].Running)
                {
                    //string received = serverSocket.ReceiveFrameString();
                    string received = string.Empty;
                    bool   result   = subscriber.TryReceiveFrameString(out received);

                    if (result == true)
                    {
                        try
                        {
                            this.SubscriptEntry(name, received);
                        }
                        catch (Exception err)
                        {
                            Logging.logger.Error(err.Message);
                            throw (err);
                        }
                    }
                    DelayTime();
                }
                SubRM[name].Working = false;
                subscriber.Close();
            }
        }
Example #12
0
 private void monitor()
 {
     while (running)
     {
         while (!reloading)
         {
             try
             {
                 // We only listen for updates if the user has selected anything to listen to
                 if (configuration.watches != null && configuration.watches.Count > 0)
                 {
                     using (var subscriber = new SubscriberSocket())
                     {
                         subscriber.Connect("tcp://api.eddp.co:5556");
                         subscriber.Subscribe("eddp.delta.system");
                         while (running && !reloading)
                         {
                             if (subscriber.TryReceiveFrameString(new TimeSpan(0, 0, 1), out string topic))
                             {
                                 string message = subscriber.ReceiveFrameString();
                                 Logging.Debug("Message is " + message);
                                 JObject json = JObject.Parse(message);
                                 if (topic == "eddp.delta.system")
                                 {
                                     handleSystemDelta(json);
                                 }
                             }
                         }
                     }
                 }
             }
             catch (SocketException ex)
             {
                 Logging.Warn("EDDP Monitor connection exception: ", ex);
             }
             catch (Exception ex)
             {
                 Logging.Error("EDDP Monitor exception: " + ex.Message, ex);
             }
             finally
             {
                 Thread.Sleep(1000);
             }
         }
         Thread.Sleep(1000);
         reloading = false;
     }
 }
Example #13
0
        public void ThreadB()
        {
            try
            {
                using (var subSocket = new SubscriberSocket())
                {
                    subSocket.Options.ReceiveHighWatermark = 1000;
                    FillIP   = ConfigurationManager.AppSettings["FillIP"];
                    FillPort = ConfigurationManager.AppSettings["FillPort"];
                    subSocket.Connect("tcp://" + FillIP + ":" + FillPort);

                    subSocket.SubscribeToAnyTopic();
                    //subSocket.Subscribe(OrderClient.MachineGuid + ":" + OrderClient.UserGuid);

                    //Console.WriteLine("Subscriber socket connecting...");
                    while (true)
                    {
                        try
                        {
                            if (ScannerBox.openedMainForm == false)
                            {
                                break;
                            }
                            string messageReceived;
                            if (subSocket.TryReceiveFrameString(out messageReceived))
                            {
                                //string messageReceived = subSocket.ReceiveFrameString();
                                Console.WriteLine("messageReceived " + messageReceived);
                                string[] arr = messageReceived.Split(':');
                                //machineID + ":" + userID+":"+OrderNo+":"+ExchangeOrderId+":"+status+":"+status_msg+":"+other_msg
                                //[3d0e9dfa-5c5d-85a2-1833-e1e1cf52c13e:b5479e69-9bab-1023-068f-f8bafaafb7de:35:1470420475:0:0:0
                                //machineID + ":" + userID + ":" + OrderNo + ":" + OrderStatus + ":" + ExchangeOrderId + ":" + status + ":" + status_msg + ":" + other_msg;
                                dictFillDetails[arr[2]] = arr[3] + ":" + arr[4] + ":" + arr[5] + ":" + arr[6] + ":" + arr[7];
                            }
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("fillsubscriber : " + e.Message);
                        }
                        System.Threading.Thread.Sleep(100);
                    }
                }
            }
            finally
            {
                NetMQConfig.Cleanup();
            }
        }
Example #14
0
    // private void FixedUpdate()
    // {
    // Debug.Log(_joint.currentForce);
    // }

    // Update is called once per frame
    private void Update()
    {
        _timeSinceLastPub += Time.deltaTime;
        if (_timeSinceLastPub >= 1 / ZmqPubRate)
        {
            var pubMsg = new Msg();
            //var position = _hip.transform.position;
            //var position = _hip.position;
            //var velocity = _hip.velocity;
            var force = _joint.currentForce;
            //var rotation = _hip.rotation;
            //var angularvelocity = _hip.angularVelocity;
            var msgData = new MsgDatab
            {
                //Position = new[] { position.x, position.y, position.z },
                //Velocity = new[] { velocity.x, velocity.y, velocity.z },
                Force = new[] { force.x, force.y, force.z },
                //Rotation = new[] { rotation.eulerAngles.x, rotation.eulerAngles.y, rotation.eulerAngles.z },
                //Angularvelocity = new[] { angularvelocity.x, angularvelocity.y, angularvelocity.z },
                ID = id
            };
            var pubMsgPayload = Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(msgData));
            pubMsg.InitGC(pubMsgPayload, pubMsgPayload.Length);
            _pub.Send(ref pubMsg, false);
            _timeSinceLastPub = 0;
        }

        string recvStr;

        if (_sub.TryReceiveFrameString(out recvStr))
        {
            var recvJson = JsonConvert.DeserializeObject <Dictionary <string, string> >(recvStr);
            if (int.Parse(recvJson["ID"]) != id)
            {
                return;
            }
            var forceX = float.Parse(recvJson["force_x"]);
            var forceY = float.Parse(recvJson["force_y"]);
            var forceZ = float.Parse(recvJson["force_z"]);
            _hip.AddRelativeForce(forceX, forceY, -forceZ);    //negative z because conversion from right-hand to left-hand coordinates
        }
    }
Example #15
0
    // Client thread which does not block Update()
    void NetMQClient()
    {
        AsyncIO.ForceDotNet.Force();
        NetMQConfig.ManualTerminationTakeOver();
        NetMQConfig.ContextCreate(true);

        //string msg;
        var timeout = new System.TimeSpan(0, 0, 1); //1sec

        Debug.Log("Connect to the server.");

        var subSocket = new SubscriberSocket();

        subSocket.Options.ReceiveHighWatermark = 0;
        subSocket.Connect("tcp://192.168.1.122:55555");
        subSocket.Subscribe("");

        bool is_connected = true;

        while (is_connected && stop_thread_ == false)
        {
            is_connected = subSocket.TryReceiveFrameString(timeout, out msg);

            //Debug.Log(msg);
            //byte[] decodedBytes = System.Convert.FromBase64String(msg);
            //Debug.Log(decodedBytes);
            //string decodedText = Encoding.UTF8.GetString(decodedBytes);
            //Debug.Log(decodedText);
            //Mat buffer = new Mat(decodedText, ImreadModes.Unchanged);
            //image = Cv2.ImDecode(buffer, ImreadModes.Unchanged);
            //using (var window = new Window("window", image: src, flags: WindowMode.AutoSize)) {
            //Cv2.WaitKey();
            //}
            //Debug.Log(src);
        }

        subSocket.Close();
        Debug.Log("ContextTerminate.");
        NetMQConfig.ContextTerminate();
        NetMQConfig.Cleanup();
    }
Example #16
0
        public void ThreadB()
        {
            try
            {
                //string topic = args[0] == "All" ? "" : args[0];
                //string topic = "";
                //Console.WriteLine("Subscriber started for Topic : {0}", _topic);

                using (var subSocket = new SubscriberSocket())
                {
                    subSocket.Options.ReceiveHighWatermark = 0;
                    subSocket.Connect("tcp://" + publisherIP + ":" + publisherPort);
                    subSocket.SubscribeToAnyTopic();

                    //Console.WriteLine("Subscriber socket connecting...");
                    while (true)
                    {
                        try
                        {
                            string messageReceived;

                            System.Threading.Thread.Sleep(5);

                            if (subSocket.TryReceiveFrameString(out messageReceived))
                            {
                                //Writing the messages received in a log file
                                double millis = (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds;

                                File.AppendAllText("D:/FeedLogNew.txt", messageReceived + "," + (millis / 1000) + "\n");
                            }
                        }
                        catch (Exception e)
                        {
                        }
                    }
                }
            }
            catch (Exception e)
            {
            }
        }
Example #17
0
 private void ListenerWork()
 {
     AsyncIO.ForceDotNet.Force();
     using (var subSocket = new SubscriberSocket())
     {
         subSocket.Options.ReceiveHighWatermark = 1000;
         subSocket.Connect("tcp://localhost:12345");
         subSocket.Subscribe("");
         while (!_listenerCancelled)
         {
             string frameString;
             if (!subSocket.TryReceiveFrameString(out frameString))
             {
                 continue;
             }
             _messageQueue.Enqueue(frameString);
         }
         subSocket.Close();
     }
     NetMQConfig.Cleanup();
 }
Example #18
0
        //!
        //! client function, listening for messages in receiveMessageQueue from server (executed in separate thread)
        //!
        public void listener()
        {
            AsyncIO.ForceDotNet.Force();
            using (var receiver = new SubscriberSocket())
            {
                receiver.Subscribe("client");
                receiver.Subscribe("ncam");
                receiver.Subscribe("record");

                receiver.Connect("tcp://" + VPETSettings.Instance.serverIP + ":5556");

                lastReceiveTime = currentTimeTime;

                Debug.Log("Listener connected: " + "tcp://" + VPETSettings.Instance.serverIP + ":5556");
                string input;
                while (isRunning)
                {
                    if (receiver.TryReceiveFrameString(out input))
                    {
                        this.receiveMessageQueue.Add(input.Substring(7));
                        lastReceiveTime = currentTimeTime;
                    }
                    else
                    {
                        listenerRestartCount = Mathf.Min(int.MaxValue, listenerRestartCount + 1);
                        // VPETSettings.Instance.msg = string.Format("Exception in Listener: {0}", listenerRestartCount);
                        if (currentTimeTime - lastReceiveTime > receiveTimeout)
                        {
                            // break;
                        }
                    }
                }

                receiver.Disconnect("tcp://" + VPETSettings.Instance.serverIP + ":5556");
                receiver.Close();
                receiver.Dispose();
            }
            //NetMQConfig.Cleanup();
        }
Example #19
0
    void Update()
    {
        received   = false;
        calibrated = true;
        string dataString = "null received";


        //Tries to receive a string published from ZeroMQ Publisher
        if (subscriberSocket.TryReceiveFrameString(TimeSpan.FromMilliseconds(5), out dataString))
        {
            //Debug.Log("RCV_ : " + dataString);
            received = true;
        }
        else
        {
            //Debug.LogError("RCV_Error: " + dataString);
        }

        //If received a string only then edit the string and change the rotation of the CubeSat
        if (received)
        {
            // received string is  like  "topic accx accy accz gyrox gyroy gyroz"
            char     splitChar  = ' ';
            string[] dataRaw    = dataString.Split(splitChar);
            string   identifier = dataRaw[1].Substring(0, (dataRaw[1]).Length < 9 ? dataRaw[1].Length : 9);

            if (identifier.Equals("calibrate"))
            {
                calibrated         = false;
                calibrationCounter = 0;
                //reseting angles
                curr_angle_x = 0;
                curr_angle_y = 0;
                curr_angle_z = 0;

                //reseting calibrating values
                calibratedX = 0;
                calibratedY = 0;
                calibratedZ = 0;

                return;
            }

            // normalized accelerometer values
            //float ax = float.Parse(dataRaw[1]) * acc_normalizer_factor;
            //float ay = float.Parse(dataRaw[2]) * acc_normalizer_factor;
            //float az = float.Parse(dataRaw[3]) * acc_normalizer_factor;

            // normalized gyrocope values
            float gx = float.Parse(dataRaw[1]) * gyro_normalizer_factor;
            float gy = float.Parse(dataRaw[2]) * gyro_normalizer_factor;
            float gz = float.Parse(dataRaw[3]) * gyro_normalizer_factor;

            //Debug.Log("The data raw of 1 iz: " + gx);

            // prevent
            //if (Mathf.Abs(ax) - 1 < 0) ax = 0;
            //if (Mathf.Abs(ay) - 1 < 0) ay = 0;
            //if (Mathf.Abs(az) - 1 < 0) az = 0;


            //curr_offset_x += ax;
            //curr_offset_y += ay;
            //curr_offset_z += 0; // The IMU module have value of z axis of 16600 caused by gravity

            gyroX.text = string.Format("Gyroscope X: {0:N4}", gx);
            gyroY.text = string.Format("Gyroscope Y: {0:N4}", gy);
            gyroZ.text = string.Format("Gyroscope Z: {0:N4}", gz);

            status.text = (calibrated) ? "Status: Running" : "Status: Calibrating";
            count.text  = string.Format("Counter: {0:N0}", counter);

            // prevent little noise effect
            //if (Mathf.Abs(gx) < 0.025f) gx = 0f;
            //if (Mathf.Abs(gy) < 0.025f) gy = 0f;
            //if (Mathf.Abs(gz) < 0.025f) gz = 0f;

            if (calibrated)
            {
                counter++;
                curr_angle_x = gx;
                curr_angle_y = gy;
                curr_angle_z = gz;

                /*curr_angle_x += gx-avgGx;
                *  curr_angle_y += gy-avgGy;
                *  curr_angle_z += gz-avgGz;*/

                //if (enableTranslation) target.transform.position = new Vector3(curr_offset_x, curr_offset_y, curr_offset_z);
                if (enableRotation)
                {
                    target.transform.rotation = Quaternion.Euler(curr_angle_x * factor, curr_angle_y * factor, curr_angle_z * factor);
                }

                rotX.text = string.Format("Rotation X: {0:N4}", curr_angle_x * factor);
                rotY.text = string.Format("Rotation Y: {0:N4}", curr_angle_y * factor);
                rotZ.text = string.Format("Rotation Z: {0:N4}", curr_angle_z * factor);
            }
            else
            {
                calibrationCounter++;
                calibratedX += gx;
                calibratedY += gy;
                calibratedZ += gz;
                if (calibrationCounter == 40)
                {
                    calibrated = true;
                    avgGx      = calibratedX / (float)40;
                    avgGy      = calibratedY / (float)40;
                    avgGz      = calibratedZ / (float)40;
                }
            }
        }
    }
Example #20
0
        public void ThreadB()
        {
            try
            {
                //string topic = args[0] == "All" ? "" : args[0];
                //string topic = "";
                //Console.WriteLine("Subscriber started for Topic : {0}", _topic);

                using (var subSocket = new SubscriberSocket())
                {
                    subSocket.Options.ReceiveHighWatermark = 0;
                    publisherIP   = ConfigurationManager.AppSettings["publisherIP"];
                    publisherPort = ConfigurationManager.AppSettings["publisherPort"];
                    subSocket.Connect("tcp://" + publisherIP + ":" + publisherPort);
                    //subSocket.SubscribeToAnyTopic();
                    if (parentSD.dictFilters.Count == 0)
                    {
                        subSocket.SubscribeToAnyTopic();
                    }
                    else
                    {
                        foreach (var filters in parentSD.dictFilters)
                        {
                            //Console.WriteLine("Subscribing Socket for Symbol : " + filters.Key);
                            subSocket.Subscribe(filters.Key);
                        }
                    }

                    //Console.WriteLine("Subscriber socket connecting...");
                    while (true)
                    {
                        try
                        {
                            if (ScannerBox.openedMainForm == false)
                            {
                                break;
                            }
                            string messageReceived;

                            System.Threading.Thread.Sleep(5);

                            if (subSocket.TryReceiveFrameString(out messageReceived))
                            {
                                //Writing the messages received in a log file
                                long   millis      = (long)((DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds);
                                string feedMessage = messageReceived + "," + millis;
                                //File.AppendAllText("D:/FeedLog.txt", messageReceived + "," + millis + "\n");

                                //string messageReceived = subSocket.ReceiveFrameString();
                                string[] origMessageSplit = messageReceived.Split(';');
                                string[] arr = origMessageSplit[0].Split('|');

                                //string tokenno, ltp, ltq, bidprice, bidsize, askprice, asksize, feedtime
                                //token,ltp,ltq,b_amt,b_qty,a_amt,a_qty,lft,ltt,totalVol,open,high,low
                                string tokenno  = arr[0];
                                double ltp      = Convert.ToDouble(arr[1]) / 100.0;
                                string ltq      = arr[2];
                                double bidprice = Convert.ToDouble(arr[3]) / 100.0;
                                string bidsize  = arr[4];
                                double askprice = Convert.ToDouble(arr[5]) / 100.0;
                                string asksize  = arr[6];

                                DateTime dt1      = epoch.AddMilliseconds(Convert.ToInt64(arr[7]));
                                string   feedtime = dt1.ToString("dd/MM/yyyy HH:mm:ss");

                                string ltt       = arr[8];
                                string tradetime = "";
                                if (ltt.Equals("0") == false)
                                {
                                    DateTime dt2 = epoch.AddMilliseconds(Convert.ToInt64(ltt));
                                    tradetime = dt2.ToString("dd/MM/yyyy HH:mm:ss.ff");
                                }

                                string volume = arr[9];
                                string open   = "0";
                                string high   = "0";
                                string low    = "0";

                                if (arr.Length >= 12)
                                {
                                    open = arr[10];
                                    high = arr[11];
                                    low  = arr[12];
                                }

                                //DateTime dt = DateTime.Now;
                                //string feedtime = dt.ToString("HH:mm:ss");

                                Feed feed = new Feed(tokenno, feedtime, Convert.ToString(ltp), ltq, bidsize, Convert.ToString(bidprice), Convert.ToString(askprice), asksize, tradetime, volume, open, high, low);

                                ScannerBox.qfeed.Enqueue(feed);
                                millis      = (long)((DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds);
                                feedMessage = feedMessage + "," + millis;
                                ScannerBox.qOrgfeed.Enqueue(feedMessage);
                                //Timestamp2 and Log into file.
                                string key = feed.tokenno;
                                dictFeedDetails[key] = feed;

                                if (dictTrades.ContainsKey(tokenno) == false)
                                {
                                    dictTrades[tokenno] = new Dictionary <string, TradeDetails>();
                                }

                                Dictionary <string, TradeDetails> dictTradeDetails = dictTrades[tokenno];
                                if (dictTradeDetails.ContainsKey(ltt) == false)
                                {
                                    dictTradeDetails[ltt] = new TradeDetails(tradetime, ltp, ltq);
                                }

                                if (origMessageSplit.Length > 1)
                                {
                                    dictFeedLevels[key] = origMessageSplit[1];
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e.Message);
                        }
                    }
                }
            }
            finally
            {
                NetMQConfig.Cleanup();
            }
        }
    private void ListenerWork()
    {
        Debug.Log("Setting up subscriber sock");
        AsyncIO.ForceDotNet.Force();
        using (var subSocket = new SubscriberSocket())
        {
            // set limit on how many messages in memory
            subSocket.Options.ReceiveHighWatermark = 1000;
            // socket connection
            // subSocket.Connect("tcp://localhost:5572");
            subSocket.Connect("tcp://" + sub_to_ip + ":" + sub_to_port);
            // subscribe to topics; "" == all topics
            subSocket.Subscribe("");
            Debug.Log("sub socket initiliased");

            string topic;
            //string frame;
            string timestamp;
            //string blend_shapes;
            //string head_pose;
            string facsvatar_json;
            while (!_listenerCancelled)
            {
                //string frameString;
                // wait for full message
                //if (!subSocket.TryReceiveFrameString(out frameString)) continue;
                //Debug.Log(frameString);
                //_messageQueue.Enqueue(frameString);

                List <string> msg_list = new List <string>();
                if (!subSocket.TryReceiveFrameString(out topic))
                {
                    continue;
                }
                //if (!subSocket.TryReceiveFrameString(out frame)) continue;
                if (!subSocket.TryReceiveFrameString(out timestamp))
                {
                    continue;
                }
                //if (!subSocket.TryReceiveFrameString(out blend_shapes)) continue;
                //if (!subSocket.TryReceiveFrameString(out head_pose)) continue;
                if (!subSocket.TryReceiveFrameString(out facsvatar_json))
                {
                    continue;
                }

                //Debug.Log("Received messages:");
                //Debug.Log(frame);
                //Debug.Log(timestamp);
                //Debug.Log(facsvatar_json);

                // check if we're not done; timestamp is empty
                if (timestamp != "")
                {
                    msg_list.Add(topic);
                    msg_list.Add(timestamp);
                    msg_list.Add(facsvatar_json);
                    long timeNowMs = UnixTimeNowMillisec();
                    msg_list.Add(timeNowMs.ToString());  // time msg received; for unity performance

                    if (facsvatar_logging == true)
                    {
                        //Debug.Log("NetMqListener log");

                        //Debug.Log(timeNowMs);
                        //Debug.Log(timestamp2);
                        //Debug.Log(timeNowMs - timestamp2);

                        // write to csv
                        // string csvLine = string.Format("{0},{1},{2}", msg_count, timestamp2, timeNowMs);
                        string csvLine = string.Format("{0},{1}", msg_count, timeNowMs);
                        csv_writer.WriteLine(csvLine);
                    }
                    msg_count++;

                    _messageQueue.Enqueue(msg_list);
                }
                // done
                else
                {
                    Debug.Log("Received all messages");
                }
            }
            subSocket.Close();
        }
        NetMQConfig.Cleanup();
    }
Example #22
0
    private void ListenerWork()
    {
        Debug.Log("Setting up subscriber sock");
        AsyncIO.ForceDotNet.Force();
        using (var subSocket = new SubscriberSocket())
        {
            // set limit on how many messages in memory
            subSocket.Options.ReceiveHighWatermark = 1000;
            // socket connection
            // subSocket.Connect("tcp://localhost:5572");
            subSocket.Connect("tcp://" + sub_to_ip + ":" + sub_to_port);
            // subscribe to topics; "" == all topics
            subSocket.Subscribe("");
            Debug.Log("sub socket initiliased");

            string topic;
            //string frame;
            string timestamp;
            //string blend_shapes;
            //string head_pose;
            string facsvatar_json;
            while (!_listenerCancelled)
            {
                //string frameString;
                // wait for full message
                //if (!subSocket.TryReceiveFrameString(out frameString)) continue;
                //Debug.Log(frameString);
                //_messageQueue.Enqueue(frameString);

                List <string> msg_list = new List <string>();
                if (!subSocket.TryReceiveFrameString(out topic))
                {
                    continue;
                }
                //if (!subSocket.TryReceiveFrameString(out frame)) continue;
                if (!subSocket.TryReceiveFrameString(out timestamp))
                {
                    continue;
                }
                //if (!subSocket.TryReceiveFrameString(out blend_shapes)) continue;
                //if (!subSocket.TryReceiveFrameString(out head_pose)) continue;
                if (!subSocket.TryReceiveFrameString(out facsvatar_json))
                {
                    continue;
                }

                //Debug.Log("Received messages:");
                //Debug.Log(frame);
                //Debug.Log(timestamp);
                //Debug.Log(blend_shapes);
                //Debug.Log(head_pose);

                // check if we're not done; timestamp is empty
                if (timestamp != "")
                {
                    //msg_list.Add(blend_shapes);
                    //msg_list.Add(head_pose);
                    msg_list.Add(facsvatar_json);
                    _messageQueue.Enqueue(msg_list);
                }
                // done
                else
                {
                    Debug.Log("Received all messages");
                }
            }
            subSocket.Close();
        }
        NetMQConfig.Cleanup();
    }
Example #23
0
        private void SingleSubPubEntry(object pubname)
        {
            string pn = (string)pubname;


            if (SubPubRM.ContainsKey(pn))
            {
                SubPubRun spr = SubPubRM[pn];
                using (PublisherSocket publisher = new PublisherSocket())
                    using (SubscriberSocket subsciber = new SubscriberSocket())
                    {
                        //List<string> EndPointl = new List<string>();
                        string e = string.Empty;
                        foreach (Point p in spr.subs)
                        {
                            e = "tcp://" + p.ip + ":" + p.port;
                            subsciber.Connect(e);
                            subsciber.Subscribe("");
                        }

                        e = "tcp://*:" + spr.pub.port;
                        try
                        {
                            publisher.Bind(e);
                        }
                        catch (Exception err)
                        {
                            Logging.logger.Error(ModName + " bind socket failed " + " " + err.Message);
                            throw (err);
                        }
                        spr.pubsock = publisher;
                        spr.subsock = subsciber;
                        string received;
                        string pubdata;
                        bool   result;
                        spr.Working = true;
                        while (spr.Running)
                        {
                            received = string.Empty;
                            result   = subsciber.TryReceiveFrameString(out received);

                            if (result == true)
                            {
                                pubdata = string.Empty;
                                try
                                {
                                    pubdata = this.Entry4SubPubData(spr.pub.name, received);
                                }
                                catch (Exception err)
                                {
                                    Logging.logger.Error(err.Message);
                                    pubdata = string.Empty;
                                    throw (err);
                                }
                                if (pubdata != null)
                                {
                                    publisher.SendFrame(pubdata);
                                }
                            }

                            DelayTime();
                        }
                        spr.Working = false;
                        publisher.Close();
                        subsciber.Close();
                    }
            }
            else
            {
                Logging.logger.Error("SingleSubPubEntry can not get pubname " + pubname);
                return;
            }
        }
Example #24
0
        public void ThreadB()
        {
            try
            {
                //string topic = args[0] == "All" ? "" : args[0];
                //string topic = "";
                //Console.WriteLine("Subscriber started for Topic : {0}", _topic);

                using (var subSocket = new SubscriberSocket())
                {
                    subSocket.Options.ReceiveHighWatermark = 1000;
                    publisherIP   = ConfigurationManager.AppSettings["publisherIP"];
                    publisherPort = ConfigurationManager.AppSettings["publisherPort"];
                    subSocket.Connect("tcp://" + publisherIP + ":" + publisherPort);
                    //subSocket.SubscribeToAnyTopic();
                    if (parentSD.dictFilters.Count == 0)
                    {
                        subSocket.SubscribeToAnyTopic();
                    }
                    else
                    {
                        foreach (var filters in parentSD.dictFilters)
                        {
                            //Console.WriteLine("Subscribing Socket for Symbol : " + filters.Key);
                            subSocket.Subscribe(filters.Key);
                        }
                    }

                    //Console.WriteLine("Subscriber socket connecting...");
                    while (true)
                    {
                        try
                        {
                            if (ScannerBox.openedMainForm == false)
                            {
                                break;
                            }
                            string messageReceived;
                            if (subSocket.TryReceiveFrameString(out messageReceived))
                            {
                                //string messageReceived = subSocket.ReceiveFrameString();
                                string[] arr = messageReceived.Split(',');
                                //SELECT Symbol, feedtime, expiry, OptType, StrikePrice, Exch, PCloseRate, LastRate, TotalQty, Series, MLot, ScripNo, OpenRate, HighRate, LowRate, AvgRate

                                Feed feed = new Feed(arr[0], arr[1], arr[2], arr[3], arr[4], arr[5], arr[6], arr[7], arr[8], arr[9], arr[12], arr[13], arr[14], arr[15]);
                                bool flagSymbolCondition = true;
                                bool flagExpiryCondition = true;
                                bool flagExchCondition   = true;
                                bool flagStrikeCondition = true;

                                bool flagClosePriceCondition = true;
                                bool flagLtpCondition        = true;
                                bool flagQuantityCondition   = true;

                                bool foundKey = false;

                                List <SymbolFilter> listSymbolFilter;
                                if (parentSD.dictFilters.TryGetValue(feed.symbol.Trim(), out listSymbolFilter))
                                {
                                    foreach (var symbolfilter in listSymbolFilter)
                                    {
                                        if (symbolfilter.symbol != null && string.Compare(feed.symbol, symbolfilter.symbol) != 0)
                                        {
                                            flagSymbolCondition = false;
                                        }
                                        else
                                        {
                                            flagSymbolCondition = true;
                                        }

                                        if (symbolfilter.expiry != null && symbolfilter.expiry != "")
                                        {
                                            // MessageBox.Show(feed.expiry + " not equal " + symbolfilter.expiry);
                                            //Console.WriteLine(feed.expiry + " and " + symbolfilter.expiry);
                                            //DateTime dt1 = DateTime.ParseExact(symbolfilter.expiry, "dd-MM-yyyy", CultureInfo.InvariantCulture);

                                            if (string.Compare(feed.expiry, symbolfilter.expiry) != 0)
                                            {
                                                flagExpiryCondition = false;
                                            }
                                            else
                                            {
                                                flagExpiryCondition = true;
                                            }
                                        }

                                        if (symbolfilter.exch != null && symbolfilter.exch != "" && string.Compare(feed.exch, symbolfilter.exch) != 0)
                                        {
                                            flagExchCondition = false;
                                        }
                                        else
                                        {
                                            flagExchCondition = true;
                                        }

                                        if (flagExchCondition == true)
                                        {
                                            if (symbolfilter.strike != null && symbolfilter.strike != "" && string.Compare(feed.strike, symbolfilter.strike) != 0)
                                            {
                                                flagStrikeCondition = false;
                                            }
                                            else
                                            {
                                                flagStrikeCondition = true;
                                            }
                                        }

                                        double closePrice = Convert.ToDouble(feed.closePrice);
                                        double ltp        = Convert.ToDouble(feed.ltp);
                                        int    quantity   = Convert.ToInt32(feed.quantity);

                                        if (symbolfilter.closePrice != 0 && closePrice < symbolfilter.closePrice)
                                        {
                                            flagClosePriceCondition = false;
                                        }
                                        else
                                        {
                                            flagClosePriceCondition = true;
                                        }

                                        if (symbolfilter.ltp != 0 && ltp < symbolfilter.ltp)
                                        {
                                            flagLtpCondition = false;
                                        }
                                        else
                                        {
                                            flagLtpCondition = true;
                                        }

                                        if (symbolfilter.quantity != 0 && quantity < symbolfilter.quantity)
                                        {
                                            flagQuantityCondition = false;
                                        }
                                        else
                                        {
                                            flagQuantityCondition = true;
                                        }

                                        if (flagSymbolCondition && flagExpiryCondition && flagExchCondition &&
                                            flagStrikeCondition && flagClosePriceCondition &&
                                            flagLtpCondition && flagQuantityCondition)
                                        {
                                            ScannerBox.qfeed.Enqueue(feed);

                                            string key   = feed.symbol + "," + feed.expiry + "," + feed.strike + "," + feed.callput + "," + feed.exch;
                                            string value = feed.feedtime + "," + feed.closePrice + "," + feed.ltp + "," + feed.quantity + "," + feed.openRate + "," + feed.highRate + "," + feed.lowRate;

                                            foundKey             = true;
                                            dictFeedDetails[key] = value;
                                        }
                                    }
                                }

                                //check if it needs to be removed from the hashmap and the data table
                                if (foundKey == false)
                                {
                                    var exisiting = ScannerBox.dtFeed.Rows.Find(new Object[] { feed.symbol, feed.expiry, feed.strike, feed.callput, feed.exch });
                                    if (exisiting != null)
                                    {
                                        exisiting.Delete();
                                    }
                                }
                                //Console.WriteLine(messageReceived);
                            }
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e.Message);
                        }
                    }
                }
            }
            finally
            {
                NetMQConfig.Cleanup();
            }
        }
Example #25
0
    void Update()
    {
        received = false;
        string dataString = "null received";


        //Tries to receive a string published from ZeroMQ Publisher
        if (subscriberSocket.TryReceiveFrameString(TimeSpan.FromMilliseconds(5), out dataString))
        {
            //Debug.Log("RCV_ : " + dataString);
            received = true;
        }
        else
        {
            //Debug.LogError("RCV_Error: " + dataString);
        }

        //If received a string only then edit the string and change the rotation of the CubeSat
        if (received)
        {
            // received string is  like  "topic accx accy accz gyrox gyroy gyroz"
            char     splitChar = ' ';
            string[] dataRaw   = dataString.Split(splitChar);

            // normalized accelerometer values
            //float ax = float.Parse(dataRaw[1]) * acc_normalizer_factor;
            //float ay = float.Parse(dataRaw[2]) * acc_normalizer_factor;
            //float az = float.Parse(dataRaw[3]) * acc_normalizer_factor;

            //receiving if a button was pressed to recalibrate
            if (dataRaw[1].Equals("calibrate"))
            {
                calibrated = false;
                //reseting angles
                curr_angle_x = 0;
                curr_angle_y = 0;
                curr_angle_z = 0;

                //reseting calibrating values
                calibratedX = 0;
                calibratedY = 0;
                calibratedZ = 0;
            }

            // normalized gyrocope values
            float gx = float.Parse(dataRaw[5]) * gyro_normalizer_factor;
            float gy = float.Parse(dataRaw[6]) * gyro_normalizer_factor;
            float gz = float.Parse(dataRaw[7]) * gyro_normalizer_factor;

            //Debug.Log("The data raw of 1 iz: " + gx);

            // prevent
            //if (Mathf.Abs(ax) - 1 < 0) ax = 0;
            //if (Mathf.Abs(ay) - 1 < 0) ay = 0;
            //if (Mathf.Abs(az) - 1 < 0) az = 0;


            //curr_offset_x += ax;
            //curr_offset_y += ay;
            //curr_offset_z += 0; // The IMU module have value of z axis of 16600 caused by gravity


            // prevent little noise effect
            if (Mathf.Abs(gx) < 0.025f)
            {
                gx = 0f;
            }
            if (Mathf.Abs(gy) < 0.025f)
            {
                gy = 0f;
            }
            if (Mathf.Abs(gz) < 0.025f)
            {
                gz = 0f;
            }

            if (calibrated)
            {
                curr_angle_x += gx - avgGx;
                curr_angle_y += gy - avgGy;
                curr_angle_z += gz - avgGz;

                //if (enableTranslation) target.transform.position = new Vector3(curr_offset_x, curr_offset_y, curr_offset_z);
                if (enableRotation)
                {
                    target.transform.rotation = Quaternion.Euler(curr_angle_x * factor, curr_angle_y * factor, curr_angle_z * factor);
                }
            }
            else
            {
                calibrationCounter++;
                calibratedX += gx;
                calibratedY += gy;
                calibratedZ += gz;
                if (calibrationCounter % 40 == 0)
                {
                    calibrated = true;
                    avgGx      = calibratedX / (float)40;
                    avgGy      = calibratedY / (float)40;
                    avgGz      = calibratedZ / (float)40;
                }
            }
        }
    }