Example #1
0
 /// <summary>
 /// Выполнить метод ProcUnreadIncomingReq для заданного КП с обработкой исключений
 /// </summary>
 protected bool ExecProcUnreadIncomingReq(KPLogic kpLogic, Connection conn, ref KPLogic targetKP)
 {
     try
     {
         return kpLogic.ProcUnreadIncomingReq(conn, ref targetKP);
     }
     catch (Exception ex)
     {
         WriteToLog((Localization.UseRussian ?
             "Ошибка при обработке не считанного входящего запроса: " :
             "Error processing unread incoming request: ") + ex.Message);
         targetKP = null;
         return false;
     }
 }
Example #2
0
 /// <summary>
 /// Обработать не считанный входящий запрос, относящийся к произвольному КП на линии связи
 /// </summary>
 /// <remarks>Если targetKP равен null, значит метод должен вернуть КП, которому адресован запрос. 
 /// Возвращает true, если запрос успешно считан и разобран.
 /// Метод выполняется в потоке канала связи</remarks>
 public virtual bool ProcUnreadIncomingReq(Connection conn, ref KPLogic targetKP)
 {
     WriteToLog("");
     WriteToLog(GetProcReqText(conn, targetKP));
     return false;
 }
Example #3
0
        /// <summary>
        /// Получить текст для вывода в журнал при обработке входящего запроса
        /// </summary>
        private string GetProcReqText(Connection conn, KPLogic targetKP)
        {
            StringBuilder sb = new StringBuilder(DateTime.Now.ToString(CommUtils.CommLineDTFormat));

            if (Localization.UseRussian)
            {
                sb.Append(" Обработка входящего запроса");
                if (targetKP != null)
                {
                    sb.Append(" от ");
                    AppendKPDescr(sb);
                }
                if (!string.IsNullOrEmpty(conn.RemoteAddress))
                    sb.Append(", удалённый адрес: ").Append(conn.RemoteAddress);
            }
            else
            {
                sb.Append(" Process incoming request");
                if (targetKP != null)
                {
                    sb.Append(" from the ");
                    AppendKPDescr(sb);
                }
                if (!string.IsNullOrEmpty(conn.RemoteAddress))
                    sb.Append(", remote address: ").Append(conn.RemoteAddress);
            }

            return sb.ToString();
        }
Example #4
0
        private Log.WriteLineDelegate writeToLog; // метод записи в журнал линии связи

        #endregion Fields

        #region Constructors

        /// <summary>
        /// Конструктор
        /// </summary>
        public KPLogic(int number)
        {
            // private fields
            conn = null;
            appDirs = new AppDirs();
            writeToLog = text => { }; // заглушка
            terminated = false;
            caption = "";
            sessText = "";
            sendCmdText = "";
            tagTable = null;
            tagTableColLen = null;

            // protected fields
            curData = new SrezTableLight.CnlData[0];
            curDataModified = new bool[0];
            arcSrezList = new List<TagSrez>();
            eventList = new List<KPEvent>();
            lastArcSrezList = new List<TagSrez>();
            lastEventList = new List<KPEvent>();
            lastCmdList = new List<Command>();
            lastCommSucc = false;
            kpStats.Reset();

            // public properties
            Bind = false;
            Number = number;
            Name = "";
            Dll = Assembly.GetCallingAssembly().GetName().Name;
            Address = 0;
            CallNum = "";
            ReqParams = KPReqParams.Default;
            ReqTriesCnt = 1;
            SerialPort = null;
            CustomParams = null;
            CommonProps = null;
            CommLineSvc = null;

            CanSendCmd = false;
            ConnRequired = true;
            KPTags = new KPTag[0];
            TagGroups = new TagGroup[0];
            WorkState = WorkStates.Undefined;
            LastSessDT = DateTime.MinValue;
            LastCmdDT = DateTime.MinValue;
        }
Example #5
0
        /// <summary>
        /// Считать строки
        /// </summary>
        public override List<string> ReadLines(int timeout, Connection.TextStopCondition stopCond, 
            out bool stopReceived, out string logText)
        {
            try
            {
                List<string> lines = new List<string>();
                stopReceived = false;

                DateTime nowDT = DateTime.Now;
                DateTime startDT = nowDT;
                DateTime stopDT = startDT.AddMilliseconds(timeout);
                SerialPort.ReadTimeout = 0;

                while (!stopReceived && startDT <= nowDT && nowDT <= stopDT)
                {
                    string line;
                    try { line = SerialPort.ReadLine().Trim(); }
                    catch (TimeoutException) { line = ""; }

                    if (line != "")
                    {
                        lines.Add(line);
                        stopReceived = stopCond.CheckCondition(lines, line);
                    }

                    // накопление входных данных в буфере порта
                    if (!stopReceived)
                        Thread.Sleep(DataAccumThreadDelay);

                    nowDT = DateTime.Now;
                }

                logText = BuildReadLinesLogText(lines);
                return lines;
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException(CommPhrases.ReadLinesError + ": " + ex.Message, ex);
            }
        }
Example #6
0
        /// <summary>
        /// Считать данные с условиями остановки чтения
        /// </summary>
        public override int Read(byte[] buffer, int offset, int maxCount, int timeout, Connection.BinStopCondition stopCond, 
            out bool stopReceived, CommUtils.ProtocolLogFormats logFormat, out string logText)
        {
            try
            {
                int readCnt = 0;
                DateTime nowDT = DateTime.Now;
                DateTime startDT = nowDT;
                DateTime stopDT = startDT.AddMilliseconds(timeout);

                stopReceived = false;
                byte stopCode = stopCond.StopCode;
                int curInd = offset;
                SerialPort.ReadTimeout = 0;

                while (readCnt <= maxCount && !stopReceived && startDT <= nowDT && nowDT <= stopDT)
                {
                    bool readOk;
                    try { readOk = SerialPort.Read(buffer, curInd, 1) > 0; }
                    catch (TimeoutException) { readOk = false; }

                    if (readOk)
                    {
                        stopReceived = buffer[curInd] == stopCode;
                        curInd++;
                        readCnt++;
                    }
                    else
                    {
                        // накопление входных данных в буфере порта
                        Thread.Sleep(DataAccumThreadDelay);
                    }

                    nowDT = DateTime.Now;
                }

                logText = BuildReadLogText(buffer, offset, readCnt, logFormat);
                return readCnt;
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException(CommPhrases.ReadDataWithStopCondError + ": " + ex.Message, ex);
            }
        }