示例#1
0
        /*
         * private void TCPListenerThread()
         * {
         *  try
         *  {
         *      _tcpListener = new TcpListener(IPAddress.Any, _tcpIpPort);
         *      _tcpListener.Start();
         *      Debug.Print("TCP Listener starting");
         *      while (!_shutdown)
         *      {
         *          Debug.Print("TCP Listener waiting for client");
         *          var tcpClient = _tcpListener.AcceptTcpClient();
         *          Debug.Print("TCP Listener contacted by client");
         *          if (_tcpClient == null)
         *          {
         *              //old client vanished? Assign new.
         *              Debug.Print("TCP Listener starting clients thread");
         *              _tcpClient = tcpClient;
         *              _tcpClientThread = new Thread(() => TCPReaderThread(_tcpClient.GetStream()));
         *              _tcpClientThread.Start();
         *          }
         *      }
         *  }
         *  catch (Exception e)
         *  {
         *      DBCommon.LogError(211, e, "StartServer()");
         *  }
         * }
         */

        private void TCPReaderThread(NetworkStream stream)
        {
            while (_shutdown)
            {
                try
                {
                    if (stream == null)
                    {
                        return;
                    }
                    var byteData = new byte[1024];
                    stream.Read(byteData, 0, byteData.Length);
                    try
                    {
                        Debug.Print("DCS-BIOS data received over TCP");
                        if ((_dcsBiosNotificationMode & DcsBiosNotificationMode.AddressValue) == DcsBiosNotificationMode.AddressValue)
                        {
                            _dcsProtocolParser.AddArray(byteData);
                        }
                    }
                    catch (Exception e)
                    {
                        DBCommon.LogError(9231, e, "Encoding.Default.GetString(readArray)");
                    }
                }
                catch (Exception e)
                {
                    DBCommon.LogError(93211, e, "ServerReadThreadProc()");
                }
            }
            Debug.Print("TCP Listener ServerReadThreadProc returning");
        }
示例#2
0
 private void ExtractDCSBIOSOutputsInFormula()
 {
     try
     {
         var found    = false;
         var controls = DCSBIOSControlLocator.GetControls();
         foreach (var dcsbiosControl in controls)
         {
             if (_formula.Contains(dcsbiosControl.identifier))
             {
                 //   Console.WriteLine("Variable " + dcsbiosControl.identifier + " set to 0");
                 _variables.Add(dcsbiosControl.identifier, 0);
                 var dcsbiosOutput = DCSBIOSControlLocator.GetDCSBIOSOutput(dcsbiosControl.identifier);
                 _dcsbiosOutputs.Add(dcsbiosOutput);
                 DCSBIOSProtocolParser.RegisterAddressToBroadCast(dcsbiosOutput.Address);
                 found = true;
             }
         }
         if (!found)
         {
             throw new Exception("Could not find any DCS-BIOS Controls in formula expression.");
         }
         //_expression = new Expression(_formula);
     }
     catch (Exception ex)
     {
         DBCommon.LogError(1955594, ex, "ExtractDCSBIOSOutputsInFormula() function");
         throw;
     }
 }
示例#3
0
 public uint GetUIntValue(uint data)
 {
     if (_debug)
     {
         DBCommon.DebugP(ToDebugString() + "    >>        Data is : " + data);
     }
     lock (_lockObject)
     {
         return((data & Mask) >> Shiftvalue);
     }
 }
示例#4
0
        public void Shutdown()
        {
            try
            {
                try
                {
                    _shutdown = true;
                    DBCommon.DebugP("DCSBIOS is SHUTTING DOWN");
                    _dcsProtocolParser.Shutdown();
                    _dcsbiosListeningThread?.Abort();
                }
                catch (Exception)
                {
                }
                try
                {
                    _udpReceiveClient.Close();
                }
                catch (Exception)
                {
                }
                try
                {
                    _udpSendClient.Close();
                }
                catch (Exception)
                {
                }

                /*
                 * try
                 * {
                 *  _tcpListener.Stop();
                 * }
                 * catch (Exception)
                 * {
                 * }
                 * try
                 * {
                 *  _tcpClient.Close();
                 * }
                 * catch (Exception)
                 * {
                 * }
                 */
                _started = false;
            }
            catch (Exception ex)
            {
                SetLastException(ex);
                DBCommon.LogError(9212, ex, "DCSBIOS.Shutdown()");
            }
        }
