wxr
2020-11-04 e6a26ee148587327478d9a82624a820c907b6e16
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
using System;
using System.Net.Sockets;
using System.Net;
using Newtonsoft.Json.Linq;
 
namespace HDL_ON
{
    public class UdpSocket
    {
        static UdpSocket _busSocket;
        public static UdpSocket _BusSocket
        {
            get
            {
                if(_busSocket == null)
                {
                    _busSocket = new UdpSocket();
                }
                return _busSocket;
            }
        }
 
        /// <summary>
        /// 监听端口
        /// </summary>
        public int port
        {
            get
            {
                if (MainPage.LoginUser != null && Entity.DB_ResidenceData.residenceData != null)
                {
                    return Entity.DB_ResidenceData.residenceData.GatewayType == 0 ? 6000 : 8585;
                }
                return 6000;
            }
        }
 
        //本地Socket
        private Socket busSocket;
 
        /// <summary>
        /// 启动Socket接收和发送功能
        /// </summary>
        public void Start ()
        {
            if (IsRunning || port == 0) {
                return;
            }
 
            busSocket = new Socket (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            busSocket.EnableBroadcast = true;
            try {
                busSocket.Bind (new IPEndPoint (IPAddress.Any, port));
 
                busSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse("224.0.168.188")));
            }
            catch{
                busSocket = null;
                return;
            }
 
            asyncBeginReceive ();
 
            MainPage.Log ($"udp port : {port}");
        }
 
        /// <summary>
        /// 停止Socket
        /// </summary>
        public void Stop()
        {
            if (!IsRunning)
            {
                return;
            }
            try
            {
                busSocket.Close();
            }
            catch { }
            busSocket = null;
            MainPage.Log("Socket关闭");
        }
 
        /// <summary>
        /// 当前的Socket是否运行
        /// </summary>
        public bool IsRunning
        {
            get
            {
                return null == busSocket ? false : true;
            }
        }
 
        /// <summary>
        /// 开始异步接收数据
        /// </summary>
        private void asyncBeginReceive()
        {
            if (!IsRunning)
            {
                return;
            }
 
            try {
                Packet packet = new Packet ();
                busSocket.BeginReceiveFrom (packet.Bytes, 0, packet.Bytes.Length, SocketFlags.None, ref packet.RemoteEndPoint, new AsyncCallback (asyncEndReceive), packet);
            } 
            catch (Exception e) {
                System.Threading.Thread.Sleep (1);
                asyncBeginReceive ();
                Console.WriteLine($"asyncBeginReceive {e.Message}");
            } 
        }
 
        /// <summary>
        /// 异步接收数据结束
        /// </summary>
        /// <param name="iar"></param>
        private void asyncEndReceive(IAsyncResult iar)
        {
            if (!IsRunning)
            {
                return;
            }
 
            try
            {
                asyncBeginReceive();
                Packet packet = (Packet)iar.AsyncState;
                int len = busSocket.EndReceiveFrom(iar, ref packet.RemoteEndPoint);
 
                byte[] bytes = packet.Bytes;
                packet.Bytes = new byte[len];
                Array.Copy(bytes, 0, packet.Bytes, 0, packet.Bytes.Length);
 
                //mqtt连接数据读取  A协议网络设备信息读取回复 处理
                if (((IPEndPoint)packet.RemoteEndPoint).Port == 8585)
                {
                    var reString = System.Text.Encoding.UTF8.GetString(bytes);
                    var jt = Newtonsoft.Json.JsonConvert.DeserializeObject<JObject>(reString);
                    JToken jtc = null;
                    jt.TryGetValue("command", out jtc);
                    if (jtc != null && jtc.ToString() == "search_response")
                    {
                        JToken jto = null;
                        jt.TryGetValue("objects", out jto);
                        if (jto != null)
                        {
                            var jt2 = Newtonsoft.Json.JsonConvert.DeserializeObject<JObject>(jto.ToString());
                            JToken model_id = null;
                            jt2.TryGetValue("model_id", out model_id);
                            if (model_id != null)
                            {
                                if (model_id.ToString() == "")//Bus网关
                                {
                                    var revIp = jt2.GetValue("ip_address").ToString();
                                    var revMac = jt2.GetValue("device_mac").ToString();
                                    var revName = jt2.GetValue("device_name").ToString();
                                    //if (revIp == Entity.DB_ResidenceData.residenceData.residenceGatewayMAC)
                                    {
                                        DriverLayer.Control.ins.reportIp = revIp;
                                        DriverLayer.Control.ins.ChangeCommunicationMode(DriverLayer.CommunicationMode.tcp_local_client);
                                    }
                                }
                                else if (model_id.ToString() == "4")//声必可语音面板
                                {
 
                                }
                            }
                        }
                    }
                }
                else if(((IPEndPoint)packet.RemoteEndPoint).Port == 6000)//处理bus 6000端口的数据
                {
                    packet.Manager();
                }
            }
            catch (Exception ex)
            {
                MainPage.Log($"异步接收数据结束 {ex.Message},{((Packet)iar.AsyncState).Bytes}");
            }
        }
 
        /// <summary>
        /// 异步发送数据
        /// </summary>
        /// <param name="tempPacket"></param>
        public void AsyncBeginSend(Packet tempPacket)
        {
            try
            {
                if (!IsRunning)
                {
                    tempPacket.HaveSendCount++;
                    return;
                }
                tempPacket.FlagDateTime = System.DateTime.Now;
                tempPacket.HaveSendCount++;
                busSocket.BeginSendTo(tempPacket.Bytes, 0, tempPacket.Bytes.Length, SocketFlags.None, tempPacket.RemoteEndPoint, new AsyncCallback(asyncEndSend), tempPacket);
            }
            catch (Exception ex)
            {
                MainPage.Log($"AsyncBeginSend error {ex.Message}");
            }
        }
 
        /// <summary>
        /// 异步发送数据结束
        /// </summary>
        /// <param name="iar"></param>
        private void asyncEndSend(IAsyncResult iar)
        {
            Packet tempUDPPacketBuffer = (Packet)iar.AsyncState;
            try
            {
                int bytesSent = busSocket.EndSendTo(iar);
            }
            catch {
            
            }
        }
    }
}