中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

C#如何實現串口調試工具

發布時間:2022-01-26 11:44:00 來源:億速云 閱讀:201 作者:柒染 欄目:開發技術

C#如何實現串口調試工具,很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。

前文

由于經常用到串口調試, 盡管有現成的軟件, 因為前端時間涉及一個二次開發, 就因為一個RtsEnable設置, 折騰半天, 網上各種版本的也很多, 功能擴展的很開也多。所以現在自己做了一個夠用版,基于自己的需求,簡單的實現發送接收功能, 至于那些擴展功能可以自己根據需求添加。

正文

先上個運行效果圖:

C#如何實現串口調試工具

項目架構

該實例用的GalaSoft.Mvvm, 該插件可以直接在NuGet中并且添加。

C#如何實現串口調試工具

1.串口參數 , 為了方便, 端口號并沒有用動態加載的方式, 如下枚舉結構:

namespace System.Windows.Data
{
    //
    // 摘要:
    //     提供將自定義邏輯應用于綁定的方法。
    public interface IValueConverter
    {
        //
        // 摘要:
        //     轉換值。
        //
        // 參數:
        //   value:
        //     綁定源生成的值。
        //
        //   targetType:
        //     綁定目標屬性的類型。
        //
        //   parameter:
        //     要使用的轉換器參數。
        //
        //   culture:
        //     要用在轉換器中的區域性。
        //
        // 返回結果:
        //     轉換后的值。 如果該方法返回 null,則使用有效的 null 值。
        object Convert(object value, Type targetType, object parameter, CultureInfo culture);
        //
        // 摘要:
        //     轉換值。
        //
        // 參數:
        //   value:
        //     綁定目標生成的值。
        //
        //   targetType:
        //     要轉換為的類型。
        //
        //   parameter:
        //     要使用的轉換器參數。
        //
        //   culture:
        //     要用在轉換器中的區域性。
        //
        // 返回結果:
        //     轉換后的值。 如果該方法返回 null,則使用有效的 null 值。
        object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture);
    }
}

2.串口參數配置類 ,

作用: 主要用于綁定界面的參數選項。

