Esempio n. 1
0
        private static void StartMainWindow()
        {
            Stopwatch watch2 = new Stopwatch();

            //检查同名进程数
            ELogger.Info(string.Format("程序{0}启动...", Application.ProductName));
            Process[] processes = System.Diagnostics.Process.GetProcessesByName(Application.ProductName);
            ELogger.Info(string.Format("发现进程数{0}", processes.Length));

            //只允许运行1个实例
            if (processes.Length <= 1)
            {
                watch2.Start();
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                ELogger.Info(string.Format("启动主线程..."));
                watch2.Stop();
                ELogger.Info("记录2耗时:" + watch2.ElapsedMilliseconds); //记录5耗时:11889
                Application.Run(new Form1());
                ELogger.Info(string.Format("主线程结束..."));
            }
            else
            {
                ELogger.Info("不允许多实例运行,退出");
                //单实例,不允许多实例运行
                System.Environment.Exit(1);
            }
        }
Esempio n. 2
0
 /// <summary>
 /// 表格添加行后的事件触发
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
 {
     try
     {
         dataGridView1.Rows[e.RowIndex].Selected = true;
     }
     catch (Exception ex)
     {
         ELogger.Error("Received error:" + ex.Message + ex.StackTrace);
     }
 }
Esempio n. 3
0
 static void Main()
 {
     try
     {
         StartMainWindow();
         //Application.EnableVisualStyles();
         //Application.SetCompatibleTextRenderingDefault(false);
         //Application.Run(new Form1());
     }
     catch (Exception ex)
     {
         ELogger.Error("Main error:" + ex.Message + ex.StackTrace);
     }
 }
Esempio n. 4
0
 /// <summary>
 /// 异步接收触发函数
 /// </summary>
 /// <param name="ar"></param>
 private void Received(IAsyncResult ar)
 {
     try
     {
         if (ReadEnable)
         {
             int lenth = socket.EndReceive(ar);
             backgroundWorker1.ReportProgress(lenth, ar.AsyncState as byte[]);
             ReceiveOnce();
         }
     }
     catch (Exception ex)
     {
         ELogger.Error("Received error:" + ex.Message + ex.StackTrace);
     }
 }
Esempio n. 5
0
        /// <summary>
        /// 构造函数
        /// </summary>
        public Form1()
        {
            InitializeComponent();

            table.Columns.Add("方向");
            table.Columns.Add("协议层数据");
            table.Columns.Add("数据层数据");
            table.Columns.Add("时间");
            table.Columns.Add("SR");
            table.Columns.Add("NR");
            dataGridView1.DataSource = table;
            dataGridView1.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            dataGridView1.Columns[0].FillWeight   = 10;
            dataGridView1.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            dataGridView1.Columns[1].FillWeight   = 20;
            dataGridView1.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            dataGridView1.Columns[2].FillWeight   = 60;
            dataGridView1.Columns[3].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            dataGridView1.Columns[3].FillWeight   = 10;
            dataGridView1.Columns[4].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            dataGridView1.Columns[4].FillWeight   = 5;
            dataGridView1.Columns[5].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            dataGridView1.Columns[5].FillWeight   = 5;

            table2.Columns.Add("地址");
            table2.Columns.Add("值");
            table2.Columns.Add("时间");
            table2.PrimaryKey        = new DataColumn[] { table2.Columns[0] };
            dataGridView2.DataSource = table2;
            dataGridView2.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            dataGridView2.Columns[0].FillWeight   = 10;
            dataGridView2.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            dataGridView2.Columns[1].FillWeight   = 20;
            dataGridView2.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            dataGridView2.Columns[2].FillWeight   = 60;

            ReadCSV();
            if (!ReadEnable)
            {
                backgroundWorker1.RunWorkerAsync();
            }
            else
            {
                waitHandel.Set();
            }
            ELogger.Info("启动成功");
        }
Esempio n. 6
0
 /// <summary>
 /// 后台线程完成工作
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
 {
     try
     {
         ReadEnable = false;
         tm.Stop();
         tm.Dispose();
         System.Threading.Thread.Sleep(1000);
         socket.Close();
         sendTCPClient.Close();
         UDPPushClient.Close();
     }
     catch (Exception ex)
     {
         ELogger.Error("backgroundWorker1_RunWorkerCompleted error:" + ex.Message + ex.StackTrace);
     }
 }