示例#5
0
 private void ProcessArrays()
 {
     try
     {
         var interval = 0;
         DBCommon.DebugP("ProtocolParser starting processing loop");
         while (!_shutdown)
         {
             try
             {
                 if (interval >= 100)
                 {
                     //Debug.Print("_arraysToProcess.Count = " + _arraysToProcess.Count);
                     interval = 0;
                 }
                 //lock (_lockArrayToProcess)
                 //{
                 byte[] array = null;
                 while (_arraysToProcess.TryDequeue(out array))
                 {
                     if (array != null)
                     {
                         for (int i = 0; i < array.Length; i++)
                         {
                             ProcessByte(array[i]);
                         }
                     }
                 }
                 //}
                 interval++;
             }
             catch (Exception e)
             {
                 DBCommon.LogError(9243, e, "DCSBIOSProtocolParser.ProcessArrays(), arrays to process : " + _arraysToProcess.Count);
             }
             _autoResetEvent.WaitOne();
         }
         DBCommon.DebugP("ProtocolParser exiting processing loop");
     }
     catch (ThreadAbortException) { }
     catch (Exception e)
     {
         DBCommon.LogError(9244, e, "DCSBIOSProtocolParser.ProcessArrays(), arrays to process : " + _arraysToProcess.Count);
     }
 }
示例#6
0
 public int Evaluate()
 {
     try
     {
         /*Console.WriteLine("_formula : " + _formula);
          * foreach (var variable in _variables)
          * {
          *  Console.WriteLine("variable : " + variable.Key + " = " + variable.Value);
          * }*/
         var a = _engine.Calculate(_formula, _variables);
         return(Convert.ToInt32(a));
     }
     catch (Exception ex)
     {
         DBCommon.LogError(1033494, ex, "Evaluate() function");
         throw;
     }
 }
示例#7
0
        public override string ToString()
        {
            /*
             * fixed_step = <INC/DEC>
             * set_state = <integer>
             * action = TOGGLE
             */
            try
            {
                switch (_selectedDCSBIOSInput.Interface)
                {
                case DCSBIOSInputType.FIXED_STEP:
                {
                    return("DCSBIOSInput{" + _controlId + "|FIXED_STEP|" + _selectedDCSBIOSInput.SpecifiedFixedStepArgument + "}");
                }

                case DCSBIOSInputType.SET_STATE:
                {
                    return("DCSBIOSInput{" + _controlId + "|SET_STATE|" + _selectedDCSBIOSInput.SpecifiedSetStateArgument + "}");
                }

                case DCSBIOSInputType.ACTION:
                {
                    return("DCSBIOSInput{" + _controlId + "|ACTION|" + _selectedDCSBIOSInput.SpecifiedActionArgument + "}");
                }

                case DCSBIOSInputType.VARIABLE_STEP:
                {
                    return("DCSBIOSInput{" + _controlId + "|VARIABLE_STEP|" + _selectedDCSBIOSInput.SpecifiedVariableStepArgument + "}");
                }
                }
            }
            catch (Exception ex)
            {
                DBCommon.LogError(78311, ex, "Error in DCSBIOSInput.ToString(), ControlId = " + _controlId);
                throw;
            }
            return("SHOULD NEVER ARRIVE HERE");
        }
示例#8
0
 public void ReceiveDataUdp()
 {
     try
     {
         DBCommon.DebugP("DCSBIOS entering threaded receive data loop");
         while (!_shutdown)
         {
             var byteData = _udpReceiveClient.Receive(ref _ipEndPointReceiverUdp);
             if ((_dcsBiosNotificationMode & DcsBiosNotificationMode.AddressValue) == DcsBiosNotificationMode.AddressValue)
             {
                 _dcsProtocolParser.AddArray(byteData);
             }
         }
         DBCommon.DebugP("DCSBIOS exiting threaded receive data loop");
     }
     catch (ThreadAbortException) { }
     catch (Exception e)
     {
         SetLastException(e);
         DBCommon.LogError(9213, e, "DCSBIOS.ReceiveData()");
     }
 }
