using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Windows.Forms; using System.Xml; using Forks.Utils.IO; namespace ClientForWEDS { public partial class Form1 : Form { string _myOper = ""; string _svPath = ""; string _zdPath = ""; private int lineC = 0; private string lastFile = ""; private Thread thred; ManualResetEvent ma; bool on_off = true; bool stop = false; public Form1() { InitializeComponent(); CheckForIllegalCrossThreadCalls = false; } private void Form1_Load(object sender, EventArgs e) { LoadLanguage("Chinese"); ConfigUtil.Init(); //_zdPath = ConfigUtil.ZDPath; _svPath = Path.Combine(ConfigUtil.RdPath, string.Format("{0}\\", DateTime.Today.ToString("yyyy-MM-dd"))); if (!FS.DirectoryExists(_svPath)) FS.CreateDirectory(Path.GetDirectoryName(_svPath)); cbLineMd.SelectedIndex = 0; txtIP.Text = ConfigUtil.IP1; txtIP2.Text = ConfigUtil.IP2; txtIP3.Text = ConfigUtil.IP3; txtTimeout.Text = ConfigUtil.Timeout; nudPort.Text = ConfigUtil.Port; txtReciveZDPath.Text = ConfigUtil.ZDPath; erpTextBox.Text = ConfigUtil.ERPURL; userTextBox.Text = ConfigUtil.UserName; passTextBox.Text = ConfigUtil.Password; if (ConfigUtil.ValidateType == "no") rbNoValidate.Checked = true; else if (ConfigUtil.ValidateType == "pass") { rbPassValidate.Checked = true; } else if (ConfigUtil.ValidateType == "admin") { rbAdminValidate.Checked = true; } btntpConn.Click += delegate { tabControl1.SelectedTab = tpConnection; }; btntpRecive.Click += delegate { tabControl1.SelectedTab = tpReciveFile; }; //dateTimePicker1.Value = DateTime.Now; thred = new Thread(StartTx); thred.IsBackground = true; thred.Start(); } private List ipList = new List(); private bool isLineing = false; private void StartTx(object obj) { while (true) { if (stop) return; if (on_off) { ma = new ManualResetEvent(false); ma.WaitOne(); } var iList = new List(); foreach (var ip in ipList) { iList.Add(ip); } //不能直接用ipList,在foreach时候 ipList可能在线程外会被修改 foreach (var ip in iList) { txtLog.AppendText("开始连接:" + ip + " \r\n"); lastFile = ""; isLineing = true; LineZd(ip); //----等待读取记录----- var c = 0; while (c < 60 * 2) { c++; if (!isLineing) { //axW4commsv21.CloseZd(); break; } Thread.Sleep(500); } //------------------ if (FS.FileExists(lastFile)) { DecodeFileToTxt(lastFile, ip); } Thread.Sleep(3000); } var s10 = 10000; var m10 = 600000; Thread.Sleep(s10); } } void DisableBt(bool enabled) { btnConnection.Enabled = enabled; btnDisconnection.Enabled = enabled; } private void btnConnection_Click(object sender, EventArgs e) { DisableBt(false); lineC = 0; LineZd(txtIP.Text); } private void btnDisconnection_Click(object sender, EventArgs e) { axW4commsv21.CloseZd(); txtLog.SelectionStart = txtLog.Text.Length; txtUDP.SelectionStart = txtUDP.Text.Length; } private string tcpMode = "以太网通讯(TCP/IP)"; private void LineZd(string ip) { int connectionKind; string connType = cbLineMd.SelectedItem.ToString(); if (connType == tcpMode) { connectionKind = 0; } else { MessageBox.Show("不支持的连接方式"); return; } axW4commsv21.OverTime = Convert.ToInt32(txtTimeout.Text); axW4commsv21.LineMd = connectionKind; axW4commsv21.NetPort = Convert.ToInt32(nudPort.Value); axW4commsv21.LineZd(ip, txtValidate.Text); lblState.Text = ip + ":" + nudPort.Value.ToString(); } Dictionary _dicMessage; void LoadLanguage(string languageName) { _dicMessage = new Dictionary(); var xml = new XmlDocument(); xml.Load(Application.StartupPath + "\\language\\" + languageName + ".xml"); var nodeList = xml.ChildNodes[1].ChildNodes; foreach (XmlNode node in nodeList) { if (node.Name == "Messages") { foreach (XmlNode item in node.ChildNodes) { if (item.Attributes == null) continue; _dicMessage.Add(item.Attributes["Key"].Value, item.Attributes["Value"].Value); } continue; } if ((!node.Name.Equals("Label") && !node.Name.Equals("ComboBox") && !node.Name.Equals("Button") && !node.Name.Equals("RadioButton") && !node.Name.Equals("CheckBox")) || node.Attributes == null) continue; var control = FindControl(this, node.Attributes["Name"].Value); if (control != null && node.Attributes["Text"] != null) control.Text = node.Attributes["Text"].Value; } } Control FindControl(Control pControl, string pControlName) { if (pControl.Name == pControlName) return pControl; for (int i = 0; i != pControl.Controls.Count; i++) { Control subControl = FindControl(pControl.Controls[i], pControlName); if (subControl != null) return subControl; } return null; } private void rbValidate_Checked(object sender, EventArgs e) { var realKind = cbLineMd.SelectedItem.ToString(); if (rbNoValidate.Checked) { if (realKind.Equals(tcpMode)) { txtValidate.Text = "id=\r\n" + "card=\r\n" + "password=\r\n" + "line=\r\n"; } } if (rbPassValidate.Checked) { if (realKind.Equals(tcpMode)) { txtValidate.Text = "id=\r\n" + "card=\r\n" + "password=\r\n" + "line=12345\r\n"; } } if (rbAdminValidate.Checked) { if (realKind.Equals(tcpMode)) { txtValidate.Text = "id=001\r\n" + "card=50EF082A\r\n" + "password=1234\r\n" + "line=12345\r\n"; } } } private void axW4commsv21_InfoZdEvent(object sender, AxWEDS4_CommSV2.__W4commsv2_InfoZdEvent e) { txtUDP.Text += "ip=" + e.zdadd + enterStr + axW4commsv21.InfoZd + enterStr; } private string enterStr = "\r\n"; private void axW4commsv21_OnEvent(object sender, EventArgs e) { DisableBt(true); var length = txtLog.Text.Length; if (length > 1000) txtLog.Text = txtLog.Text.Substring(length - 100); switch (axW4commsv21.RunEvent) { case "ok": switch (axW4commsv21.RunZl) { case "linezd": //txtLog.Text += (_dicMessage["LineZdSuccess"] + enterStr); switch (_myOper) { case "upfile": txtLog.Text += (_dicMessage["StartReciveFileToPcFromZd"] + enterStr); lastFile = GetRdPath(); axW4commsv21.UploadFile(lastFile, _zdPath); break; case "dwnpht": txtLog.Text += (_dicMessage["StartSendZhaoPianToZdFromPc"] + enterStr); axW4commsv21.DwloadFile(GetRdPath(), _zdPath); break; case "retime": txtLog.Text += (_dicMessage["StartReTime"] + enterStr); //if (rbDatetimeNow.Checked) { // axW4commsv21.ReTime(DateTime.Now); //} else { // DateTime time = new DateTime(dateTimePicker1.Value.Year, dateTimePicker1.Value.Month, dateTimePicker1.Value.Day, Convert.ToInt32(nudHour.Value), Convert.ToInt32(nudMinute.Value), 0); // axW4commsv21.ReTime(time); //} break; } break; case "uploadfile": if (_myOper == "upfile") { txtLog.Text += (_dicMessage["ReadFileSuccess"] + GetRdPath() + enterStr); txtLog.Text += (_dicMessage["BeginDeleteZdFile"] + enterStr); axW4commsv21.DeleteFile(_zdPath); } break; case "dwloadfile": switch (_myOper) { case "dwnpht": txtLog.Text += (_dicMessage["WriteZhaoPianSuccess"] + enterStr); _myOper = "dwnwdda"; txtLog.Text += (_dicMessage["StartWriteFileFromPcToZd"] + enterStr); _zdPath = txtZdDangAnPath.Text.Trim(); //_svPath = txtSvDangAnPath.Text.Trim(); axW4commsv21.DwloadFile(GetRdPath(), _zdPath); break; case "dwnwdda": txtLog.Text += (_dicMessage["WriteDangAnFileSuccess"] + enterStr); txtLog.Text += (_dicMessage["Disconnectioning"] + enterStr); axW4commsv21.CloseZd(); isLineing = false; break; } break; case "deletefile": if (_myOper == "upfile") { txtLog.Text += (_dicMessage["DeleteZdFileSuccess"] + enterStr); txtLog.Text += (_dicMessage["Disconnectioning"] + enterStr); axW4commsv21.CloseZd(); isLineing = false; } break; case "retime": txtLog.Text += (_dicMessage["ReTimeSuccess"] + enterStr); txtLog.Text += (_dicMessage["Disconnectioning"] + enterStr); axW4commsv21.CloseZd(); break; } break; case "error": if (axW4commsv21.RunZl == "linezd") txtLog.Text += (_dicMessage["ConnectionFaileAndPleaseCheckPass"] + enterStr); else if (axW4commsv21.RunZl == "closezd") txtLog.Text += (_dicMessage["DisconnectionFails"] + enterStr); else if (axW4commsv21.RunZl == "uploadfile") { if (_myOper == "upfile") { txtLog.Text += (_dicMessage["ReadFileNotExists"] + _zdPath + enterStr); txtLog.Text += (_dicMessage["Disconnectioning"] + enterStr); axW4commsv21.CloseZd(); isLineing = false; } } else if (axW4commsv21.RunZl == "dwloadfile") { txtLog.Text += (_dicMessage["WriteFileFails"] + GetRdPath() + enterStr); txtLog.Text += (_dicMessage["Disconnectioning"] + enterStr); axW4commsv21.CloseZd(); isLineing = false; } else if (axW4commsv21.RunZl == "deletefile") { if (_myOper == "upfile") { txtLog.Text += (_dicMessage["DeleteZdFileNotExistsOrStopSudden"] + enterStr); txtLog.Text += (_dicMessage["Disconnectioning"] + enterStr); axW4commsv21.CloseZd(); isLineing = false; } } break; case "overtime": if (axW4commsv21.RunZl == "linezd") txtLog.Text += (_dicMessage["ConnectionFails"] + enterStr); isLineing = false; break; } txtLog.SelectionStart = txtLog.Text.Length - 1; txtLog.ScrollToCaret(); } private int i = 0; string GetRdPath() { i++; var filePath = Path.Combine(_svPath, string.Format("{0}{1}.wds", DateTime.Now.ToString("HH.mm.sss"), i)); return filePath; } private void axW4commsv21_LineZdEvent(object sender, EventArgs e) { var length = txtUDP.Text.Length; if (length > 200) txtUDP.Text = txtUDP.Text.Substring(length - 100); switch (axW4commsv21.LineEvent) { case 0: txtLog.Text += _dicMessage["Disconnectioned"] + enterStr; break; case 1: case 2: lineC++; if (lineC <= 1) { txtUDP.Text = ""; txtUDP.Text += axW4commsv21.DataZd; txtLog.Text += axW4commsv21.Zdip + enterStr + _dicMessage["ConnectionSuccess"] + enterStr + _dicMessage["PassedAdmin"] + enterStr; } break; default: throw new Exception(); } txtUDP.SelectionStart = txtUDP.Text.Length - 1; txtUDP.ScrollToCaret(); } private void stopButton_Click(object sender, EventArgs e) { on_off = true; txtLog.AppendText("停止采集 :" + DateTime.Now.ToLongTimeString() + "\r\n"); btnRecive.Enabled = true; lblState.BackColor = Color.WhiteSmoke; } private void btnRecive_Click(object sender, EventArgs e) { ipList.Clear(); if (txtIP.Text.Length > 0) ipList.Add(txtIP.Text); if (txtIP2.Text.Length > 0) ipList.Add(txtIP2.Text); if (txtIP3.Text.Length > 0) ipList.Add(txtIP3.Text); _zdPath = txtReciveZDPath.Text.Trim(); on_off = false; ma.Set(); txtLog.AppendText("开始采集 :" + DateTime.Now.ToLongTimeString() + "\r\n"); _myOper = "upfile"; btnRecive.Enabled = false; lblState.BackColor = Color.GreenYellow; ////_svPath = txtReciveServerPath.Text.Trim(); //if (_zdPath != "" && _svPath != "") { // _myOper = "upfile"; // LineZd(txtIP.Text); //} } private void saveBt_Click(object sender, EventArgs e) { using (var reader = FS.OpenReader(ConfigUtil.ConfigFilePath, true)) { var nutFile = NutFile.Parse(reader); if (rbNoValidate.Checked) nutFile.SetValue(ConfigUtil.ConfigItem.ValidateType, "no"); else if (rbPassValidate.Checked) { nutFile.SetValue(ConfigUtil.ConfigItem.ValidateType, "pass"); } else if (rbAdminValidate.Checked) { nutFile.SetValue(ConfigUtil.ConfigItem.ValidateType, "admin"); } nutFile.SetValue(ConfigUtil.ConfigItem.IP1, txtIP.Text.Trim()); nutFile.SetValue(ConfigUtil.ConfigItem.IP2, txtIP2.Text.Trim()); nutFile.SetValue(ConfigUtil.ConfigItem.IP3, txtIP3.Text.Trim()); nutFile.SetValue(ConfigUtil.ConfigItem.Port, nudPort.Text.Trim()); nutFile.SetValue(ConfigUtil.ConfigItem.Timeout, txtTimeout.Text.Trim()); nutFile.SetValue(ConfigUtil.ConfigItem.ZDPath, txtReciveZDPath.Text.Trim()); nutFile.SetValue(ConfigUtil.ConfigItem.ERPURL, erpTextBox.Text.Trim()); nutFile.SetValue(ConfigUtil.ConfigItem.UserName, userTextBox.Text.Trim()); nutFile.SetValue(ConfigUtil.ConfigItem.Password, passTextBox.Text.Trim()); using (TextWriter writer = FS.OpenWriter(ConfigUtil.ConfigFilePath, createDirsIfNotExist: true)) { nutFile.Write(writer); } } ConfigUtil.IP1 = txtIP.Text; ConfigUtil.IP2 = txtIP2.Text; ConfigUtil.IP3 = txtIP3.Text; ConfigUtil.Port = nudPort.Text; ConfigUtil.Timeout = txtTimeout.Text; ConfigUtil.ZDPath = txtReciveZDPath.Text; ConfigUtil.ERPURL = erpTextBox.Text; ConfigUtil.UserName = userTextBox.Text; ConfigUtil.Password = passTextBox.Text; MessageBox.Show("保存成功"); } //解密文件 private void DecodeFileToTxt(string filePath, string ip) { var encodeFile = filePath; var list = new List(); if (encodeFile == "") return; if (File.Exists(encodeFile)) { var fsRead = new FileStream(encodeFile, FileMode.Open); var sr = new StreamReader(fsRead); while (true) { var line = sr.ReadLine(); if (line == null) { break; } var str = axW4commsv21.OptStr(line); list.Add(str); } sr.Close(); fsRead.Close(); } AddToTxt(list, ip); var msg = DoInsert(list, ip); if (string.IsNullOrEmpty(msg)) txtLog.AppendText("成功上传" + list.Count + "条记录\r\n"); } private static string DoInsert(List list, string ip = "") { var rdList = new List(); //110003,2017-10-16 13:42:10,f,0,1,,jk134210 foreach (var str in list) { if (string.IsNullOrEmpty(str)) continue; var arrStr = str.Split(','); if (arrStr.Length < 2) continue; var att = new AttLog(); int id; if (int.TryParse(arrStr[0], out id)) { att.ID = id; } else { continue; } try { att.DateTime = Convert.ToDateTime(arrStr[1]); } catch (Exception) { continue; } if (!string.IsNullOrEmpty(ip)) { att.IP = ip; } else { var index = str.IndexOf("ip="); if (index > -1) { var ipStr = str.Substring(index+3); att.IP = ipStr; } } rdList.Add(att); } var groupBy = rdList.GroupBy(x => x.IP); var msg = new StringBuilder(); foreach (var details in groupBy) { var s = RpcHelper.Insert(details.ToList(), details.Key); if (!string.IsNullOrEmpty(s)) msg.AppendLine(s); } return msg.ToString(); } private void AddToTxt(IEnumerable msg, string ip) { var filePath = Path.Combine(_svPath, string.Format("log.txt")); using (var fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write)) { using (var sw = new StreamWriter(fs)) { sw.BaseStream.Seek(0, SeekOrigin.End); foreach (var s in msg) { sw.WriteLine(s + ",ip=" + ip); } sw.Flush(); } } } private void button1_Click(object sender, EventArgs e) { var list = new List(); var file = textBox1.Text; if (file == "") { MessageBox.Show("先选择日志文件"); return; } if (File.Exists(file)) { var fsRead = new FileStream(file, FileMode.Open); var sr = new StreamReader(fsRead); while (true) { var line = sr.ReadLine(); if (line == null) { break; } list.Add(line); } sr.Close(); fsRead.Close(); } var msg = DoInsert(list); if (string.IsNullOrEmpty(msg)) MessageBox.Show("操作成功"); else { MessageBox.Show(msg); } } public class AttLog { public int ID { get; set; } public DateTime DateTime { get; set; } public string IP { get; set; } public bool Uploaded { get; set; } } private void button2_Click(object sender, EventArgs e) { DialogResult dr = openFileDialogDangAn.ShowDialog(); if (dr == DialogResult.OK) { textBox1.Text = openFileDialogDangAn.FileName; } } } }