示例#1
0
 /// <summary>
 /// Reads data with the stop condition.
 /// </summary>
 public override int Read(byte[] buffer, int offset, int maxCount, int timeout, BinStopCondition stopCond,
                          out bool stopReceived, ProtocolFormat format, out string logText)
 {
     stopReceived = false;
     logText      = "";
     return(0);
 }
        public static string ProtocolFormatToUserDisplayString(ProtocolFormat format)
        {
            string result = "";

            switch (format)
            {
            case ProtocolFormat.RoboSepS_1_0:
                result = SeparatorResourceManager.GetSeparatorString(StringId.RoboSepS_1_0);
                break;

            case ProtocolFormat.RoboSepS_1_1:
                result = SeparatorResourceManager.GetSeparatorString(StringId.RoboSepS_1_1);
                break;

            case ProtocolFormat.RoboSepS_1_2:
                result = SeparatorResourceManager.GetSeparatorString(StringId.RoboSepS_1_2);
                break;

            case ProtocolFormat.RoboSep16:
                result = SeparatorResourceManager.GetSeparatorString(StringId.RoboSep16);
                break;

            case ProtocolFormat.RoboSep16_1_2:
                result = SeparatorResourceManager.GetSeparatorString(StringId.RoboSep16_1_2);
                break;
            }
            return(result);
        }
        /// <summary>
        /// Reads data.
        /// </summary>
        public override int Read(byte[] buffer, int offset, int count, int timeout,
                                 ProtocolFormat format, out string logText)
        {
            try
            {
                // this read method avoids ObjectDisposedException when the thread is aborted
                int readCnt = 0;
                SerialPort.ReadTimeout = 0;
                Stopwatch stopwatch = Stopwatch.StartNew();

                while (readCnt < count && stopwatch.ElapsedMilliseconds <= timeout)
                {
                    try { readCnt += SerialPort.Read(buffer, offset + readCnt, count - readCnt); }
                    catch (TimeoutException) { }

                    // accumulate data in the internal port buffer
                    if (readCnt < count)
                    {
                        Thread.Sleep(DataAccumDelay);
                    }
                }

                logText = BuildReadLogText(buffer, offset, count, readCnt, format);
                return(readCnt);
            }
            catch (Exception ex)
            {
                throw new ScadaException(CommPhrases.ReadDataError + ": " + ex.Message, ex);
            }
        }
示例#4
0
        /// <summary>
        /// Reads data with the stop condition.
        /// </summary>
        public override int Read(byte[] buffer, int offset, int maxCount, int timeout, BinStopCondition stopCond,
                                 out bool stopReceived, ProtocolFormat format, out string logText)
        {
            try
            {
                int        readCnt  = 0;
                IPEndPoint endPoint = CreateRemoteEndPoint();
                stopReceived = false;
                UdpClient.Client.ReceiveTimeout = DatagramReceiveTimeout;
                Stopwatch stopwatch = Stopwatch.StartNew();

                while (readCnt < maxCount && !stopReceived && stopwatch.ElapsedMilliseconds <= timeout)
                {
                    // read data
                    byte[] datagram = ReceiveDatagram(ref endPoint, out int readPos, out bool isNew);

                    if (datagram != null && datagram.Length > 0)
                    {
                        // search for stop code
                        int stopCodeInd = -1;

                        for (int i = readPos, len = datagram.Length; i < len && !stopReceived; i++)
                        {
                            if (stopCond.CheckCondition(datagram, i))
                            {
                                stopCodeInd  = i;
                                stopReceived = true;
                            }
                        }

                        // copy received data to the buffer
                        int requiredCnt = stopReceived ? stopCodeInd - readCnt + 1 : maxCount - readCnt;
                        int copyCnt     = Math.Min(datagram.Length - readPos, requiredCnt);
                        Buffer.BlockCopy(datagram, readPos, buffer, readCnt + offset, copyCnt);
                        readCnt += copyCnt;
                        readPos += copyCnt;
                    }

                    // accumulate data in the internal connection buffer
                    if (readCnt < maxCount && !stopReceived && isNew)
                    {
                        Thread.Sleep(DataAccumDelay);
                    }

                    StoreDatagram(datagram, readPos);
                }

                logText = BuildReadLogText(buffer, offset, readCnt, format);
                return(readCnt);
            }
            catch (Exception ex)
            {
                throw new ScadaException(CommPhrases.ReadDataStopCondError + ": " + ex.Message, ex);
            }
        }
        public static bool isPlatformRS16(ProtocolFormat format)
        {
            bool result = false;

            switch (format)
            {
            case ProtocolFormat.RoboSep16:
            case ProtocolFormat.RoboSep16_1_2:
                result = true;
                break;
            }
            return(result);
        }
