zs
2024-11-21 9f5cd73648a4dd6ad80d5c8e1c14746a8a27b1b6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using System.Threading;
using DataCapture_MA.log4Net;
using DataCapture_MA.Entity;
using DataCapture_MA.DataHnadle;
using DataCapture_MA.AutoMapperConfig;
using System.IO;
using IWshRuntimeLibrary;
 
namespace DataCapture_MA
{
    public partial class CaptrueForm : Form
    {
        bool RunningFlag = false;
        Socket skt = WZ.Useful.Commons.NetworkUtil.CreateUdpSocket();
        EndPoint RemotePoint = null;
        public delegate void MyInvoke(string strRecv);
        public CaptrueForm()
        {
            InitializeComponent();
 
            var hostName = Dns.GetHostName();
            var ips = Dns.GetHostAddresses(hostName);
            string targetSubnet = "10.133.13"; // 目标网段
 
            bool foundTargetSubnet = false;
 
            foreach (var ip in ips)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork) // 只显示IPv4地址
                {
                    ipSelect.Items.Add(ip);
                    // 检查是否包含目标网段
                    if (ip.ToString().StartsWith(targetSubnet))
                    {
                        ipSelect.SelectedItem = ip; // 选中匹配的 IP
                        foundTargetSubnet = true;
                    }
                }
            }
 
            if (!foundTargetSubnet && ipSelect.Items.Count > 0)
            {
                //MessageBox.Show($"未找到网段为 {targetSubnet} 的IP地址,将默认选中第一个IP。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                ipSelect.SelectedIndex = 0;
            }
            to_ipTxt.Text = ipSelect.SelectedItem?.ToString();
 
            // 初始化 AutoMapper
            AutoMapper.Mapper.Initialize(cfg =>
            {
                cfg.AddProfile<MapperConfiguration>();
            });
 
