using ModbusDemo.Uitls;
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;
namespace ModbusDemo.VIewModel
{
class SettingsUCViewModel : BindableBase
{
public DelegateCommand DisConnectionCmm { get; set; }
//链接窗口的命令
public DelegateCommand ConnectionCmm { get; set; }
//获取串口
private SerialPort _serialPort;
//设置串口名字
private string _portName = "COM1";
public string PortName
{
get { return _portName; }
set
{
_portName = value;
RaisePropertyChanged();
}
}
//设置波特率
private string _baudRate = "19200";
public string BaudRate
{
get { return _baudRate; }
set
{
_baudRate = value;
RaisePropertyChanged();
}
}
//设置数据位
private string _dataBits = "8";
public string DataBits
{
get { return _dataBits; }
set
{
_dataBits = value;
RaisePropertyChanged();
}
}
//设置校验位
private Parity _parity = Parity.Even;
public Parity Parity
{
get { return _parity; }
set
{
_parity = value;
RaisePropertyChanged();
}
}
//设置停止位
private StopBits _stopBits = StopBits.One;
public StopBits StopBits
{
get { return _stopBits; }
set
{
_stopBits = value;
RaisePropertyChanged();
}
}
public SettingsUCViewModel()
{
}
///
/// 从容器中获取创建的窗口
///
///
public SettingsUCViewModel(SerialPort serialPort)
{
_serialPort = serialPort;
ConnectionCmm = new DelegateCommand(Connection);
DisConnectionCmm = new DelegateCommand(DisConnection);
}
private void DisConnection()
{
if (_serialPort.IsOpen)
{
_serialPort.Close();
}
}
///
/// 串口参数设置
///
private void Connection()
{
//todo,做数据的判空处理
if (!_serialPort.IsOpen)
{
_serialPort.PortName = GetComboBoxItemValue(this.PortName);
_serialPort.BaudRate = int.Parse(GetComboBoxItemValue(this.BaudRate));
_serialPort.Parity = this.Parity;
_serialPort.StopBits = this.StopBits;
_serialPort.DataBits = int.Parse(GetComboBoxItemValue(this.DataBits));
_serialPort.Open();
}
List bytes = new List();
bytes.Add(0x01);
bytes.Add(0x05);
bytes.Add(BitConverter.GetBytes(301)[1]);
bytes.Add(BitConverter.GetBytes(301)[0]);
bytes.Add(0xFF);
bytes.Add(0x00);
byte[] bytes1 = CRCUitl.CalculateCRC(bytes.ToArray(), bytes.Count);
bytes.Add(bytes1[0]);
bytes.Add(bytes1[1]);
byte[] bytes2 = bytes.ToArray();
System.Threading.Thread.Sleep(200); // 等待200毫秒
byte[] response = new byte[_serialPort.BytesToRead];
//int bytesRead = serialPort.Read(response, 0, response.Length);
//string hexResponse = BitConverter.ToString(response, 0, bytesRead);
_serialPort.Write(bytes2, 0, bytes2.Length);
}
///
/// 处理下拉框的选择信息
///
///
///
private string GetComboBoxItemValue(string ComboBoxItem)
{
string displayText = ComboBoxItem.ToString();
string cleanText = displayText.Replace("System.Windows.Controls.ComboBoxItem: ", "");
return cleanText;
}
}
}