示例#6
0
 /// <summary>
 /// Writes the specified data.
 /// </summary>
 public override void Write(byte[] buffer, int offset, int count, ProtocolFormat format, out string logText)
 {
     try
     {
         NetStream.Write(buffer, offset, count);
         logText = BuildWriteLogText(buffer, offset, count, format);
     }
     catch (IOException ex)
     {
         logText = CommPhrases.WriteDataError + ": " + ex.Message;
     }
     catch (Exception ex)
     {
         throw new ScadaException(CommPhrases.WriteDataError + ": " + ex.Message, ex);
     }
 }
示例#7
0
        /// <summary>
        /// Reads data.
        /// </summary>
        public override int Read(byte[] buffer, int offset, int count, int timeout,
                                 ProtocolFormat format, out string logText)
        {
            try
            {
                int        readCnt  = 0;
                IPEndPoint endPoint = CreateRemoteEndPoint();
                UdpClient.Client.ReceiveTimeout = DatagramReceiveTimeout;
                Stopwatch stopwatch = Stopwatch.StartNew();

                while (readCnt < count && stopwatch.ElapsedMilliseconds <= timeout)
                {
                    // read data
                    byte[] datagram = ReceiveDatagram(ref endPoint, out int readPos, out bool isNew);

                    // copy received data to the buffer
                    if (datagram != null && datagram.Length > 0)
                    {
                        int requiredCnt = count - readCnt; // left to read
                        int copyCnt     = Math.Min(datagram.Length - readPos, requiredCnt);
                        Buffer.BlockCopy(datagram, readPos, buffer, readCnt + offset, copyCnt);
                        readCnt += copyCnt;
                        readPos += copyCnt;
                    }

                    // accumulate data in the internal connection buffer
                    if (readCnt < count && isNew)
                    {
                        Thread.Sleep(DataAccumDelay);
                    }

                    StoreDatagram(datagram, readPos);
                }

                logText = BuildReadLogText(buffer, offset, count, readCnt, format);
                return(readCnt);
            }
            catch (SocketException ex)
            {
                logText = CommPhrases.ReadDataError + ": " + ex.Message;
                return(0);
            }
            catch (Exception ex)
            {
                throw new ScadaException(CommPhrases.ReadDataError + ": " + ex.Message, ex);
            }
        }
示例#8
0
        Dictionary <string, string> LoadReplyFile(string fileName)
        {
            Dictionary <string, string> dict = new Dictionary <string, string>();

            string[] lines = Files.ReadLines(fileName, true);
            string[] item;
            for (int i = 0; i < lines.Length; i++)
            {
                item = lines[i].Split(new string[] { @"\->" }, StringSplitOptions.RemoveEmptyEntries);
                if (item.Length == 2)
                {
                    dict.Add(BitConverter.ToString(ProtocolFormat.Format(item[0], Settings.Connection.UsedEncoding)), item[1]);
                }
            }

            return(dict);
        }
