ningshuxia
2022-11-29 7c9c5916f1e3149e9190ce90bd985c5a5b3ff892
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IStation.Untity;
using IStation.Model;
using SuperSocket.Server;
using SuperSocket; 
using IStation.Server;
using System.Reflection;
using System.IO;
 
namespace IStation.Server
{
    /// <summary>
    /// 接收信息辅助类
    /// </summary>
    internal class RequestReceivedHelper
    {
 
        //接收数据
        public static async ValueTask Receive(IAppSession session, PackageInfo packageInfo)
        {
            await Task.Run(async () =>
            {
                try
                {
                    var mySession = (MySession)session;
                    await Task.Run(async () =>
                    {
                        var allBytes = packageInfo.Body;
                        var messageBts = BitTransfer.ToString(allBytes);
                        LogHelper.Info($" {mySession.SessionName}接收到数据:{messageBts}!");
                        if (allBytes == null || allBytes.Count() < 12)
                            return;
 
                        var bytePrefix = new byte[8];
                        Array.Copy(allBytes, 0, bytePrefix, 0, 8);
                        var prefix = Encoding.ASCII.GetString(bytePrefix);
                        if (prefix != Settings.Transfer.SZJTKT.Prefix)
                        {
                            LogHelper.Info($"收到一条无法识别的数据:{messageBts}!");
                            return;
                        }
                        mySession.Send("OK"); //前缀认证成功 返回 “OK”
 
 
                        // 解析数据,每64个字节为一帧数据
                        var prefixLength = prefix.Length + 1;
                        var dataCount = 64;
                        var byteCount = allBytes.Count() - prefixLength;
                        var count = (byteCount / dataCount);
 
                        var recordCount = 0;
                        for (int i = 0; i < count; i++)
                        {
                            var bytes = allBytes.Skip(prefixLength + (i * dataCount)).Take(dataCount).ToArray();
                            var list = HandleData(bytes);
                            if (list != null && list.Count > 0)
                            {
                                Thread.Sleep(1000);
                                //插入数据
                                LogHelper.Debug(JsonHelper.Object2Json(list));
                                var bol = Insert(Settings.Transfer.SZJTKT.RegisterCode, list);
                                if (!bol)
                                {
                                    LogHelper.Info($" 插入{list.Count()}条数据失败!");
                                }
                                else
                                {
                                    recordCount += list.Count;
                                    LogHelper.Info($"成功插入{list.Count()}条数据!");
                                }
                            }
                        }
 
                        LogHelper.Info($"共插入{recordCount}条数据!");
 
                    }
                    );
                }
                catch (Exception ex)
                {
                    LogHelper.Error(ex.Message);
                }
 
            });
 
        }
 
        #region 数据解析
 
        /// <summary>
        /// 处理数据
        /// </summary> 
        public static List<Model.MonitorDataDockingSrcRecord> HandleData(byte[] bytes)
        {
            var appParas = AppParasHelper.Get();
            if (appParas == null || appParas.RuleItems == null)
            {
                LogHelper.Error(" json is null");
                return default;
            }
 
            DateTime? dataTime = ParsingTime(bytes);
            if (!dataTime.HasValue)
            {
                return default;
            }
 
            /*byte[] byteProductID = new byte[4];
             Array.Copy(bytes, 9, byteProductID, 0, 4);
             var productId = Bytes2Int4(byteProductID);
             if (productId.ToString() != Settings.Transfer.SZJTKT.ProductId)
             return false;*/
 
            var list = new List<Model.MonitorDataDockingSrcRecord>();
            foreach (var x in appParas.RuleItems)
            {
                double ratio = 1;
                var record = new Model.MonitorDataDockingSrcRecord();
                record.SignId = x.SignId;
                record.RecordType = Model.eMonitorType.General;
                record.SrcTime = dataTime.Value;
                record.SrcValue = null;
                if (x.SignId == "kt_41" || x.SignId == "kt_43") //累积流量小数位倍率转换
                {
                    ratio = 0.001;
                }
                switch (x.Rule)
                {
                    case eRule.Double:
                        {
                            var btValue = bytes.Skip(x.Index).Take(x.Size).ToArray();
                            record.SrcValue = (Bytes2Double(btValue) * ratio).ToString();
                        }
                        break;
                    case eRule.Int4:
                        {
                            var btValue = bytes.Skip(x.Index).Take(x.Size).ToArray();
                            record.SrcValue = (Bytes2Int4(btValue) * ratio).ToString();
                        }
                        break;
                    case eRule.Int32:
                        {
                            var btValue = bytes.Skip(x.Index).Take(x.Size).ToArray();
                            record.SrcValue = (Bytes2Int32(btValue) * ratio).ToString();
                        }
                        break;
                    default: break;
                }
                list.Add(record);
            }
            if (list.Count < 1)
            {
                LogHelper.Error("数据解析失败!");
                return default;
            }
 
            #region 累积流量拼接
            var forwardCumulativeFlowInteger = list.Find(x => x.SignId == "kt_33");
            var forwardCumulativeFlowDecimal = list.Find(x => x.SignId == "kt_41");
            var reverseCumulativeFlowInteger = list.Find(x => x.SignId == "kt_37");
            var reverseCumulativeFlowDecimal = list.Find(x => x.SignId == "kt_43");
            var fcfdValue = forwardCumulativeFlowDecimal.SrcValue;
            if (!string.IsNullOrEmpty(fcfdValue))
            {
                if (double.TryParse(fcfdValue, out double value))
                {
                    if (double.TryParse(forwardCumulativeFlowInteger.SrcValue, out double fcfdValueReal))
                    {
 
                    }
                    forwardCumulativeFlowInteger.SrcValue = (fcfdValueReal + value).ToString();
                }
            }
 
            var rcfdValue = reverseCumulativeFlowDecimal.SrcValue;
            if (!string.IsNullOrEmpty(rcfdValue))
            {
                if (double.TryParse(rcfdValue, out double value))
                {
                    if (double.TryParse(reverseCumulativeFlowInteger.SrcValue, out double rcfdValueReal))
                    {
 
                    }
                    reverseCumulativeFlowInteger.SrcValue = (rcfdValueReal + value).ToString();
                }
            }
            #endregion
 
            return list;
        }
 
