private void TimerThread()
        {
            int interval = 5;

            try
            {
                while (_working)
                {
                    Thread.Sleep(interval);
                    if (_working)
                    {
                        for (int i = 0; i < _subscribedTimers.Length; i++)
                        {
                            _subscribedTimers[i].TimeElapsed(interval);
                        }
                    }
                }
            }
            catch (ThreadAbortException)
            {}
            catch (Exception ex)
            {
                _log.Log(this, ex.ToString());
            }
        }
        private void ReaderThread()
        {
            // sprawdzanie co minutę
            int interval = 1000 * 60;

            #if DEBUG
            interval = 1000 * 10;
            #endif
            try
            {
                while (_working)
                {
                    // pobranie kanału RSS
                    for (int i = 0; i < _subscribedRSS.Length; i++)
                    {
                        _subscribedRSS[i].TimeElapsed(1);
                    }
                    Thread.Sleep(interval);
                }
            }
            catch (ThreadAbortException)
            {}
            catch (Exception ex)
            {
                _log.Log(this, ex.ToString());
            }
        }
Exemple #3
0
        private void ProcessingMethod()
        {
            Microsoft.DirectX.DirectInput.Device keyboard = null;
            try
            {
                // utworzenie obiektu do odczytywania stanu klawiatury
                keyboard = new Microsoft.DirectX.DirectInput.Device(Microsoft.DirectX.DirectInput.SystemGuid.Keyboard);
                keyboard.SetDataFormat(Microsoft.DirectX.DirectInput.DeviceDataFormat.Keyboard);
                keyboard.SetEventNotification(_event);
                keyboard.SetCooperativeLevel(IntPtr.Zero, Microsoft.DirectX.DirectInput.CooperativeLevelFlags.Background | Microsoft.DirectX.DirectInput.CooperativeLevelFlags.NonExclusive);
                keyboard.Acquire();

                while (_working)
                {
                    _event.WaitOne();
                    if (!_working)
                    {
                        break;
                    }
                    Microsoft.DirectX.DirectInput.KeyboardState state = keyboard.GetCurrentKeyboardState();
                    for (int i = 0; i < _spiesVariables.Length; i++)
                    {
                        _spiesVariables[i].CheckState(state);
                    }
                    _event.Reset();
                    if (!_working)
                    {
                        break;
                    }
                }
            }
            catch (ThreadAbortException)
            {
            }
            catch (Exception ex)
            {
                _log.Log(this, ex.ToString());
            }
            finally
            {
                if (keyboard != null)
                {
                    try
                    {
                        keyboard.Unacquire();
                    }
                    catch { }
                    try
                    {
                        keyboard.Dispose();
                    }
                    catch { }
                    keyboard = null;
                }
            }
        }
        private void StartServer()
        {
            if (!_working)
            {
                if (_configuration.Applications.Length == 0)
                {
                    _log.Log(this, "Brak aplikacji WWW do uruchomienia.");
                    return;
                }

                _working = true;
                _signal.Reset();
                // wystartowanie wątka
                _processingThread = new Thread(new ThreadStart(ProcessingMethod));
                _processingThread.Start();
            }
        }