示例#9
0
        /// <summary>
        /// Process input data
        /// </summary>
        /// <param name="input">Input string</param>
        /// <returns>Packet bytes</returns>
        private byte[] processInput(string input)
        {
            var arguments = input.Split(new string[] { ";" }, StringSplitOptions.None);

            if (arguments.Length >= 2)
            {
                return(newPacket(Conv.ToInt(arguments[0], 0), ProtocolFormat.Format(arguments[1], Encoding.UTF8)));
            }
            else if (arguments.Length >= 1)
            {
                return(newPacket(0, ProtocolFormat.Format(arguments[0], Encoding.UTF8)));
            }
            else
            {
                return(new byte[0]);
            }
        }
示例#10
0
        public byte[] AcknowledgeReception(byte[] message)
        {
            if (message.Length > 2)
            {
                int frameNum = 0;
                try
                {
                    int frame  = Conv.SwapBytes(BitConverter.ToUInt16(message, 0));
                    int length = (frame & 2047) - 6; // dala length
                    frameNum = (frame & 12288) + 6 + (128 << 8) + +(1 << 8);
                }
                catch (Exception) { }

                return(ProtocolFormat.Format(@"\s" + frameNum.ToString(), Encoding.UTF8));
            }
            return(new byte[0]);
        }
示例#11
0
        /// <summary>
        /// Reads data with the stop condition.
        /// </summary>
        public override int Read(byte[] buffer, int offset, int maxCount, int timeout, BinStopCondition stopCond,
                                 out bool stopReceived, ProtocolFormat format, out string logText)
        {
            try
            {
                int readCnt   = 0;
                int curOffset = offset;
                stopReceived          = false;
                NetStream.ReadTimeout = OneByteReadTimeout;
                Stopwatch stopwatch = Stopwatch.StartNew();

                while (readCnt < maxCount && !stopReceived && stopwatch.ElapsedMilliseconds <= timeout)
                {
                    // read one byte
                    bool readOk;
                    try { readOk = NetStream.DataAvailable && NetStream.Read(buffer, curOffset, 1) > 0; }
                    catch (IOException) { readOk = false; }

                    if (readOk)
                    {
                        stopReceived = stopCond.CheckCondition(buffer, curOffset);
                        curOffset++;
                        readCnt++;
                    }
                    else
                    {
                        Thread.Sleep(DataAccumDelay);
                    }
                }

                logText = BuildReadLogText(buffer, offset, readCnt, format);

                if (readCnt > 0)
                {
                    UpdateActivityTime();
                }

                return(readCnt);
            }
            catch (Exception ex)
            {
                throw new ScadaException(CommPhrases.ReadDataStopCondError + ": " + ex.Message, ex);
            }
        }
        public static string ProtocolFormatToFeatureSectionName(ProtocolFormat format)
        {
            string result = "";

            switch (format)
            {
            case ProtocolFormat.RoboSepS_1_0:
            case ProtocolFormat.RoboSepS_1_1:
            case ProtocolFormat.RoboSepS_1_2:
                result = "FeatureList_RSS";
                break;

            case ProtocolFormat.RoboSep16:
            case ProtocolFormat.RoboSep16_1_2:
                result = "FeatureList_RS16";
                break;
            }
            return(result);
        }
示例#13
0
        /// <summary>
        /// Reads data.
        /// </summary>
        public override int Read(byte[] buffer, int offset, int count, int timeout,
                                 ProtocolFormat format, out string logText)
        {
            try
            {
                int readCnt = 0;
                NetStream.ReadTimeout = timeout; // timeout is not maintained if all available data has been read
                Stopwatch stopwatch = Stopwatch.StartNew();

                while (readCnt < count && stopwatch.ElapsedMilliseconds <= timeout)
                {
                    // read data
                    try
                    {
                        if (NetStream.DataAvailable) // checking DataAvailable is critical on Linux
                        {
                            readCnt += NetStream.Read(buffer, readCnt + offset, count - readCnt);
                        }
                    }
                    catch (IOException) { }

                    // accumulate data in the internal connection buffer
                    if (readCnt < count)
                    {
                        Thread.Sleep(DataAccumDelay);
                    }
                }

                logText = BuildReadLogText(buffer, offset, count, readCnt, format);

                if (readCnt > 0)
                {
                    UpdateActivityTime();
                }

                return(readCnt);
            }
            catch (Exception ex)
            {
                throw new ScadaException(CommPhrases.ReadDataError + ": " + ex.Message, ex);
            }
        }