示例#9
0
 /*
  * private static byte[] GetBytes(string str)
  * {
  *  var bytes = new byte[str.Length * sizeof(char)];
  *  Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
  *  return bytes;
  * }
  *
  * private static string GetString(byte[] bytes)
  * {
  *  var chars = new char[bytes.Length / sizeof(char)];
  *  Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
  *  return new string(chars);
  * }
  */
 private void SetLastException(Exception ex)
 {
     try
     {
         if (ex == null)
         {
             return;
         }
         DBCommon.LogError(666, ex, "Via DCSBIOS.SetLastException()");
         var message = ex.GetType() + Environment.NewLine + ex.Message + Environment.NewLine + ex.StackTrace;
         if (DBCommon.Debug)
         {
             DBCommon.DebugP(message);
         }
         lock (_lockExceptionObject)
         {
             _lastException = new Exception(message);
         }
     }
     catch (Exception)
     {
     }
 }
示例#10
0
        public int SendDataFunction(string stringData)
        {
            var result = 0;

            lock (_lockObjectForSendingData)
            {
                try
                {
                    //byte[] bytes = _iso8859_1.GetBytes(stringData);
                    var unicodeBytes = Encoding.Unicode.GetBytes(stringData);
                    var asciiBytes   = new List <byte>(stringData.Length);
                    asciiBytes.AddRange(Encoding.Convert(Encoding.Unicode, Encoding.ASCII, unicodeBytes));
                    result = _udpSendClient.Send(asciiBytes.ToArray(), asciiBytes.ToArray().Length, _ipEndPointSenderUdp);
                    //result = _udpSendClient.Send(bytes, bytes.Length, _ipEndPointSender);
                }
                catch (Exception e)
                {
                    DBCommon.DebugP("Error sending data to DCS-BIOS. " + e.Message + Environment.NewLine + e.StackTrace);
                    SetLastException(e);
                    DBCommon.LogError(9216, e, "DCSBIOS.SendDataFunction()");
                }
            }
            return(result);
        }
