/// <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); } }
/// <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); } }