示例#14
0
        /// <summary>
        /// Writes the specified data.
        /// </summary>
        public override void Write(byte[] buffer, int offset, int count, ProtocolFormat format, out string logText)
        {
            try
            {
                if (string.IsNullOrEmpty(RemoteAddress))
                {
                    throw new InvalidOperationException("Remote address is undefined.");
                }
                if (RemotePort <= 0)
                {
                    throw new InvalidOperationException("Remote port is undefined.");
                }

                byte[] datagram;

                if (offset > 0)
                {
                    datagram = new byte[count];
                    Array.Copy(buffer, offset, datagram, 0, count);
                }
                else
                {
                    datagram = buffer;
                }

                try
                {
                    int sentCnt = UdpClient.Send(datagram, count, RemoteAddress, RemotePort);
                    logText = BuildWriteLogText(datagram, 0, count, format);
                }
                catch (SocketException ex)
                {
                    logText = CommPhrases.WriteDataError + ": " + ex.Message;
                }
            }
            catch (Exception ex)
            {
                throw new ScadaException(CommPhrases.WriteDataError + ": " + ex.Message, ex);
            }
        }
        public static ProtocolFormat StringToProtocolFormat(string s)
        {
            ProtocolFormat result = ProtocolFormat.RoboSepS_1_2;

            try
            {
                ProtocolFormat newValue = (ProtocolFormat)Enum.Parse(typeof(ProtocolFormat), s, true);
                if (Enum.IsDefined(typeof(ProtocolFormat), newValue))
                {
                    result = newValue;
                    Console.WriteLine("Converted '{0}' to {1}.", s, newValue.ToString());
                }
                else
                {
                    Console.WriteLine("{0} is not an underlying value of the ProtocolFormat enumeration.", s);
                }
            }
            catch (ArgumentException)
            {
                Console.WriteLine("{0} is not a member of the ProtocolFormat enumeration.", s);
            }
            return(result);
        }
示例#16
0
        /// <summary>
        /// Reads the currently available data.
        /// </summary>
        public int ReadAvailable(byte[] buffer, int offset, int maxCount, ProtocolFormat format, out string logText)
        {
            try
            {
                int count = Math.Min(TcpClient.Available, maxCount);
                NetStream.ReadTimeout = DefaultReadTimeout;
                int readCnt = NetStream.DataAvailable ? NetStream.Read(buffer, offset, count) : 0;
                logText = BuildReadLogText(buffer, offset, count, readCnt, format);

                if (readCnt > 0)
                {
                    UpdateActivityTime();
                }

                return(readCnt);
            }
            catch (Exception ex)
            {
                throw new ScadaException((Locale.IsRussian ?
                                          "Ошибка при считывании доступных данных: " :
                                          "Error reading available data: ") + ex.Message, ex);
            }
        }
示例#17
0
        /// <summary>
        /// Reads data with the stop condition.
        /// </summary>
        public override int Read(byte[] buffer, int offset, int maxCount, int timeout, BinStopCondition stopCond,
                                 out bool stopReceived, ProtocolFormat format, out string logText)
        {
            try
            {
                int readCnt = 0;
                int curInd  = offset;
                stopReceived           = false;
                SerialPort.ReadTimeout = 0;
                Stopwatch stopwatch = Stopwatch.StartNew();

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

                    if (readOk)
                    {
                        stopReceived = stopCond.CheckCondition(buffer, curInd);
                        curInd++;
                        readCnt++;
                    }
                    else
                    {
                        Thread.Sleep(DataAccumDelay);
                    }
                }

                logText = BuildReadLogText(buffer, offset, readCnt, format);
                return(readCnt);
            }
            catch (Exception ex)
            {
                throw new ScadaException(CommPhrases.ReadDataStopCondError + ": " + ex.Message, ex);
            }
        }
