wxr
2023-08-23 96e9ff2e5a54f54cdbb6b8b2f049fdf6a837de3c
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.Text;
using HDL_ON.Entity;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Shared.Net;
 
namespace HDL_ON.DriverLayer
{
    public class Control_Udp
    {
        /// <summary>
        /// 通讯端口
        /// </summary>
        public int port = 0;
 
        /// <summary>
        /// 控制失败次数
        /// </summary>
        public int controlLostCount = 0;
 
        /// <summary>
        /// 所有对一端口的控制都会放到这个集合里
        /// </summary>
        static List<Control_Udp> controlList = new List<Control_Udp>(50);
        
 
        public System.Net.IPEndPoint EndPoint
        {
            get
            {
                try
                {
                    return new System.Net.IPEndPoint(System.Net.IPAddress.Parse(new NetWiFi().BroadcastIpAddress.ToString()),6000);
                }
                catch
                {
                    //防止异常导致程序退出
                    return new System.Net.IPEndPoint(System.Net.IPAddress.Parse("127.0.0.1"), 6000);
                }
            }
        }
        /// <summary>
        /// 重发验证
        /// </summary>
        public static void ReceiveRepeatManager(string receiveFlag,byte []usefulBytes)
        {
            for (int i = 0; i < controlList.Count; i++)
            {
                try
                {
                    var control = controlList[i];
                    if (control.SendFlag == receiveFlag)
                    {
                        control.UsefulBytes = usefulBytes;//
                        control.run();
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"control error : {ex.Message}");
                }
            }
        }
        /// <summary>
        /// 添加到内存数组里面
        /// </summary>
        void add()
        {
            /// <summary>
            /// 达到50条数据后就清理一下
            /// </summary>
            if (50 < controlList.Count)
            {
                lock (controlList)
                {
                    for (int i = 0; i < controlList.Count;)
                    {
                        if (controlList[i] == null || 3 <= controlList[i].packet.HaveSendCount)
                        {
                            controlList.RemoveAt(i);
                        }
                        else
                        {
                            i++;
                        }
                    }
 
                }
            }
            controlList.Add(this);
        }
 
        //当前数据的关键数据
        string sendFlag = string.Empty;
        protected string SendFlag
        {
            get
            {
                return sendFlag;
            }
            set
            {
                sendFlag = value;
                usefulBytes = null;
            }
        }
 
        private byte[] usefulBytes;
        /// <summary>
        /// 获取回来的有用信息,如果获取回来的数据为null,就会抛出异常信息
        /// </summary>
        public byte[] UsefulBytes
        {
            get
            {
                if (null == usefulBytes)
                {
                    // throw new Exception("不好意思,网络不稳定或者远程设备不在线,请稍候再试!");
                }
 
                return this.usefulBytes;
            }
            set
            {
                usefulBytes = value;
            }
        }
 
        //发送数据了之后当前线程等待或者运行的信号
        System.Threading.ManualResetEvent allDone = new System.Threading.ManualResetEvent(false);
 
        /// <summary>
        /// 发送了数据后,线程就是等待状态,直到接收到反馈或者超时后退出
        /// </summary>
        void wait()
        {
            allDone.Reset();
            allDone.WaitOne();
        }
 
        /// <summary>
        /// 让当前线程继续执行
        /// </summary>
        void run()
        {
            allDone.Set();
            packet.HaveSendCount = 4;
        }
 
        //数据发送处理
        void managerSendCount(object o)
        {
            add();
            //Bus socket无法控制,重启机制
            if (controlLostCount > 10)
            {
                UdpSocket._BusSocket.Stop();
                new System.Threading.Thread(() =>
                {
                    System.Threading.Thread.Sleep(1000);
                    UdpSocket._BusSocket.Start(UdpSocket._BusSocket.Port);
                    controlLostCount = 0;
                })
                { IsBackground = true }.Start();
            }
 
            try
            {
                MainPage.Log("发送数据:" + SendFlag);
                UdpSocket._BusSocket.AsyncBeginSend(packet);
                packet.HaveSendCount--;
 
                //这里是重发两次
                while (packet.HaveSendCount < 3)
                {
                    if (packet.FlagDateTime.AddMilliseconds(1000).Ticks <= DateTime.Now.Ticks)
                    {
                        MainPage.Log("重发数据:" + SendFlag);
                        UdpSocket._BusSocket.AsyncBeginSend(packet);
                        controlLostCount++;
                    }
                    System.Threading.Thread.Sleep(1000);
                }
            }
            catch (Exception ex)
            {
                MainPage.Log("managerSendCount:" + ex.ToString());
            }
            finally
            {
                allDone.Set();
            }
        }
 
        /// <summary>
        /// 当前数据包
        /// </summary>
        Packet packet;
        /// <summary>
        /// 读取网关IP
        /// </summary>
        public void SearchLocalGateway(bool broadcast = false)
        {
            try
            {
                var sendJob = new JObject { { "id", Control.Ins.msg_id.ToString() }, { "time_stamp", Utlis.GetTimestamp ()} };
                var bodyString = JsonConvert.SerializeObject(sendJob);
                
                var sendBytes = Control.Ins.ConvertSendBodyData(CommunicationTopic.SearchLoaclGateway, bodyString, false);
                if (broadcast)
                {
                    //广播
                    packet = new Packet(sendBytes, new System.Net.IPEndPoint(System.Net.IPAddress.Parse("255.255.255.255"), 8585));
                }
                else
                {
                    //组播发送
                    packet = new Packet(sendBytes, new System.Net.IPEndPoint(System.Net.IPAddress.Parse("239.0.168.188"), 8585));
                }
                packet.HaveSendCount = 4;
                System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(managerSendCount));
                thread.IsBackground = true;
                thread.Start(packet);
                //wait();不需要等待
 
            }
            catch (Exception ex)
            {
                MainPage.Log($"Send bus data error {ex.Message}");
            }
        }
 
        /// <summary>
        /// 读取网关IP
        /// </summary>
        public void SendLinkCommand(string topic,string bodyString)
        {
            try
            {
                var sendBytes = Control.Ins.ConvertSendBodyData(topic, bodyString, false);
                //组播发送
                packet = new Packet(sendBytes, new System.Net.IPEndPoint(System.Net.IPAddress.Parse("239.0.168.188"), 8585));
                packet.HaveSendCount = 4;
                System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(managerSendCount));
                thread.IsBackground = true;
                thread.Start(packet);
            }
            catch (Exception ex)
            {
                MainPage.Log($"Send bus data error {ex.Message}");
            }
        }
 
        /// <summary>
        /// 发送udp A协议数据
        /// </summary>
        public void SendLocalHdlLinkData(byte[] sendBytes,string id, int resend = 3)
        {
            packet = new Packet(sendBytes, new System.Net.IPEndPoint(System.Net.IPAddress.Parse(Control.Ins.reportIp), 8585));
            packet.HaveSendCount = 3 - resend;//重发次数
            sendFlag = id;
            System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(managerSendCount));
            thread.IsBackground = true;
            thread.Start(packet);
            //if (isWait)
            //{
            //    wait(); 
            //}
            MainPage.Log($"发送Hdl-Link数据,IP:{Control.Ins.reportIp}:8585");
        }
    }
 
}