Esempio n. 7
0
 /// <summary>
 /// 定时发送的定时器
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void tm_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
 {
     try
     {
         ASDUClass ymBuffer = new ASDUClass();
         ymBuffer.Pack(ASDUClass.TransRes.Active, ASDUClass.FunType.CalEnergyPulse);
         SendList.Enqueue(new APDUClass(new APCIClassIFormat(++sr, nr), ymBuffer));
         if (SendList.Count > 0)
         {
             byte[] SendBuffer = SendList.Dequeue().ToArray();
             backgroundWorker1.ReportProgress(-1, SendBuffer);
             socket.Send(SendBuffer);
         }
     }
     catch (Exception ex)
     {
         ELogger.Error("tm_Elapsed error:" + ex.Message + ex.StackTrace);
     }
 }
Esempio n. 8
0
        private void ReadCSV()
        {
            StreamReader sr = new StreamReader(Application.StartupPath + @"\TAGLIST.CSV");
            String       line;
            int          i = 0;

            //越过第一行标题
            sr.ReadLine();
            while ((line = sr.ReadLine()) != null)
            {
                TagInfo  aTagInfo = new TagInfo();
                string[] strarr   = line.Split(',');
                aTagInfo.ADDRNO  = Convert.ToInt32(strarr[0]);
                aTagInfo.TAGNAME = strarr[1];
                aTagInfo.TAGMC   = strarr[2];
                aTagInfo.TAGLX   = strarr[3];
                lstTagInfo.Add(aTagInfo.ADDRNO, aTagInfo);
                i++;
            }
            sr.Close();
            ELogger.Info("1214:初始化TAGLIST个数:" + i.ToString());
        }
Esempio n. 9
0
 private void checkState()
 {
     while (true)
     {
         Thread.Sleep(10000);
         if (client.Connected == false)
         {
             try
             {
                 client.Close();
                 client = new TcpClient();
                 client.Connect(hostip, port);
                 IsConnection = true;
             }
             catch
             {
                 IsConnection = false;
                 ELogger.Info("网闸外侧连接失败");
             }
         }
     }
 }
Esempio n. 10
0
        Thread checkStateThread; //检查网络状态线程

        public TcpClientEx(string hostip, int port)
        {
            this.hostip = hostip;
            this.port   = port;

            client = new TcpClient();
            try
            {
                client.Connect(hostip, port);
                if (client.Connected)
                {
                    IsConnection = true;
                    Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "网闸外侧连接成功");
                    ELogger.Info("网闸外侧连接成功");
                }
            }
            catch (Exception ex)
            {
                IsConnection = false;
            }
            checkStateThread = new Thread(new ThreadStart(checkState));
            checkStateThread.IsBackground = true;
            checkStateThread.Start();
        }
Esempio n. 11
0
        /// <summary>
        /// 从纯数组获取apci的方法
        /// </summary>
        /// <param name="apcibuffer">含apci的数组</param>
        /// <returns>apci</returns>
        public static APCIClass GetApci(byte[] apcibuffer)
        {
            if (apcibuffer[0] != 0x68)
            {
                throw new Exception("APCI头不对");
            }
            else if (apcibuffer.Length < 0)
            {
                throw new Exception("APCI长度不对");
            }
            else
            {
                switch (apcibuffer[2] & 0x03)
                {
                case 3:
                {
                    if (apcibuffer[1] != 4)
                    {
                        throw new Exception("U格式数据长度异常");
                    }
                    APCIClassUFormat.UFormatType utype = (APCIClassUFormat.UFormatType)apcibuffer[2];
                    APCIClassUFormat             apci  = new APCIClassUFormat(utype);
                    apci.uisType = UISFormat.U;
                    return(apci);
                }

                case 1:
                {
                    if (apcibuffer[1] != 4)
                    {
                        throw new Exception("S格式数据长度异常");
                    }
                    short nr = (short)((short)(apcibuffer[4] >> 1) + (short)((short)apcibuffer[5] << 7));
                    if (nr <= 0)
                    {
                        ELogger.Debug("nr小于0,apcibuffer=" + BitConverter.ToString(apcibuffer));
                    }
                    APCIClassSFormat apci = new APCIClassSFormat(nr);
                    apci.uisType = UISFormat.S;
                    return(apci);
                }

                case 2:
                case 0:
                {
                    if (apcibuffer[1] < 4)
                    {
                        throw new Exception("I格式数据长度异常");
                    }
                    short ns = (short)((short)(apcibuffer[2] >> 1) + (short)((short)apcibuffer[3] << 7));
                    short nr = (short)((short)(apcibuffer[4] >> 1) + (short)((short)apcibuffer[5] << 7));
                    if (nr <= 0)
                    {
                        ELogger.Debug("nr小于0,apcibuffer=" + BitConverter.ToString(apcibuffer));
                    }
                    APCIClassIFormat apci = new APCIClassIFormat(ns, nr);
                    apci.APDULenth = apcibuffer[1];
                    apci.uisType   = UISFormat.I;
                    return(apci);
                }

                default:
                    throw new Exception("格式解析异常");
                }
            }
        }
