C # Asynchronous data reception serial operation class

Source: Internet
Author: User
Data | Using C # Asynchronously to invoke the traditional 32-bit API for serial operation, the entire structure is particularly simple. Receiving data requires only defining data-receiving events.

Upload source code I will not, need the source code please contact me (dyj057@gmail.com). You can also teach me how to upload the source code.


Using System;
Using System.Runtime.InteropServices;

<summary>
(C) 2003-2005 C2217 Studio retains all rights
///
File name: IbmsSerialPort.cs
File ID:
File Description:
Encapsulates the functionality of the dynamic link library IbmsSerialPort.dll, which is provided in the. NET Environment
The function of a serial port to receive and send data asynchronously.
///
Current Version: 1.0
///
Author: Deng Yang
Date Created: 2005-2-2
Last Modification Date: 2005-2-2
///
History Modification Record:
///
</summary>


Namespace Ibms.Tool.IO
{

<summary>
When the serial port receives the data, an event is generated.
Sprecvdataargs is the parameter of the event, and the RecvData in the parameter contains the data received.
How to use:
</summary>
public class Sprecvdataargs:eventargs
{
<summary>
byte array of received data
</summary>
Private byte[] RecvData;

<summary>
constructor, which requires a byte[] that contains data to be instantiated as an initialization parameter Sprecvdataargs
</summary>
<param name= "RecvData" > Received Data </param>
Public Sprecvdataargs (byte[] recvdata)
{
if (RecvData = null)
{
Throw (new ArgumentNullException ());
}

This.recvdata = RecvData;
}

<summary>
Returns the contents of the received data
</summary>
Public byte[] RecvData
{
Get
{
return recvdata;
}
}
}


<summary>
Encapsulates the functionality of the dynamic link library IbmsSerialPort.dll, providing asynchronous in the. NET Environment
The function of receiving and sending serial port. Specifically, it is the mode of automatically receiving data asynchronously through signals.
</summary>
public class Ibmsserialport:idisposable
{

#region Platform invoke Declaration code

<summary>
Declaring the IbmsSerialPort.dll ibms_openport function
</summary>
<param name= "Nport" > Serial number </param>
<param name= "nrate" > Baud rate </param>
<returns></returns>
[DllImport ("IbmsSerialPort.dll")]
public static extern IntPtr ibms_openport (int nport, int nrate);

<summary>
Declaring the IbmsSerialPort.dll ibms_close function
</summary>
[DllImport ("IbmsSerialPort.dll")]
public static extern void Ibms_close (IntPtr port);

<summary>
Declaring the IbmsSerialPort.dll ibms_senddata function
</summary>
<param name= "Data" ></param>
<param name= "Ndatasize" ></param>
<returns></returns>
[DllImport ("IbmsSerialPort.dll")]
public static extern bool Ibms_senddata (INTPTR port, byte[] Data,int ndatasize);

<summary>
Declaring the IbmsSerialPort.dll ibms_setfunchandle function
</summary>
<param name= "Handdatafunc" ></param>
[DllImport ("IbmsSerialPort.dll")]
public static extern void Ibms_setfunchandle (IntPtr port, Handlefunc handdatafunc);

#endregion

#region definition Field

<summary>
Defining a data processing delegate, passing the function pointer of the API to the dynamic link library
</summary>
public delegate void Handlefunc (IntPtr pData, int ndatasize);

<summary>
To define a prototype for a data-receiving event
</summary>
public delegate void RecvData (Object Sender,sprecvdataargs e);

<summary>
Defining data-receiving events
</summary>
public event RecvData Onrecvdata;

<summary>
Serial processing of Delegates receiving data
</summary>
Private Handlefunc _handledatafunc;

<summary>
Serial number, starting from 1 integers, max 255
</summary>
private int port;

<summary>
The baud rate supported by the serial port must be one of the standard baud rates
</summary>
private standerdrate rate;

<summary>
The current open state of the serial port
</summary>
private bool Openstatus=false;

<summary>
Serial handle
</summary>
Private INTPTR PortHandle;

#region definition of standard serial port baud rate

<summary>
Standard baud rate
</summary>
public enum Standerdrate
{
R50=50,
R75=75,
R110=110,
r150=150,
R300=300,
r600=600,
R1200=1200,
r2400=2400,
r4800=4800,
r9600=9600,
R19200=19200,
r38400=38400,
r57600=57600,
r76800=76800,
r115200=115200
};

#endregion

#endregion

#region Definition Method

<summary>
Constructors
</summary>
Public Ibmsserialport ()
{
PortHandle = (IntPtr) 0;

_handledatafunc = new Handlefunc (ondllrecvdata);
}

<summary>
Open serial port
</summary>
<param name= "Nport" > Serial number </param>
<param name= "nrate" > Baud rate </param>
<exception cref= "ApplicationException" > Throw application exception, shifting error description </exception>
public void Open (int nport, standerdrate nrate)
{

if (Nport > 255 | | nport < 0)
{
Throw (new ArgumentOutOfRangeException ());
}

Port = nport;
rate = nrate;

PortHandle = Ibms_openport (port, (int) rate);

if ((IntPtr) 0 = porthandle)
{
Throw (New ApplicationException ("Open serial port Failed"));
}

Registering function pointers
Ibms_setfunchandle (PortHandle, _handledatafunc);

Openstatus = true;

}


<summary>
Close serial port
</summary>
public void Close ()
{
if (openstatus)
{
Ibms_close (PortHandle);

}

Openstatus = false;

}


<summary>
Send data
</summary>
<param name= "SendData" > Data content </param>
<exception cref= "ApplicationException" > Throw application exception, shifting error description </exception>
public void SendData (byte[] data)
{
if (!openstatus)
{
Throw (New ApplicationException ("Serial not open, send data Failed"));
}

if (! Ibms_senddata (porthandle, data, data.) Length))
{
Throw (New ApplicationException ("Serial Port Send Data failed"));
}
}

<summary>
Processing of received serial data
</summary>
<param name= "PData" > Serial data receive buffer first address </param>
<param name= "Ndatasize" > Data size, general data size not exceeding 2k</param>
unsafe protected void Ondllrecvdata (IntPtr punhandledata, int ndatasize)
{
int datasize= ndatasize;

BYTE * pData = (byte *) Punhandledata;

byte[] data = new Byte[datasize];

Copy data to byte array
for (int i=0; i<datasize; i++)
{
Data[i]= Pdata[i];
}

Firing events
Onrecvdata (This, new Sprecvdataargs (data));

}


#endregion

#region Define Properties

<summary>
Returns the current string number
</summary>
public int Port
{
Get
{
return port;
}
}

<summary>
Returns the baud rate of the current serial port
</summary>
Public Standerdrate Rate
{
Get
{
return rate;
}
}

<summary>
Returns the status of the current serial port
</summary>
public bool Openstatus
{
Get
{
return openstatus;
}
}


#endregion


#region timely release of unmanaged resources

<summary>
The IDisposable interface must be implemented because it contains unmanaged resources (uses the system serial port)
When you are finished using the class, you must remember to call Dispose () and reclaim the system resources
<example>
///
Method 1
/// {
SerialPort Port =new SerialPort ();
/// ...
Releasing resources in the finaly of Try-catch-finaly
///
Port. Dispose ();
/// }
///
Method 2
using (SerialPort port = new SerialPort ())
/// {
/// ...
/// }
The Dispose () method is automatically invoked when a variable is outside the scope
///
</example>
</summary>

~ibmsserialport ()
{
Dispose (FALSE);
}

protected virtual void Dispose (bool disposing)
{
if (disposing)
{
To clean up a managed object
}

To clean up Unmanaged resources
Close ();
}


#region IDisposable Members

public void Dispose ()
{
TODO: Add Serialport.dispose implementation
Dispose (TRUE);

Gc. SuppressFinalize (this);
}

#endregion
#endregion

}

}





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.