PB serial programming materials

Source: Internet
Author: User

Original article address: petabytes of serial programming materials (translated) Author: notbig

PB serial programming materials
---- Mscomm32
The MSComm control transmits and receives data through the serial port to provide the serial communication function for applications. MSComm controls are very convenient for serial programming. programmers do not have to spend time learning more complex API functions and can use them in VC, VB, Delphi, and other languages. Microsoft Communications Control (MSComm) is an ActiveX control provided by Microsoft to simplify serial communication programming in windows. It provides an easy way for applications to send and receive data through a serial interface. Specifically, it provides two methods to deal with communication problems: the event-driven method and the query method.
1. MSComm control
The MSComm control provides two communication methods: event-driven and query.
1.1 event-driven approach
Event-driven communication is a very effective method for handling serial port interactions. In many cases, you need to be notified when an event occurs. For example, the serial Receive Buffer contains characters, or the carrier detect (CD) or request to send (RTS) when a character arrives online or a change occurs. In these cases, you can use the oncomm event of the MSComm control to capture and process these communication events. The oncomm event can also check and handle communication errors. For a list of all communication events and communication errors, see commevent attributes. In the programming process, you can add your own processing code to the oncomm event handler. The advantage of this method is that the program responds promptly and has high reliability. Each MSComm control corresponds to a serial port. If the application needs to access multiple serial ports, multiple MSComm controls must be used.
1.2 Query Method
The query method is actually event-driven, but in some cases, this method is more convenient. After each key function of the program, you can check the value of the commevent attribute to query events and errors. This method may be more desirable if the application is small and self-maintained. For example, if you write a simple dialing program, there is no need to generate an event for each received character, because the only character waiting for receiving is the modem's "OK" response.
2. Common attributes of the MSComm control
The MSComm control has many important attributes, but you must first be familiar with these attributes.
Set and return the communication port number.
Settings is set as a string and returns the baud rate, parity, data bit, stop bit.
Set portopen and return the status of the communication port. You can also open or close the port.
Input returns and deletes characters from the receiving buffer.
Output writes a string to the transmission buffer.
The descriptions are as follows:
Set the comport attribute and return the communication port number.
Syntax: object. commp ORT [value] (value: an integer value indicating the port number .)
Note: during design, the value can be set to any number from 1 to 16 (the default value is 1 ). However, if you use the portopen attribute to open a port that does not exist, the MSComm control produces error 68 (the device is invalid ).
Note: You must set the comport Attribute before opening the port.
Rthreshold attribute: specifies the number of characters to be received before the MSComm control sets the commevent attribute to comevreceive and generates oncomm.
Syntax object. rthreshold [= value] (value integer expression, indicating the number of characters to be received before the oncomm event is generated. )
After receiving characters, if the rthreshold attribute is set to 0 (default), no oncomm event is generated. For example, if rthreshold is set to 1, the MSComm control generates an oncomm event when the receiving buffer receives each character.
Ctsholding attribute: determines whether data can be sent by querying the status of the clear to send (CTS) line. Clear to send is the signal sent by the modem to the connected computer, indicating that the transmission can be performed. This attribute is invalid at design and read-only at runtime.
Syntax: object. ctsholding (Boolean)
The ctsholding attribute setting value of the MSComm control:
The true clear to send line is a high level.
False clear to send line is low.
Note: If the clear to send line is low (ctsholding = false) and times out, the MSComm control sets the commevent attribute to comeventctsto (clear to send timeout) and generates an oncomm event.
The clear to send line is used for the hardware handshaking of RTS/CTS (request to send/clear to send. To determine the status of the clear to send line, the ctsholding attribute provides a method for manual query.
For more information about handshaking protocols, see handshaking attributes.
Sthreshold attribute: Before the MSComm control sets the commevent attribute to comevsend and generates an oncomm event, it sets and returns the minimum number of characters allowed in the transport buffer.
Syntax object. sthreshold [= value]
Value integer expression, which represents the minimum number of characters in the transport buffer before the oncomm event is generated.
Note: If the sthreshold attribute is set to 0 (default), the data transmission event will not generate an oncomm event. If the sthreshold attribute is set to 1, the MSComm control generates an oncomm event when the transmission buffer is completely empty. If the number of characters in the transmission buffer is less than value, the commevent attribute is set to comevsend and an oncomm event is generated. The comevsend event is activated only once when the number of characters overlaps with sthreshold. For example, if sthreshold is equal to 5, comevsend only occurs when the number of characters in the output queue drops from 5 to 4. If there are no more characters than sthreshold in the output queue, the comevsend event will never happen.
Handshake constant
Constant Value description
Comnone 0 has no handshake.
Comxonxoff 1 Xon/xoff handshake.
Comrts 2 request-to-send/clear-to-send handshake.
Comrtsxonxoff 3 request-to-send and clear-to-send handshakes are acceptable.
Oncomm constant
Constant Value description
Comevsend 1 sends an event.
Comevreceive 2 receives events.
Comevcts 3 clear-to-send line changes.
Comevdsr 4 data-set ready line changes.
Comevcd 5 carrier detect line variation.
Comevring 6 zhenling detection.
The comeveof 7 file ends.
Error constant
Constant Value description
Comeventbreak 1001 receives the interrupt signal
Comeventctsto 1002 clear-to-send times out
Comeventdsrto 1003 data-set ready timeout
Comeventframe 1004 Frame Error
Comeventoverrun 1006 port speeding
Comeventcdto 1007 carrier detect timeout
Comeventrxover 1008 receives Buffer Overflow
Comeventrxparity 1009 parity error
Comeventtxfull 1010 transmission buffer full
Comeventdcb 1011 error in retrieval port device control block (DCB)
Inputmode constant
Constant Value description
Cominputmodetext 0 (default) retrieves data in text format using the INPUT attribute.
Cominputmodebinary 1 retrieves data in binary mode through the INPUT attribute.
Cdholding attribute: query the status of the carrier detect (CD) line to determine whether the current transmission exists. Carrier detect is a signal sent from the modem to the connected computer, indicating that the modem is online. This attribute is invalid at design and read-only at runtime.
Syntax object. cdholding
Setting Value: the setting value of the cdholding attribute is:
Set description
True carrier detect line is high
False carrier detect line is low
Note: When the carrier detect line is high (cdholding = true) and times out, the MSComm control sets the commevent attribute to comeventcdto (carrier detect timeout error) and generates an oncomm event.
Note: It is especially important to capture a lost transfer in a host application, such as a bulletin board, because callers can be suspended at any time (discard transfer ).
Carrier detect is also known as receive line signal detect (RlSD ).
Data type boolean
Dsrholding attribute: determines the status of the data set ready (DSR) line. The data set ready signal is sent from the modem to the connected computer, indicating that the operation is ready. This attribute is invalid at design and read-only at runtime.
Syntax: object. dsrholding
The object is located at the object expression, and its value is "applied" to the object in the list.
The dsrholding attribute returns the following values:
Value description
True data set ready line height
False data set ready line low
Note: When the data set ready line is high (dsrholding = true) and times out, the MSComm control sets the commevent attribute to comeventdsrto (data preparation times out) and generates an oncomm event. This attribute is useful when writing data set ready/Data Terminal ready handshaking routines for data terminal equipment (DTE) machines.
Data Type: Boolean
Settings attribute: Set and return the baud rate, parity, data bit, and stop bit parameters.
Syntax: object. settings [= value]
Note: When the port is opened, if the value is invalid, the MSComm control produces error 380 (invalid attribute value ).
Value is composed of four set values in the following format:
"BBBB, P, D, S"
Bbbb indicates the baud rate, P indicates the parity, D indicates the number of data digits, and s indicates the number of stopped digits.
The default value is: "9600, N, 8, 1"
Inputlen attribute: Set and return the number of characters that the INPUT attribute reads from the receiving buffer.
Syntax object. inputlen [= value]
The inputlen property syntax includes the following parts:
Value integer expression, indicating the number of characters read by the INPUT attribute from the receiving buffer.
Note: The default value of the inputlen attribute is 0. When inputlen is set to 0, the MSComm control is used to read all the content in the receiving buffer.
If the inputlen character in the receiving buffer is invalid, the INPUT attribute returns a zero-length string (""). Before using input, you can choose to check the inbuffercount attribute to determine whether the buffer has a required number of characters. This attribute is useful when reading data from a machine whose output format is set to long.
Eofenable attribute: determines whether the MSComm control looks for the EOF character during the input process. If the EOF character is found, the input is stopped and the oncomm event is activated. The commevent attribute is set to comeveof,
Syntax: object. eofenable [= value]
The eofenable attribute syntax includes the following parts:
Value Boolean expression to determine whether the oncomm event is activated when the EOF character is found, as described in "set value.
Value:
True when the EOF character is found, the oncomm event is activated.
False (default) The oncomm event is not activated when the EOF character is found.
Note: When the eofenable attribute is set to false, the oncomm control will not find the EOF character in the input stream.
Error message (MS Comm control)
The following table lists the errors that can be captured by the MSComm control:
Value description
380 invalid attribute value cominvalidpropertyvalue
383 the attribute is read-only comsetnotsupported
394 the attribute is read-only comgetnotsupported
Port 8000 is invalid when it is opened.
8001 the timeout value must be greater than 0.
8002 invalid port number comportinvalid
8003 the attribute is valid only at run time.
8004 attribute read-only at runtime
Port 8005 has enabled comportalreadyopen
8006 the device identifier is invalid or does not support this identifier
8007 the device baud rate is not supported
8008 the specified byte size is invalid
8009 default parameter error
8010 hardware unavailable (locked by other devices)
8011 the function cannot allocate a queue.
8012 comnoopen is not enabled on the device
8013 the device has been enabled
8014 cannot use comm notifications
8015 the comm status comsetcommstatefailed cannot be set
8016 cannot set comm event shielding
8018 the operation is effective only when the port is opened
8019 devices busy
8020 read comm device error comreaderror
8021 internal error comdcberror when Retrieving Device Control Blocks for this port

Research on Serial Communication Programming Technology in PowerBuilder

Abstract: This paper introduces how to implement serial communication by calling Win32 API functions in PowerBuilder, using mscomm32.ocx communication controls, using VCL communication components and calling functions in DLL (dynamic link library, the advantages and disadvantages of various methods are analyzed and summarized.

Key words: Serial Communication; event-driven; application interface; Dynamic Link Library

0 Introduction

In automatic control, the PC is used to monitor the project in real time. Generally, the PC is required to have functions such as data collection, data processing, and control signal generation and transmission on the user interface. In this case, the PC must be connected to the process control signal, and the serial port of the PC must be operated directly. Serial Communication is widely used in industrial monitoring, data collection, and real-time control systems, featuring long transmission distance, simple connection, flexible and convenient use, and high data transmission reliability.

PowerBuilder (PB for short) is a visual and object-oriented rapid interactive application development tool. PB is favored by developers with its concise and efficient integrated development environment, powerful data window technology, and convenient report generation and printing functions. In various development software, Pb provides top-level programming support for databases. However, PB has little support for the underlying computer and does not provide commands, functions, or controls for serial communication, it is difficult to communicate with other devices. Based on my accumulated experience in PB programming, I have introduced several methods for serial communication in Pb.

1. Serial Data Communication

1.1 Working Principle

Windows is an event-driven, device-independent multi-user operating system. It prohibits applications from directly interacting with hardware. programmers can only manage hardware through various drivers provided by windows. Windows system functions include the communication support interrupt function. Windows system opens a user-defined input/output buffer (read/write buffer) for each communication device ), data access and communication ports are completed by the system background. The application only needs to complete the input and output buffer operations. The actual process is that each time a piece of data is received, a low-level hardware interruption occurs, the serial driver in Windows gets control, and the received data is placed in the input data buffer, then return the control to the running application. If the buffer data is full, the serial driver uses the defined flow control mechanism to notify the sender to stop sending data. Data in the queue is processed in the "first-in-first-out" order.

1.2 Communication Mode

The data in serial communication is transmitted in sequence one by one. The communication methods are as follows:

(1) asynchronous communication

In asynchronous communication, data is transmitted by frame (including one character or one byte of data). The data of each serial frame consists of the Start bit, data bit, parity bit, and stop bit.

(2) synchronous communication

In synchronous communication mode, synchronous characters are used to indicate data transmission (usually 1-2), and the clock is used to synchronize the sending end and the receiving end, that is, after the specified synchronization characters are detected, data is continuously transmitted in order until the communication ends.

(3) Query Method

The query method is to regularly query the receiving buffer of the serial port. If there is data in the receiving buffer, the data will be read. If there is no data in the buffer, the execution will continue, so it will take a lot of CPU time, it is actually a derivative of the synchronization method.

(4) event-driven approach

The event-driven method sets Event Notifications. When an expected event occurs, Windows sends a notification, which is similar to the interrupt method in the DOS environment.

The asynchronous method can improve the overall performance of the system. This method is recommended for scenarios with high requirements on system robustness. The query method is the most direct method of reading the serial port, but there is a fatal weakness in the regular query, that is, the query occurs on a regular basis and may occur too early or too late. When the data changes rapidly, especially when the serial port of the master computer is extended to multiple ports through the expansion board, it is necessary to regularly query all serial ports in turn, which is prone to data loss. Although the smaller the scheduled interval, the higher the real-time data, the more resources the system occupies. The event-driven method is an efficient serial port reading method, which is highly Real-time. Especially when multiple serial ports are extended, after the application receives the message, it processes the message to avoid data loss. The event-driven method can better handle serial port communication interactions. Its advantage is that the program responds promptly and has high reliability. We recommend that you use event-driven mode when real-time requirements are high.

1.3 implementation steps

The general steps for serial communication using the serial port of a PC are as follows:

(1) Enable and configure the serial port

To use a serial port for communication in an application, you must submit a resource application to the operating system before use. You must open the serial port to ensure the reliability of data transmission, when the serial port is opened, it is generally set to non-shared mode. Once the serial port is opened, other applications cannot open or use it.

Before using the serial port for data communication, you must configure it. The serial port configuration mainly includes the baud rate, data bits, Stop bits, parity check, sending buffer size, and receiving buffer size.

(2) data read/write and timeout settings

After the serial port is opened and configured, you can perform read and write operations on it. You can perform read and write operations on the serial port using query, synchronization, asynchronous, event-driven, and other methods.

If data transmission is suddenly interrupted during serial communication, the read/write operations on the serial port may enter an indefinite waiting state. To avoid this situation, you must set the wait time for the serial port read/write operations, after the wait time is exceeded, the read/write operations on the serial port will be automatically abandoned, so that even if the data transmission is suddenly interrupted, the program will not be suspended or blocked.

(3) disable the serial port

After the serial port is used up, close it. Otherwise, if the serial port is not closed, the serial port will always be open, and other applications will not be able to open or use it.

2. How to implement serial communication in PowerBuilder Programming

There are four common methods to implement Serial Communication Using PowerBuilder: communication controls, such as MSComm controls, Win32 API functions, and serial communication components; the fourth is to call DLL (Dynamic Connection Library) to implement serial communication programming. The following four methods are discussed respectively.

2.1 use the MSComm communication control to implement serial communication programming

2.1.1 MSComm control

The mscomm32.ocx control can be used in PowerBuilder to implement serial communication programming. The serial communication control mscomm32.ocx (MSComm for short) is a 32-bit ActiveX Control for serial communication programming in Windows provided by Microsoft. This control encapsulates most of the operations of serial communication into the control and provides interface attributes and events for a series of communication commands. It allows the establishment of a serial port connection, you can connect to other communication devices (such as modem), send commands, exchange data, and monitor and respond to various errors and events that may occur during communication, you can use it to create a full-duplex event-driven communication program.

The MSComm control provides two communication methods: event-driven and query. The query method checks the commevent attribute values to determine communication events and errors. When the serial port receives or sends a specified amount of data or the status changes, the MSComm communication control captures these events and errors to trigger the oncomm event, check the value of the commevent attribute of the MSComm control to obtain the event and error code value and perform corresponding processing.

2.1.2 main attributes and events of the MSComm control

Comport: Set and return the communication port number, and set the COM1 value to 1.

Setting: Set and return the serial communication parameters in the form of a string, in the format of "baud rate, parity, data bit, stop bit ".

Portopen: Set and return the status of the communication port. Set this parameter to true to enable the serial port. Set this parameter to false to disable the serial port and clear the receiving and transmission buffers.

Inputmode: sets the format for reading data from the buffer. The format is 0 text and 1 binary;

Input: reads data from the receiving buffer;

Output: write data to the sending buffer;

Inbuffercount: set the number of bytes in the receiving buffer;

Outbuffercount: specifies the number of bytes in the sending buffer;

Inputlen: Sets and returns the number of bytes that the INPUT attribute reads from the receiving buffer;

Rthreshold: When the commevent attribute is comevreceive and the oncomm is generated, the number of characters to be received is returned.

Commevent: returns the most recent communication event or error;

Oncomm event: TYPE = "audio/MPEG">

Implementation of PowerBuilder serial Programming

Because the company's software products need to communicate with the POS machine, the author studies the implementation of Pb serial programming.

PB is a good development tool for database management systems, but PB is not very useful in Web and computer interface communication. Fortunately, we have Ole and COM technologies that make it easy for us to use the functions of some components without having to focus on the underlying business logic. There are two methods to use Pb for serial programming: one is to use Microsoft's communication control (MSComm control) and the other is to use Win32 API functions. The following describes how to use the MSComm control to implement serial programming.

The serial communication control mscomm32.ocx (MSComm for short) is a 32-bit ActiveX Control for serial communication programming in Windows provided by Microsoft. This control encapsulates most of the operations of serial communication into the control and provides interface attributes and events for a series of communication commands. It allows the establishment of a serial port connection, you can connect to other communication devices (such as modem), send commands, exchange data, and monitor and respond to various errors and events that may occur during communication, you can use it to create a full-duplex event-driven communication program. The MSComm control provides two communication methods: event-driven and query. The query method checks the commevent attribute values to determine communication events and errors. When the serial port receives or sends a specified amount of data or the status changes, the MSComm communication control captures these events and errors to trigger the oncomm event, check the value of the commevent attribute of the MSComm control to obtain the event and error code value and perform corresponding processing.

1. mscomm32.ocx Registration

We can create a registration program separately and package it into your application. If the target computer to be installed already has the "MSComm" control, no work is required. If you do not have the "MSComm" control, you need to run the registration program.

The PB encoding of the program is as follows:
Registryset ("hkey_classes_root/licenses/4250e830-6ac2-11cf-8adb-00aa00c00905", "", regstring !," Kjljvjjjoquqmjjjvpqqkqmqykypoqjquoun ")
Run ("regsvr32 mscomm32.ocx ")
MessageBox ('hs', 'Restart the computer ')
This is a simple code, and the mscomm32.ocx file is in the current running directory. If the file is successfully registered, a system message is displayed. To make the interface more friendly, you can perform step-by-step modification, such as "Run (" regsvr32/s mscomm32.ocx ")", so that no system message is displayed on the screen.
You can also use the API function to restart the Windows system through the "exitwindowsex" function (user32.dll.
2. Use the mscomm32 Control for Serial Communication
Common attributes of the mscomm32 control are as follows:
Comport: set or return the serial port number. The default value is 1.
Setting: set or return the baud rate, parity bit, data bit, and stop bit of the serial end. The default value is 9600, N, 8, and 1 ″.
Portopen: if it is set to true, the port is opened. If it is set to false, the port is closed.
Inbuffersize: set or return the size of the receiving buffer. The default value is 1024 characters.
Inbuffercount: return the number of bytes read by the same generation in the receiving buffer. Set the attribute to 0 to clear the receiving buffer.
Outbuffersize: set or return the sending buffer, Which is 512 bytes by default.
Outbuffercounter: return the number of characters waiting for sending in the sending buffer. You can use 0 to clear the buffer.
Output: transmits data to the sending buffer.
Rthreshold: This attribute determines that when the number of bytes in the receiving buffer reaches or exceeds this value, the code is comeventreceive.
The oncomm event. If the bit is set to 0, the oncomm event is not generated.
Commevent: An oncomm event occurs when a communication error occurs. The value of the commevent event can be used to determine
Specific errors or events of oncomm events are commonly used as follows (for more details, refer to the MSComm control Help File)
Comeventbreak: receives the interrupt signal
Comeventframe: frame error detected by hardware.
Comeventrxover: receives Buffer Overflow.
Comeventtxfull: The sending buffer overflows.
Comeventreceive: receives the specified number of characters.
Inputlen: set or return the number of inputs read in the receiving buffer. If the value is 0, the content of the entire buffer zone is read.
Input: return and delete the data that accepts the buffer.

 

3. Pb instance code

We can set the above attributes according to the needs of our program. The MSComm control provides two communication methods: event-driven and query. Since I only need to communicate with the POS machine, I use a simple query method. For the query method, we only need to use PB to operate the output and input attributes of mscomm32. The following is the sample code:

 

Oleobject I _ole_comm // declare an OLE object to connect to the MSComm control

I _ole_comm = create oleobject

Vresult = I _ole_comm.connecttonewobject ('mscommlib. MSComm ')

// Initialize the mscomm32 parameter below and enable the serial port

If p_comport = 1 then

I _ole_comm.commp ORT = 1 // 1 indicates the COM1 port, and 2 indicates the com2 Port

Elseif p_comport = 2 then

I _ole_comm.commp ORT = 2

Else

I _errcode =-1

I _errtext = 'uo _ rs232ld. f_setdevice: An error occurred while opening the serial port com '+ String (p_comport) +'. Make sure the port exists and is not used by other programs'

Return I _errcode

End if

I _ole_comm.settings = "9600, N, 8, 1" // The baud rate is set to 9600, which is consistent with the baud rate set by the POS machine.

I _ole_comm.inputlen = 0

I _ole_comm.inbuffersize = 90

I _ole_comm.outbuffersize = 60

I _ole_comm.sthreshold = 0

I _ole_comm.rthreshold = 9

I _ole_comm.handshaking = 0

I _ole_comm.inbuffercount = 0

I _ole_comm.dtrenable = true

If not I _ole_comm.portopen then

I _ole_comm.portopen = true

End if

// Send messages to the serial port

I _ole_comm.output = "Hello World"

// Receives the serial packet and waits cyclically for receiving the packet uploaded by the POS machine. If the packet times out, it returns

Do While true

Yield ()

Sleep (20)

Vinput + = I _ole_comm.input // retrieve data from the COM port

If pos (vinput, vend)> 0 Then exit // If a message Terminator exists, a loop is introduced.

Loop

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.