Exemple #5
0
 private void ProcessingThread()
 {
     try
     {
         while (_working)
         {
             _event.WaitOne();
             LCDData[] data = null;
             lock (_syncQueue)
             {
                 data = _queue.ToArray();
                 _queue.Clear();
             }
             _event.Reset();
             if (data != null && data.Length > 0)
             {
                 for (int i = 0; i < data.Length; i++)
                 {
                     if (data[i].Command)
                     {
                         _port.WriteControl(data[i].LCD, data[i].Data, data[i].Multiplier);
                     }
                     else
                     {
                         _port.WriteData(data[i].LCD, data[i].Data, data[i].Multiplier);
                     }
                 }
             }
         }
     }
     catch (ThreadAbortException)
     {
     }
     catch (Exception ex)
     {
         _log.Log(this, ex.ToString());
     }
 }
        private void ProcessingMethod()
        {
            FsuipcSdk.Fsuipc fsuipc    = null;
            bool             connected = false;

            try
            {
                int ret      = 0;
                int interval = _configuration.Settings.Interval;
                int fs       = 0;
                switch (_configuration.Settings.FSVersion)
                {
                case FSVersion.Dowolna:
                    fs = FsuipcSdk.Fsuipc.SIM_ANY;
                    break;

                case FSVersion.FS2002:
                    fs = FsuipcSdk.Fsuipc.SIM_FS2K2;
                    break;

                case FSVersion.FS2004:
                    fs = FsuipcSdk.Fsuipc.SIM_FS2K4;
                    break;

                case FSVersion.FSX:
                    fs = FsuipcSdk.Fsuipc.SIM_FSX;
                    break;

                default:
                    throw new Exception("Nieobsługiwana wersja symulatora '" + _configuration.Settings.FSVersion.ToString() + "'.");
                }
                _log.Log(this, "Próba połączenia z symulatorem w wersji '" + _configuration.Settings.FSVersion.ToString() + "'.");
                fsuipc = new FsuipcSdk.Fsuipc();
                while (_working)
                {
                    if (fsuipc.FSUIPC_Open(fs, ref ret))
                    {
                        _log.Log(this, "Połączono z symulatorem w wersji '" + _configuration.Settings.FSVersion.ToString() + "'.");
                        connected = true;
                        break;
                    }
                    Thread.Sleep(100);
                }

                List <VariableToWrite> vars = new List <VariableToWrite>();
                _signal.Set();
                while (_working)
                {
                    _signal.WaitOne();
                    if (!_working)
                    {
                        break;
                    }

                    // pobranie tablicy z wartościami do zapisu
                    lock (_syncQueue)
                    {
                        while (_writeQueue.Count > 0)
                        {
                            vars.Add(_writeQueue.Dequeue());
                        }
                    }
                    _signal.Reset();
                    if (vars.Count > 0)
                    {
                        int ile = 0;
                        while (vars.Count > 0)
                        {
                            VariableToWrite v = vars[0];
                            if (!(v.Variable is SpecialOutputVariable))
                            {
                                ile++;
                            }
                            ret = v.Variable.SetValue(v.Value, fsuipc);
                            if (ret != FsuipcSdk.Fsuipc.FSUIPC_ERR_OK)
                            {
                                _log.Log(this, string.Format("Błąd ({0}) podczas zapisywania wartości zmiennej o identyfikatorze '{1}'.", ret, v.Variable.ID));
                            }
                            vars.RemoveAt(0);
                        }

                        if (ile > 0 && (_autoFlush.State || _flush.State))
                        {
                            #if DEBUG
                            _log.Log(this, "FSUIPC_Process");
                            #endif
                            if (!fsuipc.FSUIPC_Process(ref ret))
                            {
                                _log.Log(this, string.Format("Błąd ({0}) podczas wysyłania wartości do symulatora.", ret));
                            }

                            _flush.Reset();
                        }
                    }
                }
            }
            catch (ThreadAbortException)
            {
            }
            catch (Exception ex)
            {
                _log.Log(this, ex.ToString());
            }
            finally
            {
                if (fsuipc != null)
                {
                    try
                    {
                        fsuipc.FSUIPC_Close();
                        if (connected)
                        {
                            _log.Log(this, "Rozłączono z symulatorem '" + _configuration.Settings.FSVersion.ToString() + "'.");
                        }
                    }
                    catch { }
                }
            }
        }