        /// <summary>
        /// 解析时间
        /// </summary> 
        private static DateTime? ParsingTime(byte[] bytes)
        {
            if (bytes == null || bytes.Count() < 12)
                return null;
            DateTime? dt = null;
            try
            {
                var byte4 = new byte[4];
 
                Array.Copy(bytes, 4, byte4, 0, 4);
                var dateInt = Bytes2Int4(byte4);//数据读取日期  
                Array.Copy(bytes, 8, byte4, 0, 4);
                var hmsInt = Bytes2Int4(byte4);//数据读取时间 
 
                var hmsStr = hmsInt.ToString();
                if (hmsStr.Length < 3)
                    hmsStr = "0000" + hmsStr;
                if (hmsStr.Length < 5)
                    hmsStr = "00" + hmsStr;
                if (hmsStr.Length < 6)
                    hmsStr = "0" + hmsStr;
                var hms = hmsStr.Substring(0, 2) + ":" + hmsStr.Substring(2, 2) + ":" + hmsStr.Substring(4, 2);
                var date = DateTime.ParseExact(dateInt.ToString(), "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
                var time = $"{date.ToString("d")} {hms}";
                dt = Convert.ToDateTime(time);
            }
            catch (Exception ex)
            {
                LogHelper.Error($"时间解析:{ex.Message}  Bytes:{Byte2String(bytes)}");
                return null;
            }
 
            return dt;
        }
 
        #region  字节转化方法
        public static int Bytes2Int4(byte[] src, int offset = 0)
        {
            src = src.Reverse().ToArray();
            int value;
            value = (int)(((src[offset] & 0xFF) << 24)
                    | ((src[offset + 1] & 0xFF) << 16)
                    | ((src[offset + 2] & 0xFF) << 8)
                    | (src[offset + 3] & 0xFF));
            return value;
        }
        public static double Bytes2Double(byte[] value, int offset = 0)
        {
            return BitConverter.ToSingle(value, 0);//采用了IEEE-754二进制浮点数算术标准
        }
        public static int Bytes2Int32(byte[] bytes)
        {
            return Convert.ToInt32(Byte2String(bytes.Reverse().ToArray()), 16); ;
        }
        public static string Byte2String(byte[] bytes)
        {
            string returnStr = "";
            if (bytes != null)
            {
                for (int i = 0; i < bytes.Length; i++)
                {
                    returnStr += bytes[i].ToString("X2");
                }
            }
            return returnStr;
        }
        #endregion
 
        #endregion
 
        #region 插入数据
        /// <summary>
        /// 插入数据
        /// </summary>
        /// <param name="registerCode">注册码</param>
        /// <param name="list"> 列表数据</param> 
        private static bool Insert(string registerCode, List<MonitorDataDockingSrcRecord> list)
        {
            try
            {
                var records = list.Select(x => new DataDockingStandardRecordDto(x.SignId, x.RecordType, x.SrcTime.Value, x.SrcValue));
                var model = new { RegisterCode = registerCode, Records = records };
                var url = Settings.Transfer.SZJTKT.TransferUrl;
                var data = JsonHelper.Object2Json(model);
                LogHelper.Debug(url + "/" + data);
                var responseText = HttpRequestHelper.Post(url, data);
                var result = JsonHelper.Json2Object<Result>(responseText);
                if (result.Code != 0)
                {
                    throw new Exception(result.Message);
                }
                return result.Data;
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex.Message);
                return false;
            }
        }
        #endregion
 
    }
}