示例#18
0
        /// <summary>
        /// Writes the specified data.
        /// </summary>
        public override void Write(byte[] buffer, int offset, int count, ProtocolFormat format, out string logText)
        {
            try
            {
                SerialPort.DiscardInBuffer();
                SerialPort.DiscardOutBuffer();

                try
                {
                    SerialPort.Write(buffer, offset, count);
                    logText    = BuildWriteLogText(buffer, offset, count, format);
                    WriteError = false;
                }
                catch (TimeoutException ex)
                {
                    logText = CommPhrases.WriteDataError + ": " + ex.Message;
                }
            }
            catch (Exception ex)
            {
                WriteError = true;
                throw new ScadaException(CommPhrases.WriteDataError + ": " + ex.Message, ex);
            }
        }
示例#19
0
 /// <summary>
 /// Reads data.
 /// </summary>
 public override int Read(byte[] buffer, int offset, int count, int timeout,
                          ProtocolFormat format, out string logText)
 {
     logText = "";
     return(0);
 }
 public static void SetProtocolFormat(ProtocolFormat type)
 {
     SeparatorResourceManager.GetInstance().protocolFormat = type;
 }
示例#21
0
 /// <summary>
 /// Builds a log text about reading data.
 /// </summary>
 protected static string BuildReadLogText(byte[] buffer, int offset, int readCnt, ProtocolFormat format)
 {
     return($"{CommPhrases.ReceiveNotation} ({readCnt}): " +
            ScadaUtils.BytesToString(buffer, offset, readCnt, format == ProtocolFormat.Hex));
 }
示例#22
0
 /// <summary>
 /// Builds a log text about writing data.
 /// </summary>
 protected static string BuildWriteLogText(byte[] buffer, int offset, int count, ProtocolFormat format)
 {
     return($"{CommPhrases.SendNotation} ({count}): " +
            ScadaUtils.BytesToString(buffer, offset, count, format == ProtocolFormat.Hex));
 }
示例#23
0
 /// <summary>
 /// Reads data.
 /// </summary>
 /// <returns>The number of bytes read.</returns>
 public abstract int Read(byte[] buffer, int offset, int count, int timeout,
                          ProtocolFormat format, out string logText);
示例#24
0
        private void SendMsg(string message)
        {
            var byteMsg = ProtocolFormat.Format(message, Settings.Connection.UsedEncoding);

            SendMsg(byteMsg);
        }
示例#25
0
        private string ProcessData(byte[] message, bool input)
        {
            string description = "";

            if (Settings.Messages.PacketView == Fx.Logging.ePacketView.Custom)
            {
                var protocol = (IPluginProtocol)Global.PL.GetPlugin(Settings.Messages.PacketViewPlugin);
                Send(protocol.AcknowledgeReception(message));
            }

            var endChar = Settings.Connection.UsedEncoding.GetString(ProtocolFormat.Format(Settings.Messages.LineSeparatingChar, Settings.Connection.UsedEncoding));

            if (Settings.Messages.UseLineSeparatingChar && endChar != "")
            {
                Global.LogPacket.LineSeparatingChar = endChar;
            }
            else
            {
                Global.LogPacket.LineSeparatingChar = "";
            }


            if (Settings.Messages.ShowBaudRate)
            {
                description = Settings.Connection.BaudRate + "[Bd]";
            }

            string text = "";

            if (input)
            {
                // ----- Reply statistics -----
                Statistic.ReplyCounter.All++;
                var diff = DateTime.Now - SendTime;
                if (diff.TotalMilliseconds > 2000)
                {
                    Statistic.ReplyCounter.Over2s++;
                }
                else if (diff.TotalMilliseconds > 1000)
                {
                    Statistic.ReplyCounter.Over1s++;
                }
                else if (diff.TotalMilliseconds > 500)
                {
                    Statistic.ReplyCounter.Over500ms++;
                }
                else if (diff.TotalMilliseconds > 250)
                {
                    Statistic.ReplyCounter.Over250ms++;
                }
                else if (diff.TotalMilliseconds > 100)
                {
                    Statistic.ReplyCounter.Over100ms++;
                }

                // ----- Log message -----
                text = Global.LogPacket.Add(description, message, Color.Blue, Settings.Messages.ShowTime, input);

                // ----- Send auto-reply -----
                if (Settings.Messages.EnableReplyFile)
                {
                    string key = BitConverter.ToString(message);
                    if (ReplyData.ContainsKey(key))
                    {
                        string value = ReplyData[key];
                        Send(value);
                    }
                }
            }
            else
            {
                SendTime = DateTime.Now;
                text     = Global.LogPacket.Add(description, message, Color.Black, Settings.Messages.ShowTime, input);
            }


            return(text);
        }
