|
- using Modbus.Device;
- using Prism.Commands;
- using Prism.Mvvm;
- using System;
- using System.Collections.Generic;
- using System.IO.Ports;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows;
-
- namespace ModbusDemo.VIewModel
- {
- public class AttachUCViewModel : BindableBase
- {
-
- private SerialPort _serialPort;
- public DelegateCommand ReadOddRegisterCmm { get; set; }
- //读取的结果
- private string _readResult;
-
- public string ReadResult
- {
- get { return _readResult; }
- set
- {
- _readResult = value;
- RaisePropertyChanged();
- }
- }
- //显示操作的时间
- private int _time;
-
- public int Time
- {
- get { return _time; }
- set
- {
- _time = value;
- RaisePropertyChanged();
- }
- }
-
-
- public AttachUCViewModel()
- {
-
- }
- public AttachUCViewModel(SerialPort serialPort)
- {
- ReadOddRegisterCmm = new DelegateCommand(ReadOddRegister);
- _serialPort = serialPort;
- }
-
- private void ReadOddRegister()
- {
- // 创建 Modbus RTU 主站
-
- IModbusSerialMaster master = ModbusSerialMaster.CreateRtu(_serialPort);
- byte slaveId = 1;
- ushort totalRegisters = 1000;
- ushort chunkSize = 100;
- int numChunks = (int)Math.Ceiling((double)totalRegisters / chunkSize);
-
- ushort[] allRegisters = new ushort[totalRegisters];
- Task[] tasks = new Task[numChunks];
- DateTime startTime = DateTime.Now;
- for (int i = 0; i < numChunks; i++)
- {
- ushort startAddress = (ushort)(10300 + i * chunkSize);
- ushort currentChunkSize = 100;
-
- int chunkIndex = i;
- tasks[i] = Task.Run(() =>
- {
- try
- {
- ushort[] registers = master.ReadHoldingRegisters(slaveId, startAddress, currentChunkSize);
- Array.Copy(registers, 0, allRegisters, chunkIndex * chunkSize, currentChunkSize);
- }
- catch (Exception ex)
- {
- Console.WriteLine($"线程 {chunkIndex} 读取寄存器时出错: {ex.Message}");
- }
- });
- }
-
- // 等待所有任务完成
- Task.WaitAll(tasks);
- Time = (int)(DateTime.Now - startTime).TotalMilliseconds;
- StringBuilder result = new StringBuilder();
- int count = 0;
- for (int i = 1; i < totalRegisters; i += 2)
- {
- result.Append(allRegisters[i].ToString()+" ");
- count++;
- if (count % 50 == 0)
- {
- result.AppendLine();
- }
- }
- ReadResult = result.ToString();
-
- }
- }
-
- }
|