Example #1
0
        public void Disconnect()
        {
            if (poller != null && poller.IsRunning)
            {
                poller.Stop();
            }
            socket?.Close();

            HapticPulseReceived = null;
        }
Example #2
0
 /// <summary>
 /// Stops this instance.
 /// </summary>
 public void Stop()
 {
     _cancellation.Cancel();
     _socket.Close();
 }
Example #3
0
    void NetMQClient()
    {
        //thanks for Yuta Itoh sample code to connect via NetMQ with Pupil Service
        string IPHeader = ">tcp://" + ServerIP + ":";
        var    timeout  = new System.TimeSpan(0, 0, 1);     //1sec

        // Necessary to handle this NetMQ issue on Unity editor
        // https://github.com/zeromq/netmq/issues/526
        AsyncIO.ForceDotNet.Force();
        NetMQConfig.ManualTerminationTakeOver();
        NetMQConfig.ContextCreate(true);

        string subport = "";

        Debug.Log("Connect to the server: " + IPHeader + ServicePort + ".");
        _requestSocket = new RequestSocket(IPHeader + ServicePort);

        _requestSocket.SendFrame("SUB_PORT");
        _isconnected = _requestSocket.TryReceiveFrameString(timeout, out subport);

        _lastT = DateTime.Now;

        if (_isconnected)
        {
            StartProcess();
            var subscriberSocket = new SubscriberSocket(IPHeader + subport);
            subscriberSocket.Subscribe("gaze");             //subscribe for gaze data
            subscriberSocket.Subscribe("notify.");          //subscribe for all notifications
            _setStatus(EStatus.ProcessingGaze);
            var msg = new NetMQMessage();
            while (_isDone == false)
            {
                _isconnected = subscriberSocket.TryReceiveMultipartMessage(timeout, ref (msg));
                if (_isconnected)
                {
                    try
                    {
                        string msgType = msg[0].ConvertToString();
                        //Debug.Log(msgType);
                        if (msgType == "gaze")
                        {
                            var message = MsgPack.Unpacking.UnpackObject(msg[1].ToByteArray());
                            MsgPack.MessagePackObject mmap = message.Value;
                            lock (_dataLock)
                            {
                                _pupilData = JsonUtility.FromJson <Pupil.PupilData3D>(mmap.ToString());
                                if (_pupilData.confidence > 0.5f)
                                {
                                    OnPacket(_pupilData);
                                }
                            }
                        }
                        //Debug.Log(message);
                    }
                    catch
                    {
                        //	Debug.Log("Failed to unpack.");
                    }
                }
                else
                {
                    //	Debug.Log("Failed to receive a message.");
                    Thread.Sleep(500);
                }
            }

            StopProcess();

            subscriberSocket.Close();
        }
        else
        {
            Debug.Log("Failed to connect the server.");
        }

        _requestSocket.Close();
        // Necessary to handle this NetMQ issue on Unity editor
        // https://github.com/zeromq/netmq/issues/526
        Debug.Log("ContextTerminate.");
        NetMQConfig.ContextTerminate();
    }
Example #4
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 #5
0
 private void OnDestroy()
 {
     _pub.Close();
     _sub.Close();
 }
