MainForm.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Configuration;
  4. using System.Drawing;
  5. using System.IO;
  6. using System.Text;
  7. using System.Windows.Forms;
  8. using TwinCAT.Ads;
  9. namespace SIASUN.TwinCatLogger
  10. {
  11. public partial class MainForm : Form
  12. {
  13. public MainForm()
  14. {
  15. InitializeComponent();
  16. this.ShowInTaskbar = true;
  17. this.WindowState = FormWindowState.Normal;
  18. }
  19. public string GetConfiguration(string key)
  20. {
  21. try
  22. {
  23. string value = System.Configuration.ConfigurationManager.AppSettings[key];
  24. if (!string.IsNullOrEmpty(value))
  25. return value;
  26. }
  27. catch (Exception ce)
  28. {
  29. }
  30. return "";
  31. }
  32. private void MainForm_Load(object sender, EventArgs e)
  33. {
  34. this.Visible = false;
  35. this.notifyIcon1.Visible = true;
  36. //this.skinEngine1.SkinFile = "EmeraldColor1.ssk"; //皮肤文件.ssk
  37. runInDebug = GetConfiguration("测试模式").ToLower() == "true";
  38. //try
  39. //{
  40. // AutoStartTask.CreateLogonTask(!runInDebug);
  41. //}
  42. //catch (Exception ex)
  43. //{
  44. // textNotice.Text = "创建开机自动启动任务失败:" + ex.Message;
  45. //}
  46. 单文件行数 = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["单文件行数"]);
  47. //LogonStart.CreateLogonTask(!runInDebug);
  48. timer1.Interval = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["刷新时间"]);
  49. if (LoadPointList())
  50. timer2.Enabled = true;
  51. }
  52. private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
  53. {
  54. //e.Cancel = true; // 取消关闭窗体
  55. //HideToolStripMenuItem_Click(sender, e);
  56. if (MessageBox.Show("是否确认退出程序?", "退出", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
  57. {
  58. e.Cancel = false;
  59. }
  60. else
  61. {
  62. e.Cancel = true;
  63. }
  64. }
  65. private void MainForm_SizeChanged(object sender, EventArgs e)
  66. {
  67. if (WindowState == FormWindowState.Minimized)
  68. {
  69. HideToolStripMenuItem_Click(sender, e);
  70. }
  71. }
  72. private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
  73. {
  74. if (e.Button == MouseButtons.Left)
  75. {
  76. OpenToolStripMenuItem_Click(sender, e);
  77. }
  78. }
  79. private void exitToolStripMenuItem_Click(object sender, EventArgs e)
  80. {
  81. exitToolStripMenuItem.Enabled = false;
  82. this.Close();
  83. exitToolStripMenuItem.Enabled = true;
  84. }
  85. private void HideToolStripMenuItem_Click(object sender, EventArgs e)
  86. {
  87. this.Hide();
  88. }
  89. private void OpenToolStripMenuItem_Click(object sender, EventArgs e)
  90. {
  91. this.ShowInTaskbar = true;
  92. this.Show();
  93. this.WindowState = FormWindowState.Normal;
  94. this.Activate();
  95. }
  96. #region 数据
  97. bool runInDebug = false;
  98. int 单文件行数 = 0;
  99. int 当前行数 = 0;
  100. struct PlcPoint
  101. {
  102. public string name;
  103. public string address;
  104. public Type type;
  105. }
  106. List<PlcPoint> pointList = new List<PlcPoint>();
  107. List<int> handleList = new List<int>();
  108. private TcAdsClient adsClient = new TcAdsClient();
  109. private string[] plcAdress = ConfigurationManager.AppSettings["PLC地址"].Split(':');
  110. private int startSignal = 0;
  111. private bool isRecording = false;
  112. private bool isManuel = false;
  113. private long stopWatch = 0;
  114. private string filePrefix = "Log_";
  115. private string filePath = "";
  116. private StreamWriter fileWriter = null;
  117. #endregion
  118. private Type GetTypeByName(string typename)
  119. {
  120. if (typename.ToUpper() == "BOOL")
  121. return typeof(bool);
  122. if (typename.ToUpper() == "BYTE")
  123. return typeof(Byte);
  124. if (typename.ToUpper() == "WORD")
  125. return typeof(UInt16);
  126. if (typename.ToUpper() == "DWORD")
  127. return typeof(UInt32);
  128. if (typename.ToUpper() == "INT")
  129. return typeof(Int16);
  130. if (typename.ToUpper() == "DINT")
  131. return typeof(Int32);
  132. if (typename.ToUpper() == "REAL")
  133. return typeof(float);
  134. if (typename.ToUpper() == "LREAL")
  135. return typeof(Double);
  136. return null;
  137. }
  138. private bool LoadPointList()
  139. {
  140. string filePath = GetConfiguration("点表文件");
  141. pointList.Clear();
  142. try
  143. {
  144. string line;
  145. string[] arrItem;
  146. PlcPoint plcPoint = new PlcPoint() { name = "", address = "", type = null };
  147. // 创建一个 StreamReader 的实例来读取文件 ,using 语句也能关闭 StreamReader
  148. using (System.IO.StreamReader sr = new System.IO.StreamReader(filePath, Encoding.GetEncoding("GB2312")))
  149. {
  150. // 从文件读取并显示行,直到文件的末尾
  151. while ((line = sr.ReadLine()) != null)
  152. {
  153. arrItem = line.Split(',');
  154. if (arrItem.Length != 3)
  155. continue;
  156. plcPoint.name = arrItem[0].Trim();
  157. plcPoint.address = arrItem[1].Trim();
  158. if (plcPoint.address.Length == 0)
  159. continue;
  160. plcPoint.type = GetTypeByName(arrItem[2].Trim());
  161. if (plcPoint.type == null)
  162. continue;
  163. pointList.Add(plcPoint);
  164. textNotice.Text = "已从" + filePath + "读取" + pointList.Count.ToString() + "条数据定义";
  165. }
  166. }
  167. return true;
  168. }
  169. catch (Exception ex)
  170. {
  171. textNotice.Text = "读取数据点表文件(" + filePath + ")发生错误:" + ex.Message;
  172. return false;
  173. }
  174. }
  175. private void timer2_Tick(object sender, EventArgs e)
  176. {
  177. if (!adsClient.IsConnected || startSignal == 0)
  178. {
  179. BeginConnect();
  180. }
  181. else if (isRecording)
  182. {
  183. stopWatch++;
  184. if (this.InvokeRequired)
  185. this.BeginInvoke((Action)delegate
  186. {
  187. lableTime.Text = string.Format("{0:D2}:{1:D2}:{2:D2}", stopWatch / 3600, stopWatch / 60, stopWatch % 60);
  188. });
  189. else
  190. lableTime.Text = string.Format("{0:D2}:{1:D2}:{2:D2}", stopWatch / 3600, stopWatch / 60, stopWatch % 60);
  191. }
  192. else
  193. {
  194. if (lableTime.Text == "")
  195. lableTime.Text = "00:00:00";
  196. else
  197. lableTime.Text = "";
  198. }
  199. }
  200. private void timer1_Tick(object sender, EventArgs e)
  201. {
  202. try
  203. {
  204. if (adsClient.IsConnected)
  205. {
  206. if (isManuel)
  207. {
  208. ReadAllValues();
  209. return;
  210. }
  211. bool isStart = (bool)adsClient.ReadAny(startSignal, typeof(bool));
  212. if (!isRecording)
  213. {
  214. if (isStart)
  215. StartRecording();
  216. }
  217. else
  218. {
  219. if (!isStart)
  220. StopRecording();
  221. else
  222. ReadAllValues();
  223. }
  224. }
  225. }
  226. catch (Exception ex)
  227. {
  228. textNotice.Text = "数据读取定时器发生错误:" + ex.Message;
  229. }
  230. }
  231. public int getHandle(string varName)
  232. {
  233. try
  234. {
  235. int handle = 0;
  236. if (varName.Contains("."))
  237. handle = adsClient.CreateVariableHandle(varName);
  238. else
  239. handle = adsClient.CreateVariableHandle("." + varName);
  240. return handle;
  241. }
  242. catch (Exception ex)
  243. {
  244. textNotice.Text = "获取PLC变量(" + varName + ")发生错误:" + ex.Message;
  245. return 0;
  246. }
  247. }
  248. private void BeginConnect()
  249. {
  250. try
  251. {
  252. adsClient.Connect(plcAdress[0], Convert.ToInt32(plcAdress[1]));
  253. startSignal = getHandle(System.Configuration.ConfigurationManager.AppSettings["启动信号"]);
  254. if (startSignal == 0)
  255. return;
  256. for (int i = 0; i < pointList.Count; i++)
  257. {
  258. handleList.Add(getHandle(pointList[i].address));
  259. }
  260. button1.Enabled = true;
  261. timer1.Enabled = true;
  262. }
  263. catch (Exception ex)
  264. {
  265. textNotice.Text = "连接PLC发生发生错误:" + ex.Message;
  266. timer1.Enabled = false;
  267. button1.Enabled = false;
  268. }
  269. }
  270. private void StartRecording()
  271. {
  272. if (!CreateLogFile())
  273. return;
  274. isRecording = true;
  275. stopWatch = 0;
  276. button1.Text = "正在记录";
  277. textNotice.Text = "已创建记录文件:" + filePath;
  278. }
  279. private void StopRecording()
  280. {
  281. fileWriter.Flush();
  282. fileWriter.Close();
  283. isRecording = false;
  284. button1.Text = "开始记录";
  285. textNotice.Text = "已保存到记录文件:" + filePath;
  286. }
  287. private bool CreateLogFile()
  288. {
  289. filePath = filePrefix + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".csv";
  290. 当前行数 = 0;
  291. try
  292. {
  293. fileWriter = new StreamWriter(filePath, false, Encoding.GetEncoding("GB2312"));
  294. fileWriter.Write("时间");
  295. for (int i = 0; i < pointList.Count; i++)
  296. {
  297. fileWriter.Write("," + pointList[i].name);
  298. }
  299. fileWriter.WriteLine();
  300. fileWriter.Flush();
  301. return true;
  302. }
  303. catch (Exception ex)
  304. {
  305. textNotice.Text = "创建记录文件(" + filePath + ")发生错误:" + ex.Message;
  306. timer1.Enabled = false;
  307. button1.Enabled = false;
  308. timer2.Enabled = false;
  309. return false;
  310. }
  311. }
  312. public delegate void AsyncEventHandler();
  313. private static object m_Lock = new object();
  314. private string getValue(int index)
  315. {
  316. try
  317. {
  318. if (handleList[index] == 0)
  319. return "";
  320. string value = adsClient.ReadAny(handleList[index], pointList[index].type).ToString();
  321. return value;
  322. }
  323. catch (Exception ex)
  324. {
  325. textNotice.Text = "读取PLC变量(" + pointList[index].name + ")值时发生错误:" + ex.Message;
  326. return "";
  327. }
  328. }
  329. private void ReadAllValues()
  330. {
  331. AsyncEventHandler asy = new AsyncEventHandler(AsyncReadAllValues);
  332. IAsyncResult result = asy.BeginInvoke(null, asy);
  333. }
  334. private void AsyncReadAllValues()
  335. {
  336. StringBuilder line = new StringBuilder();
  337. line.Append(DateTime.Now.ToString("HH:mm:ss:fff"));
  338. for (int i = 0; i < handleList.Count; i++)
  339. {
  340. string value = getValue(i);
  341. line.Append("," + value);
  342. }
  343. lock (m_Lock)
  344. {
  345. fileWriter.WriteLine(line);
  346. 当前行数++;
  347. if (单文件行数 > 0 && 当前行数 >= 单文件行数)
  348. {
  349. fileWriter.Flush();
  350. fileWriter.Close();
  351. CreateLogFile();
  352. }
  353. }
  354. }
  355. private void button1_Click(object sender, EventArgs e)
  356. {
  357. if (isRecording)
  358. {
  359. StopRecording();
  360. isManuel = true;
  361. timer1.Enabled = false;
  362. timer2.Enabled = false;
  363. button1.Text = "已停止";
  364. }
  365. else
  366. {
  367. if (isManuel)
  368. {
  369. isManuel = false;
  370. timer1.Enabled = true;
  371. timer2.Enabled = true;
  372. button1.Text = "开始记录";
  373. }
  374. else
  375. {
  376. isManuel = true;
  377. StartRecording();
  378. }
  379. }
  380. }
  381. }
  382. }