Exemple #7
0
        private void ProcessingMethod()
        {
            FsuipcSdk.Fsuipc fsuipc    = null;
            bool             connected = false;

            try
            {
                int ret      = 0;
                int interval = _configuration.Settings.Interval;
                int fs       = 0;
                switch (_configuration.Settings.FSVersion)
                {
                case FSVersion.Dowolna:
                    fs = FsuipcSdk.Fsuipc.SIM_ANY;
                    break;

                case FSVersion.FS2002:
                    fs = FsuipcSdk.Fsuipc.SIM_FS2K2;
                    break;

                case FSVersion.FS2004:
                    fs = FsuipcSdk.Fsuipc.SIM_FS2K4;
                    break;

                case FSVersion.FSX:
                    fs = FsuipcSdk.Fsuipc.SIM_FSX;
                    break;

                default:
                    throw new Exception("Nieobsługiwana wersja symulatora '" + _configuration.Settings.FSVersion.ToString() + "'.");
                }
                _log.Log(this, "Próba połączenia z symulatorem w wersji '" + _configuration.Settings.FSVersion.ToString() + "'.");
                fsuipc = new FsuipcSdk.Fsuipc();
                while (_working)
                {
                    if (fsuipc.FSUIPC_Open(fs, ref ret))
                    {
                        _log.Log(this, "Połączono z symulatorem w wersji '" + _configuration.Settings.FSVersion.ToString() + "'.");
                        connected = true;
                        break;
                    }
                    Thread.Sleep(100);
                }

                byte   v1 = 0;
                short  v2 = 0;
                int    v4 = 0;
                long   v8 = 0;
                object v  = null;
                bool   ok = false;

                while (_working)
                {
                    //lock (FsuipcSdk.Fsuipc.__FSUIPC_LOCKER)
                    //FsuipcSdk.Fsuipc.__FSUIPC_EVENT.WaitOne();
                    //try
                    {
                        for (int i = 0; i < _spiesVariables.Length; i++)
                        {
                            if (!fsuipc.FSUIPC_Read(_spiesVariables[i].Offset, _spiesVariables[i].Size, ref _spiesVariables[i].Token, ref ret))
                            {
                                _log.Log(this, "Błąd (" + ret.ToString() + " podczas żądania odczytu wartości zmiennej o identyfikatorze '" + _spiesVariables[i].ID + "'.");
                            }
                        }

                        if (!fsuipc.FSUIPC_Process(ref ret))
                        {
                            _log.Log(this, "Błąd (" + ret.ToString() + ") podczas żądania odczytania żądanych wartości.");
                        }
                        else
                        {
                            for (int i = 0; i < _spiesVariables.Length; i++)
                            {
                                switch (_spiesVariables[i].FSType)
                                {
                                case FSDataType.Byte:
                                    ok = fsuipc.FSUIPC_Get(ref _spiesVariables[i].Token, ref v1);
                                    v  = v1;
                                    break;

                                case FSDataType.Short:
                                    ok = fsuipc.FSUIPC_Get(ref _spiesVariables[i].Token, ref v2);
                                    v  = v2;
                                    break;

                                case FSDataType.Int:
                                    ok = fsuipc.FSUIPC_Get(ref _spiesVariables[i].Token, ref v4);
                                    v  = v4;
                                    break;

                                case FSDataType.Long:
                                    ok = fsuipc.FSUIPC_Get(ref _spiesVariables[i].Token, ref v8);
                                    v  = v8;
                                    break;

                                case FSDataType.ByteArray:
                                    byte[] buf = new byte[_spiesVariables[i].Size];
                                    ok = fsuipc.FSUIPC_Get(ref _spiesVariables[i].Token, buf.Length, ref buf);
                                    v  = buf;
                                    break;
                                }

                                if (ok)
                                {
                                    _spiesVariables[i].SetValue(v);
                                }
                                else
                                {
                                    _log.Log(this, "Błąd podczas pobierania wartości zmiennej o identyfikatorze '" + _spiesVariables[i].ID + "', Offset = 0x" + _spiesVariables[i].Offset.ToString("X4") + ".");
                                }
                            }
                        }
                    }
                    //finally
                    //{
                    //    FsuipcSdk.Fsuipc.__FSUIPC_EVENT.Set();
                    //}
                    if (interval > 0)
                    {
                        Thread.Sleep(interval);
                    }
                }
            }
            catch (ThreadAbortException)
            {
            }
            catch (Exception ex)
            {
                _log.Log(this, ex.ToString());
            }
            finally
            {
                if (fsuipc != null)
                {
                    try
                    {
                        fsuipc.FSUIPC_Close();
                        if (connected)
                        {
                            _log.Log(this, "Rozłączono z symulatorem '" + _configuration.Settings.FSVersion.ToString() + "'.");
                        }
                    }
                    catch { }
                }
            }
        }
