Exemplo n.º 1
0
        /// <summary>
        /// Принять команду от SCADA-Сервера
        /// </summary>
        public bool ReceiveCommand(out KPLogic.Command cmd)
        {
            int    kpNum;
            int    cmdNum;
            double cmdVal;

            byte[] cmdData;

            if (ReceiveCommand(out kpNum, out cmdNum, out cmdVal, out cmdData))
            {
                cmd         = new KPLogic.Command();
                cmd.CmdType = cmdData == null ?
                              (double.IsNaN(cmdVal) ? KPLogic.CmdType.Request : KPLogic.CmdType.Standard) :
                              KPLogic.CmdType.Binary;
                cmd.KPNum  = kpNum;
                cmd.CmdNum = cmdNum;
                if (cmd.CmdType == KPLogic.CmdType.Standard)
                {
                    cmd.CmdVal = cmdVal;
                }
                else if (cmd.CmdType == KPLogic.CmdType.Binary)
                {
                    cmd.CmdData = cmdData;
                }
                return(true);
            }
            else
            {
                cmd = null;
                return(false);
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Принять команду от SCADA-Сервера
        /// </summary>
        public bool ReceiveCommand(out KPLogic.Command cmd)
        {
            int kpNum;
            int cmdNum;
            double cmdVal;
            byte[] cmdData;

            if (ReceiveCommand(out kpNum, out cmdNum, out cmdVal, out cmdData))
            {
                cmd = new KPLogic.Command();
                cmd.CmdType = cmdData == null ?
                    (double.IsNaN(cmdVal) ? KPLogic.CmdType.Request : KPLogic.CmdType.Standard) :
                    KPLogic.CmdType.Binary;
                cmd.KPNum = kpNum;
                cmd.CmdNum = cmdNum;
                if (cmd.CmdType == KPLogic.CmdType.Standard)
                    cmd.CmdVal = cmdVal;
                else if (cmd.CmdType == KPLogic.CmdType.Binary)
                    cmd.CmdData = cmdData;
                return true;
            }
            else
            {
                cmd = null;
                return false;
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Записать команду управления в файл
        /// </summary>
        /// <param name="cmdDir">Директория команд</param>
        /// <param name="sender">Имя приложения, отправившего команду</param>
        /// <param name="cmd">Команда КП</param>
        /// <param name="msg">Сообщение</param>
        /// <returns>Успешно ли произведена запись команды</returns>
        public static bool SaveCmd(string cmdDir, string sender, KPLogic.Command cmd, out string msg)
        {
            StringBuilder sbCmdData = new StringBuilder();

            if (cmd.CmdData != null)
            {
                int cmdDataLen = cmd.CmdData.Length;
                for (int i = 0; i < cmdDataLen; i++)
                {
                    sbCmdData.Append(cmd.CmdData[i].ToString("X2"));
                }
            }

            string[] cmdParams = new string[] {
                "KPNum=" + cmd.KPNum,
                "CmdNum=" + cmd.CmdNum,
                "CmdVal=" + cmd.CmdVal.ToString(),
                "CmdData=" + sbCmdData
            };

            return(SaveCmd(cmdDir, sender, cmd.CmdType.ToString(), cmdParams, out msg));
        }
Exemplo n.º 4
0
        /// <summary>
        /// Загрузить из файла команду и проверить её корретность
        /// </summary>
        private bool LoadCmd(string fileName, out string cmdType,
                             out Dictionary <string, string> cmdParams, out KPLogic.Command kpCmd)
        {
            bool result = false;

            cmdType   = "";
            cmdParams = null;
            kpCmd     = null;

            FileStream   fileStream   = null;
            StreamReader streamReader = null;

            try
            {
                string   target   = "";
                DateTime date     = DateTime.MinValue;
                DateTime time     = DateTime.MinValue;
                int      lifeTime = 0;
                bool     endFound = false;

                fileStream   = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                streamReader = new StreamReader(fileStream, Encoding.Default);

                while (!streamReader.EndOfStream)
                {
                    string line  = streamReader.ReadLine().Trim();
                    string lineL = line.ToLower();

                    if (cmdParams == null)
                    {
                        if (lineL == "[command]")
                        {
                            cmdParams = new Dictionary <string, string>();
                        }
                    }
                    else
                    {
                        if (lineL.StartsWith("target="))
                        {
                            target = lineL.Remove(0, 7);
                        }
                        else if (lineL.StartsWith("date="))
                        {
                            string[] vals = lineL.Remove(0, 5).Split('.');
                            date = new DateTime(int.Parse(vals[2]), int.Parse(vals[1]), int.Parse(vals[0]));
                        }
                        else if (lineL.StartsWith("time="))
                        {
                            string[] vals = lineL.Remove(0, 5).Split(':');
                            time = new DateTime(DateTime.MinValue.Year, DateTime.MinValue.Month,
                                                DateTime.MinValue.Day, int.Parse(vals[0]), int.Parse(vals[1]), int.Parse(vals[2]));
                        }
                        else if (lineL.StartsWith("lifetime="))
                        {
                            lifeTime = int.Parse(lineL.Remove(0, 9));
                        }
                        else if (lineL.StartsWith("cmdtype="))
                        {
                            cmdType = line.Remove(0, 8);

                            try
                            {
                                KPLogic.CmdType kpCmdType = (KPLogic.CmdType)Enum.Parse(
                                    typeof(KPLogic.CmdType), cmdType, true);
                                kpCmd = new KPLogic.Command(kpCmdType);
                            }
                            catch { }
                        }
                        else if (lineL.StartsWith("end="))
                        {
                            endFound = true;
                        }
                        else
                        {
                            int ind = lineL.IndexOf("=");
                            if (ind >= 0)
                            {
                                cmdParams[lineL.Substring(0, ind)] = lineL.Substring(ind + 1);
                            }

                            if (kpCmd != null)
                            {
                                if (lineL.StartsWith("kpnum="))
                                {
                                    kpCmd.KPNum = int.Parse(lineL.Remove(0, 6));
                                }
                                else if (lineL.StartsWith("cmdnum="))
                                {
                                    if (kpCmd.CmdType != KPLogic.CmdType.Request)
                                    {
                                        kpCmd.CmdNum = int.Parse(lineL.Remove(0, 7));
                                    }
                                }
                                else if (lineL.StartsWith("cmdval="))
                                {
                                    if (kpCmd.CmdType == KPLogic.CmdType.Standard)
                                    {
                                        lineL = lineL.Remove(0, 7);
                                        string s1 = lineL.Replace('.', ',');
                                        string s2 = lineL.Replace(',', '.');
                                        double val;
                                        if (double.TryParse(s1, out val))
                                        {
                                            kpCmd.CmdVal = val;
                                        }
                                        else if (double.TryParse(s2, out val))
                                        {
                                            kpCmd.CmdVal = val;
                                        }
                                    }
                                }
                                else if (lineL.StartsWith("cmddata="))
                                {
                                    if (kpCmd.CmdType == KPLogic.CmdType.Binary)
                                    {
                                        int    len     = lineL.Length;
                                        byte[] cmdData = new byte[(len - 8) / 2];

                                        for (int i = 9, j = 0; i < len; i += 2, j++)
                                        {
                                            string byteStr = lineL[i - 1].ToString() + lineL[i].ToString();
                                            cmdData[j] = byte.Parse(byteStr, NumberStyles.HexNumber);
                                        }

                                        kpCmd.CmdData = cmdData;
                                    }
                                }
                            }
                        }
                    }
                }

                if (cmdParams != null && target == "scadacommsvc" && endFound)
                {
                    // удаление успешно обработанного файла команды
                    streamReader.Close();
                    streamReader = null;
                    fileStream.Close();
                    fileStream = null;
                    File.Delete(fileName);

                    // проверка команды
                    DateTime cmdDT = new DateTime(date.Year, date.Month, date.Day,
                                                  time.Hour, time.Minute, time.Second);
                    DateTime nowDT   = DateTime.Now;
                    string   cmdInfo = (Localization.UseRussian ? " Тип: " : " Type: ") + cmdType;
                    cmdInfo += kpCmd == null ? "" : (Localization.UseRussian ?
                                                     ", КП: " + kpCmd.KPNum + ", номер: " + kpCmd.CmdNum :
                                                     ", device: " + kpCmd.KPNum + ", number: " + kpCmd.CmdNum);

                    if (nowDT.AddSeconds(-lifeTime) <= cmdDT && cmdDT <= nowDT.AddSeconds(lifeTime))
                    {
                        log.WriteAction((Localization.UseRussian ? "Получена команда из файла." :
                                         "The command is received from file.") + cmdInfo, Log.ActTypes.Action);
                        result = true;
                    }
                    else
                    {
                        log.WriteAction((Localization.UseRussian ? "Получена неактуальная команда из файла." :
                                         "The outdated command is received from file.") + cmdInfo, Log.ActTypes.Action);
                    }

                    cmdType = cmdType.ToLower();
                }
            }
            catch (ThreadAbortException)
            {
            }
            catch (Exception ex)
            {
                log.WriteAction(string.Format(Localization.UseRussian ? "Ошибка при приёме команды из файла {0}: {1}" :
                                              "Error receiving command from file {0}: {1}", Path.GetFileName(fileName), ex.Message),
                                Log.ActTypes.Exception);
            }
            finally
            {
                if (streamReader != null)
                {
                    streamReader.Close();
                }
                if (fileStream != null)
                {
                    fileStream.Close();
                }
            }

            return(result);
        }
Exemplo n.º 5
0
        private void btnSendCmd_Click(object sender, EventArgs e)
        {
            if (lastKP != null)
            {
                bool cmdOK = false;
                KPLogic.Command cmd = new KPLogic.Command();
                cmd.KPNum = lastKP.Number;

                if (rbCmdStand.Checked)
                {
                    txtCmdVal.Focus();
                    cmd.CmdType = KPLogic.CmdType.Standard;
                    cmd.CmdNum = decimal.ToInt32(numCmdNum.Value);

                    double cmdVal = ScadaUtils.StrToDouble(txtCmdVal.Text);
                    if (double.IsNaN(cmdVal))
                    {
                        ScadaUtils.ShowError(AppPhrases.IncorrectCmdVal);
                    }
                    else
                    {
                        cmd.CmdVal = cmdVal;
                        cmdOK = true;
                    }
                }
                else if (rbCmdBin.Checked)
                {
                    cmd.CmdType = KPLogic.CmdType.Binary;
                    cmd.CmdNum = decimal.ToInt32(numCmdNum.Value);

                    byte[] cmdData;
                    string cmdDataStr = txtCmdData.Text;

                    if (rbCmdHex.Checked)
                    {
                        if (ScadaUtils.HexToBytes(cmdDataStr.Trim(), out cmdData))
                        {
                            cmdOK = true;
                            cmd.CmdData = cmdData;
                        }
                        else
                        {
                            ScadaUtils.ShowError(AppPhrases.IncorrectHexCmdData);
                        }
                    }
                    else if (cmdDataStr.Length > 0)
                    {
                        cmd.CmdData = Encoding.Default.GetBytes(cmdDataStr);
                        cmdOK = true;
                    }
                    else
                    {
                        ScadaUtils.ShowError(AppPhrases.CmdDataRequired);
                    }
                }
                else
                {
                    cmd.CmdType = KPLogic.CmdType.Request;
                    cmdOK = true;
                }

                // сохранение команды в файле
                if (cmdOK)
                {
                    string msg;
                    if (KPUtils.SaveCmd(cmdDir, "ScadaCommCtrl", cmd, out msg))
                    {
                        ScadaUtils.ShowInfo(msg);
                    }
                    else
                    {
                        errLog.WriteAction(msg);
                        ScadaUtils.ShowError(msg);
                    }
                }
            }
        }