轮胎外观检测添加思谋语义分割模型检测工具
C3204
2026-03-30 06c627ec032b3f3876fd7db8a3ff0ff1a6614fa2
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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
using Modbus.Device;
using Modbus.Extensions.Enron;
using LB_VisionProcesses.Communicators;
using LB_VisionProcesses.Processes;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Text;
using LB_VisionProcesses.Communicators.Modbus;
 
namespace LB_VisionProcesses.Processes
{
    [Serializable]
    public class ModbusTCPMasterTool : BaseProcess
    {
        private ModbusSerialMaster Master = null;
 
        string CommunicatorName { get { return Params.Inputs["通讯口名"]?.ToString(); } }
 
        public ModbusTCPMasterTool()
        {
            strProcessName = "MoudbusTCP主站工具";
            strProcessClass = "LB_VisionProcesses.Processes.ModbusTCPMasterTool";
 
            // 连接参数
            Params.Inputs.Add("通讯口名", "");
            Params.Inputs.Add("首地址", 100);
            Params.Inputs.Add("寄存器个数", 300);
 
            // 读写参数
            Params.Inputs.Add("通讯类型", ModbusType.Write);
            Params.Inputs.Add("功能码", ModbusFunctionCode.HoldingRegisters);
            Params.Inputs.Add("设备地址", 1);
            Params.Inputs.Add("寄存器地址", 100);
            Params.Inputs.Add("读写寄存器个数", 1);
 
            Params.Inputs.Add("通讯消息", "");
            Params.Outputs.Add("收到消息", "");
        }
 
        bool ModbusRead(ModbusFunctionCode FunctionCode, byte slaveAddress, ushort startAddress, ushort numberOfPoints, out ushort[] msg)
        {
            if (Master == null)
            {
                msg = new ushort[] { };
                return false;
            }
 
            try
            {
                switch (FunctionCode)
                {
                    case ModbusFunctionCode.Coils:
                        bool[] Coils = Master.ReadCoils(slaveAddress, startAddress, numberOfPoints);
                        msg = new ushort[Coils.Length];
                        for (int i = 0; i < Coils.Length; i++)
                            msg[i] = (ushort)(Coils[i] ? 1 : 0);
                        break;
                    case ModbusFunctionCode.DiscreteInputs:
                        bool[] Inputs = Master.ReadInputs(slaveAddress, startAddress, numberOfPoints);
                        msg = new ushort[Inputs.Length];
                        for (int i = 0; i < Inputs.Length; i++)
                            msg[i] = (ushort)(Inputs[i] ? 1 : 0);
                        break;
                    case ModbusFunctionCode.HoldingRegisters:
                        ushort[] HoldingRegisters = Master.ReadHoldingRegisters(slaveAddress, startAddress, numberOfPoints);
                        msg = HoldingRegisters;
                        break;
                    case ModbusFunctionCode.InputRegisters:
                        ushort[] InputRegisters = Master.ReadInputRegisters(slaveAddress, startAddress, numberOfPoints);
                        msg = InputRegisters;
                        break;
                    default:
                        msg = new ushort[] { };
                        return false;
                }
                return true;
            }
            catch { msg = new ushort[] { }; return false; }
        }
 
        bool ModbusWrite(ModbusFunctionCode FunctionCode, byte slaveAddress, ushort startAddress, ushort numberOfPoints, string msg)
        {
            if (Master == null)
                return false;
 
            try
            {
                // 分割字符串并转换为 ushort 数组
                ushort[] data = msg.Split(' ', StringSplitOptions.RemoveEmptyEntries)
                                           .Select(hex => Convert.ToUInt16(hex))
                                           .ToArray();
 
                // (0x00 = false, 非0 = true)
                bool[] result = msg.Split(' ', StringSplitOptions.RemoveEmptyEntries)
                                         .Select(hex => Convert.ToByte(hex, 16) != 0)
                                         .ToArray();
 
                switch (FunctionCode)
                {
                    case ModbusFunctionCode.Coils:
                        Master.WriteMultipleCoils(slaveAddress, startAddress, result);
                        break;
                    case ModbusFunctionCode.DiscreteInputs:
                    case ModbusFunctionCode.InputRegisters:
                    case ModbusFunctionCode.HoldingRegisters:
                        Master.WriteMultipleRegisters(slaveAddress, startAddress, data);
                        break;
                    default:
                        return false;
                }
                return true;
            }
            catch { return false; }
        }
 
