Click or drag to resize

SerialPort Class

Implements the serial port communication.
Inheritance Hierarchy
SystemObject
  SystemMarshalByRefObject
    System.ComponentModelComponent
      ZylSoft.SerialSerialPort

Namespace: ZylSoft.Serial
Assembly: ZylSerialPort (in ZylSerialPort.dll) Version: 1.83.8519.34486
Syntax
public class SerialPort : Component

The SerialPort type exposes the following members.

Constructors
Properties
 NameDescription
Public propertyAutoReceive Set this property to true, if you want to receive the incoming data automatically in the Received event. Otherwise you have to use ReadBuffer method to get the received data. The default value is true.
Public propertyAutoReconnect Set this property to true, if you want to automatically reconnect to the serial port after a Faulted event, when the port is available again. Set AutoReconnect to true, before the port is faulted, otherwise it will have no effect. The default value is false.
Public propertyAutoReconnectCheckInterval The time interval in milliseconds the serial port is trying to periodically reconnect, after a Faulted event occur, if AutoReconnect is set to true. It must be a positive value. The default value is 4000.
Public propertyBaudRate Baud rate at which the communications device operates.
Protected propertyCanRaiseEventsGets a value indicating whether the component can raise an event.
(Inherited from Component)
Public propertyCloseWhenLineStatusIsZero When this property is true and LineStatus becomes 0 (supposing that it was non 0 after the port has been opened), the port will be closed automatically. Set it to true, for improved fault detection. If you have problems with the port closing itself automatically immediately after open, set this property to false. The default value is true.
Public propertyConnectedTo Returns the port where the component is connected to.
Public propertyConnectionTime Indicates when the last connection was established.
Public propertyContainerGets the IContainer that contains the Component.
(Inherited from Component)
Public propertyCustomBaudRate Custom baud rate value, used when BaudRate is set to Custom.
Public propertyCustomPortName Custom port name can be used when Port is set to Custom. You can use any name, different from COMMxx.
Public propertyDataWidth Number of bits in the bytes transmitted and received.
Public propertyDelayObsolete.
Time interval between two receivings in milliseconds (frequency). Same as Interval.
Protected propertyDesignModeGets a value that indicates whether the Component is currently in design mode.
(Inherited from Component)
Public propertyDiscardNulls Specifies whether null bytes are discarded. If this member is true, null bytes are discarded when received. The default value is false.
Public propertyDsrSensitivity Specifies whether the communications driver is sensitive to the state of the DSR signal. If this member is true, the driver ignores any bytes received, unless the DSR modem input line is high. The default value is false.
Public propertyEnableDtrOnOpen Enable DTR when the port is opening. The default value is true.
Public propertyEnableRtsOnOpen Enable RTS when the port is opening. The default value is true.
Public propertyEofChar Value of the character used to signal the end of data (ANSI: 0 - 255). The default value is (char)26.
Public propertyErrorChar Value of the character used to replace bytes received with a parity error (ANSI: 0 - 255). The default value is (char)0.
Protected propertyEventsGets the list of event handlers that are attached to this Component.
(Inherited from Component)
Public propertyEvtChar Value of the character used to signal an event (ANSI: 0 - 255). The default value is (char)26.
Public propertyHandle The Windows handle of the serial port. You can use it in some Windows API methods.
Public propertyHardwareFlowControl Hardware flow control of the serial port.
Public propertyIdleInterval Idle time interval in milliseconds. If the elapsed time from the last receive is higher than IdleInterval, Idle event occurs. If IdleInterval is 0, Idle event never occurs. It works only for AutoReceive = true.
Public propertyIdleTimeoutInterval You can set a time-out value to automatically close the connection and fire the IdleTimeout event, if there is no data received in several milliseconds. A value of zero indicates that time-out is not used.
Public propertyInputBuffer Recommended size of the device's internal input buffer, in bytes. The device driver receives the recommended buffer sizes, but is free to use any input and output (I/O) buffering scheme, as long as it provides reasonable performance and data is not lost due to overrun (except under extreme circumstances).
Public propertyInterval Time interval between two receivings in milliseconds (frequency). It must be a positive value. The default value is 100.
Public propertyCode exampleIsFaulted Indicates that the last connection was faulted.
Public propertyIsIdle True if Idle occurred, until Resumed. It works only for AutoReceive = true.
Public propertyIsReceiving This property is false when the component is receiving data from the port, otherwise is false. Use this property to check if the component is inside a receiving process.
Public propertyIsSending This property is true when the component is sending data to the port, otherwise is false. Use this property to check if the component is inside a sending process.
Public propertyLastDataReceived Last data received from the serial port.
Public propertyLastTimeReceived Last date-time when data received from the serial port.
Public propertyLineStatus Line status of the serial port. The first 4 bits (LSB) of the result contains CTS, DSR, RING and DCD (RLSD or CD) signals status.
Public propertyLogDateTime When this property is true, a date-time stamp will be added before the logged data.
Public propertyLogFile Name and path of the log file.
Public propertyLogInput Enables or disables input logging. If you enable it, all the incoming data will be logged to the LogFile.
Public propertyMaxLineLength The maximum length of a line, when ReadStringLine or ReadStringUpToEndChars methods are used in synchronous mode (AutoReceive = false). If maximum length is reached, the methods return with empty string. If this value is 0, there is no maximum length. The default value is 0.
Public propertyMinCheckDisconnectedInterval The minimum time interval in milliseconds, for which the port availability is checked. For time critical usage it's recommended to set it to a higher value. The default value is 25.
Public propertyNeedSynchronization Set this property to true for thread safety. The default value is false. Note: if you set it to true, you may experiment thread interblocking and lower speed.
Public propertyNewLine Gets or sets the value used to interpret the end of line in the ReadLine or SendAsciiStringLine methods. Default value is Environment.NewLine, a string containing "\r\n" for non-Unix platforms, or a string containing "\n" for Unix platforms.
Public propertyOutputBuffer Recommended size of the device's internal output buffer, in bytes. The device driver receives the recommended buffer sizes, but is free to use any input and output (I/O) buffering scheme, as long as it provides reasonable performance and data is not lost due to overrun (except under extreme circumstances).
Public propertyPacketSize The size of the packets in bytes you want to receive automatically in the Received event. Use this property, if you want to receive packets of equal size in the Received event. If the value is 0, this property will be ignored. It works only for AutoReceive = true. Default value is 0.
Public propertyParityBits Parity scheme to be used.
Public propertyParityCheck If this property is true, parity checking is performed and parity errors are reported. This should not be confused with the Parity member, which controls the type of parity used in communications. The default value is false.
Public propertyPort Physical name of the serial port.
Public propertyPriority Priority of the receiver thread.
Public propertyReadIntervalTimeout Maximum time allowed to elapse between the arrival of two characters on the communications line, in milliseconds. During a ReadFile operation, the time period begins when the first character is received. If the interval between the arrival of any two characters exceeds this amount, the ReadFile operation is completed and any buffered data is returned. A value of zero indicates that interval time-outs are not used. A value of MAXDWORD, combined with zero values for both the ReadTotalTimeoutConstant and ReadTotalTimeoutMultiplier members, specifies that the read operation is to return immediately with the characters that have already been received, even if no characters have been received.
Public propertyReadTotalTimeoutConstant Constant used to calculate the total time-out period for read operations, in milliseconds. For each read operation, this value is added to the product of the ReadTotalTimeoutMultiplier member and the requested number of bytes. A value of zero for both the ReadTotalTimeoutMultiplier and ReadTotalTimeoutConstant members indicates that total time-outs are not used for read operations.
Public propertyReadTotalTimeoutMultiplier Multiplier used to calculate the total time-out period for read operations, in milliseconds. For each read operation, this value is multiplied by the requested number of bytes to be read.
Public propertyReplaceParityErrors Specifies whether bytes received with parity errors are replaced with the character specified by the ErrorChar member. If this member is true and the ParityCheck member is true, replacement occurs. The default value is false.
Public propertySiteGets or sets the ISite of the Component.
(Inherited from Component)
Public propertySkipSetupFailed When this property is true, if setting serial parameters like DCB in the Open method fails, will ignore this. Otherwise method Open will return false and the port will not be opened. The default value is false.
Public propertySoftwareFlowControl Software flow control of the serial port.
Public propertyStopBits Number of stop bits to be used.
Public propertyTxContinueOnXoff Specifies whether transmission stops when the input buffer is full and the driver has transmitted the Xoff character. If this member is true, transmission continues after the Xoff character has been sent. If this member is false, transmission does not continue until the input buffer is within XonLim bytes of being empty and the driver has transmitted the Xon character. The default value is false.
Public propertyStatic memberUnlockKey Unlock key.
Public propertyWriteTotalTimeoutConstant Constant used to calculate the total time-out period for write operations, in milliseconds. For each write operation, this value is added to the product of the WriteTotalTimeoutMultiplier member and the number of bytes to be written. A value of zero for both the WriteTotalTimeoutMultiplier and WriteTotalTimeoutConstant members indicates that total time-outs are not used for write operations.
Public propertyWriteTotalTimeoutMultiplier Multiplier used to calculate the total time-out period for write operations, in milliseconds. For each write operation, this value is multiplied by the number of bytes to be written.
Public propertyXoffChar Value of the XOFF character for both transmission and reception (ANSI: 0 - 255). The default value is (char)19.
Public propertyXoffLim Maximum number of bytes allowed in the input buffer before the XOFF character is sent. The maximum number of bytes allowed is calculated by subtracting this value from the size, in bytes, of the input buffer. The default value is 1.
Public propertyXonChar Value of the XON character for both transmission and reception (ANSI: 0 - 255). The default value is (char)17.
Public propertyXonLim Minimum number of bytes allowed in the input buffer before the XON character is sent. The default value is 0, which means InputBuffer div 4.
Top
Methods
 NameDescription
