以下是一个示例代码,用于C#串口接收数据并将其转发给API接口:
using System;
using System.IO.Ports;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace SerialPortToAPI
{
class Program
{
static async Task Main(string[] args)
{
// 初始化串口
SerialPort port = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
port.Encoding = Encoding.UTF8;
port.DataReceived += Port_DataReceived;
port.Open();
// 当收到数据时发送到API接口
async void Port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string data = sp.ReadExisting();
Console.WriteLine("Received data: " + data);
// 发送数据到API接口
using (HttpClient client = new HttpClient())
{
string url = "http://api.example.com/data";
HttpResponseMessage response = await client.PostAsync(url, new StringContent(data, Encoding.UTF8, "application/json"));
if (!response.IsSuccessStatusCode)
{
Console.WriteLine("Error posting data to API: " + response.StatusCode);
}
}
}
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
// 关闭串口
port.Close();
}
}
}
在此示例代码中,串口被初始化为使用9600波特率,无校验位,8位数据位和1个停止位。当数据从串口接收后,它被发送到API接口。这里使用了一个HttpClient
实例来发送POST请求。在发送请求时,需要指定要发送的数据、内容编码和内容类型。成功发送后,API将返回一个HTTP响应。如果该响应的状态码不是成功状态码,将打印错误消息。最后,当用户按下任意键时,串口将关闭。
请注意,此示例代码仅演示了如何将从串口接收的数据发送到API接口。如果你需要更多的控制或处理接收到的数据,请在事件处理程序中进行更多的操作。同时,这里也只使用了HTTP POST请求,你可以根据你的需要选择其他的HTTP请求方法。