IDMIOPortEvents interface should be used to receive notifications from communication port controls. It is very important since communication media like TCP/IP network or RS-232 serial protocol have large delays (hundreds of milliseconds and even seconds), so that data exchange is essentially asynchronous. Events allows you send and receive data when they are ready, without wait.
|OnRead||1||Fired when incoming data are ready|
|OnWrite||2||Fired when data are writed to the port|
|OnError||3||Fired on communication errors|
|OnConnect||4||Fired when connection established|
|OnDisconnect||5||Fired when connection closed|
|event OnRead(Data): HResult|
Use OnRead event handler to implement asynchronous reading from the communication ports. In the default (character) mode, Data parameter has string type. If COM port component was opened in the binary mode, this parameter is an array of bytes. It should be emphasized that asynchronous communications usually is a great problem since you can't wait for your device finish to transmit all data - for RS232 ports (and, to a greater extent, for TCP/IP sockets) it can take seconds. At once, your application must remain interactive while data are going.
Internally, reading data from "slow" ports requires multithreading. From the component user's standpoint, you must handle OnRead event. Keep in mind that data packet from the device may be broken at the arbitrary position, so that you should analyze incoming data and perform something only when all data actually are ready. Usually you will rely on special "terminator" characters as shown in the example below:
Dim TCBuf ' allocate buffer for incoming data Sub TCPort_OnRead(Str) dim tctemp TCBuf=TCBuf+Str ' accumulate incoming data in TCBuf if (InStr(TCBuf, vbCrLf)>0) then ' terminator arrived? tctemp=Mid(TCBuf, 2, 5) ' extract readout if IsNumeric(tctemp) then ' check whether it is correct ' here you can safely process the device data end if TCBuf="" ' clear buffer end if End Sub
Notice: for objects with IDMCPortLibX interface you may define Terminator property in order to engage internal bufferization.
|event OnWrite: HResult|
OnWrite event can be used to determine when COM port finish transmission. This may be important if asynchronous write mode was selected. In the default synchronous write mode, OnWrite fired just after Write method returns.
|event OnError(Code): HResult|
For serial communication port controls, this event fired when some error condition is detected, typically when you are trying to open port which is not exists or already opened by other control or application. Data parameter may contain a string that explains the reason of error.
|event OnConnect(Data): HResult|