How to set the DTR / RTS state to be used when CreateFile () opens a COM port

I wrote / supported a terminal emulator called uCon ( http://www.umonfw.com/ucon ). All of this is based on the "good" Win32 and is completely located in the "C". Recently, I was offered to support the ability to connect uCon to a COM port and configure DTR / RTS for purposes outside of RS232 flow control. I know that I can do this after CreateFile () is called using EscapeCommFunction () and / or SetCommState (); however, these functions can only be called AFTER CreateFile () returns an open port handle. Unfortunately, when CreateFile () opens the port, it sets the DTR / RTS to its default state, which may (or may not) be different from the state in which I want to save the DTR.

For example, suppose a user has a card connected to the serial port of a PC, and the DTR line is used to set the card to a non-standard state. When the DTR is inactive, the board works "normally", but sometimes the DTR-active is used to switch the hardware to a different state.

In most cases, I saw CreateFile () bring the DTR active, then my call to clear the DTR returns it to inactive; however, that I should avoid the glitch. I found a set of functions called GetDefaultCommConfig () and SetDefaultCommConfig (), but could not get them to work successfully. So my question is ...

Is there a way to predefine the default state that will be set on RS232 control lines when calling CreateFile ()? Has anyone used GetDefaultCommConfig () / SetDefaultCommConfig () successfully?

It seems to me that this should allow me to pre-set the value of the DTR used when CreateFile () is called ...

 
 int
 EstablishDefaultDTR (char * comPortName, int dtr)
 {
     COMMCONFIG cc;
     DWORD bsize = sizeof (COMMCONFIG);

     if (GetDefaultCommConfig (comPortName, & cc, & bsize) == 0) {
         ShowLastError ("GetDefaultCommConfig ()");
         return (-1);
     }

     if (dtr)
        cc.dcb.fDtrControl = DTR_CONTROL_ENABLE;
     else
        cc.dcb.fDtrControl = DTR_CONTROL_DISABLE;

     if (SetDefaultCommConfig (comPortName, & cc, bsize) == 0) {
         ShowLastError ("SetDefaultCommConfig ()");
         return (-1);
     }
 }

But, as you may have guessed, this is not so. Any ideas?

+4
source share
2 answers

Maybe not the fastest way, but it works:

#include <stdlib.h> #include <stdio.h> int EstablishDefaultDTR(char *comPortName, int dtr){ char commandString[256]; if ( !system(NULL) ){ ShowLastError("system()"); return(-1); } sprintf( commandString, "MODE %s dtr=%s%", comPortName, dtr? "on":"off" ); return system( commandString ); } 
+3
source

You are not initializing the COMMCONFIG structure. This can be a problem, as the documentation explicitly states that you should install dwSize at least

cc.dwSize = sizeof (COMMCONFIG);

+2
source

Source: https://habr.com/ru/post/1285751/


All Articles