lixiaojun
2022-07-28 7c1a4c8369edc38dcf4dc96400df03ca390ad4ef
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace IStation.Model
{
    /// <summary>
    /// 报文头
    /// </summary>
    public class Header
    {
        /// <summary>
        /// 
        /// </summary>
        public Header() { }
        private Header(byte[] bts) 
        {
            Type = (eDatagramType)BitConverter.ToInt32(bts, 4);
            Array.Copy(bts, 8, Memo, 0, 4);
            KeyNum = BitConverter.ToInt32(bts, 12);
            PackLen = BitConverter.ToInt32(bts, 16);
        }
 
        /// <summary>
        /// 
        /// </summary>
        public byte[] Head
        {
            get { return _head.ToArray(); }
        }
        private byte[] _head = new byte[4] { 0xa5, 0xa5, 0xa5, 0xa5, };
 
        /// <summary>
        /// 
        /// </summary>
        public eDatagramType Type { get; set; }
 
        /// <summary>
        /// 
        /// </summary>
        public byte[] Memo { get; set; } = new byte[4];
 
        /// <summary>
        /// 
        /// </summary>
        public int KeyNum { get; set; }
 
        /// <summary>
        /// 
        /// </summary>
        public int PackLen { get; set; }
 
        /// <summary>
        /// 
        /// </summary>
        public static Header Get(byte[] bts)
        {
            if (bts == null)
                return null;
            if (bts.Count() != 20)
                return null;
            if (bts[0] != 0xa5)
                return null;
            if (bts[1] != 0xa5)
                return null;
            if (bts[2] != 0xa5)
                return null;
            if (bts[3] != 0xa5)
                return null;
            return new Header(bts);
        }
 
        /// <summary>
        /// 
        /// </summary>
        public byte[] GetBuffer()
        {
            var bts = new byte[20];
            Array.Copy(Head, 0, bts, 0, 4);
            var typeBuffer = BitConverter.GetBytes((int)Type);
            Array.Copy(typeBuffer, 0, bts, 4, 4);
            Array.Copy(Memo, 0, bts, 8, 4);
            var keyNumBuffer = BitConverter.GetBytes(KeyNum);
            Array.Copy(keyNumBuffer, 0, bts, 12, 4);
            var packLenBuffer = BitConverter.GetBytes(PackLen);
            Array.Copy(packLenBuffer, 0, bts, 16, 4);
            return bts;
        }
 
 
 
 
    }
}