Exemple #8
0
        private void ClientThread(object client)
        {
            NetworkStream stream    = null;
            TcpClient     tcpClient = client as TcpClient;

            try
            {
                stream = tcpClient.GetStream();
                while (_working)
                {
                    byte[]       data  = new byte[1];
                    IAsyncResult async = stream.BeginRead(data, 0, 1, null, null);
                    if (stream.EndRead(async) == 0)
                    {
                        break;
                    }
                    bool isVariable = data[0] == 1;
                    data  = new byte[4];
                    async = stream.BeginRead(data, 0, 4, null, null);
                    if (stream.EndRead(async) == 0)
                    {
                        break;
                    }
                    int length = BitConverter.ToInt32(data, 0);
                    if (length > 0)
                    {
                        data  = new byte[length];
                        async = stream.BeginRead(data, 0, length, null, null);
                        if (stream.EndRead(async) == 0)
                        {
                            break;
                        }
                        if (isVariable)
                        {
                            Variable      v  = Variable.Deserialize(new MemoryStream(data));
                            VariableEvent ve = null;
                            if (_variablesListeners.TryGetValue(v.ID, out ve))
                            {
                                ve.FireSignal(v);
                            }
                        }
                    }
                }
            }
            catch (ThreadAbortException)
            { }
            catch (Exception ex)
            {
                _log.Log(this, "Błąd połączenia z klientem: " + tcpClient.Client.RemoteEndPoint.ToString() + ", błąd: " + ex.Message);
            }
            finally
            {
                _log.Log(this, "Zamknięto połączenie z klientem: " + tcpClient.Client.RemoteEndPoint.ToString());
                if (stream != null)
                {
                    try
                    {
                        stream.Close();
                        stream.Dispose();
                        stream = null;
                    }
                    catch { }
                }
                if (tcpClient != null)
                {
                    try
                    {
                        tcpClient.Close();
                        tcpClient = null;
                    }
                    catch { }
                }
            }
        }
        public void Start(HomeSimCockpitSDK.StartStopType startType)
        {
            Stop(startType);

            // próba otworzenia połączenia z RS232
            _working = true;

            if (_registered.Count == 0 && !_requireFunction)
            {
                return;
            }

            _motors.Clear();
            _servos.Clear();

            // sprawdzenie które interfejsy trzeba uruchomić
            List <RS232Configuration> interfaces = new List <RS232Configuration>();
            List <Device>             devices    = new List <Device>();

            foreach (KeyValuePair <string, IOutputVariable> kvp in _registered)
            {
                Device[] ints = kvp.Value.Devices;
                foreach (Device inte in ints)
                {
                    if (interfaces.Find(delegate(RS232Configuration o)
                    {
                        return(o.Id == inte.Interface.Id);
                    }) == null)
                    {
                        interfaces.Add(inte.Interface);
                        inte.Interface.Log    = _log;
                        inte.Interface.Module = this;
                    }
                    if (devices.Find(delegate(Device o)
                    {
                        return(o.Id == inte.Id);
                    }) == null)
                    {
                        devices.Add(inte);
                    }
                }
            }

            if (_runSteppers)
            {
                foreach (StepperDevice stepperDevice in _configuration.StepperDevices)
                {
                    if (interfaces.Find(delegate(RS232Configuration o)
                    {
                        return(o.Id == stepperDevice.Interface.Id);
                    }) == null)
                    {
                        interfaces.Add(stepperDevice.Interface);
                        stepperDevice.Interface.Log    = _log;
                        stepperDevice.Interface.Module = this;
                    }
                    if (devices.Find(delegate(Device o)
                    {
                        return(o.Id == stepperDevice.Id);
                    }) == null)
                    {
                        devices.Add(stepperDevice);
                        if (stepperDevice.Motor1 != null && !string.IsNullOrEmpty(stepperDevice.Motor1.Id))
                        {
                            if (!_motors.ContainsKey(stepperDevice.Motor1.Id))
                            {
                                _motors.Add(stepperDevice.Motor1.Id, stepperDevice.Motor1);
                            }
                        }
                        if (stepperDevice.Motor2 != null && !string.IsNullOrEmpty(stepperDevice.Motor2.Id))
                        {
                            if (!_motors.ContainsKey(stepperDevice.Motor2.Id))
                            {
                                _motors.Add(stepperDevice.Motor2.Id, stepperDevice.Motor2);
                            }
                        }
                    }
                }
            }

            if (_runServos)
            {
                foreach (ServoDevice servoDevice in _configuration.ServoDevices)
                {
                    if (interfaces.Find(delegate(RS232Configuration o)
                    {
                        return(o.Id == servoDevice.Interface.Id);
                    }) == null)
                    {
                        interfaces.Add(servoDevice.Interface);
                        servoDevice.Interface.Log    = _log;
                        servoDevice.Interface.Module = this;
                    }
                    if (devices.Find(delegate(Device o)
                    {
                        return(o.Id == servoDevice.Id);
                    }) == null)
                    {
                        devices.Add(servoDevice);
                        foreach (Servo servo in servoDevice.Servos)
                        {
                            if (!string.IsNullOrEmpty(servo.Id) && !_servos.ContainsKey(servo.Id))
                            {
                                _servos.Add(servo.Id, servo);
                            }
                        }
                    }
                }
            }

            _interfaces = interfaces.ToArray();
            _devices    = devices.ToArray();

            // otwarcie potrzebnych interfejsów
            for (int i = 0; i < _interfaces.Length; i++)
            {
                _interfaces[i].Open();
            }

            // inicjalizacja urządzeń
            for (int j = 0; j < _devices.Length; j++)
            {
                if (_devices[j] is LEDDisplayDevice)
                {
                    ((LEDDisplayDevice)_devices[j]).Dictionary = _configuration.LEDDisplaysDictionary;
                }
                _devices[j].Initialize();
            }

            // inicjalizacja zmiennych
            foreach (KeyValuePair <string, IOutputVariable> kvp in _registered)
            {
                if (kvp.Value is LEDDisplay)
                {
                    ((LEDDisplay)kvp.Value).Dictionary = _configuration.LEDDisplaysDictionary;
                }
                if (kvp.Value is LEDDisplayGroup)
                {
                    ((LEDDisplayGroup)kvp.Value).Dictionary = _configuration.LEDDisplaysDictionary;
                }
                kvp.Value.Initialize();
            }

            _log.Log(this, "Uruchomiono simOUT");
        }
        private void ProcessingMethod(object argument)
        {
            Device joystick = null;

            InputVariable[] variables  = null;
            Controller      controller = (Controller)((object[])argument)[0];

            variables = (InputVariable[])((object[])argument)[1];
            try
            {
                System.Diagnostics.Debug.WriteLine(string.Format("Startuje wątek obsługi kontrolera: {0}", controller.ToString2()));
                System.Diagnostics.Debug.WriteLine(string.Format("Joy: {0}, Ilość zmiennych: {1}", controller.ToString2(), variables.Length));

                // znalezienie kontrolera

                // najpierw szukanie po ID
                foreach (DeviceInstance di in Manager.GetDevices(DeviceClass.GameControl, EnumDevicesFlags.AttachedOnly))
                {
                    if (di.InstanceGuid == controller.Id)
                    {
                        joystick = new Device(di.InstanceGuid);
                        break;
                    }
                }

                // później szukanie po Nazwie i numerze enumeracji
                if (joystick == null && controller.Index > -1)
                {
                    System.Diagnostics.Debug.WriteLine(string.Format("Szukanie joysticka po indeksie i nazwie, {0}", controller.ToString2()));

                    DeviceList list = Manager.GetDevices(DeviceClass.GameControl, EnumDevicesFlags.AttachedOnly);
                    if (list.Count > controller.Index)
                    {
                        int index = 0;
                        foreach (DeviceInstance di in list)
                        {
                            //if (index++ == controller.Index)
                            if (di.InstanceName == controller.Name)
                            {
                                //if (di.InstanceName == controller.Name)
                                if (index++ == controller.Index)
                                {
                                    System.Diagnostics.Debug.WriteLine(string.Format("Znaleziono szukany joystick {0}", controller.ToString2()));
                                    joystick = new Device(di.InstanceGuid);
                                }
                                break;
                            }
                        }
                    }
                }

                if (joystick == null)
                {
                    throw new Exception(string.Format("Nie znaleziono kontrolera '{0}' o parametrach: nazwa = '{1}', id = '{2}'.", controller.Alias, controller.Name, controller.Id));
                }

                // ustawienie urządzenia
                System.Diagnostics.Debug.WriteLine(string.Format("Konfiguracja kontrolera: {0}", controller.ToString2()));
                for (int i = 0; i < variables.Length; i++)
                {
                    variables[i].ConfigureController(joystick);
                }

                if (controller.UpdateType == UpdateStateType.ByEvent)
                {
                    AutoResetEvent e = new AutoResetEvent(false);
                    lock (_events)
                    {
                        _events.Add(e);
                    }
                    joystick.SetDataFormat(DeviceDataFormat.Joystick);
                    joystick.SetEventNotification(e);
                    joystick.SetCooperativeLevel(IntPtr.Zero, CooperativeLevelFlags.Background | CooperativeLevelFlags.NonExclusive);
                    joystick.Acquire();

                    Thread.Sleep(100);

                    // pierwsze użycie
                    JoystickState state = joystick.CurrentJoystickState;
                    for (int i = 0; i < variables.Length; i++)
                    {
                        variables[i].FirstCheckState(ref state);
                    }

                    while (_working)
                    {
                        joystick.Poll();
                        state = joystick.CurrentJoystickState;

                        for (int i = 0; i < variables.Length; i++)
                        {
                            variables[i].CheckState(ref state);
                        }

                        e.Reset();
                        e.WaitOne();
                    }
                }
                else
                {
                    joystick.SetDataFormat(DeviceDataFormat.Joystick);
                    joystick.SetCooperativeLevel(IntPtr.Zero, CooperativeLevelFlags.Background | CooperativeLevelFlags.NonExclusive);
                    joystick.Acquire();

                    Thread.Sleep(100);

                    // pierwsze użycie
                    JoystickState state = joystick.CurrentJoystickState;
                    for (int i = 0; i < variables.Length; i++)
                    {
                        variables[i].FirstCheckState(ref state);
                    }

                    System.Diagnostics.Debug.WriteLine(string.Format("Rozpoczęcie pętli odczytującej stan kontrolera ({0} ms): {1}", controller.ReadingStateInterval, controller.ToString2()));

                    while (_working)
                    {
                        joystick.Poll();
                        state = joystick.CurrentJoystickState;

                        for (int i = 0; i < variables.Length; i++)
                        {
                            variables[i].CheckState(ref state);
                        }

                        Thread.Sleep(controller.ReadingStateInterval);
                    }
                }
            }
            catch (ThreadAbortException)
            {
                System.Diagnostics.Debug.WriteLine(string.Format("Anulowano wątek obsługi kontrolera: {0}", controller.ToString2()));
            }
            catch (Exception ex)
            {
                _log.Log(this, ex.ToString());
            }
            finally
            {
                System.Diagnostics.Debug.WriteLine(string.Format("Kończenie obsługi kontrolera: {0}", controller.ToString2()));
                if (variables != null)
                {
                    for (int i = 0; i < variables.Length; i++)
                    {
                        variables[i].Clear(joystick);
                    }
                }

                if (joystick != null)
                {
                    try
                    {
                        joystick.Unacquire();
                    }
                    catch { }
                    try
                    {
                        joystick.Dispose();
                    }
                    catch { }
                    joystick = null;
                }
                System.Diagnostics.Debug.WriteLine(string.Format("Zakończono obsługę kontrolera: {0}", controller.ToString2()));
            }
        }
 void _simconnect_OnRecvOpen(SimConnect sender, SIMCONNECT_RECV_OPEN data)
 {
     _log.Log(this, "Connected to FSX");
 }