        /// <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();
 
                foreach (var port in IProcess.lstCommunicators)
                {
                    if (port.CommunicatorName != CommunicatorName || !(port is ModbusRTUMaster RTU))
                        break;
 
                    if (!RTU.bConnected)
                    {
                        Msg = $"通讯口[{CommunicatorName}]未连接";
                        Result = false;
                        return Result;
                    }
 
                    // 断开已有连接
                    if (Master != null)
                        Master.Dispose();
 
                    Master = ModbusSerialMaster.CreateRtu(RTU.SerialPort);
                    Master.Transport.WriteTimeout = 2000;
                    Master.Transport.ReadTimeout = 2000;
                    Master.Transport.WaitToRetryMilliseconds = 500;
                    Master.Transport.Retries = 3;
                }
 
                if (!Enum.TryParse(Params.Inputs["功能码"].ToString(), out ModbusFunctionCode FunctionCode))
                {
                    Msg = $"通讯口[{CommunicatorName}]功能码类型不正确,值为:{Params.Inputs["功能码"].ToString()}";
                    Result = false;
                    return Result;
                }
 
                if (!Enum.TryParse(Params.Inputs["通讯类型"].ToString(), out ModbusType ModbusType))
                {
                    Msg = $"通讯口[{CommunicatorName}]通讯类型类型不正确,值为:{Params.Inputs["通讯类型"].ToString()}";
                    Result = false;
                    return Result;
                }
 
                string WriteMsg = Params.Inputs["通讯消息"].ToString();
                string ShouldReadMsg = Params.Inputs["通讯消息"].ToString();
 
                byte slaveAddress = Convert.ToByte(Params.Inputs["设备地址"].ToString());
                ushort startAddress = Convert.ToUInt16(Params.Inputs["寄存器地址"].ToString());
                ushort numberOfPoints = Convert.ToUInt16(Params.Inputs["读写寄存器个数"].ToString());
 
                switch (ModbusType)
                {
                    case ModbusType.Read:
                        ModbusRead(FunctionCode, slaveAddress, startAddress, numberOfPoints, out ushort[] readResult);
 
                        // 直接输出读到的结果
                        if (string.IsNullOrEmpty(ShouldReadMsg) || ShouldReadMsg == "")
                            Params.Outputs["收到消息"] = string.Join(" ", readResult);
                        else
                        {
                            // 分割字符串并转换为 ushort 数组
                            ushort[] data = ShouldReadMsg.Split(' ', StringSplitOptions.RemoveEmptyEntries)
                                                       .Select(hex => Convert.ToUInt16(hex))
                                                       .ToArray();
 
                            if (data != readResult)
                            {
                                Msg = $"通讯口[{CommunicatorName}]读到的结果错误,实际为{readResult}";
                                Result = false;
                            }
                        }
                        break;
                    case ModbusType.Write:
                        ModbusWrite(FunctionCode, slaveAddress, startAddress, numberOfPoints, WriteMsg);
                        break;
                    default:
                        Msg = $"通讯类型只支持读和写!";
                        Result = false;
                        break;
                }
            }
            catch (Exception ex)
            {
                Params.Outputs.Add("收到消息", "");
                Msg = $"通讯异常,原因是:{ex.Message}";
                Result = false;
            }
            return Result;
        }
 
        public override void InitRunParams()
        {
            Result = true;
            Msg = "";
 
            if (Record != null)
                Record.Dispose();
        }
 
        public override void Dispose()
        {
            if (Master != null)
                Master.Dispose();
 
            return;
        }
 
        public override object Clone()
        {
            return MemberwiseClone();
        }
    }
}