C3204
2025-12-18 d85cbf0ccd61d95b96695756e0c90db8b7679545
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
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Text;
 
namespace LB_VisionProcesses.Communicators
{
    [Serializable]
    [Process("通讯测试", Category = "通讯工具", Description = "创建通讯测试工具")]
    public class CommunicatorConfig : IProcess
    {
        /// <summary>
        /// 通讯集合(Key:通讯名,Value:通讯句柄)
        /// </summary>
        public ConcurrentDictionary<string, BaseCommunicator> dicCommunicators { get; set; }
 
        public CommunicatorConfig(ConcurrentDictionary<string, BaseCommunicator> dicCommunicators)
        {
            this.dicCommunicators = dicCommunicators;
 
            strProcessName = "通讯测试";
            strProcessClass = "LB_VisionProcesses.Communicators.CommunicatorConfig";
 
            Params.Inputs.Add("通讯口名", "");
            Params.Inputs.Add("通讯类型", CommunicatorType.Receiver);
            Params.Inputs.Add("是否启用CRC校验", false);
            Params.Inputs.Add("通讯消息", "");
            Params.Outputs.Add("收到消息", "");
        }
 
        /// <summary>
        /// 加载算法
        /// </summary>
        /// <param name="fullPath">完整路径带.json</param>
        /// <returns></returns>
        public override bool Load(string fullPath = null)
        {
            try
            {
                if (string.IsNullOrEmpty(fullPath))
                    return false;
 
                if (!fullPath.Contains(".json"))
                {
                    Debug.WriteLine("文件路径不完整");
                    return false;
                }
                if (string.IsNullOrEmpty(fullPath) || fullPath.Trim() == "")
                {
                    Debug.WriteLine("文件路径不完整");
                    return false;
                }
 
                // 获取不带文件名的目录路径
                string directoryPath = Path.GetDirectoryName(fullPath);
                strProcessName = Path.GetFileNameWithoutExtension(fullPath);
 
                if (!File.Exists(fullPath))
                {
                    Debug.WriteLine("文件不存在创建空文件");
                    Save(directoryPath);
                    return true;
                }
 
                string strJson = string.Empty;
                using (StreamReader streamReader = new StreamReader(fullPath, Encoding.UTF8))
                {
                    strJson = streamReader.ReadToEnd();
                    streamReader.Close();
                }
                Params = JsonConvert.DeserializeObject<ProcessParams>(strJson);
                if (Params == null)
                    return false;
 
                Params.FixDeserializedData();
                return true;
            }
            catch { return false; }
        }
 
        /// <summary>
        /// 保存算法
        /// </summary>
        /// <param name="filePath">不带.json</param>
        /// <returns></returns>
        public override bool Save(string filePath = null)
        {
            try
            {
                if (string.IsNullOrEmpty(filePath) || filePath.Trim() == "")
                {
                    Debug.WriteLine("文件路径不完整");
                    return false;
                }
 
                string strJson = string.Empty;
                var settings = new JsonSerializerSettings
                {
                    Formatting = Newtonsoft.Json.Formatting.Indented,
                    // 自定义缩进(4空格)
                    ContractResolver = new DefaultContractResolver
                    {
                        NamingStrategy = new CamelCaseNamingStrategy()
                    }
                };
                strJson = JsonConvert.SerializeObject(Params, settings);
 
                Params = JsonConvert.DeserializeObject<ProcessParams>(strJson);
                if (Params == null)
                    return false;
 
                //判断文件夹是否存在,防呆输入为文件名称
                if (!Directory.Exists(filePath))
                {
                    try
                    {
                        Directory.CreateDirectory(filePath);
                    }
                    catch (Exception)
                    { }
                }
                File.WriteAllText(filePath + "//" + strProcessName + ".json", strJson, Encoding.UTF8);
                return true;
            }
            catch { return false; }
        }
 
        public override bool Run()
        {
            try
            {
                InitRunParams();
                Params.Outputs["收到消息"] = "";
                string CommunicatorName = Params.Inputs["通讯口名"].ToString();
 
                if (!dicCommunicators.ContainsKey(CommunicatorName))
                {
                    Msg = $"通讯口[{CommunicatorName}]不存在";
                    Result = false;
                    return Result;
                }
 
                BaseCommunicator BaseCommunicator = dicCommunicators[CommunicatorName];
 
                if (BaseCommunicator == null)
                {
                    Msg = $"通讯口[{CommunicatorName}]未实例化";
                    Result = false;
                    return Result;
                }
 
                if (!BaseCommunicator.bConnected)
                {
                    Msg = $"通讯口[{CommunicatorName}]未连接";
                    Result = false;
                    return Result;
                }
 
                if (!Enum.TryParse(Params.Inputs["通讯类型"].ToString(), out CommunicatorType CommunicatorType))
                {
                    Msg = $"通讯口[{CommunicatorName}]通讯类型不正确,值为:{Params.Inputs["通讯类型"].ToString()}";
                    Result = false;
                    return Result;
                }
 
 
                if (Params.Inputs["通讯消息"] is List<string>)
                {
                    List<string> listMsg = (List<string>)Params.Inputs["通讯消息"];
                    if (listMsg.Count > 0)
                        Params.Inputs["通讯消息"] = string.Join(',', listMsg);
                }
 
                string SendMsg = Params.Inputs["通讯消息"].ToString();
                string ShouldReceiveMsg = Params.Inputs["通讯消息"].ToString();
                bool CheckRule = Convert.ToBoolean(Params.Inputs["是否启用CRC校验"]);
 
                switch (CommunicatorType)
                {
                    case CommunicatorType.Sender:
                        if (CheckRule)
                        {
                            byte[] HexByte = BaseCommunicator.strToHexByte(SendMsg);
                            ushort crcHexByte = BaseCommunicator.CRC16Calculate(HexByte, HexByte.Length);
 
                            string crcString = crcHexByte.ToString("X4");
                            //HexByte = strToHexByte(strSendMsg + crcString);
                            SendMsg = SendMsg + crcString;
                        }
                        Result = BaseCommunicator.SendMessage(SendMsg);
                        break;
                    case CommunicatorType.Receiver:
                        string receiveMsg = BaseCommunicator.ReceiveMsg();
                        Params.Outputs["收到消息"] = receiveMsg;
 
                        //不设置消息时默认PASS
                        if (ShouldReceiveMsg == "")
                        {
                            Result = true;
                            return Result;
                        }
 
                        if (!receiveMsg.Contains(ShouldReceiveMsg))
                        {
                            Msg = $"通讯口[{CommunicatorName}]收到消息不全,应包含{ShouldReceiveMsg}";
                            Result = false;
                        }
                        break;
                    default:
                        Msg = $"通讯类型只支持发送消息和接收消息!";
                        Result = false;
                        break;
                }
            }
            catch (Exception ex)
            {
                Msg = $"通讯异常,原因是:{ex.Message}";
                Result = false;
            }
            return Result;
        }
 
        public override void InitRunParams()
        {
            Result = true;
            Msg = "";
 
            if (Record != null)
                Record.Dispose();
        }
 
        public override void Dispose()
        {
            return;
        }
 
        public override object Clone()
        {
            return MemberwiseClone();
        }
    }
}