Exemple #12
0
        private void SendingThread()
        {
            bool connected = false;

            _Debug("Rozpoczęcie wykonywanie wątku wysyłającego dane.");
            IPEndPoint endPoint = new IPEndPoint(_configuration.Output.IP, _configuration.Output.Port);

            try
            {
                // próba połączenia
                _Debug("Próba połączenia z serwerem " + endPoint.ToString());
                _log.Log(this, "Próba połączenia z serwerem IOCP: " + endPoint.ToString());
                _tcp = null;
                IAsyncResult res = null;
                while (_working && (_tcp == null || !_tcp.Connected))
                {
                    try
                    {
                        if (_tcp == null)
                        {
                            _Debug("Tworzę obiekt TcpClient");
                            _tcp = new TcpClient();
                            _Debug("Rozpoczynam próbę łączenia");
                            res = _tcp.BeginConnect(_configuration.Output.IP, _configuration.Output.Port, null, null);
                            _Debug("Czekam 3s na połączenie");
                            res.AsyncWaitHandle.WaitOne(3000, true);
                        }
                        if (!_tcp.Connected && res.IsCompleted)
                        {
                            _Debug("Brak połączenia");
                            try
                            {
                                _Debug("Zamykam link TCP");
                                _tcp.Client.Close();
                            }
                            catch {}
                            _tcp = null;
                        }
                        else
                        {
                            _Debug("Połączono lub łączenie w toku");
                        }
                    }
                    catch (SocketException ex)
                    {
                        _Debug("Błąd przy łączeniu : " + ex.ToString());
                        _log.Log(this, "Błąd połączenia z serwerem IOCP: " + endPoint.ToString() + ", błąd: " + ex.Message);
                    }
                }
                if (_tcp != null && _tcp.Connected && _working)
                {
                    connected = true;
                    _Debug("Połączono, pobieram strumień");
                    _stream = _tcp.GetStream();
                    _log.Log(this, "Pomyślnie połączono z serwerem IOCP: " + endPoint.ToString());
                    List <Variable> vs = new List <Variable>();
                    _Debug("Pobrano strumień, rozpoczęcie pętli wysyłającej dane");
                    while (_working && _tcp.Client.Connected && _stream.CanWrite)
                    {
                        if (_event.WaitOne(3000))
                        {
                            _event.Reset();
                            lock (_variables)
                            {
                                while (_variables.Count > 0)
                                {
                                    vs.Add(_variables.Dequeue());
                                }
                            }
                            StringBuilder resp = new StringBuilder();
                            resp.Append("Arn.Resp:");
                            for (int i = 0; i < vs.Count; i++)
                            {
                                resp.Append(string.Format("{0}={1}:", vs[i].ID, vs[i].Value));
                            }
                            resp.Append("\r\n");
                            byte [] data = Encoding.ASCII.GetBytes(resp.ToString());
                            _stream.Write(data, 0, data.Length);
                            vs.Clear();
                        }
                        else
                        {
                            if (_tcp.Client.Poll(10, SelectMode.SelectRead))
                            {
                                break;
                            }
                        }
                    }
                }
                _Debug("Zakończono połączenie");
                //_log.Log(this, "Zakończono połączenie z serwerem IOCP: " + endPoint.ToString());
            }
            catch (Exception ex)
            {
                _Debug("Błąd: " + ex.ToString());
                if (!(ex is ThreadAbortException))
                {
                    _log.Log(this, "Błąd połączenia z serwerem IOCP: " + endPoint.ToString() + ", błąd: " + ex.Message);
                }
            }
            finally
            {
                if (_stream != null)
                {
                    try
                    {
                        _stream.Close();
                        _stream.Dispose();
                    }
                    catch { }
                    _stream = null;
                }
                if (_tcp != null)
                {
                    try
                    {
                        _tcp.Client.Disconnect(false);
                    }
                    catch { }
                    try
                    {
                        _tcp.Client.Close();
                    }
                    catch { }
                    try
                    {
                        _tcp.Close();
                    }
                    catch { }
                    _tcp = null;
                }
                if (connected)
                {
                    _log.Log(this, "Zakończono połączenie z serwerem IOCP: " + endPoint.ToString());
                }
            }
        }