示例#11
0
 //Returns true if address was found in formula
 //If true do a subsequent call to Evaluate() to get new value
 public bool CheckForMatch(uint address, uint data)
 {
     try
     {
         var result = false;
         foreach (var dcsbiosOutput in _dcsbiosOutputs)
         {
             if (dcsbiosOutput.Address == address)
             {
                 dcsbiosOutput.CheckForValueMatchAndChange(data);
                 result = true;
                 //Console.WriteLine("Variable " + dcsbiosOutput.ControlId + " set to " + dcsbiosOutput.LastIntValue);
                 _variables[dcsbiosOutput.ControlId] = dcsbiosOutput.LastIntValue;
                 //_expression.Parameters[dcsbiosOutput.ControlId] = dcsbiosOutput.LastIntValue;
             }
         }
         return(result);
     }
     catch (Exception ex)
     {
         DBCommon.LogError(1933494, ex, "CheckForMatch() function");
         throw;
     }
 }
        private void UpdateStrings(uint address, uint data)
        {
            //Common.DebugP("**********Received address 0x" + address.ToString("x") + " ****************");
            lock (_lockObject)
            {
                if (address == 0x55)
                {
                    //start of update cycle
                    return;
                }
                if (address == 0xfffe)
                {
                    //end of update cycle, clear all existing values.
                    //broadcast every string now
                    if (OnDCSBIOSStringReceived != null)
                    {
                        foreach (var kvp in _dcsBiosStrings)
                        {
                            //kvp.Value.Address == start address for the string
                            if (kvp.Value.IsComplete)
                            {
                                OnDCSBIOSStringReceived(kvp.Value.Address, kvp.Value.StringValue);
                            }
                        }
                    }
                }
                else
                {
                    foreach (var kvp in _dcsBiosStrings)
                    {
                        if (kvp.Value.IsMatch(address))
                        {
                            try
                            {
                                //Send "AB"
                                //0x4241
                                //41 = A
                                //42 = B
                                var hex = Convert.ToString(data, 16);

                                //Little Endian !
                                var secondByte = new[] { Convert.ToByte(hex.Substring(0, 2), 16) };
                                var firstByte  = new[] { Convert.ToByte(hex.Substring(2, 2), 16) };
                                var firstChar  = _iso8859_1.GetString(firstByte);
                                var secondChar = _iso8859_1.GetString(secondByte);
                                kvp.Value.Add(address, firstChar, secondChar);
                                //Common.DebugP("**********Received (0x" + data.ToString("x") + ") ****************");
                                //Common.DebugP("**********Received data:(0x" + data.ToString("x") + ") following from DCS : 1st : " + firstChar + "(0x" + firstByte[0].ToString("x") + "), 2nd " + secondChar + "(0x" + secondByte[0].ToString("x") + ") ****************");

                                //kvp.Value.StepUp();
                            }
                            catch (Exception ex)
                            {
                                DBCommon.DebugP("**********Received (0x" + data.ToString("x") + ") Exception = " + ex.Message + Environment.NewLine + ex.StackTrace);
                                throw;
                            }
                        }
                    }
                }
            }
        }
        public static void LoadControls()
        {
            if (_airframe == DCSAirframe.NONE || _airframe == DCSAirframe.NOFRAMELOADEDYET)
            {
                return;
            }
            if (_dcsbiosControls.Count > 0 && !_airFrameChanged)
            {
                return;
            }
            _dcsbiosControls = new List <DCSBIOSControl>();
            try
            {
                lock (_lockObject)
                {
                    //Always read CommonData.json
                    var directoryInfo = new DirectoryInfo(_jsonDirectory);
                    IEnumerable <FileInfo> files;
                    try
                    {
                        DBCommon.DebugP("Searching for " + _airframe.GetDescription() + ".json in directory " + _jsonDirectory);
                        try
                        {
                            files = directoryInfo.EnumerateFiles(_airframe.GetDescription() + ".json", SearchOption.TopDirectoryOnly);
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Failed to find DCS-BIOS files. -> " + Environment.NewLine + ex.Message);
                        }
                        foreach (var file in files)
                        {
                            DBCommon.DebugP("Opening " + file.DirectoryName + "\\" + file.Name);
                            var    reader = file.OpenText();
                            string text;
                            try
                            {
                                text = reader.ReadToEnd();
                            }
                            finally
                            {
                                reader.Close();
                            }

                            var jsonData = DCSBIOSJsonFormatterVersion1.Format(text);

                            /*var newfile = File.CreateText(@"e:\temp\regexp_debug_output.txt.txt");
                             * newfile.Write(jsonData);
                             * newfile.Close();*/
                            var dcsBiosControlList = JsonConvert.DeserializeObject <DCSBIOSControlRootObject>(jsonData);
                            _dcsbiosControls.AddRange(dcsBiosControlList.DCSBIOSControls);
                        }
                        var commonDataText         = File.ReadAllText(_jsonDirectory + "\\CommonData.json");
                        var commonDataControlsText = DCSBIOSJsonFormatterVersion1.Format(commonDataText);
                        var commonDataControls     = JsonConvert.DeserializeObject <DCSBIOSControlRootObject>(commonDataControlsText);
                        _dcsbiosControls.AddRange(commonDataControls.DCSBIOSControls);


                        var metaDataEndText         = File.ReadAllText(_jsonDirectory + "\\MetadataEnd.json");
                        var metaDataEndControlsText = DCSBIOSJsonFormatterVersion1.Format(metaDataEndText);
                        var metaDataEndControls     = JsonConvert.DeserializeObject <DCSBIOSControlRootObject>(metaDataEndControlsText);
                        _dcsbiosControls.AddRange(metaDataEndControls.DCSBIOSControls);
                        _airFrameChanged = false;
                    }
                    finally
                    {
                        //nada
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("LoadControls() : " + Environment.NewLine + ex.Message + Environment.NewLine + ex.StackTrace);
            }
        }
示例#14
0
        public void Startup()
        {
            try
            {
                /*
                 *  None, do as normal.
                 */

                /*
                 *  Client, try establish connection to the master FP on the network every two seconds. After connection listen to data from master and add that to the arraysToProcess queue.
                 */

                /*
                 *  Master, start listening TCP socket, for every client contacting via TCP add them as clients and send raw DCS-BIOS data to them
                 */

                if (_started)
                {
                    return;
                }
                _shutdown = false;
                DBCommon.DebugP("DCSBIOS is STARTING UP");
                _dcsProtocolParser = DCSBIOSProtocolParser.GetParser();
                _dcsProtocolParser.Attach(_iDcsBiosDataListener);

                _ipEndPointReceiverUdp = new IPEndPoint(IPAddress.Any, ReceivePort);
                _ipEndPointSenderUdp   = new IPEndPoint(IPAddress.Parse(SendToIp), SendPort);

                _udpReceiveClient = new UdpClient();
                _udpReceiveClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                _udpReceiveClient.Client.Bind(_ipEndPointReceiverUdp);
                _udpReceiveClient.JoinMulticastGroup(IPAddress.Parse(ReceiveFromIp));

                _udpSendClient = new UdpClient();
                _udpSendClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                _udpSendClient.EnableBroadcast = true;

                _dcsbiosListeningThread?.Abort();
                _dcsbiosListeningThread = new Thread(ReceiveDataUdp);
                _dcsbiosListeningThread.Start();
                _dcsProtocolParser.Startup();

                //_tcpListeningThread = new Thread(TCPListenerThread);
                //_tcpListeningThread.Start();


                if (!_started)
                {
                    _started = true;
                }
            }
            catch (Exception e)
            {
                SetLastException(e);
                DBCommon.LogError(9211, e, "DCSBIOS.Startup()");
                if (_udpReceiveClient != null && _udpReceiveClient.Client.Connected)
                {
                    _udpReceiveClient.Close();
                    _udpReceiveClient = null;
                }
                if (_udpSendClient != null && _udpSendClient.Client.Connected)
                {
                    _udpSendClient.Close();
                    _udpSendClient = null;
                }

                /*if (_tcpListener != null)
                 * {
                 *  _tcpListener.Stop();
                 *  _tcpListener = null;
                 * }
                 * if (_tcpClient != null)
                 * {
                 *  _tcpClient.Close();
                 *  _tcpClient = null;
                 * }*/
            }
        }
示例#15
0
 public void Shutdown()
 {
     DBCommon.DebugP("ProtocolParser shutting down");
     _shutdown = true;
     _autoResetEvent.Set();
 }
示例#16
0
 public void Startup()
 {
     DBCommon.DebugP("ProtocolParser starting up");
     _processingThread = new Thread(ProcessArrays);
     _processingThread.Start();
 }
示例#17
0
        internal void ProcessByte(byte b)
        {
            try
            {
                switch (_state)
                {
                case DCSBiosStateEnum.WAIT_FOR_SYNC:
                    /* do nothing */
                    break;

                case DCSBiosStateEnum.ADDRESS_LOW:
                    _address = b;
                    _state   = DCSBiosStateEnum.ADDRESS_HIGH;
                    break;

                case DCSBiosStateEnum.ADDRESS_HIGH:
                    _address = (uint)(b << 8) | _address;
                    _state   = _address != 0x5555 ? DCSBiosStateEnum.COUNT_LOW : DCSBiosStateEnum.WAIT_FOR_SYNC;
                    break;

                case DCSBiosStateEnum.COUNT_LOW:
                    _count = b;
                    _state = DCSBiosStateEnum.COUNT_HIGH;
                    break;

                case DCSBiosStateEnum.COUNT_HIGH:
                    _count = (uint)(b << 8) | _count;
                    _state = DCSBiosStateEnum.DATA_LOW;
                    break;

                case DCSBiosStateEnum.DATA_LOW:
                    _data = b;
                    _count--;
                    _state = DCSBiosStateEnum.DATA_HIGH;
                    break;

                case DCSBiosStateEnum.DATA_HIGH:
                    _data = (uint)(b << 8) | _data;
                    _count--;
                    //_iDcsBiosDataListener.DcsBiosDataReceived(_address, _data);
                    if (OnDcsDataAddressValue != null && IsBroadcastable(_address))
                    {
                        OnDcsDataAddressValue(_address, _data);
                    }
                    _address += 2;
                    if (_count == 0)
                    {
                        _state = DCSBiosStateEnum.ADDRESS_LOW;
                    }
                    else
                    {
                        _state = DCSBiosStateEnum.DATA_LOW;
                    }
                    break;
                }
                if (b == 0x55)
                {
                    //Console.WriteLine(Environment.TickCount - ticks);
                    //ticks = Environment.TickCount;
                    _syncByteCount++;
                }
                else
                {
                    _syncByteCount = 0;
                }
                if (_syncByteCount == 4)
                {
                    _state         = DCSBiosStateEnum.ADDRESS_LOW;
                    _syncByteCount = 0;
                }
            }
            catch (Exception e)
            {
                DBCommon.LogError(924094, e, "DCSBIOSProtocolParser.ProcessByte()");
            }
        }