示例#26
0
 /// <summary>
 /// Reads data with the stop condition.
 /// </summary>
 public abstract int Read(byte[] buffer, int offset, int maxCount, int timeout, BinStopCondition stopCond,
                          out bool stopReceived, ProtocolFormat format, out string logText);
示例#27
0
 /// <summary>
 /// Writes the specified data.
 /// </summary>
 public abstract void Write(byte[] buffer, int offset, int count, ProtocolFormat format, out string logText);
示例#28
0
 /// <summary>
 /// Writes the specified data.
 /// </summary>
 public override void Write(byte[] buffer, int offset, int count, ProtocolFormat format, out string logText)
 {
     logText = "";
 }
示例#29
0
        private void frmMain_Load(object sender, EventArgs e)
        {
            conn.ChangedState += new ChangedStateEventHandler(ConnChangedState);

            // ----- GET APPLICATION VERSION -> TO CAPTION -----
            this.Text = this.Text + " v" + Application.ProductVersion.Substring(0, Application.ProductVersion.Length - 2);

            // ----- LOAD SETTINGS -----
            Settings.LoadXml();

            // ----- Load plug-ins -----
            Global.PL.LoadPlugins();
            ProtocolFormat.SetPlugins(Global.PL.PluginsProtocol);
            LoadPlugins();

            // ----- Creating data folder -----
            if (!Directory.Exists(Paths.GetFullPath(Settings.App.DataFolder)))
            {
                Directory.CreateDirectory(Paths.GetFullPath(Settings.App.DataFolder));
            }

            Global.LogPacket.LogFileDirectory = Paths.GetFullPath(Settings.Messages.LogFileDirectory);
            Global.LogPacket.SaveToFile       = Settings.Messages.SaveToFile;
            ;
            // ----- APPLY SETTINGS TO FORM -----
            ApplySettingsToForm();

            // ----- READ SENDING HISTORY -----
            ReadHistory();

            // ----- LOAD COMMAND MENU -----
            LoadMenu();



            formSet = new frmSettings();

            olvPacket.UpdateObjects(Global.LogPacket.Recods); //SetObjects

            colTime.AspectGetter = delegate(object x) {
                if (x == null)
                {
                    return("");
                }
                return(((LogRecord)x).time.ToString("hh:mm:ss.fff"));
            };
            colDelay.AspectGetter = delegate(object x) {
                if (x == null)
                {
                    return("");
                }
                return(((LogRecord)x).delay.TotalSeconds.ToString("0.000"));
            };
            colLength.AspectGetter = delegate(object x) {
                if (x == null)
                {
                    return("");
                }
                return(((LogRecord)x).data.Length);
            };
            colIO.AspectGetter = delegate(object x) {
                if (x == null)
                {
                    return("");
                }
                if (((LogRecord)x).input)
                {
                    return(">>");
                }
                else
                {
                    return("<<");
                }
            };
            colPacket.AspectGetter = delegate(object x) {
                if (x == null)
                {
                    return("");
                }
                return(((LogRecord)x).dataText);
            };
        }