|
- using ModbusDemo.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
- {
- /// <summary>
- /// 这是CoilUC的VM用来支持数据绑定
- /// </summary>
- public class CoilUCViewModel : BindableBase
- {
- //获取读线圈的类
- private IModbusRTU _modbusRTU;
- //定义读线圈的命令
- public DelegateCommand ReadCoilCmm { get; set; }
- //获取当前使用的串口
- private SerialPort _serialPort;
- //显示当前链接串口的信息
- public string SerialPortInfo
- {
- get
- {
- return "当前链接的状态:" + "串口号:" + _serialPort.PortName + ",波特率:" + _serialPort.BaudRate
- + ",数据位:" + _serialPort.DataBits + ",校验位:" + _serialPort.Parity + ",停止位:" + _serialPort.StopBits;
- }
-
- }
-
-
- //读取的从站id
- private string _slaveAddress;
-
- public string SlaveAddress
- {
- get { return _slaveAddress; }
- set
- {
- _slaveAddress = value;
- RaisePropertyChanged();
- }
- }
-
- private string _startAddress;
-
- //读取的起始地址
- public string StartAddress
- {
- get { return _startAddress; }
- set
- {
- _startAddress = value;
- RaisePropertyChanged();
- }
- }
-
- private string _numberOfPoints;
-
- //读取的位数
- public string NumberOfPoints
- {
- get { return _numberOfPoints; }
- set
- {
- _numberOfPoints = value;
- RaisePropertyChanged();
- }
- }
-
- private string _readResult;
-
- //读取的结果
- public string ReadResult
- {
- get { return _readResult; }
- set
- {
- _readResult = value;
- RaisePropertyChanged();
- }
- }
-
-
-
- public CoilUCViewModel()
- {
-
- }
-
- public CoilUCViewModel(SerialPort serialPort, ModbusRTU modbusRTU)
- {
- _serialPort = serialPort;
- ReadCoilCmm = new DelegateCommand(ReadCoil);
- _modbusRTU = modbusRTU;
- }
-
- private void ReadCoil()
- {
-
-
- try
- {
- bool[] result = _modbusRTU.ReadCoil(byte.Parse(SlaveAddress),
- ushort.Parse(StartAddress),
- ushort.Parse(NumberOfPoints));
-
- if(result != null)
- {
- string temp = "";
- foreach(var item in result)
- {
- temp += item;
- temp += " ";
- }
- ReadResult = temp;
- }
-
-
- }
- catch (Exception)
- {
-
- MessageBox.Show("参数配置错误");
- }
-
-
-
-
- }
- }
- }
|