You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

138 line
3.3 KiB

  1. using ModbusDemo.Device;
  2. using Prism.Commands;
  3. using Prism.Mvvm;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.IO.Ports;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. using System.Windows;
  11. namespace ModbusDemo.VIewModel
  12. {
  13. /// <summary>
  14. /// 这是CoilUC的VM用来支持数据绑定
  15. /// </summary>
  16. public class CoilUCViewModel : BindableBase
  17. {
  18. //获取读线圈的类
  19. private IModbusRTU _modbusRTU;
  20. //定义读线圈的命令
  21. public DelegateCommand ReadCoilCmm { get; set; }
  22. //获取当前使用的串口
  23. private SerialPort _serialPort;
  24. //显示当前链接串口的信息
  25. public string SerialPortInfo
  26. {
  27. get
  28. {
  29. return "当前链接的状态:" + "串口号:" + _serialPort.PortName + ",波特率:" + _serialPort.BaudRate
  30. + ",数据位:" + _serialPort.DataBits + ",校验位:" + _serialPort.Parity + ",停止位:" + _serialPort.StopBits;
  31. }
  32. }
  33. //读取的从站id
  34. private string _slaveAddress;
  35. public string SlaveAddress
  36. {
  37. get { return _slaveAddress; }
  38. set
  39. {
  40. _slaveAddress = value;
  41. RaisePropertyChanged();
  42. }
  43. }
  44. private string _startAddress;
  45. //读取的起始地址
  46. public string StartAddress
  47. {
  48. get { return _startAddress; }
  49. set
  50. {
  51. _startAddress = value;
  52. RaisePropertyChanged();
  53. }
  54. }
  55. private string _numberOfPoints;
  56. //读取的位数
  57. public string NumberOfPoints
  58. {
  59. get { return _numberOfPoints; }
  60. set
  61. {
  62. _numberOfPoints = value;
  63. RaisePropertyChanged();
  64. }
  65. }
  66. private string _readResult;
  67. //读取的结果
  68. public string ReadResult
  69. {
  70. get { return _readResult; }
  71. set
  72. {
  73. _readResult = value;
  74. RaisePropertyChanged();
  75. }
  76. }
  77. public CoilUCViewModel()
  78. {
  79. }
  80. public CoilUCViewModel(SerialPort serialPort, ModbusRTU modbusRTU)
  81. {
  82. _serialPort = serialPort;
  83. ReadCoilCmm = new DelegateCommand(ReadCoil);
  84. _modbusRTU = modbusRTU;
  85. }
  86. private void ReadCoil()
  87. {
  88. try
  89. {
  90. bool[] result = _modbusRTU.ReadCoil(byte.Parse(SlaveAddress),
  91. ushort.Parse(StartAddress),
  92. ushort.Parse(NumberOfPoints));
  93. if(result != null)
  94. {
  95. string temp = "";
  96. foreach(var item in result)
  97. {
  98. temp += item;
  99. temp += " ";
  100. }
  101. ReadResult = temp;
  102. }
  103. }
  104. catch (Exception)
  105. {
  106. MessageBox.Show("参数配置错误");
  107. }
  108. }
  109. }
  110. }