Exemplo n.º 1
0
        internal DeviceConnectionState Initialize(bool Enable, int Timeout)
        {
            m_Timeout         = Timeout;
            m_IsGateEmulation = m_IsGateEmulationHard || !Enable;

            m_ConnectionState = DeviceConnectionState.ConnectionInProcess;
            FireConnectionEvent(m_ConnectionState, "Gate initializing");

            if (m_IsGateEmulation)
            {
                m_ConnectionState = DeviceConnectionState.ConnectionSuccess;

                FireConnectionEvent(m_ConnectionState, "Gate initialized");

                return(m_ConnectionState);
            }

            try
            {
                ClearWarning();

                m_ConnectionState = DeviceConnectionState.ConnectionSuccess;
                FireConnectionEvent(m_ConnectionState, "Gate initialized");
            }
            catch (Exception ex)
            {
                m_ConnectionState = DeviceConnectionState.ConnectionFailed;
                FireConnectionEvent(m_ConnectionState, String.Format("Gate initialization error: {0}", ex.Message));
            }


            return(m_ConnectionState);
        }
Exemplo n.º 2
0
        public void SetConnectionStatus(DeviceConnectionState State, string Message)
        {
            m_IsTimeoutEnabled = State == DeviceConnectionState.ConnectionInProcess;

            switch (State)
            {
            case DeviceConnectionState.ConnectionSuccess:
                ProgressGo(100, false);
                break;

            case DeviceConnectionState.ConnectionTimeout:
            case DeviceConnectionState.ConnectionFailed:
                ProgressGo(100, false);
                SetError(Message);
                break;

            case DeviceConnectionState.ConnectionInProcess:
                ProgressGo(0, 100, true);
                break;

            case DeviceConnectionState.DisconnectionInProcess:
                ProgressGo(100, 0, true);
                break;

            case DeviceConnectionState.DisconnectionSuccess:
                ProgressGo(0, false);
                break;

            case DeviceConnectionState.None:
                ProgressGo(0, false);
                break;
            }
        }