Esempio n. 12
0
        /// <summary>
        /// 后台线程提交数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            try
            {
                if (e.ProgressPercentage == -1)
                {
                    APDUClass           temp       = new APDUClass(e.UserState as byte[]);
                    APCIClass.UISFormat dataFormat = temp.GetApciType();
                    if (temp != null)
                    {
                        table.Rows.Add("TX", temp.ApciToString(), temp.AsduToString(), DateTime.Now, temp.GetSR(), temp.GetNR());
                    }
                }
                else if (e.ProgressPercentage > 0)
                {
                    byte[] receive = new byte[e.ProgressPercentage];
                    Array.Copy(e.UserState as byte[], receive, e.ProgressPercentage);
                    if (receive.Length > 6 && receive[8] == 0x14 && receive[6] == 0x01)
                    {
                        System.Diagnostics.Debug.WriteLine("??");
                    }

                    APDUClass temp = new APDUClass(receive);

                    APCIClass.UISFormat dataFormat = temp.GetApciType();
                    if (dataFormat == APCIClass.UISFormat.I)
                    {
                        //if (nr > short.MaxValue)
                        //{
                        //    nr = 0;
                        //}
                        SendList.Enqueue(new APDUClass(new APCIClassSFormat(++nr), null));
                        //sr++;
                    }
                    else if (dataFormat == APCIClass.UISFormat.S)
                    {
                        //if (nr > short.MaxValue)
                        //{
                        //    nr = 0;
                        //}
                        SendList.Enqueue(new APDUClass(new APCIClassSFormat(++nr), null));
                        //sr++;
                    }

                    if (temp != null)
                    {
                        string  sSendMessage = string.Empty;
                        string  sTagName     = string.Empty;
                        TagInfo ATagInfo;
                        table.Rows.Add("RX", temp.ApciToString(), temp.AsduToString(), DateTime.Now, temp.GetSR(), temp.GetNR());
                        if ((temp.Res.Equals(ASDUClass.TransRes.ResAll)) || (temp.Res.Equals(ASDUClass.TransRes.EnergyCall)))
                        {
                            var datas = temp.GetData();
                            foreach (var data in datas)
                            {
                                ELogger.Trace("接收:" + data.Addr.ToString() + "=" + data.Data.ToString());

                                //      find.Add(data.Addr,table2.Rows.Add(data.Addr,data.Data,data.Time));

                                //向网闸外侧服务发送实时数据
                                if (lstTagInfo.TryGetValue(data.Addr, out ATagInfo))
                                {
                                    //listTgas.Add(ATagInfo);
                                    lock (objlock)
                                    {
                                        if (dicTag.ContainsKey(ATagInfo.TAGNAME))
                                        {
                                            dicTag.Remove(ATagInfo.TAGNAME);
                                            dicTag.Add(ATagInfo.TAGNAME, data.Data);
                                        }
                                        else
                                        {
                                            dicTag.Add(ATagInfo.TAGNAME, data.Data);
                                        }
                                    }
                                }
                            }
                        }
                        else if (temp.Res == ASDUClass.TransRes.AutoSend)
                        {
                            var datas = temp.GetData();
                            if (datas == null)
                            {
                                return;
                            }
                            foreach (var data in datas)
                            {
                                ELogger.Trace("接收:" + data.Addr.ToString() + "=" + data.Data.ToString());
                                try
                                {
                                    //向网闸外侧服务发送实时数据
                                    if (lstTagInfo.TryGetValue(data.Addr, out ATagInfo))
                                    {
                                        //listTgas.Add(ATagInfo);
                                        lock (objlock)
                                        {
                                            if (dicTag.ContainsKey(ATagInfo.TAGNAME))
                                            {
                                                dicTag.Remove(ATagInfo.TAGNAME);
                                                dicTag.Add(ATagInfo.TAGNAME, data.Data);
                                            }
                                            else
                                            {
                                                dicTag.Add(ATagInfo.TAGNAME, data.Data);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        System.Diagnostics.Debug.WriteLine("");
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":backgroundWorker1_ProgressChanged send error:" + ex.Message + ex.StackTrace);
                                    ELogger.Error("backgroundWorker1_ProgressChanged send error:" + ex.Message + ex.StackTrace);
                                }
                            }
                        }
                    }
                }
                if (table.Rows.Count > 20)
                {
                    table.Rows.RemoveAt(0);
                }
            }
            catch (Exception ex)
            {
                ELogger.Error("backgroundWorker1_ProgressChanged error:" + ex.Message + ex.StackTrace);
            }
        }
Esempio n. 13
0
        /// <summary>
        /// 后台线程启动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                UDPPushClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                IPEndPoint send = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9020);
                Remote = (EndPoint)(send);

                APDUClass myBuffer = new APDUClass(new APCIClassUFormat(APCIClassUFormat.UFormatType.StartSet), null);
                tm     = new System.Timers.Timer();
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.Connect(IPAddress.Parse(textBox1.Text), 2404);
                socket.SendTimeout    = 500;
                socket.ReceiveTimeout = 500;

                sendTCPClient = new TcpClientEx(SENDTCPIP, SENDTCPPORT);

                SendList.Enqueue(new APDUClass(new APCIClassUFormat(APCIClassUFormat.UFormatType.StartSet), null));
                sr = 0;
                nr = 0;
                ASDUClass clockBuffer = new ASDUClass();
                clockBuffer.Pack(ASDUClass.TransRes.Active, ASDUClass.FunType.ClockConfirm);
                ASDUClass calBuffer = new ASDUClass();
                calBuffer.Pack(ASDUClass.TransRes.Active, ASDUClass.FunType.CalAll);

                ASDUClass ymBuffer = new ASDUClass();
                ymBuffer.Pack(ASDUClass.TransRes.Active, ASDUClass.FunType.CalEnergyPulse);

                //       SendList.Enqueue(new APDUClass(new APCIClassIFormat(++sr, nr), clockBuffer));
                SendList.Enqueue(new APDUClass(new APCIClassIFormat(++sr, nr), calBuffer));
                SendList.Enqueue(new APDUClass(new APCIClassIFormat(++sr, nr), ymBuffer));
                //SendList.Enqueue(new APDUClass(new APCIClassUFormat(APCIClassUFormat.UFormatType.StopSet), null));

                ReadEnable = true;
                ReceiveOnce();
                tm.AutoReset = true;
                tm.Interval  = scaneRate;
                tm.Elapsed  += new System.Timers.ElapsedEventHandler(tm_Elapsed);
                tm.Start();

                new Thread(t =>
                {
                    while (true)
                    {
                        foreach (var item in dicTag)
                        {
                            var sSendMessage = string.Format(sJsonRT, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), item.Key, item.Value);

                            if (sendTCPClient.IsConnection)
                            {
                                sendTCPClient.SendMessage(sSendMessage);
                                UDPPushClient.SendTo(EncodeUDP(sSendMessage), Remote);
                                Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":" + sSendMessage);
                                ELogger.Info("发送:" + sSendMessage);
                            }
                        }
                        Thread.Sleep(PauseTime);
                    }
                }).Start();
                waitHandel.WaitOne();
            }
            catch (Exception ex)
            {
                ELogger.Error("backgroundWorker1_DoWork error:" + ex.Message + ex.StackTrace);
            }
        }