Public methodStatic memberAsciiByteArrayToString Converts ASCII / ANSI byte array to string.
Public methodStatic memberByteArrayToDecimalString Converts byte array to decimal string representation.
Public methodStatic memberByteArrayToHexaString Converts byte array to hexadecimal string representation.
Public methodClearInputBuffer Clears input buffer.
Public methodClearOutputBuffer Clears output buffer.
Public methodClose Closes the serial port.
Public methodCreateObjRefCreates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
(Inherited from MarshalByRefObject)
Public methodDetectDevice(String, String, SerialCommPort, SerialBaudRate) Detects the serial port where the device is connected to and returns as output parameters the communication port and baud rate. In the detection process senToken will be sent and receivedToken is expected to receive.
Public methodDetectDevice(String, String, SerialBaudRate, SerialBaudRate, SerialCommPort, SerialBaudRate) Detects the serial port where the device is connected to and returns as output parameters the communication port and baud rate. In the detection process senToken will be sent and receivedToken is expected to receive. Only baud rate values between startBaudRate and endBaudRate are checked.
Public methodDisposeReleases all resources used by the Component.
(Inherited from Component)
Protected methodDispose(Boolean) Clean up any resources being used.
(Overrides ComponentDispose(Boolean))
Public methodEcho Sends the last received buffer back.
Public methodEqualsDetermines whether the specified object is equal to the current object.
(Inherited from Object)
Public methodFastDetectDevice Detects the serial port where the device is connected to and returns as output parameters the communication port and baud rate. In the detection process senToken will be sent and receivedToken is expected to receive. Only baud rates between 4800 and 921600 will be checked.
Protected methodFinalize Finalizer.
(Overrides ComponentFinalize)
Public methodGetAvailableInputBufferSize Returns the number of bytes of data in the receive buffer (bytes to read). It is used when AutoReceive = false.
Public methodGetAvailableOutputBufferSize Returns the number of bytes of data in the send buffer (bytes to write).
Public methodStatic memberGetCommPortDescription(SerialCommPort) Returns the OS level description of the port.
Public methodStatic memberGetCommPortDescription(String) Returns the OS level description of the port.
Public methodStatic memberGetCommPortPath(SerialCommPort) Returns the OS level name of the port. E.g.: \Device\PCISerial1 If the port does not exists, returns empty string.
Public methodStatic memberGetCommPortPath(String) Returns the OS level name of the port. E.g.: \Device\PCISerial1 If the port does not exists, returns empty string.
Public methodStatic memberGetCommPortType(SerialCommPort) Returns the type of the serial port.
Public methodStatic memberGetCommPortType(String) Returns the type of the serial port.
Public methodGetCts Returns the state of CTS (clear-to-send) line.
Public methodStatic memberGetCts(UInt64) Returns the state of CTS (clear-to-send) line from lineStatus parameter.
Public methodGetDcd Returns the state of DCD (Data Carrier Detect, or alternately Carrier Detect abbreviated as CD, or RLSD (receive-line-signal-detect) line.
Public methodStatic memberGetDcd(UInt64) Returns the state of DCD (Data Carrier Detect, or alternately Carrier Detect abbreviated as CD, or RLSD (receive-line-signal-detect) line from lineStatus parameter.
Public methodGetDsr Returns the state of DSR (data-set-ready) line.
Public methodStatic memberGetDsr(UInt64) Returns the state of DSR (data-set-ready) line from lineStatus parameter.
Public methodStatic memberGetExistingCommPortNames Returns the existing serial port names of the system.
Public methodStatic memberGetExistingCommPorts Returns the existing serial ports of the system.
Public methodGetHashCodeServes as the default hash function.
(Inherited from Object)
Public methodGetLifetimeServiceRetrieves the current lifetime service object that controls the lifetime policy for this instance.
(Inherited from MarshalByRefObject)
Public methodGetRing Returns the state of RING line.
Public methodStatic memberGetRing(UInt64) Returns the state of RING line from lineStatus parameter.
Protected methodGetServiceReturns an object that represents a service provided by the Component or by its Container.
(Inherited from Component)
Public methodGetTypeGets the Type of the current instance.
(Inherited from Object)
Public methodInitializeLifetimeServiceObtains a lifetime service object to control the lifetime policy for this instance.
(Inherited from MarshalByRefObject)
Public methodStatic memberCode exampleInsertControlCharacters Replaces readable text with control characters.
Public methodStatic memberIntToSerialCommPort Converts string to SerialCommPort.
Public methodStatic memberIsCommPortAvailable(SerialCommPort) Checks if the serial port is available (It exists and is not busy, opened by another or the same process).
Public methodStatic memberIsCommPortAvailable(String) Checks if the serial port is available (It exists and is not busy, opened by another or the same process).
Public methodStatic memberIsCommPortBusy(SerialCommPort) Checks if a serial port is already opened by another or the same process (busy). If the port does not exists, SerialPortException is thrown.
Public methodStatic memberIsCommPortBusy(String) Checks if a serial port is already opened by another or the same process (busy). If the port does not exists, SerialPortException is thrown.
Public methodIsConnected Returns true if the serial port is connected (open).
Public methodStatic memberIsExistingCommPort(SerialCommPort) Checks if a serial port exists.
Public methodStatic memberIsExistingCommPort(String) Checks if a serial port exists.
Protected methodMemberwiseCloneCreates a shallow copy of the current Object.
(Inherited from Object)
Protected methodMemberwiseClone(Boolean)Creates a shallow copy of the current MarshalByRefObject object.
(Inherited from MarshalByRefObject)
Protected methodOnConnected Raises the Connected event.
Protected methodOnDetecting Raises the Detecting event.
Protected methodOnDisconnected Raises the Disconnected event.
Protected methodOnError Raises the Error event.
Protected methodOnFaulted Raises the Faulted event.
Protected methodOnIdle Raises the Idle event.
Protected methodOnIdleTimeout Raises the IdleTimeout event.
Protected methodOnLineStatusChanged Raises the LineStatusChanged event.
Protected methodOnReceived Raises the Received event.
Protected methodOnReconnecting Raises the Reconnecting event.
Protected methodOnResumed Raises the Resumed event.
Protected methodOnSent Raises the Sent event.
Public methodOpen Opens the serial port.
Public methodStatic memberRandomDataGenerator Generates random data in string format (chars between 0 - 255).
Public methodReadBuffer Synchronously reads the received data from the serial port to a byte array. It works only if AutoReceive property is false, otherwise returns null.
Public methodReadBufferToEnumerable Synchronously reads the received data from the serial port to a byte list. It works only if AutoReceive property is false, otherwise returns null.
Public methodReadBufferToString Synchronously reads the received data from the serial port to ANSI string. It works only if AutoReceive property is false, otherwise returns null.
Public methodReadByte Synchronously reads one byte from the serial port, if data available. It works only if AutoReceive property is false, otherwise returns null.
Public methodReadBytes Reads numberOfBytes bytes from the serial port and discards them. It works only if AutoReceive property is false.
Public methodReadChar Synchronously reads one character from the serial port. It works only if AutoReceive property is false, otherwise returns empty string.
Public methodReadChars Reads numberOfChars chars from the serial port into string and discards them. It works only if AutoReceive property is false.
Public methodReadLine Reads the serial port up to the first occurrence of NewLine sequence. NewLine can be set by the NewLine property. It works only if AutoReceive property is false.
Public methodReadStringUpToEndChars(CollectionString, Int32) Reads the serial port up to the first occurrence of one of the endChars sequences of the endCharsList collection. It works only if AutoReceive property is false.
Public methodReadStringUpToEndChars(String, Int32) Reads the serial port up to the first occurrence of endChars sequence. It works only if AutoReceive property is false.
Public methodReadStringUpToEndChars(CollectionString, String, Int32) Reads the serial port up to the first occurrence of one of the endChars sequences of the endCharsList collection. It works only if AutoReceive property is false.
Public methodReadStringUpToEndChars(CollectionString, String, Int32, Boolean, String) Reads the serial port up to the first occurrence of one of the endChars sequences of the endCharsList collection. It works only if AutoReceive property is false.
Public methodStatic memberCode exampleReplaceControlCharacters Replaces control characters with readable text.
Public methodResetIdleState Resets the idle state of the port.
Public methodSendAsciiString Sends an ANSI string to the serial port.
Public methodSendAsciiStringLine Sends an ANSI string to the serial port and add the NewLine value at the end of the string. NewLine can be set by the NewLine property.
Public methodSendAsciiStringOnNewThread Sends an ANSI string to the serial port on a separate thread.
Public methodSendByte Sends a byte to the serial port.
Public methodSendByteArray(Byte) Sends a byte array to the serial port.
Public methodSendByteArray(Byte, Int32) Sends a specified number of bytes from a byte array to the serial port.
Public methodSendByteArray(Byte, Int32, Int32) Sends a specified number of bytes from a byte array to the serial port.
Public methodSendByteArrayOnNewThread Sends a byte array to the serial port on a separate thread.
Public methodSendCharArray(Char) Sends a char array to the serial port.
Public methodSendCharArray(Char, Int32) Sends a specified number of chars from a char array to the serial port.
Public methodSendCharArray(Char, Int32, Int32) Sends a specified number of chars from a char array to the serial port.
Public methodSendString Sends a string with the selected encoding to the serial port.
Public methodSendStringOnNewThread Sends a string with the selected encoding to the serial port on a separate thread.
Public methodSendUnicodeString Sends a UTF16 string to the serial port.
Public methodSendUtf32String Sends a UTF32 string to the serial port.
Public methodSendUtf8String Sends a UTF8 string to the serial port.
Public methodSerialCommPortToString Converts SerialCommPort to string.
Public methodSetBreak Sets break line. When value is true, suspends character transmission and places the transmission line in a break state. When value is false, restores character transmission and places the transmission line in a nonbreak state.
Public methodSetDtr Sets DTR (data-terminal-ready) line.
Public methodSetFaulted Emulates faulted state, raises the Faulted event and close the port. If AutoReconnect is true, it will try to reconnect.
Public methodSetRts Sets RTS (request-to-send) line.
Public methodSetXonXoff Sets XOnXoff state. When value is true, causes transmission to act as if an XON character has been received. When value is false, Causes transmission to act as if an XOFF character has been received.
Public methodStatic memberStringToAsciiByteArray Converts string to ASCII / ANSI byte array.
Public methodStatic memberStringToDecimalString Converts a string to decimal representation.
Public methodStatic memberStringToHexaString Converts a string to hexadecimal representation.
Public methodStatic memberStringToSerialCommPort Converts string to SerialCommPort.
Public methodStatic memberStringToUnicodeByteArray Converts string to UTF16 byte array.
Public methodStatic memberStringToUtf32ByteArray Converts string to UTF32 byte array.
Public methodStatic memberStringToUtf8ByteArray Converts string to UTF8 byte array.
Public methodTestDevice Tests if the connection is alive sending sentToken and expecting to receive receivedToken.
Public methodToStringReturns a String containing the name of the Component, if any. This method should not be overridden.
(Inherited from Component)
Public methodStatic memberUnicodeByteArrayToString Converts UTF16 byte array to string.
Public methodStatic memberUnicodeCharArrayToUnicodeByteArray Converts a char array to byte array.
Public methodStatic memberUtf32ByteArrayToString Converts UTF32 byte array to string.
Public methodStatic memberUtf8ByteArrayToString Converts UTF8 byte array to string.
Top
Events
 NameDescription
Public eventConnected Occurs after the serial port is connected.
Public eventDetecting Occurs when the serial port detection process is in progress. and there are new values of port or baud rate to be checked.
Public eventDisconnected Occurs when the serial port is disconnected.
Public eventDisposedOccurs when the component is disposed by a call to the Dispose method.
(Inherited from Component)
Public eventError Fires when an error occurs. The error will be cleared automatically.
Public eventCode exampleFaulted Occurs when the serial port communication is faulted. After a Faulted event, the port will be closed automatically.
Public eventIdle If the elapsed time from the last receive is higher than IdleInterval (milliseconds), Idle event occurs. If IdleTinerval is 0, this event will never occur. It works only for AutoReceive = true.
Public eventIdleTimeout Occurs when there is no data received in several milliseconds, the interval is specified in the IdleTimeoutInterval property.
Public eventLineStatusChanged Occurs when the line status of the serial port is changed.
Public eventReceived Occurs when data was received. You will get the received data in DataEventArg.Buffer, when AutoReceive is true. When AutoReceive is false, DataEventArg.Buffer property is null and you have to read the data with one of the Read methods.
Public eventReconnecting Occurs when the serial port connection was lost (faulted) and tries to reconnect. AutoReconnect must be true.
Public eventResumed Occurs when the receiver is idle and data is received. It works only for AutoReceive = true.
Public eventSent Occurs when data was sent.
Top
Remarks
Events are raised on a secondary thread when data is received. Because these events are raised on a secondary thread, and not the main thread, attempting to modify some elements in the main thread, such as UI elements, could raise a threading exception. If it is necessary to modify elements in the main Form or Control, post change requests back using Invoke (or BeginInvoke to avoid deadlock), which will do the work on the proper thread.
See Also