Exemplo n.º 3
0
        internal void Deinitialize()
        {
            var oldState = m_ConnectionState;

            m_ConnectionState = DeviceConnectionState.DisconnectionInProcess;
            FireConnectionEvent(DeviceConnectionState.DisconnectionInProcess, "Commutation disconnecting");

            try
            {
                if (!m_IsCommutationEmulation && oldState == DeviceConnectionState.ConnectionSuccess)
                {
                    CallAction(ACT_DISABLE_POWER);
                }

                if (m_CheckSafetyThread != null)
                {
                    //завершаем работу потока, контролирующего срабатывание оптической системы безопасности
                    m_SafetyOn = false;
                    m_CheckSafetyThread.StopCycle(true);
                }

                m_ConnectionState = DeviceConnectionState.DisconnectionSuccess;
                FireConnectionEvent(DeviceConnectionState.DisconnectionSuccess, "Commutation disconnected");
            }
            catch (Exception)
            {
                m_ConnectionState = DeviceConnectionState.DisconnectionError;
                FireConnectionEvent(DeviceConnectionState.DisconnectionError, "Commutation disconnection error");
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Initializes the device module.
        /// </summary>
        public static void InitializeDeviceModule(bool isFirst = true)
        {
            if (isInitialized)
            {
                return;
            }
            if (Application.platform == RuntimePlatform.Android)
            {
                Ximmerse.InputSystem.XDevicePlugin.Init();
                //Apply logs:
                XDevicePlugin.SetLogger((int level, string _tag, string log) =>
                {
                    Debug.LogFormat("level:{0} ,tag:{1}, log:{2}", level, _tag, log);
                });

                if (isFirst)
                {
                    XDevicePlugin.CopyAssetsToPath(kConfigFileDirectory);
                }
                DevicerHandle.SlideInContext = XDevicePlugin.NewContext(XDevicePlugin.XContextTypes.kXContextTypeSlideIn);/// 创建SlideIn设备上下文
                DevicerHandle.HmdHandle      = XDevicePlugin.GetDeviceHandle(DevicerHandle.SlideInContext, "XHawk-0");
                if (isFirst)
                {
                    TagTrackingUtil.ApplyDefaultConfig();
                }

                DeviceConnectionState vpuConn = (DeviceConnectionState)XDevicePlugin.GetInt(DevicerHandle.HmdHandle, XDevicePlugin.XVpuAttributes.kXVpuAttr_Int_ConnectionState, 0);
                isVPUConnected = vpuConn == DeviceConnectionState.Connected;
                XDevicePlugin.RegisterObserver(DevicerHandle.HmdHandle, XDevicePlugin.XVpuAttributes.kXVpuAttr_Int_ConnectionState, new XDevicePlugin.XDeviceConnectStateChangeDelegate(OnVPUConnectionStateChanged), DevicerHandle.HmdHandle);
                isInitialized = true;

                Debug.LogFormat("Slide in HLAPI initialized successfully. HLAPI version : {0}, Algorithm version: {1}", HLAPIVersion.Version, HLAPIVersion.AlgVersion);
                Debug.LogFormat("VPU device state {0} ", vpuConn);
            }
            else if (Application.platform == RuntimePlatform.WindowsEditor || Application.platform == RuntimePlatform.WindowsPlayer)
            {
                Ximmerse.InputSystem.XDevicePlugin.Init();
                XDevicePlugin.SetLogger((int level, string _tag, string log) =>
                {
                    Debug.LogFormat("level:{0} ,tag:{1}, log:{2}", level, _tag, log);
                });
                DevicerHandle.SlideInContext = XDevicePlugin.NewContext(XDevicePlugin.XContextTypes.kXContextTypeSlideIn);/// 创建SlideIn设备上下文
                DevicerHandle.HmdHandle      = XDevicePlugin.GetDeviceHandle(DevicerHandle.SlideInContext, "XHawk-0");
                Debug.LogFormat("VPU Context: {0}, Hmd handle:{1}", DevicerHandle.SlideInContext.mNativeHandle.ToInt32(), DevicerHandle.HmdHandle.mNativeHandle.ToInt32());
                TagTrackingUtil.ApplyDefaultConfig();


                var vpuConn = (DeviceConnectionState)XDevicePlugin.GetInt(DevicerHandle.HmdHandle, XDevicePlugin.XVpuAttributes.kXVpuAttr_Int_ConnectionState, 0);
                isVPUConnected = vpuConn == DeviceConnectionState.Connected;
                XDevicePlugin.RegisterObserver(DevicerHandle.HmdHandle, XDevicePlugin.XVpuAttributes.kXVpuAttr_Int_ConnectionState, new XDevicePlugin.XDeviceConnectStateChangeDelegate(OnVPUConnectionStateChanged), DevicerHandle.HmdHandle);
                isInitialized = true;

                Debug.LogFormat("Slide in HLAPI initialized successfully. HLAPI version : {0}, Algorithm version: {1}", HLAPIVersion.Version, HLAPIVersion.AlgVersion);
                Debug.LogFormat("VPU device state {0} ", vpuConn);
            }
            else
            {
                Debug.LogWarningFormat("Tracking Library not available for current platform : {0}. Currently we supports Android/Windows platform.", Application.platform);
            }
        }
        private void DataReceivedInternal(IAsyncResult ar)
        {
            SslStream stream    = (SslStream)ar.AsyncState;
            int       byteCount = -1;

            try
            {
                byteCount = stream.EndRead(ar);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
                ConnectionState = DeviceConnectionState.Error;
                Dispose(resetState: false);
            }

            if (byteCount > 0)
            {
                var data = new ArraySegment <byte>(receiveBuffer, 0, byteCount);
                DataReceived?.Invoke(this, data);
                deviceReceiveBuffer.OnReceive(data);
            }

            StartReceive();
        }
        private void Connect()
        {
            if (tcpClient == null || !tcpClient.Connected)
            {
                var host = getHost?.Invoke();
                try
                {
                    state = DeviceConnectionState.Connecting;

                    tcpClient = new TcpClient();
                    tcpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
                    tcpClient.Connect(host, 8009);

                    sslStream = new SslStream(tcpClient.GetStream(), false, new RemoteCertificateValidationCallback(DontValidateServerCertificate), null);
                    sslStream.AuthenticateAsClient(host, new X509CertificateCollection(), SslProtocols.Tls12, false);
                    StartReceive();

                    state = DeviceConnectionState.Connected;
                }
                catch (Exception ex)
                {
                    state = DeviceConnectionState.Error;
                    setDeviceState?.Invoke(DeviceState.ConnectError, null);
                    logger.Log(string.Format("ex [{0}]: {1}", host, ex.Message));
                }
            }
        }
Exemplo n.º 7
0
        internal DeviceConnectionState Initialize()
        {
            m_ConnectionState = DeviceConnectionState.ConnectionInProcess;
            FireConnectionEvent(m_ConnectionState, "Gateway initializing");

            if (m_IsGatewayEmulation)
            {
                m_ConnectionState = DeviceConnectionState.ConnectionSuccess;
                FireConnectionEvent(m_ConnectionState, "Gateway initialized");

                return(m_ConnectionState);
            }

            try
            {
                ReadRegister(REG_DEVICE_STATE);

                m_Thread.StartCycle(ThreadWorker, REQUEST_DELAY_MS);

                m_ConnectionState = DeviceConnectionState.ConnectionSuccess;
                FireConnectionEvent(m_ConnectionState, "Gateway initialized");
            }
            catch (Exception ex)
            {
                m_ConnectionState = DeviceConnectionState.ConnectionFailed;

                FireConnectionEvent(m_ConnectionState, String.Format("Gateway initialization error: {0}", ex.Message));
            }

            return(m_ConnectionState);
        }
Exemplo n.º 8
0
        public async Task <bool> Connect(CooliceDevice device)
        {
            ConnectionState = DeviceConnectionState.Connecting;

            // Get the remote device, the bluetooth address has already been verified
            _device = _adapter.GetRemoteDevice(device.Address);

            try
            {
                _socket = _device.CreateRfcommSocketToServiceRecord(Java.Util.UUID.FromString(BluetoothService.BT_SERIAL_DEVICE_UUID));
            }
            catch (Java.IO.IOException e)
            {
                Log.Error(TAG, "Create Socket Failed", e);
                ConnectionState = DeviceConnectionState.Disconnected;
                return(false);
            }

            if (_socket != null)
            {
                SynchronizationContext currentContext = SynchronizationContext.Current;
                try
                {
                    await Task.Run(async() =>
                    {
                        await _socket.ConnectAsync();
                        if (_socket.IsConnected)
                        {
                            ConnectionState = DeviceConnectionState.Connected;
                            currentContext.Post((e) =>
                            {
                                if (device.BluetoothConnectionReceived != null)
                                {
                                    device.BluetoothConnectionReceived(this, new BluetoothConnectionReceivedEventArgs(ConnectionState));
                                }
                            }, null);
                        }
                    });
                }
                catch (Java.IO.IOException ex)
                {
                    ConnectionState = DeviceConnectionState.Disconnected;
                    currentContext.Post((e) =>
                    {
                        if (device.BluetoothConnectionReceived != null)
                        {
                            device.BluetoothConnectionReceived(this, new BluetoothConnectionReceivedEventArgs(ConnectionState, ex));
                        }
                    }, null);
                    Log.Error(TAG, "Bluetooth Socket Connection Failed", ex);
                    return(false);
                }
            }

            return(true);
        }
Exemplo n.º 9
0
        public void AddCommonConnectionEvent(DeviceConnectionState State, string Message)
        {
            m_ActionQueue.Enqueue(delegate
            {
                switch (State)
                {
                case DeviceConnectionState.ConnectionSuccess:
                    Cache.Main.VM.IsSafetyBreakIconVisible = !Cache.Net.GetButtonState(ComplexButtons.ButtonSC1);

                    var stateService       = Cache.Net.GetStateService;
                    Cache.Main.VM.SyncMode = stateService.SyncMode;
                    Cache.Main.VM.MmeCode  = stateService.MmeCode;

                    BackgroundWorker worker = new BackgroundWorker();
                    worker.DoWork          += (sender, args) =>
                    {
                        try
                        {
                            Cache.DatabaseProxy.ClearCacheByMmeCode(stateService.MmeCode);
                            Cache.DatabaseProxy.GetProfilesDeepByMmeCode(stateService.MmeCode);
                        }
                        catch (Exception e)
                        {
                            args.Result = e;
                        }
                    };
                    worker.RunWorkerCompleted += (sender, args) =>
                    {
                        Cache.Welcome.IsRestartEnable = true;
                        Cache.Welcome.State(ComplexParts.Sync, DeviceConnectionState.ConnectionSuccess, string.Empty);

                        if (args.Result is Exception ex)
                        {
                            new DialogWindow("Error", ex.ToString()).ShowDialog();
                        }

                        Cache.Welcome.IsBackEnable = true;
                        Cache.Main.mainFrame.Navigate(Cache.UserWorkMode);
                    };
                    worker.RunWorkerAsync();

                    break;

                case DeviceConnectionState.ConnectionFailed:
                    Cache.Welcome.IsRestartEnable = true;
                    break;

                case DeviceConnectionState.DisconnectionError:
                case DeviceConnectionState.DisconnectionSuccess:
                    if (Cache.Main.IsNeedToRestart)
                    {
                        m_Net.Initialize(Cache.Main.Param);
                    }
                    break;
                }
            });
        public void Dispose(bool resetState)
        {
            sslStream?.Close();
            tcpClient?.Close();

            if (resetState)
            {
                ConnectionState = DeviceConnectionState.None;
            }
        }
Exemplo n.º 11
0
        internal DeviceConnectionState Initialize(bool Enable, int timeoutTOU)
        {
            m_Timeout       = timeoutTOU;
            _IsTOUEmulation = _IsTOUEmulationHard || !Enable;

            _ConnectionState = DeviceConnectionState.ConnectionInProcess;
            FireConnectionEvent(_ConnectionState, "TOU initializing");

            if (_IsTOUEmulation)
            {
                _ConnectionState = DeviceConnectionState.ConnectionSuccess;
                FireConnectionEvent(_ConnectionState, "TOU initialized");

                return(_ConnectionState);
            }

            try
            {
                var timeStamp = Environment.TickCount + m_Timeout;
                ClearWarning();

                var devState = (HWDeviceState)ReadRegister(REG_DEV_STATE);

                //Если блок в состоянии None то просто подаём сигнал включения
                if (devState == HWDeviceState.None)
                {
                    CallAction(ACT_ENABLE_POWER);
                }
                else if (devState != HWDeviceState.Ready)//Если какое то друго состояние отличное от готовного
                {
                    //Выключаем питание
                    CallAction(ACT_DISABLE_POWER);
                    //Ждём перехода в выключенное состояние
                    WaitState(HWDeviceState.None);
                    //Включаем питание
                    CallAction(ACT_ENABLE_POWER);
                }

                //Ждём когда блок будет готов
                WaitState(HWDeviceState.Ready);

                _ConnectionState = DeviceConnectionState.ConnectionSuccess;

                FireConnectionEvent(_ConnectionState, "TOU initialized");
            }
            catch (Exception ex)
            {
                _ConnectionState = DeviceConnectionState.ConnectionFailed;
                FireConnectionEvent(_ConnectionState, String.Format("TOU initialization error: {0}", ex.Message));
            }

            return(_ConnectionState);
        }
Exemplo n.º 12
0
        public void AddCommonConnectionEvent(DeviceConnectionState State, string Message)
        {
            m_ActionQueue.Enqueue(delegate
            {
                switch (State)
                {
                case DeviceConnectionState.ConnectionSuccess:
                    {
                        //Cache.Calibration.PatchClamp();
                        Cache.Main.mainFrame.Navigate(Cache.ActivationWorkPage);         //Cache.SctuPage
                        Cache.Welcome.IsRestartEnable = true;
                        Cache.Welcome.IsBackEnable    = true;

                        if (Settings.Default.FTDIPresent)
                        {
                            Cache.FTDI.LedRedSwitch(false);
                            Cache.FTDI.LedGreenSwitch(false);
                        }

                        Cache.Main.IsSafetyBreakIconVisible = !Cache.Net.GetButtonState(ComplexButtons.ButtonSC1);
                    }
                    break;

                case DeviceConnectionState.ConnectionFailed:
                    {
                        Cache.Welcome.IsRestartEnable = true;

                        if (Settings.Default.FTDIPresent)
                        {
                            Cache.FTDI.LedGreenSwitch(false);
                            Cache.FTDI.LedRedBlinkStart();
                        }
                    }
                    break;

                case DeviceConnectionState.DisconnectionError:
                case DeviceConnectionState.DisconnectionSuccess:
                    {
                        if (Cache.Main.IsNeedToRestart)
                        {
                            m_Net.Initialize(Cache.Main.Param);
                        }

                        if (Settings.Default.FTDIPresent)
                        {
                            Cache.FTDI.LedRedSwitch(false);
                            Cache.FTDI.LedGreenSwitch(false);
                        }
                    }
                    break;
                }
            });
        }
Exemplo n.º 13
0
        /// <summary>
        /// Raises the device connect state change event.
        /// </summary>
        /// <param name="connect_st">Connect st.</param>
        /// <param name="ud">Ud.</param>
        private static void OnVPUConnectionStateChanged(int connect_st, System.IntPtr ud)
        {
            DeviceConnectionState connState = (DeviceConnectionState)connect_st;

            Debug.Log("Device connect state change, " + connState);

            isVPUConnected = connState == DeviceConnectionState.Connected;
            if (OnVPUConnectionStateIsChanged != null)
            {
                OnVPUConnectionStateIsChanged(isVPUConnected);
            }
        }
Exemplo n.º 14
0
        internal void State(ComplexParts Device, DeviceConnectionState ConnectionState, string Message)
        {
            switch (Device)
            {
            case ComplexParts.FTDI:
                internalControl.SetConnectionStatus(ConnectionState, Message);
                break;

            case ComplexParts.Service:
                serviceControl.SetConnectionStatus(ConnectionState, Message);
                break;

            case ComplexParts.Adapter:
                adapterControl.SetConnectionStatus(ConnectionState, Message);
                break;

            case ComplexParts.Gateway:
                gatewayControl.SetConnectionStatus(ConnectionState, Message);
                break;

            case ComplexParts.Commutation:
                commutationControl.SetConnectionStatus(ConnectionState, Message);
                break;

            case ComplexParts.Gate:
                gateControl.SetConnectionStatus(ConnectionState, Message);
                break;

            case ComplexParts.SL:
                vtmControl.SetConnectionStatus(ConnectionState, Message);
                break;

            case ComplexParts.BVT:
                bvtControl.SetConnectionStatus(ConnectionState, Message);
                break;

            case ComplexParts.Clamping:
                clampControl.SetConnectionStatus(ConnectionState, Message);
                break;

            case ComplexParts.CommutationEx:
                commutationControlEx.SetConnectionStatus(ConnectionState, Message);
                break;

            case ComplexParts.DvDt:
                dVdtControl.SetConnectionStatus(ConnectionState, Message);
                break;

            case ComplexParts.Sctu:
                sctuControl.SetConnectionStatus(ConnectionState, Message);
                break;
            }
        }
Exemplo n.º 15
0
        void LLAPIConnectionStateChange(int connect_st, System.IntPtr ud)
        {
//            switch ((XDevicePlugin.XControllerAttributes)attr_id)
//            {
//                case XDevicePlugin.XControllerAttributes.kXCAttr_Int_ConnectionState:
//                    m_state = (DeviceConnectionState)System.Runtime.InteropServices.Marshal.ReadInt32(arg);
//                    Debug.LogFormat("Connection state : {0}", m_state);
//                    break;
//            }
            m_state = (DeviceConnectionState)connect_st;
            Debug.LogFormat("Connection state : {0}", m_state);
        }
Exemplo n.º 16
0
        internal DeviceConnectionState Initialize(int Timeout)
        {
            m_ConnectionState = DeviceConnectionState.ConnectionInProcess;

            FireConnectionEvent(m_ConnectionState, "Adapter initializing");

            if (m_IsAdapterEmulation)
            {
                m_ConnectionState = DeviceConnectionState.ConnectionSuccess;

                FireConnectionEvent(m_ConnectionState, "Adapter initialized");

                return(m_ConnectionState);
            }

            try
            {
                if (m_Adapter != null)
                {
                    if (m_Adapter.Connected)
                    {
                        m_Adapter.Close();
                    }
                }

                m_Adapter = new SCCIMasterAdapter(true);
                m_Adapter.Initialize(new SerialPortConfigurationMaster
                {
                    PortNumber                  = Settings.Default.AdapterPort,
                    BaudRate                    = 115200,
                    DataBits                    = 8,
                    StopBits                    = StopBits.One,
                    ParityMode                  = Parity.None,
                    TimeoutForSyncReceive       = Timeout,
                    TimeoutForSyncStreamReceive = Timeout,
                    UseRetransmitsForArrays     = true,
                    RetransmitsCountOnError     = 5
                });

                m_ConnectionState = DeviceConnectionState.ConnectionSuccess;

                FireConnectionEvent(m_ConnectionState, "Adapter initialized");
            }
            catch (SerialConnectionException ex)
            {
                m_ConnectionState = DeviceConnectionState.ConnectionFailed;

                FireConnectionEvent(m_ConnectionState, String.Format("Adapter initialization error: {0}", ex.Message));
            }

            return(m_ConnectionState);
        }
Exemplo n.º 17
0
        private static DeviceConnectionState GetDeviceConnectionState(string deviceId)
        {
            Device device = GetDeviceFromId(deviceId);

            if (device == null)
            {
                return(DeviceConnectionState.Disconnected);
            }

            DeviceConnectionState deviceConnectionState = device.ConnectionState;

            return(deviceConnectionState);
        }
Exemplo n.º 18
0
        internal void Deinitialize()
        {
            m_ConnectionState = DeviceConnectionState.DisconnectionInProcess;
            FireConnectionEvent(DeviceConnectionState.DisconnectionInProcess, "Adapter closing");

            if (m_Adapter != null && m_Adapter.Connected)
            {
                m_Adapter.Close();
                m_Adapter = null;
            }

            m_ConnectionState = DeviceConnectionState.DisconnectionSuccess;
            FireConnectionEvent(DeviceConnectionState.DisconnectionSuccess, "Adapter closed");
        }
        public async Task <bool> ConnectAsync()
        {
            switch (ConnectionState)
            {
            case DeviceConnectionState.Connecting:
                throw new InvalidOperationException("Already trying to connect");

            case DeviceConnectionState.Connected:
                return(true);
            }

            try
            {
                ConnectionState = DeviceConnectionState.Connecting;
                try
                {
                    tcpClient = new TcpClient();
                    tcpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
                    await tcpClient.ConnectAsync(Host, 8009);

                    sslStream = new SslStream(tcpClient.GetStream(), false, delegate { return(true); }, null);
                    await sslStream.AuthenticateAsClientAsync(Host, new X509CertificateCollection(), SslProtocols.Tls12, false);

                    if (StartReceive())
                    {
                        ConnectionState = DeviceConnectionState.Connected;
                        return(true);
                    }
                    else
                    {
                        ConnectionState = DeviceConnectionState.Error;
                        return(false);
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.ToString());
                    ConnectionState = DeviceConnectionState.Error;
                    return(false);
                }
            }
            finally
            {
                if (ConnectionState != DeviceConnectionState.Connected)
                {
                    // Something went wrong
                    Dispose(resetState: false);
                }
            }
        }
Exemplo n.º 20
0
        internal void Deinitialize()
        {
            var oldState = m_ConnectionState;

            m_ConnectionState = DeviceConnectionState.DisconnectionInProcess;
            FireConnectionEvent(DeviceConnectionState.DisconnectionInProcess, "Gate disconnecting");

            if (!m_IsGateEmulation && oldState == DeviceConnectionState.ConnectionSuccess)
            {
                Stop();
            }

            m_ConnectionState = DeviceConnectionState.DisconnectionSuccess;
            FireConnectionEvent(DeviceConnectionState.DisconnectionSuccess, "Gate disconnected");
        }
Exemplo n.º 21
0
        internal void Deinitialize()
        {
            var oldState = m_ConnectionState;

            m_ConnectionState = DeviceConnectionState.DisconnectionInProcess;
            FireConnectionEvent(DeviceConnectionState.DisconnectionInProcess, "Gateway disconnecting");

            if (!m_IsGatewayEmulation && oldState == DeviceConnectionState.ConnectionSuccess)
            {
                m_Thread.StopCycle(true);
            }

            m_ConnectionState = DeviceConnectionState.DisconnectionSuccess;
            FireConnectionEvent(DeviceConnectionState.DisconnectionSuccess, "Gateway disconnected");
        }
        /// <summary>
        /// Make a connection with the device for the control messages.
        /// </summary>
        private void Connect()
        {
            if (tcpClient != null && tcpClient.Client != null && tcpClient.Connected)
            {
                return;
            }

            Close();

            try
            {
                IsDisposed = false;
                var host = getHost();
                var port = getPort();

                tcpClient = new TcpClient();
                tcpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
                currentAynchResult = tcpClient.BeginConnect(host, port, new AsyncCallback(ConnectCallback), tcpClient);
                WaitHandle wh = currentAynchResult.AsyncWaitHandle;
                try
                {
                    if (!currentAynchResult.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5), false))
                    {
                        CloseConnection();
                        throw new TimeoutException();
                    }
                }
                finally
                {
                    wh.Close();
                }
            }
            catch (Exception ex)
            {
                try
                {
                    state = DeviceConnectionState.Error;
                    setDeviceState?.Invoke(DeviceState.ConnectError, null);
                    var host = getHost?.Invoke();
                    logger.Log($"ex [{host}]: Connect {ex.Message}");
                    CloseConnection();
                }
                catch (Exception innerEx)
                {
                    Console.WriteLine($"Connect:{innerEx.Message}");
                }
            }
        }
Exemplo n.º 23
0
        internal void Deinitialize()
        {
            var oldState = m_ConnectionState;

            if (oldState == DeviceConnectionState.ConnectionSuccess)
            {
                m_Thread.StopCycle(true);
            }

            m_ConnectionState = DeviceConnectionState.DisconnectionInProcess;
            FireConnectionEvent(DeviceConnectionState.DisconnectionInProcess, "Clamping disconnecting");

            try
            {
                if (!m_IsClampingEmulation && oldState == DeviceConnectionState.ConnectionSuccess)
                {
                    var devState = (HWDeviceState)
                                   ReadRegister(REG_DEVICE_STATE);

                    try
                    {
#if !MME_005
                        WriteRegister(REG_TEMP_SETPOINT, ROOM_TEMP * 10);
                        CallAction(ACT_SET_TEMPERATURE);
#endif
                    }
                    catch (Exception ex)
                    {
                        SystemHost.Journal.AppendLog(ComplexParts.Clamping, LogMessageType.Error, $"Error during Clamp deinitialization, temperature stage: {ex.Message}");
                    }

                    if (devState == HWDeviceState.ClampingDone)
                    {
                        Unsqueeze(new TestParameters());
                    }
                }

                m_ConnectionState = DeviceConnectionState.DisconnectionSuccess;
                FireConnectionEvent(DeviceConnectionState.DisconnectionSuccess, "Clamping disconnected");
            }
            catch (Exception)
            {
                m_ConnectionState = DeviceConnectionState.DisconnectionError;
                FireConnectionEvent(DeviceConnectionState.DisconnectionError, "Clamping disconnection error");
            }

            m_ConnectionState = DeviceConnectionState.DisconnectionSuccess;
        }
Exemplo n.º 24
0
        internal void Deinitialize()
        {
            m_ConnectionState = DeviceConnectionState.DisconnectionInProcess;
            FireConnectionEvent(DeviceConnectionState.DisconnectionInProcess, "IH disconnecting");

            try
            {
                //физического блока нет - поэтому управлять нечем
                m_ConnectionState = DeviceConnectionState.DisconnectionSuccess;
                FireConnectionEvent(DeviceConnectionState.DisconnectionSuccess, "IH disconnected");
            }
            catch (Exception)
            {
                m_ConnectionState = DeviceConnectionState.DisconnectionError;
                FireConnectionEvent(DeviceConnectionState.DisconnectionError, "IH disconnection error");
            }
        }
Exemplo n.º 25
0
        public static bool IsDeviceConnected(string deviceId, out string ErrorMessage)
        {
            DeviceConnectionState state = GetDeviceConnectionState(deviceId);

            ErrorMessage = null;

            switch (state)
            {
            case DeviceConnectionState.Connected:
                ErrorMessage = $"Device {deviceId} connected!";
                return(true);

            case DeviceConnectionState.Disconnected:
                ErrorMessage = $"Device {deviceId} is currently disconnected...";
                return(false);
            }

            return(false);
        }
Exemplo n.º 26
0
        internal DeviceConnectionState Initialize(bool Enable, int Timeout)
        {
            m_IsEmulation = m_IsEmulationHard || !Enable;

            m_ConnectionState = DeviceConnectionState.ConnectionInProcess;
            FireConnectionEvent(m_ConnectionState, "IH initializing");

            if (m_IsEmulation)
            {
                m_ConnectionState = DeviceConnectionState.ConnectionSuccess;
                FireConnectionEvent(m_ConnectionState, "IH initialized");

                return(m_ConnectionState);
            }

            //физического блока IH не существует, поэтому инициализировать нечего
            m_ConnectionState = DeviceConnectionState.ConnectionSuccess;

            return(m_ConnectionState);
        }
 /// <summary>
 /// Send a message to a device.
 /// If the device is not connected, a connection is made first.
 /// </summary>
 /// <param name="send">the message</param>
 public void SendMessage(byte[] send)
 {
     startTask(() => {
         sendBuffer = send;
         if (tcpClient != null &&
             tcpClient.Client != null &&
             tcpClient.Connected &&
             state == DeviceConnectionState.Connected)
         {
             DoSendMessage();
         }
         else
         {
             if (state != DeviceConnectionState.Connecting)
             {
                 state = DeviceConnectionState.Connecting;
                 Connect();
             }
         }
     });
 }
Exemplo n.º 28
0
        internal void Deinitialize()
        {
            m_ConnectionState = DeviceConnectionState.DisconnectionInProcess;
            FireConnectionEvent(DeviceConnectionState.DisconnectionInProcess, "RCC disconnecting");

            try
            {
                if (!m_IsEmulation)
                {
                    m_IOGate.Deinitialize();
                }

                m_ConnectionState = DeviceConnectionState.DisconnectionSuccess;
                FireConnectionEvent(m_ConnectionState, "RCC disconnected");
            }
            catch (Exception)
            {
                m_ConnectionState = DeviceConnectionState.DisconnectionError;
                FireConnectionEvent(DeviceConnectionState.DisconnectionError, "RCC disconnection error");
            }
        }
        public async Task SendMessageAsync(ArraySegment <byte> send)
        {
            if (!await ConnectAsync())
            {
                ConnectionState = DeviceConnectionState.Error;
                return;
            }

            if (tcpClient != null && tcpClient.Client != null && tcpClient.Connected)
            {
                try
                {
                    await sslStream.WriteAsync(send.Array, send.Offset, send.Count);

                    await sslStream.FlushAsync();
                }
                catch (Exception)
                {
                }
            }
        }
Exemplo n.º 30
0
        internal DeviceConnectionState Initialize(bool Enable, int Timeout)
        {
            m_State = DeviceState.None;

            m_ConnectionState = DeviceConnectionState.ConnectionInProcess;
            FireConnectionEvent(m_ConnectionState, "RCC initializing");

            m_IsEmulation = m_IsEmulationHard || !Enable;

            if (m_IsEmulation)
            {
                m_ConnectionState = DeviceConnectionState.ConnectionSuccess;
                FireConnectionEvent(m_ConnectionState, "RCC initialized");

                return(m_ConnectionState);
            }
            else
            {
                m_ConnectionState = m_IOGate.Initialize(Enable, Timeout);
            }

            return(m_ConnectionState);
        }