            // 创建快捷方式
            string shortcutName = "MaDataCapture"; // 快捷方式名称
            string targetPath = Application.ExecutablePath; // 程序路径
            string startupPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup); // 启动文件夹路径
            CreateShortcut(shortcutName, targetPath, startupPath); // 创建快捷方式
 
            StartReceive(); // 启动程序
            CreateDatabase();  // 初始化数据库
 
            // 删除一个月前的数据
            new Thread(AutoDeleteHistoryDate.Handler).Start();
        }
 
 
        public static void CreateShortcut(string shortcutName, string targetPath, string startupPath)
        {
            string shortcutPath = Path.Combine(startupPath, shortcutName + ".lnk");
            if (System.IO.File.Exists(shortcutPath))
                return;
 
            WshShell shell = new WshShell();
            IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutPath);
            shortcut.TargetPath = targetPath;
            shortcut.WorkingDirectory = Path.GetDirectoryName(targetPath);
            shortcut.Save();
        }
 
        private void ReceiveHandle()
        {
            //接收数据处理线程  
            string msg;
            byte[] data = new byte[204800];
            MyInvoke myI = new MyInvoke(UpdateRcvTextBox);
            while (RunningFlag)
            {
 
                if (skt == null || !RunningFlag || skt.Available < 1)
                {
                    Thread.Sleep(200);
                    continue;
                }
                //跨线程调用控件  
                //接收UDP数据报,引用参数RemotePoint获得源地址  
                int rlen = skt.ReceiveFrom(data, ref RemotePoint);
                msg = Encoding.Default.GetString(data, 0, rlen);
                r_showBox.BeginInvoke(myI, new object[] { "From " + RemotePoint.ToString() + " << " + msg });
 
            }
        }
 
        //处理接收到的UDP
        private void UpdateRcvTextBox(string msg)
        {
            //接收数据显示  
            this.r_showBox.Text += (msg) + "\n\n";
            Log4NetHelper.WriteInfoLog(LogType.Receive, msg);
            ReceiveDataHandle.AnalysisMeassage(msg);
        }
 
        private void start_connect_Click(object sender, EventArgs e)
        {
            StartReceive();
        }
        public void StartReceive()
        {
            try
            {
                if (skt != null)
                {
                    skt.Close();
                    skt.Dispose();
                }
 
                // 创建新的 UDP 套接字
                skt = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
 
                // 设置允许重用地址和端口
                skt.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
 
                //得到本机IP,设置UDP端口号                
                IPAddress ip = IPAddress.Parse(ipSelect.SelectedItem.ToString());//本机IP
                int port = int.Parse(local_port.Text.Trim());//端口号
                IPEndPoint iPEndPoint = new IPEndPoint(ip, port);
                skt.Bind(iPEndPoint);
 
                //得到客户机IP 
                IPAddress ip2 = IPAddress.Parse(to_ipTxt.Text.Trim());//客户机IP
                int port2 = int.Parse(to_portTxt.Text.Trim());//端口号
                IPEndPoint iPEndPoint2 = new IPEndPoint(ip2, port2);
                RemotePoint = (EndPoint)(iPEndPoint2);
 
                RunningFlag = true;
 
                Thread thread = new Thread(new ThreadStart(ReceiveHandle));
                thread.Start();
 
 
 
                Log4NetHelper.WriteInfoLog(LogType.Receive, "开启UDP通信成功" + iPEndPoint.ToString());
                //ipSelect.Enabled = false;
                local_port.Enabled = false;
                to_ipTxt.Enabled = false;
                to_portTxt.Enabled = false;
                start_connect.BackColor = Color.DarkRed;
                start_connect.Enabled = false;
                colse_connect.BackColor = Color.DarkGreen;
                colse_connect.Enabled = true;
                r_showBox.Text += "数据接收已启动\n";
            }
            catch (Exception ex)
            {
                Log4NetHelper.WriteInfoLog(LogType.Receive, "开启UDP通信失败" + ex);
                MessageBox.Show(ex.Message);
            }
        }
 
        private void CreateDatabase()
        {
            try
            {
                using (var context = new DbModel())
                {
                    // 确保数据库和表存在,如果不存在则创建
                    context.Database.EnsureCreated();
 
                    // 添加一些数据
                    context.RobotInfo.Add(new RobotInfo
                    {
                        WarnningNum = 0,
                        //RobotStatus = "Normal",
                        RobotModel = "Model X",
                        RobotSerialNo = "123456",
                        WarnningContent = "清除富文本框数据",
                        CreateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                        CreateStamp = DateTimeOffset.Now.ToUnixTimeSeconds(),
                        IsDelete = false
                    });
 
                    // 保存更改
                    context.SaveChanges();
 
                    var xx = context.RobotInfo.ToList();
                }
            }
            catch (Exception ex)
            {
                r_showBox.Text = "数据库初始化异常"+ ex.Message;
            }
        }
 
        private void colse_connect_Click(object sender, EventArgs e)
        {
            try
            {
                RunningFlag = false; // 停止接收线程
 
                if (skt != null)
                {
                    skt.Close(); // 关闭套接字
                }
 
                ipSelect.Enabled = true;
                local_port.Enabled = true;
                to_ipTxt.Enabled = true;
                to_portTxt.Enabled = true;
                colse_connect.Enabled = false;
                start_connect.Enabled = true;
                colse_connect.BackColor = Color.DarkRed;
                start_connect.BackColor = Color.DarkGreen;
                r_showBox.Text += "已关闭数据接收\n";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
 
        private void sendbtn_Click(object sender, EventArgs e)
        {
            try
            {
                string sendStr = richSendTxt.Text;
                IPAddress ip2 = IPAddress.Parse(to_ipTxt.Text.Trim());//客户机IP
                int port2 = int.Parse(to_portTxt.Text.Trim());//端口号
                IPEndPoint iPEndPoint2 = new IPEndPoint(ip2, port2);
                RemotePoint = (EndPoint)(iPEndPoint2);
                skt.Connect(RemotePoint);
                skt.Send(WZ.Useful.Commons.ConvertHelper.StringToBytes(sendStr));
 
                r_showBox.Text += "To " + RemotePoint.ToString() +">> " + (sendStr) + "\n";
            }
            catch( Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
 
        private void clearBtn_Click(object sender, EventArgs e)
        {
            CreateDatabase();
            richSendTxt.Text = string.Empty;
            r_showBox.Text = string.Empty;
        }
 
        private void ipSelect_SelectedIndexChanged(object sender, EventArgs e)
        {
 
        }
    }
}