/// <summary>
    /// 串口參數設置類
    /// </summary>
    public class ComParameterConfig : ViewModelBase
    {
        public ComParameterConfig()
        {
            Port = System.Enum.GetValues(typeof(Port));
            CheckMode = System.Enum.GetValues(typeof(CheckMode));
            StopBit = System.Enum.GetValues(typeof(StopBit));
            BaudRate = new List<int>() { 110, 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 38400, 56000, 57600, 115200, };
            DataBit = new List<int>() { 6, 7, 8 };
        }

        private Array port;
        private Array checkMode;
        private Array stopBit;
        private List<int> dataBit;
        private List<int> baudRate;

        /// <summary>
        /// 端口
        /// </summary>
        public Array Port
        {
            get { return port; }
            set { port = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 校驗模式
        /// </summary>
        public Array CheckMode
        {
            get { return checkMode; }
            set { checkMode = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 停止位
        /// </summary>
        public Array StopBit
        {
            get { return stopBit; }
            set { stopBit = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 波特率
        /// </summary>
        public List<int> BaudRate
        {
            get { return baudRate; }
            set { baudRate = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 數據位
        /// </summary>
        public List<int> DataBit
        {
            get { return dataBit; }
            set { dataBit = value; RaisePropertyChanged(); }
        }

    }

3.當前配置參數類

作用: 用于保存當前的串口參數、串口功能開關接收數據等業務。

核心代碼:

/// <summary>
    /// 當前配置參數
    /// </summary>
    public class CurrentParameter : ViewModelBase
    {
        #region Private

        private int baudRdate = 9600;
        private int dataBit = 8;
        private Port port;
        private CheckMode checkMode;
        private StopBit stopBit = StopBit.One;
        private SerialPort serialPort;

        private string dataReceiveInfo;
        private string sendData;
        private bool isOpen;
        private bool receiveFormat16 = true;
        private bool sendFormat16 = true;

        private int sendCount;
        private int receiveCount;

        #endregion

        #region UI綁定參數

        /// <summary>
        /// 發送數量
        /// </summary>
        public int SendCount
        {
            get { return sendCount; }
            set { sendCount = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 接收數量
        /// </summary>
        public int ReceiveCount
        {
            get { return receiveCount; }
            set { receiveCount = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 接收區16進制
        /// </summary>
        public bool ReceiveFormat16
        {
            get { return receiveFormat16; }
            set { receiveFormat16 = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 接收區數據
        /// </summary>
        public string DataReceiveInfo
        {
            get { return dataReceiveInfo; }
            set { dataReceiveInfo = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 發送數據
        /// </summary>
        public string SendData
        {
            get
            {
                return sendData;
            }
            set { sendData = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 發送區16進制
        /// </summary>
        public bool SendFormat16
        {
            get { return sendFormat16; }
            set { sendFormat16 = value; RaisePropertyChanged(); }
        }

        #endregion

        #region 串口參數信息

        /// <summary>
        /// 開關
        /// </summary>
        public bool IsOpen
        {
            get { return isOpen; }
            set { isOpen = value; RaisePropertyChanged(); }
        }


        /// <summary>
        /// 數據位
        /// </summary>
        public int DataBit
        {
            get { return dataBit; }
            set { dataBit = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 波特率
        /// </summary>
        public int BaudRdate
        {
            get { return baudRdate; }
            set { baudRdate = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 端口
        /// </summary>
        public Port Port
        {
            get { return port; }
            set { port = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 校驗
        /// </summary>
        public CheckMode CheckMode
        {
            get { return checkMode; }
            set { checkMode = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 停止位
        /// </summary>
        public StopBit StopBit
        {
            get { return stopBit; }
            set { stopBit = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// COM
        /// </summary>
        public SerialPort SerialPort
        {
            get { return serialPort; }
            set { serialPort = value; RaisePropertyChanged(); }
        }


        #endregion

        #region 串口操作方法

        /// <summary>
        /// 開啟串口
        /// </summary>
        /// <returns></returns>
        public bool Open()
        {
            if (serialPort != null && serialPort.IsOpen)
            {
                return Close();
            }
            try
            {
                serialPort = new SerialPort();
                serialPort.DataBits = this.DataBit;
                serialPort.StopBits = ComHelper.GetStopBits(this.StopBit.ToString());
                serialPort.Parity = ComHelper.GetParity(this.CheckMode.ToString());
                serialPort.PortName = this.Port.ToString();
                serialPort.RtsEnable = true;
                serialPort.DataReceived += SerialPort_DataReceived;
                serialPort.Open();

                if (serialPort.IsOpen)
                    return IsOpen = true;
                else
                    return IsOpen = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return IsOpen = false;
        }

        /// <summary>
        /// 關閉串口
        /// </summary>
        /// <returns></returns>
        public bool Close()
        {
            try
            {
                if (serialPort.IsOpen)
                {
                    serialPort.Close();
                    return IsOpen = serialPort.IsOpen;
                }
                else
                {
                    return IsOpen = serialPort.IsOpen;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return IsOpen = false;
            }
        }

        /// <summary>
        /// 發送數據
        /// </summary>
        public void Send()
        {

            if (SendFormat16)
            {
                byte[] bytes = CRC.StringToHexByte(SendData);
                this.SerialPort.Write(bytes, 0, bytes.Length);
                SendCount = bytes.Length; //不做增量
            }
            else
            {
                this.SerialPort.Write(SendData);
                SendCount = SendData.Length;
            }
            Messenger.Default.Send("", "PlaySendFlashing");
        }

        /// <summary>
        /// 清空接收區
        /// </summary>
        public void Clear()
        {
            this.DataReceiveInfo = string.Empty;
        }

        /// <summary>
        /// 清空發送區和緩存區
        /// </summary>
        public void ClearText()
        {
            this.SendData = string.Empty;
            this.SendCount = 0;
            this.ReceiveCount = 0;
        }

        #endregion

        /// <summary>
        /// 返回事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            Messenger.Default.Send("", "PlayReciveFlashing");

            byte[] readBuffer = new byte[SerialPort.ReadBufferSize];
            SerialPort.Read(readBuffer, 0, readBuffer.Length);

            ReceiveCount = SerialPort.ReceivedBytesThreshold; //不做增量

            if (ReceiveFormat16)
            {
                //不做增量
                DataReceiveInfo = CRC.ByteToString(readBuffer, true);
            }
            else
            {
                DataReceiveInfo = Encoding.ASCII.GetString(readBuffer);
            }

        }
    }

4.核心MainViewModel類

作用: 關聯首頁的上下文, 通過DataContext綁定, 關聯界面元素、命令等作用。

public class MainViewModel : ViewModelBase
    {
        /// <summary>
        /// Initializes a new instance of the MainViewModel class.
        /// </summary>
        public MainViewModel()
        {
            ComParameterConfig = new ComParameterConfig();
            CurrentParameter = new CurrentParameter();
        }

        private ComParameterConfig comParameter;

        /// <summary>
        /// 參數類
        /// </summary>
        public ComParameterConfig ComParameterConfig
        {
            get { return comParameter; }
            set { comParameter = value; RaisePropertyChanged(); }
        }

        private CurrentParameter currentParameter;

        /// <summary>
        /// 當前配置參數
        /// </summary>
        public CurrentParameter CurrentParameter
        {
            get { return currentParameter; }
            set { currentParameter = value; RaisePropertyChanged(); }
        }

        #region Command

        private RelayCommand _ToOpen;
        public RelayCommand ToOpen
        {
            get
            {
                if (_ToOpen == null)
                {
                    _ToOpen = new RelayCommand(Open);
                }
                return _ToOpen;
            }
            set
            {
                _ToOpen = value;
            }
        }
        /// <summary>
        /// 根據配置打開端口
        /// </summary>
        public void Open()
        {
            this.CurrentParameter.Open();
        }

        private RelayCommand _ToClick;
        public RelayCommand ToClick
        {
            get
            {
                if (_ToClick == null)
                {
                    _ToClick = new RelayCommand(Click);
                }
                return _ToClick;
            }
            set
            {
                _ToClick = value;
            }
        }

        /// <summary>
        /// 發送數據
        /// </summary>
        public void Click()
        {
            this.CurrentParameter.Send();
        }


        private RelayCommand _ToClear;

        public RelayCommand ToClear
        {
            get
            {
                if (_ToClear == null)
                {
                    _ToClear = new RelayCommand(Clear);
                }
                return _ToClear;
            }
            set
            {
                _ToClear = value;
            }
        }

        /// <summary>
        /// 清空接收區
        /// </summary>
        public void Clear()
        {
            this.CurrentParameter.Clear();
        }

        private RelayCommand _ToClearText;

        public RelayCommand ToClearText
        {
            get
            {
                if (_ToClearText == null)
                {
                    _ToClearText = new RelayCommand(ClearText);
                }
                return _ToClearText;
            }
            set
            {
                _ToClearText = value;
            }
        }

        /// <summary>
        /// 清空界面值
        /// </summary>
        public void ClearText()
        {
            this.CurrentParameter.ClearText();
        }

        #endregion
    }

5.CRC校驗核心類

作用:主要實現數據校驗, 含ModbusCR標準校驗

/// <summary>
    /// CRC校驗
    /// </summary>
    public class CRC
    {

        #region  CRC16

        public static byte[] CRC16(byte[] data)
        {
            int len = data.Length;
            if (len > 0)
            {
                ushort crc = 0xFFFF;

                for (int i = 0; i < len; i++)
                {
                    crc = (ushort)(crc ^ (data[i]));
                    for (int j = 0; j < 8; j++)
                    {
                        crc = (crc & 1) != 0 ? (ushort)((crc >> 1) ^ 0xA001) : (ushort)(crc >> 1);
                    }
                }
                byte hi = (byte)((crc & 0xFF00) >> 8);  //高位置
                byte lo = (byte)(crc & 0x00FF);         //低位置

                return new byte[] { hi, lo };
            }
            return new byte[] { 0, 0 };
        }
        #endregion

        #region  ToCRC16

        public static string ToCRC16(string content)
        {
            return ToCRC16(content, Encoding.UTF8);
        }

        public static string ToCRC16(string content, bool isReverse)
        {
            return ToCRC16(content, Encoding.UTF8, isReverse);
        }

        public static string ToCRC16(string content, Encoding encoding)
        {
            return ByteToString(CRC16(encoding.GetBytes(content)), true);
        }

        public static string ToCRC16(string content, Encoding encoding, bool isReverse)
        {
            return ByteToString(CRC16(encoding.GetBytes(content)), isReverse);
        }

        public static string ToCRC16(byte[] data)
        {
            return ByteToString(CRC16(data), true);
        }

        public static string ToCRC16(byte[] data, bool isReverse)
        {
            return ByteToString(CRC16(data), isReverse);
        }
        #endregion

        #region  ToModbusCRC16

        public static string ToModbusCRC16(string s)
        {
            return ToModbusCRC16(s, true);
        }

        public static string ToModbusCRC16(string s, bool isReverse)
        {
            return ByteToString(CRC16(StringToHexByte(s)), isReverse);
        }

        public static string ToModbusCRC16(byte[] data)
        {
            return ToModbusCRC16(data, true);
        }

        public static string ToModbusCRC16(byte[] data, bool isReverse)
        {
            return ByteToString(CRC16(data), isReverse);
        }
        #endregion

        #region  ByteToString

        public static string ByteToString(byte[] arr, bool isReverse)
        {
            try
            {
                byte hi = arr[0], lo = arr[1];
                return Convert.ToString(isReverse ? hi + lo * 0x100 : hi * 0x100 + lo, 16).ToUpper().PadLeft(4, '0');
            }
            catch (Exception ex) { throw (ex); }
        }

        public static string ByteToString(byte[] arr)
        {
            try
            {
                return ByteToString(arr, true);
            }
            catch (Exception ex) { throw (ex); }
        }

        #endregion

        #region  StringToHexString

        public static string StringToHexString(string str)
        {
            StringBuilder s = new StringBuilder();
            foreach (short c in str.ToCharArray())
            {
                s.Append(c.ToString("X4"));
            }
            return s.ToString();
        }

        #endregion

        #region  StringToHexByte

        private static string ConvertChinese(string str)
        {
            StringBuilder s = new StringBuilder();
            foreach (short c in str.ToCharArray())
            {
                if (c <= 0 || c >= 127)
                {
                    s.Append(c.ToString("X4"));
                }
                else
                {
                    s.Append((char)c);
                }
            }
            return s.ToString();
        }

        private static string FilterChinese(string str)
        {
            StringBuilder s = new StringBuilder();
            foreach (short c in str.ToCharArray())
            {
                if (c > 0 && c < 127)
                {
                    s.Append((char)c);
                }
            }
            return s.ToString();
        }

        /// <summary>
        /// 字符串轉16進制字符數組
        /// </summary>
        /// <param name="hex"></param>
        /// <returns></returns>
        public static byte[] StringToHexByte(string str)
        {
            return StringToHexByte(str, false);
        }

        /// <summary>
        /// 字符串轉16進制字符數組
        /// </summary>
        /// <param name="str"></param>
        /// <param name="isFilterChinese">是否過濾掉中文字符</param>
        /// <returns></returns>
        public static byte[] StringToHexByte(string str, bool isFilterChinese)
        {
            string hex = isFilterChinese ? FilterChinese(str) : ConvertChinese(str);

            //清除所有空格
            hex = hex.Replace(" ", "");
            //若字符個數為奇數,補一個0
            hex += hex.Length % 2 != 0 ? "0" : "";

            byte[] result = new byte[hex.Length / 2];
            for (int i = 0, c = result.Length; i < c; i++)
            {
                result[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
            }
            return result;
        }
        #endregion

    }

WPF技術點:

1.自定義樣式按鈕

<Style x:Key="CommonButtonBase" TargetType="{x:Type Button}">
                <Setter Property="BorderBrush" Value="Transparent"/>
                <Setter Property="BorderThickness" Value="0"/>
                <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
                <Setter Property="HorizontalContentAlignment" Value="Center"/>
                <Setter Property="VerticalContentAlignment" Value="Center"/>
                <Setter Property="Padding" Value="1"/>
                <Setter Property="Cursor" Value="Hand"/>
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="{x:Type Button}">
                            <Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" 
                                            CornerRadius="4"
                                            BorderThickness="{TemplateBinding BorderThickness}"
                                             Background="{TemplateBinding Background}"
                                             SnapsToDevicePixels="true">
                                <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" 
                                              Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" 
                                              SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" 
                                              VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                            </Border>
                            <ControlTemplate.Triggers>
                                <Trigger Property="IsEnabled" Value="False">
                                    <Setter Property="Background" Value="#000000"/>
                                    <Setter Property="Opacity" Value="0.1"/>
                                </Trigger>
                                <Trigger Property="IsMouseOver" Value="true">
                                    <Setter Property="Foreground" Value="#FFFF00"/>
                                </Trigger>
                                <Trigger Property="IsMouseOver" Value="false">
                                    <Setter Property="Foreground" Value="White"/>
                                </Trigger>
                            </ControlTemplate.Triggers>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        
            <Style TargetType="{x:Type Button}" x:Key="Btn0093EABase" BasedOn="{StaticResource CommonButtonBase}">
                <Setter Property="Background" Value="#0093EA"/>
                <Setter Property="Foreground" Value="White"/>
                <Setter Property="FontSize" Value="22"/>
                <Setter Property="Height" Value="40"/>
                <Setter Property="Margin" Value="5"/>
            </Style>

2.轉換器用于綁定按鈕

public class FontConverters : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value != null && bool.TryParse(value.ToString(), out bool result))
            {
                if (result)
                {
                    return "關閉串口";
                }
            }
            return "打開串口";
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
//用于綁定UI的顏色狀態顯示    public class ColorConverters : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value != null && bool.TryParse(value.ToString(), out bool result))
            {
                if (result)
                {
                    return new SolidColorBrush((Color)System.Windows.Media.ColorConverter.ConvertFromString("#2E8B57"));
                }
            }
            return new SolidColorBrush((Color)System.Windows.Media.ColorConverter.ConvertFromString("#FF6347"));
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

3.引用字體

   <TextBlock Text="&#xe6e4;" Margin="20 5 0 5" FontFamily="pack://application:,,,/Font/#iconfont" 
                                   Foreground="White" FontSize="30" VerticalAlignment="Center"/>

4.綁定命令和元素

<TextBlock Text="端     口:"  Style="{DynamicResource TxtComStyle}"/>
                        <ComboBox  Grid.Row="0" Grid.Column="2" Style="{StaticResource ComboBoxStyle}" SelectedItem="{Binding CurrentParameter.Port}"
                                  ItemsSource="{Binding ComParameterConfig.Port}"
                                   />
                        <TextBlock Text="波 特 率:" Style="{DynamicResource TxtComStyle}"/>
                        <ComboBox  Grid.Row="0" Grid.Column="2" Style="{StaticResource ComboBoxStyle}" SelectedItem="{Binding CurrentParameter.BaudRdate}"
                                   ItemsSource="{Binding ComParameterConfig.BaudRate}"
                                   />
                        <TextBlock Text="數 據 位:" Style="{DynamicResource TxtComStyle}"/>
                        <ComboBox  Grid.Row="0" Grid.Column="2" Style="{StaticResource ComboBoxStyle}"  SelectedItem="{Binding CurrentParameter.DataBit}"
                                   ItemsSource="{Binding ComParameterConfig.DataBit}"
                                   />
                        <TextBlock Text="校 驗 位:" Style="{DynamicResource TxtComStyle}"/>
                        <ComboBox  Grid.Row="0" Grid.Column="2" Style="{StaticResource ComboBoxStyle}"  SelectedItem="{Binding CurrentParameter.CheckMode}"
                                   ItemsSource="{Binding ComParameterConfig.CheckMode}"
                                   />
                        <TextBlock Text="停 止 位:" Style="{DynamicResource TxtComStyle}"/>
                        <ComboBox  Grid.Row="0" Grid.Column="2" Style="{StaticResource ComboBoxStyle}"  SelectedItem="{Binding CurrentParameter.StopBit}"
                                   ItemsSource="{Binding ComParameterConfig.StopBit}"
                                   />
                        <TextBlock Text="狀     態:" Style="{DynamicResource TxtComStyle}"/>
                        <TextBlock Text="&#xe692;" Style="{DynamicResource TxtComStyle1}"  Foreground="{Binding CurrentParameter.IsOpen,Converter={StaticResource ColorConverters}}" />

寫在最后

主項目的結構圖 , 如下:

C#如何實現串口調試工具

看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速云行業資訊頻道,感謝您對億速云的支持。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

邹平县| 兴安盟| 娱乐| 上虞市| 海阳市| 桃江县| 金溪县| 正镶白旗| 阳原县| 南郑县| 芜湖县| 塔城市| 太和县| 伊吾县| 濉溪县| 巴塘县| 隆林| 方正县| 石城县| 郁南县| 神木县| 海原县| 高清| 深州市| 文安县| 永清县| 河北省| 长阳| 拉萨市| 临夏市| 崇信县| 富民县| 章丘市| 沙河市| 施秉县| 全椒县| 宝鸡市| 柳州市| 榆中县| 光山县| 汪清县|