Example #6
0
    void NetMQClient()
    {
        //thanks for Yuta Itoh sample code to connect via NetMQ with Pupil Service
        string IPHeader = ">tcp://" + ServerIP + ":";
        var    timeout  = new System.TimeSpan(0, 0, 1); //1sec

        // Necessary to handle this NetMQ issue on Unity editor
        // https://github.com/zeromq/netmq/issues/526
        AsyncIO.ForceDotNet.Force();
        NetMQConfig.ManualTerminationTakeOver();
        NetMQConfig.ContextCreate(true);

        string subport = "";

        print("Connect to the server: " + IPHeader + ServicePort + ".");
        Thread.Sleep(ServiceStartupDelay);

        _requestSocket = new RequestSocket(IPHeader + ServicePort);

        _requestSocket.SendFrame("SUB_PORT");
        _isconnected = _requestSocket.TryReceiveFrameString(timeout, out subport);
        print(_isconnected + " isconnected");
        _gazeFps.Reset();
        _eyeFps[0].Reset();
        _eyeFps[1].Reset();

        if (_isconnected)
        {
            //_serviceStarted = true;
            StartProcess();
            var subscriberSocket = new SubscriberSocket(IPHeader + subport);

            subscriberSocket.Subscribe("gaze");    //subscribe for gaze data
            subscriberSocket.Subscribe("notify."); //subscribe for all notifications
            _setStatus(EStatus.ProcessingGaze);
            var msg = new NetMQMessage();
            while (_isDone == false)
            {
                _isconnected = subscriberSocket.TryReceiveMultipartMessage(timeout, ref (msg));
                if (_isconnected)
                {
                    try
                    {
                        string msgType = msg[0].ConvertToString();
                        //						UnityEngine.Debug.Log(msgType);
                        if (msgType == "gaze")
                        {
                            var message = MsgPack.Unpacking.UnpackObject(msg[1].ToByteArray());

                            MsgPack.MessagePackObject mmap = message.Value;
                            lock (_dataLock)
                            {
                                _pupilData = JsonUtility.FromJson <Pupil.PupilData3D>(mmap.ToString());
                                if (_pupilData.confidence > 0.5f)
                                {
                                    //UnityEngine.Debug.Log(_pupilData.base_data[0].id);
                                    OnPacket(_pupilData);
                                }
                            }
                        }
                        else if (msgType == "notify.eye_process.started")
                        {
                            var message = MsgPack.Unpacking.UnpackObject(msg[1].ToByteArray());
                            MsgPack.MessagePackObject mmap = message.Value;
                            var id = JsonUtility.FromJson <Pupil.EyeStatus>(mmap.ToString());
                            UnityEngine.Debug.Log(id.eye_id);
                        }
                        //Debug.Log(message);
                    }
                    catch
                    {
                        //	Debug.Log("Failed to unpack.");
                    }
                }
                else
                {
                    print("Failed to receive a message.");
                    Thread.Sleep(500);
                }
            }

            StopProcess();
            subscriberSocket.Close();
        }
        else
        {
            print("Failed to connect the server.");
            //If needed here could come a retry connection.
        }

        //Can only send request via IPC if the connection has been established, otherwise we are facing, errors and potential freezing.
        if (_serviceStarted && _isconnected)
        {
            StopService();
        }

        //Kill process
        if (serviceProcess != null)
        {
            UnityEngine.Debug.Log("Killing Pupil service");
            serviceProcess.Kill();
            serviceProcess.Close();
        }

        _requestSocket.Close();
        // Necessary to handle this NetMQ issue on Unity editor
        // https://github.com/zeromq/netmq/issues/526
        print("ContextTerminate.");
        NetMQConfig.ContextTerminate();
    }
Example #7
0
        /// <summary>
        ///     Disconnects from the server.
        /// </summary>
        public void Disconnect(bool cancelStreams = true)
        {
            if (!PollerRunning)
            {
                return;
            }
            // Start by canceling all active real time streams
            if (cancelStreams)
            {
                while (RealTimeDataStreams.Count > 0)
                {
                    CancelRealTimeData(RealTimeDataStreams.First().Instrument);
                }
            }

            _poller?.Stop();
            _poller?.Dispose();

            lock (_realTimeRequestSocketLock)
            {
                if (_realTimeRequestSocket != null)
                {
                    try
                    {
                        _realTimeRequestSocket.Disconnect(_realTimeRequestConnectionString);
                    }
                    finally
                    {
                        _realTimeRequestSocket.ReceiveReady -= RealTimeRequestSocketReceiveReady;
                        _realTimeRequestSocket.Close();
                        _realTimeRequestSocket = null;
                    }
                }
            }

            lock (_realTimeDataSocketLock)
            {
                if (_realTimeDataSocket != null)
                {
                    try
                    {
                        _realTimeDataSocket.Disconnect(_realTimeDataConnectionString);
                    }
                    finally
                    {
                        _realTimeDataSocket.ReceiveReady -= RealTimeDataSocketReceiveReady;
                        _realTimeDataSocket.Close();
                        _realTimeDataSocket = null;
                    }
                }
            }

            lock (_historicalDataSocket)
            {
                if (_historicalDataSocket != null)
                {
                    try
                    {
                        _historicalDataSocket.Disconnect(_historicalDataConnectionString);
                    }
                    finally
                    {
                        _historicalDataSocket.ReceiveReady -= HistoricalDataSocketReceiveReady;
                        _historicalDataSocket.Close();
                        _historicalDataSocket = null;
                    }
                }
            }

            _poller = null;
        }
    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 #9