Exemple #13
0
        private void ListeningThread()
        {
            IPEndPoint endPoint  = new IPEndPoint(_configuration.Input.IP, _configuration.Input.Port);
            bool       connected = false;

            try
            {
                // próba połączenia
                _log.Log(this, "Próba połączenia z serwerem IOCP: " + endPoint.ToString());
                _tcp = null;
                IAsyncResult res = null;
                while (_working && (_tcp == null || !_tcp.Connected))
                {
                    try
                    {
                        if (_tcp == null)
                        {
                            _tcp = new TcpClient();
                            res  = _tcp.BeginConnect(_configuration.Input.IP, _configuration.Input.Port, null, null);
                            res.AsyncWaitHandle.WaitOne(3000, true);
                        }
                        if (!_tcp.Connected && res.IsCompleted)
                        {
                            try
                            {
                                _tcp.Client.Close();
                            }
                            catch {}
                            _tcp = null;
                        }
                    }
                    catch (SocketException ex)
                    {
                        _log.Log(this, "Błąd połączenia z serwerem IOCP: " + endPoint.ToString() + ", błąd: " + ex.Message);
                    }
                }
                if (_tcp != null && _tcp.Connected && _working)
                {
                    _stream = _tcp.GetStream();
                    _log.Log(this, "Pomyślnie połączono z serwerem IOCP: " + endPoint.ToString());
                    connected = true;


                    // wysłanie informacji o śledzonych zmiennych
                    List <string> vars = new List <string>();
                    foreach (KeyValuePair <string, VariableEvent> kvp in _variablesListeners)
                    {
                        vars.Add(kvp.Key);
                    }
                    StreamWriter sw   = new StreamWriter(_stream);
                    StreamReader sr   = new StreamReader(_stream);
                    string       tmp  = string.Format("Arn.Inicio:{0}:\r\n", string.Join(":", vars.ToArray()));
                    byte []      data = Encoding.ASCII.GetBytes(tmp);
                    _stream.Write(data, 0, data.Length);
                    //sw.WriteLine(tmp);

                    string  red    = null;
                    char [] colons = new char[] { ':' };
                    char [] eq     = new char[] { '=' };
                    while ((red = sr.ReadLine()) != null)
                    {
                        if (red.StartsWith("Arn.Fin:"))
                        {
                            break;
                        }

                        if (red.StartsWith("Arn.Resp:"))
                        {
                            // odczytanie zmiennych i wartości
                            string [] sv = red.Split(colons, StringSplitOptions.RemoveEmptyEntries);
                            for (int i = 1; i < sv.Length; i++)
                            {
                                string [] nv = sv[i].Split(eq);
                                _variablesListeners[nv[0]].FireSignal(int.Parse(nv[1]));
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (!(ex is ThreadAbortException))
                {
                    //_log.Log(this, "Błąd połączenia z serwerem IOCP: " + endPoint.ToString() + ", błąd: " + ex.Message);
                }
            }
            finally
            {
                if (_stream != null)
                {
                    try
                    {
                        _stream.Close();
                        _stream.Dispose();
                    }
                    catch { }
                    _stream = null;
                }
                if (_tcp != null)
                {
                    try
                    {
                        _tcp.Client.Disconnect(false);
                    }
                    catch { }
                    try
                    {
                        _tcp.Client.Close();
                    }
                    catch { }
                    try
                    {
                        _tcp.Close();
                    }
                    catch { }
                    _tcp = null;
                }

                if (connected)
                {
                    _log.Log(this, "Zakończono połączenie z serwerem IOCP: " + endPoint.ToString());
                }
            }
        }
 public void Log(string text)
 {
     _log.Log(this, text);
 }
        private void SendingThread()
        {
            _Debug("Rozpoczęcie wykonywanie wątku wysyłającego dane.");
            IPEndPoint endPoint = new IPEndPoint(_configuration.Sender.ServerIP, _configuration.Sender.ServerPort);

            try
            {
                // próba połączenia
                _Debug("Próba połączenia z serwerem " + endPoint.ToString());
                _log.Log(this, "Próba połączenia z serwerem: " + endPoint.ToString());
                _tcp = null;
                IAsyncResult res = null;
                while (_working && (_tcp == null || !_tcp.Connected))
                {
                    try
                    {
                        if (_tcp == null)
                        {
                            _Debug("Tworzę obiekt TcpClient");
                            _tcp = new TcpClient();
                            _Debug("Rozpoczynam próbę łączenia");
                            res = _tcp.BeginConnect(_configuration.Sender.ServerIP, _configuration.Sender.ServerPort, null, null);
                            _Debug("Czekam 3s na połączenie");
                            res.AsyncWaitHandle.WaitOne(3000, true);
                        }
                        if (!_tcp.Connected && res.IsCompleted)
                        {
                            _Debug("Brak połączenia");
                            try
                            {
                                _Debug("Zamykam link TCP");
                                _tcp.Client.Close();
                            }
                            catch {}
                            _tcp = null;
                        }
                        else
                        {
                            _Debug("Połączono lub łączenie w toku");
                        }
                    }
                    catch (SocketException ex)
                    {
                        _Debug("Błąd przy łączeniu : " + ex.ToString());
                        _log.Log(this, "Błąd połączenia z serwerem: " + endPoint.ToString() + ", błąd: " + ex.Message);
                    }
                }
                if (_tcp != null && _tcp.Connected && _working)
                {
                    _Debug("Połączono, pobieram strumień");
                    _stream = _tcp.GetStream();
                    _log.Log(this, "Pomyślnie połączono z serwerem: " + endPoint.ToString());
                    List <Variable> vs = new List <Variable>();
                    _Debug("Pobrano strumień, rozpoczęcie pętli wysyłającej dane");
                    while (_working && _tcp.Client.Connected && _stream.CanWrite)
                    {
                        if (_event.WaitOne(3000))
                        {
                            _event.Reset();
                            lock (_variables)
                            {
                                while (_variables.Count > 0)
                                {
                                    vs.Add(_variables.Dequeue());
                                }
                            }
                            for (int i = 0; i < vs.Count; i++)
                            {
                                byte [] data = vs[i].Serialize();
                                // typ pakietu 1 - zmienna
                                _stream.WriteByte(1);
                                byte [] dataLenght = BitConverter.GetBytes(data.Length);
                                // długość danych
                                _stream.Write(dataLenght, 0, dataLenght.Length);
                                _stream.Write(data, 0, data.Length);
                            }
                            vs.Clear();
                        }
                        else
                        {
                            if (_tcp.Client.Poll(10, SelectMode.SelectRead))
                            {
                                break;
                            }
                        }
                    }
                }
                _Debug("Zakończono połączenie");
                _log.Log(this, "Zakończono połączenie z serwerem: " + endPoint.ToString());
            }
            catch (Exception ex)
            {
                _Debug("Błąd: " + ex.ToString());
                if (!(ex is ThreadAbortException))
                {
                    _log.Log(this, "Błąd połączenia z serwerem: " + endPoint.ToString() + ", błąd: " + ex.Message);
                }
            }
            finally
            {
                if (_stream != null)
                {
                    try
                    {
                        _stream.Close();
                        _stream.Dispose();
                    }
                    catch { }
                    _stream = null;
                }
                if (_tcp != null)
                {
                    try
                    {
                        _tcp.Client.Disconnect(false);
                    }
                    catch { }
                    try
                    {
                        _tcp.Client.Close();
                    }
                    catch { }
                    try
                    {
                        _tcp.Close();
                    }
                    catch { }
                    _tcp = null;
                }
            }
        }