首先说一下,这个上位机是模拟服务器对嵌入式设备发起通信进行OTA升级。如下图所示
上位机发送过程:服务器将数据发送到云端,云端是通信模块的,比如移动/电信的云平台,云端将数据传给通信模块,比如NB模块(插SIM卡),通信模块接收到数据后会通过串口通知主控板有数据可取,主控板再获取数据。
下位机回复过程:也是一样的,从主控板到通信模块到云到服务器。
那么我们做的上位机就是替代了整个无线传输的过程,直接与主控板通信。无线传输的过程因为涉及到通信模块和云端,还是有不少的工作,比如延迟,通信模块接收不到云端数据等等,不在此讨论了。
那么第一件事就是要定通信协议。通常一帧数据由 包头+长度+命令(+确认码)+包号+数据+CRC校验码 组成。
有可能初学者(包括当年的我)不理解为什么要定义那么长的通信协议,直接发那几个关键的数据比如让主控板亮灯的命令是07,发07不就行了。那么有个问题,如果不是我们给它发送的命令,它从别处也接收到了命令07,是不是也会处理了?这就是数据的合法性问题。
举个例子,有人命令你做事情,你是不是要看看命令的人是谁(包头是否正确)?如果命令的人不是你的家人、领导等,而是别的陌生人,正常情况你是不是拒绝执行, 后面的话也懒得听了(包头不正确后续的内容直接不处理了)?如果是认识的人,你愿意听命令(包头正确),那是不是也要看看命令是否正确(命令码)?比如让你扫地,你可以执行。如果命令不正确,比如让你跳楼,你是不是应该拒绝执行,并回复命令错误(确认码)?
因此我们知道,通信协议是为了保障通信的合法和畅顺,如果对每一帧数据加密,还可以提高安全性。
协议内容如下
上位机的一帧数据由 包头+长度+命令+包号+数据+CRC校验码 组成
包头2BYTE | 长度1BYTE | 命令1BYTE | 包号2BYTE | 数据250BYTE | CRC校验码2BYTE |
---|---|---|---|---|---|
0xCC 0x33 |
下位机的一帧数据由 包头+长度+命令+确认码+包号+数据+CRC校验码 组成
包头2BYTE | 长度1BYTE | 命令1BYTE | 确认码1BYTE | 包号2BYTE | 数据250BYTE | CRC校验码2BYTE |
---|---|---|---|---|---|---|
0xCC 0x33 |
包头是固定的两个字节:0xCC 0x33,也就是说下位机接受到的第一个字节是0xCC,第二个字节是0x33。
猜猜为什么?之前做项目用的是0xAA 0x55,原因是一样的
长度是从命令开始到CRC校验码的长度。
上位机的长度:命令(1BYTE)+包号(2BYTE)+数据的长度(最大250BYTE)+CRC校验码(2BYTE),所以长度最大为255即0xFF。
下位机的长度:命令(1BYTE)+包号(2BYTE)+确认码(1BYTE)+数据的长度(最大249BYTE)+CRC校验码(2BYTE),所以长度最大为255即0xFF。
包号:主要用于传输大数据的时候,比如需要传输10K的数据,那么需要将10K的数据分成大小为250BYTE的小数据包共40个包,那么包号就从1到40。这样方便如果传输过程中通信中断,下次可以从断点传输。断电传输可以由上位机发起,也可以由下位机主动申请。
CRC校验码为除去包头和长度,从命令开始到数据的累加和。
确认码是下位机的回复确认,如果不为0则需要查看对应的错误码,比如0x01是长度不正确。
为什么设计成上位机主动发起,下位机被动回复?因为嵌入式的设备大部分情况下是一对多通信,比如家里的空调,空调(下位机)只有一个,但是遥控(上位机)可以有多个,可以是红外遥控,可以是男主人手中的带红外功能的手机,可以是女主人手机蓝牙控制,甚至可以是插了USB控制器的PC控制。所以通常情况下,下位机是比较被动的。当然,反过来也可以,具体情况具体分析。
①通信测试协议
命令:0x01
功能:上位机给下位机发送,测试通信是否OK
上位机发送
包头2BYTE | 长度1BYTE | 命令1BYTE | 包号2BYTE | 数据250BYTE | CRC校验码2BYTE |
---|---|---|---|---|---|
0xCC 0x33 | 0x05 | 0x01 | 0x0001 | 无 | 0x0002 |
下位机回复
包头2BYTE | 长度1BYTE | 命令1BYTE | 包号2BYTE | 确认码1BYTE | 数据250BYTE | CRC校验码2BYTE |
---|---|---|---|---|---|---|
0xCC 0x33 | 0x06 | 0x01 | 0x0001 | 0x00 | 无 | 0x0002 |
确认码:
0x00:OK
0xFF:包头错误
0x01:长度错误
0x02:命令不存在
0x03:CRC校验码错误
也就是说正常情况是:
上位机发送:CC 33 05 01 00 01 00 02
下位机回复:CC 33 06 01 00 01 00 00 02
如果长度错误,则是:
上位机发送:CC 33 06 01 00 01 00 02
下位机回复:CC 33 06 01 00 01 01 00 03
上位机先在UI添加一个按钮,这里需要注意的是IsEnabled=“false”,意思是这个按钮是不可用的,也就是灰色的无法点击,需要我们点击打开串口按钮成功后,才会恢复正常
<Grid Grid.Row="2">
<Button Content="通信测试" Name="Button_CommunicationTest" Click="Button_CommunicationTest_Click" Height="40" Width="70" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="10,10,0,0" IsEnabled="False"></Button>
<Label Height="1" Background="Black" VerticalAlignment="Bottom"></Label>
</Grid>
后台点击按钮的事件
public byte[] uart_send_data = new byte[256];
private ushort Get_Crc(byte[] buffer, int length)
{
ushort crc = 0;
//i = 3 从命令开始计算CRC
for (ushort i = 3; i < length; i++)
{
crc += buffer[i];
}
return crc;
}
private void Button_CommunicationTest_Click(object sender, RoutedEventArgs e)
{
//直接赋值了,这样直观一些,习惯宏定义灵活的同学可以自行修改
//包头
uart_send_data[0] = 0xCC;
uart_send_data[1] = 0x33;
//长度:从命令到CRC
uart_send_data[2] = 0x05;
//命令
uart_send_data[3] = 0x01;
//包号
uart_send_data[4] = 0x00;
uart_send_data[5] = 0x01;
//CRC校验:从命令到数据,offset:3 clc num:3
ushort crc = Get_Crc(uart_send_data, 3 + 3);
uart_send_data[6] = (byte)(crc >> 8);
uart_send_data[7] = (byte)(crc & 0x00FF);
//串口发送数据
serialPort.Write(uart_send_data, 0, 8);
}
在打开串口的代码后面,加上接收监听事件,并在外添加监听内容代码。同时开放通信测试按钮
serialPort.Open();
serialPort.DataReceived += new SerialDataReceivedEventHandler(SerialDataReceivedHandler);
Button_OpenCloseSerial.Content = "关闭串口";
Button_CommunicationTest.IsEnabled = true;
private void SerialDataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
int recv_length = serialPort.BytesToRead;
byte[] recv_data = new byte[recv_length];
serialPort.Read(recv_data, 0, recv_length);
}
下位机用的MCU是常见的STM32F103C8T6
用串口1 PA9,P10通信,初始化代码如下
void Hw_Uart1_Init(unsigned int baudrate)
{
//GPIO端口设置
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1 |RCC_APB2Periph_GPIOA, ENABLE); //使能USART1,GPIOA时钟
//USART1_TX GPIOA.9
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9; //PA.9
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //复用推挽输出
GPIO_Init(GPIOA, &GPIO_InitStructure); //初始化GPIOA.9
//USART1_RX GPIOA.10初始化
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10; //PA10
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING; //浮空输入
GPIO_Init(GPIOA, &GPIO_InitStructure); //初始化GPIOA.10
//Usart1 NVIC 配置
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 3 ; //抢占优先级3
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; //子优先级3
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //IRQ通道使能
NVIC_Init(&NVIC_InitStructure); //根据指定的参数初始化VIC寄存器
//USART 初始化设置
USART_InitStructure.USART_BaudRate = baudrate; //串口波特率
USART_InitStructure.USART_WordLength = USART_WordLength_8b; //字长为8位数据格式
USART_InitStructure.USART_StopBits = USART_StopBits_1; //一个停止位
USART_InitStructure.USART_Parity = USART_Parity_No; //无奇偶校验位
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;//无硬件数据流控制
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; //收发模式
USART_Init(USART1, &USART_InitStructure); //初始化串口1
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE); //开启串口接受中断
USART_Cmd(USART1, ENABLE); //使能串口1
}
中断接收数据代码,这里开了一个定时器3,定时器3每1ms进一次中断,从接收第一个字节后开始计时,如果超过100ms没有再进中断接收数据,认为这一帧接收结束或者超时。
volatile unsigned char g_uart1_recv_data[256] = {0};
volatile unsigned short g_uart1_recv_count = 0;
volatile unsigned short g_uart1_recv_timeout = 0;
volatile unsigned char g_uart1_recv_flag = 0;
void USART1_IRQHandler(void) //串口1中断服务程序
{
if(USART_GetFlagStatus(USART1, USART_FLAG_RXNE) == SET)
{
USART_ClearITPendingBit(USART1, USART_IT_RXNE);
g_uart1_recv_data[g_uart1_recv_count] = USART_ReceiveData(USART1);
g_uart1_recv_count++;
g_uart1_recv_timeout = 100; //超过100MS没有数据接收了
}
}
void TIM3_IRQHandler(void) //TIM3中断
{
if(TIM_GetITStatus(TIM3, TIM_IT_Update) != RESET) //检查TIM3更新中断发生与否
{
TIM_ClearITPendingBit(TIM3, TIM_IT_Update); //清除TIM3更新中断标志
if(0 != g_uart1_recv_timeout)
{
g_uart1_recv_timeout--;
g_uart1_recv_flag = 1;
}
}
}
接收到数据后,先检查包头、长度、CRC是否正确,如果不正确则回复对应的错误码
unsigned char Hw_Uart1_Recv_Check(void)
{
unsigned short crc = 0;
//包头错误
if( (HEAD_HIGH != g_uart1_recv_data[0]) || (HEAD_LOW != g_uart1_recv_data[1]) )
{
//长度
g_uart1_recv_data[2] = 0x06;
g_uart1_recv_data[6] = RECV_HEAD_ERROR;
crc = Func_Get_Crc(g_uart1_recv_data + 3, g_uart1_recv_data[2] - 2);
g_uart1_recv_data[7] = crc >> 8;
g_uart1_recv_data[8] = crc;
//串口回复
Hw_Uart1_Send(g_uart1_recv_data, g_uart1_recv_data[2] + 3);
g_uart1_recv_flag = 0;
g_uart1_recv_count = 0;
return RECV_HEAD_ERROR;
}
//长度检查,总长度减去包头和长度的3byte
if( g_uart1_recv_data[2] != (g_uart1_recv_count - 3) )
{
//长度
g_uart1_recv_data[2] = 0x06;
g_uart1_recv_data[6] = RECV_LENGTH_ERROR;
crc = Func_Get_Crc(g_uart1_recv_data + 3, g_uart1_recv_data[2] - 2);
g_uart1_recv_data[7] = crc >> 8;
g_uart1_recv_data[8] = crc;
//串口回复
Hw_Uart1_Send(g_uart1_recv_data, g_uart1_recv_data[2] + 3);
g_uart1_recv_flag = 0;
g_uart1_recv_count = 0;
return RECV_LENGTH_ERROR;
}
//CRC检查,长度减去CRC的两个字节,从命令开始计算
g_crc = Func_Get_Crc(g_uart1_recv_data + 3, g_uart1_recv_data[2] - 2);
if( ((g_crc >> 8) != g_uart1_recv_data[g_uart1_recv_count - 2]) || //crc高位
((g_crc & 0x0F) != g_uart1_recv_data[g_uart1_recv_count - 1]) ) //crc低位
{
//长度
g_uart1_recv_data[2] = 0x06;
g_uart1_recv_data[6] = RECV_CRC_ERROR;
crc = Func_Get_Crc(g_uart1_recv_data + 3, g_uart1_recv_data[2] - 3);
g_uart1_recv_data[7] = crc >> 8;
g_uart1_recv_data[8] = crc;
//串口回复
Hw_Uart1_Send(g_uart1_recv_data, g_uart1_recv_data[2] + 3);
g_uart1_recv_flag = 0;
g_uart1_recv_count = 0;
return RECV_CRC_ERROR;
}
return 0;
}
如果第一步检查没问题,则开始对命令进行处理,当然,如果命令不存在,也会回复命令错误
void Hw_Uart1_Handle(void)
{
unsigned char ret = 0;
unsigned short crc = 0;
if( (1 == g_uart1_recv_flag) && (0 == g_uart1_recv_timeout) )
{
//检查包头、长度、CRC是否正确
ret = Hw_Uart1_Recv_Check();
if(0 != ret)
{
g_uart1_recv_flag = 0;
g_uart1_recv_count = 0;
return;
}
//命令执行
switch(g_uart1_recv_data[3])
{
case CMD_COMUNICATION_TEST:
g_uart1_recv_data[6] = RECV_TEST_OK;
//长度
g_uart1_recv_data[2] = 0x06;
crc = Func_Get_Crc(g_uart1_recv_data + 3, g_uart1_recv_data[2] - 3);
g_uart1_recv_data[7] = crc >> 8;
g_uart1_recv_data[8] = crc;
//串口回复
Hw_Uart1_Send(g_uart1_recv_data, g_uart1_recv_data[2] + 3);
break;
default:
g_uart1_recv_data[6] = RECV_COMMAND_ERROR;
//长度
g_uart1_recv_data[2] = 0x06;
crc = Func_Get_Crc(g_uart1_recv_data + 3, g_uart1_recv_data[2] - 3);
g_uart1_recv_data[7] = crc >> 8;
g_uart1_recv_data[8] = crc;
//串口回复
Hw_Uart1_Send(g_uart1_recv_data, g_uart1_recv_data[2] + 3);
break;
}
g_uart1_recv_flag = 0;
g_uart1_recv_count = 0;
}
}
到此下位机准备好了
运行上位机,在监听事件里面打个断点,目的是为了看recv_data,也就是下位机的回复内容
先点击打开串口,这时可以看见通信测试按钮由灰色不可点击状态变成了正常的可点击的状态,点击它
这时候我们可以看到,我们发送的内容uart_send_data是正确的
而且MCU回复的内容也是正确的
到此,上位机和下位机通过串口可以正常通信了(握手成功),接下来就要正式进入OTA的处理环节了。
上位机所有代码如下
UI的:
<Window x:Class="Test.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Test"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="950">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="60"></RowDefinition>
<RowDefinition Height="60"></RowDefinition>
<RowDefinition Height="170"></RowDefinition>
<RowDefinition Height="130"></RowDefinition>
</Grid.RowDefinitions>
<Grid Grid.Row="0">
<Label Height="1" Background="Black" VerticalAlignment="Top"></Label>
<Label Height="40" Width="85" Content="bin文件路径:" VerticalContentAlignment="Center" VerticalAlignment="Center" HorizontalAlignment="Left"></Label>
<TextBox Name="TextBox_BinFilePath" Height="40" Width="600" VerticalContentAlignment="Center" HorizontalContentAlignment="Left" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="100,0,0,0"></TextBox>
<Button Name="Button_GetBinFilePath" Content="浏览bin路径" Height="40" Width="70" VerticalAlignment="Center" HorizontalAlignment="Right" Margin="0,0,100,0" Click="Button_GetBinFilePath_Click"></Button>
<Label Height="1" Background="Black" VerticalAlignment="Bottom"></Label>
</Grid>
<Grid Grid.Row="1">
<Label Height="40" Width="50" Content="端口号" VerticalContentAlignment="Center" VerticalAlignment="Center" HorizontalAlignment="Left"></Label>
<ComboBox Name="ComboBox_SerialPortNumber" Height="40" Width="80" VerticalContentAlignment="Center" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="50,0,0,0"></ComboBox>
<Button Content="刷新端口" Name="Button_Refresh" Click="Button_Refresh_Click" Height="40" Width="90" VerticalAlignment="Center" HorizontalAlignment="Left" VerticalContentAlignment="Center" Margin="140,0,0,0"></Button>
<Label Height="40" Width="50" Content="波特率" VerticalContentAlignment="Center" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="0,0,410,0"></Label>
<ComboBox SelectedIndex="0" Name="ComboBox_baud" Height="40" Width="80" VerticalContentAlignment="Center" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="0,0,280,0">
<ComboBoxItem Content="115200"></ComboBoxItem>
<ComboBoxItem Content="57600"></ComboBoxItem>
<ComboBoxItem Content="9600"></ComboBoxItem>
</ComboBox>
<Label Height="40" Width="50" Content="校验位" VerticalContentAlignment="Center" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="0,0,140,0"></Label>
<ComboBox SelectedIndex="0" Name="ComboBox_Parity" Height="40" Width="70" VerticalContentAlignment="Center" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="0,0,20,0">
<ComboBoxItem Content="None"></ComboBoxItem>
<ComboBoxItem Content="Odd"></ComboBoxItem>
<ComboBoxItem Content="Even"></ComboBoxItem>
<ComboBoxItem Content="Space"></ComboBoxItem>
<ComboBoxItem Content="Mark"></ComboBoxItem>
</ComboBox>
<Label Height="40" Width="50" Content="数据位" VerticalContentAlignment="Center" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="110,0,0,0"></Label>
<ComboBox SelectedIndex="0" Name="ComboBox_DataBit" Height="40" Width="40" VerticalContentAlignment="Center" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="200,0,0,0">
<ComboBoxItem Content="8"></ComboBoxItem>
<ComboBoxItem Content="7"></ComboBoxItem>
<ComboBoxItem Content="6"></ComboBoxItem>
<ComboBoxItem Content="5"></ComboBoxItem>
</ComboBox>
<Label Height="40" Width="50" Content="停止位" VerticalContentAlignment="Center" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="300,0,0,0"></Label>
<ComboBox SelectedIndex="0" Name="ComboBox_StopBit" Height="40" Width="50" VerticalContentAlignment="Center" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="400,0,0,0">
<ComboBoxItem Content="1"></ComboBoxItem>
<ComboBoxItem Content="1.5"></ComboBoxItem>
<ComboBoxItem Content="2"></ComboBoxItem>
</ComboBox>
<Label Height="40" Width="50" Content="流控制" VerticalContentAlignment="Center" VerticalAlignment="Center" HorizontalAlignment="Right" Margin="0,0,190,0"></Label>
<ComboBox SelectedIndex="0" Name="ComboBox_FlowControl" Height="40" Width="90" VerticalContentAlignment="Center" VerticalAlignment="Center" HorizontalAlignment="Right" Margin="0,0,100,0">
<ComboBoxItem Content="None"></ComboBoxItem>
<ComboBoxItem Content="Hardware"></ComboBoxItem>
<ComboBoxItem Content="Software"></ComboBoxItem>
<ComboBoxItem Content="Custom"></ComboBoxItem>
</ComboBox>
<Button Content="打开串口" Name="Button_OpenCloseSerial" Click="Button_OpenCloseSerial_Click" Height="40" Width="70" VerticalAlignment="Center" HorizontalAlignment="Right" VerticalContentAlignment="Center" Margin="0,0,10,0"></Button>
<Label Height="1" Background="Black" VerticalAlignment="Bottom"></Label>
</Grid>
<Grid Grid.Row="2">
<Button Content="通信测试" Name="Button_CommunicationTest" Click="Button_CommunicationTest_Click" Height="40" Width="70" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="10,10,0,0" IsEnabled="False"></Button>
<Label Height="1" Background="Black" VerticalAlignment="Bottom"></Label>
</Grid>
<Grid Grid.Row="3">
<TextBox Name="TextBox_RecvData" Height="110" Width="850" VerticalAlignment="Center" HorizontalAlignment="Left" VerticalContentAlignment="Top" HorizontalContentAlignment="Left" Margin="10,0,0,0"></TextBox>
<Button Name="Button_ClearRecvTextBox" Click="Button_ClearRecvTextBox_Click" Content="清除" Height="50" Width="60" VerticalAlignment="Center" HorizontalAlignment="Right" Margin="0,0,10,0"></Button>
</Grid>
</Grid>
</Window>
后台的:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Win32;
using System.IO;
using System.IO.Ports;
namespace Test
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
//读取bin文件的数据
private byte[] g_read_data;
public byte[] uart_send_data = new byte[256];
//串口
public SerialPort serialPort = new SerialPort();
public MainWindow()
{
InitializeComponent();
GetSerialPorts();
uart_send_data[0] = 0xCC;
uart_send_data[1] = 0x33;
}
private void GetSerialPorts()
{
//先清空所有选项
ComboBox_SerialPortNumber.Items.Clear();
//获取所有端口号
string[] ports = SerialPort.GetPortNames();
for (int i = 0; i < ports.Length; i++)
{
//将所有获取的端口号添加到下拉列表里
ComboBox_SerialPortNumber.Items.Add(ports[i]);
}
//如果不只有COM1,那么默认选除了COM1外的第一个
if (1 != ports.Length)
{
ComboBox_SerialPortNumber.SelectedIndex = 1;
}
else
{
ComboBox_SerialPortNumber.SelectedIndex = 0;
}
}
private void Button_GetBinFilePath_Click(object sender, RoutedEventArgs e)
{
//需要using Microsoft.Win32
//文件浏览窗口
OpenFileDialog openFileDialog = new OpenFileDialog();
//打开文件浏览窗口失败
if (!(bool)openFileDialog.ShowDialog())
{
Console.WriteLine("打开文件浏览窗口失败!");
return;
}
//把选择的文件的绝对路径显示到控件上
TextBox_BinFilePath.Text = openFileDialog.FileName;
//需要using System.IO
//文件流打开bin文件
FileStream fileStream = new FileStream(openFileDialog.FileName, FileMode.Open, FileAccess.ReadWrite);
//二进制方法读取bin文件数据
BinaryReader binaryReader = new BinaryReader(fileStream);
//打印bin文件数据的大小
Console.WriteLine("bin file length:{0}", binaryReader.BaseStream.Length);
//bin文件数据的大小
int read_length = Convert.ToInt32(binaryReader.BaseStream.Length);
//读取bin文件的内容
g_read_data = binaryReader.ReadBytes(read_length);
//一定要记得关闭数据流和文件流
binaryReader.Close();
fileStream.Close();
}
private void Button_Refresh_Click(object sender, RoutedEventArgs e)
{
GetSerialPorts();
}
private void Button_OpenCloseSerial_Click(object sender, RoutedEventArgs e)
{
if (ComboBox_SerialPortNumber.Items.IsEmpty)
{
MessageBox.Show("端口号是空的!");
return;
}
//获取button上的文字内容
string bt_str = this.Button_OpenCloseSerial.Content.ToString();
if ("打开串口" == bt_str)
{
try
{
//串口号
serialPort.PortName = ComboBox_SerialPortNumber.SelectedItem.ToString();
//波特率,string转int
ComboBoxItem comboBoxItem = (ComboBoxItem)this.ComboBox_baud.SelectedItem;
serialPort.BaudRate = Convert.ToInt32(comboBoxItem.Content.ToString());
//数据位,string转int
comboBoxItem = (ComboBoxItem)this.ComboBox_DataBit.SelectedItem;
serialPort.DataBits = Convert.ToInt32(comboBoxItem.Content.ToString());
//停止位,这玩意是个enum,不能直接转出int32
comboBoxItem = (ComboBoxItem)this.ComboBox_StopBit.SelectedItem;
Double stopbits = Convert.ToDouble(comboBoxItem.Content.ToString());
switch (stopbits)
{
case 1:
serialPort.StopBits = StopBits.One;
break;
case 1.5:
serialPort.StopBits = StopBits.OnePointFive;
break;
case 2:
serialPort.StopBits = StopBits.Two;
break;
default:
serialPort.StopBits = StopBits.One;
break;
}
//校验位
Int32 parity = ComboBox_Parity.SelectedIndex;
switch (parity)
{
case 0:
serialPort.Parity = Parity.None;
break;
case 1:
serialPort.Parity = Parity.Odd;
break;
case 2:
serialPort.Parity = Parity.Even;
break;
case 3:
serialPort.Parity = Parity.Mark;
break;
case 4:
serialPort.Parity = Parity.Space;
break;
default:
serialPort.Parity = Parity.None;
break;
}
//SerialPort里flow control的相关内容是Handshake
Int32 handshake = ComboBox_FlowControl.SelectedIndex;
switch (handshake)
{
case 0:
serialPort.Handshake = Handshake.None;
break;
case 1:
serialPort.Handshake = Handshake.XOnXOff;
break;
case 2:
serialPort.Handshake = Handshake.RequestToSend;
break;
case 3:
serialPort.Handshake = Handshake.RequestToSendXOnXOff;
break;
default:
serialPort.Handshake = Handshake.None;
break;
}
serialPort.Open();
serialPort.DataReceived += new SerialDataReceivedEventHandler(SerialDataReceivedHandler);
//serialPort.DataReceived += SerialDataReceivedHandler;
Button_OpenCloseSerial.Content = "关闭串口";
Button_CommunicationTest.IsEnabled = true;
}
catch
{
MessageBox.Show("打开串口失败!");
}
}
else
{
try
{
serialPort.DataReceived -= SerialDataReceivedHandler;
serialPort.Close();
Button_OpenCloseSerial.Content = "打开串口";
}
catch
{
MessageBox.Show("关闭串口失败!");
}
}
}
private void SerialDataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
int recv_length = serialPort.BytesToRead;
byte[] recv_data = new byte[recv_length];
serialPort.Read(recv_data, 0, recv_length);
}
private ushort Get_Crc(byte[] buffer, int length)
{
ushort crc = 0;
//i = 3 从命令开始计算CRC
for (ushort i = 3; i < length; i++)
{
crc += buffer[i];
}
return crc;
}
private void Button_CommunicationTest_Click(object sender, RoutedEventArgs e)
{
//直接赋值了,这样直观一些,习惯宏定义灵活的同学可以自行修改
//包头
uart_send_data[0] = 0xCC;
uart_send_data[1] = 0x33;
//长度:从命令到CRC
uart_send_data[2] = 0x05;
//命令
uart_send_data[3] = 0x01;
//包号
uart_send_data[4] = 0x00;
uart_send_data[5] = 0x01;
//CRC校验:从命令到数据,offset:3 clc num:3
ushort crc = Get_Crc(uart_send_data, 3 + 3);
uart_send_data[6] = (byte)(crc >> 8);
uart_send_data[7] = (byte)(crc & 0x00FF);
//串口发送数据
serialPort.Write(uart_send_data, 0, 8);
}
private void Button_ClearRecvTextBox_Click(object sender, RoutedEventArgs e)
{
TextBox_RecvData.Clear();
}
}
}