0
 public void Disconnect()
 {
     poller.Stop();
     socket.Close();
     HapticPulseReceived = null;
 }
Example #10
0
    // Client thread which does not block Update()
    void NetMQClient()
    {
        string IPHeader = ">tcp://" + IP + ":";
        var    timeout  = new System.TimeSpan(0, 0, 1); //1sec

        // Necessary to handle this NetMQ issue on Unity editor
        // https://github.com/zeromq/netmq/issues/526
        AsyncIO.ForceDotNet.Force();
        NetMQConfig.ManualTerminationTakeOver();
        NetMQConfig.ContextCreate(true);

        string subport = "";

        Debug.Log("Connect to the server: " + IPHeader + PORT + ".");
        var       requestSocket = new RequestSocket(IPHeader + PORT);
        double    t             = 0;
        const int N             = 1000;
        bool      is_connected  = false;

        for (int k = 0; k < N; k++)
        {
            var sw = new System.Diagnostics.Stopwatch();
            sw.Start();
            requestSocket.SendFrame("SUB_PORT");
            is_connected = requestSocket.TryReceiveFrameString(timeout, out subport);
            sw.Stop();
            t = t + sw.Elapsed.Milliseconds;
            //Debug.Log("Round trip time:" + sw.Elapsed + "[sec].");
            if (is_connected == false)
            {
                break;
            }
        }
        Debug.Log("Round trip average time:" + t / N + "[msec].");

        requestSocket.Close();

        if (is_connected)
        {
            //
            var subscriberSocket = new SubscriberSocket(IPHeader + subport);
            subscriberSocket.Subscribe(ID);

            var msg = new NetMQMessage();
            while (is_connected && stop_thread_ == false)
            {
                Debug.Log("Receive a multipart message.");
                is_connected = subscriberSocket.TryReceiveMultipartMessage(timeout, ref (msg));
                if (is_connected)
                {
                    Debug.Log("Unpack a received multipart message.");
                    try
                    {
                        //Debug.Log(msg[0].ConvertToString());
                        var message = MsgPack.Unpacking.UnpackObject(msg[1].ToByteArray());
                        MsgPack.MessagePackObject mmap = message.Value;
                        lock (thisLock_)
                        {
                            data_ = JsonUtility.FromJson <Pupil.PupilData3D>(mmap.ToString());
                        }
                        //Debug.Log(message);
                    }
                    catch
                    {
                        Debug.Log("Failed to unpack.");
                    }
                }
                else
                {
                    Debug.Log("Failed to receive a message.");
                    Thread.Sleep(1000);
                }
            }
            subscriberSocket.Close();
        }
        else
        {
            Debug.Log("Failed to connect the server.");
        }

        // Necessary to handle this NetMQ issue on Unity editor
        // https://github.com/zeromq/netmq/issues/526
        Debug.Log("ContextTerminate.");
        NetMQConfig.ContextTerminate();
    }
Example #11
0
 public void Close()
 {
     socket.Close();
 }
Example #12
0
 /// <summary>
 /// close socket
 /// </summary>
 public void Close()
 {
     _cancellationTokenSource?.Cancel();
     _receiveTask?.Wait();
     _Subscriber.Close();
 }