Página principal   Lista alfabética   Lista de componentes   Lista de archivos   Miembros de las clases   Archivos de los miembros  

w32socket.cpp

Ir a la documentación de este archivo.
00001 /*************************************************************************
00002 *****    MACHINE-DEPENDENT SERIAL SUPPORT INCLUDE FILE WSERIAL.C     *****
00003 *****                    (Windows 95/NT/3.1win32)                    *****
00004 *****                                                                *****
00005 *****               (C)1997, Directed Perception, Inc.               *****
00006 *****                     All Rights Reserved.                       *****
00007 *****                                                                *****
00008 *****   Licensed users may freely distribute compiled code including *****
00009 *****   this code and data. Source data and code may NOT be          *****
00010 *****   distributed without the prior written consent from           *****
00011 *****   Directed Perception, Inc.                                    *****
00012 *****         Directed Perception, Inc. reserves the right to make   *****
00013 *****   changes without further notice to any content herein to      *****
00014 *****   improve reliability, function or design. Directed Perception *****
00015 *****   shall not assume any liability arising from the application  *****
00016 *****   or use of this code, data or function.                       *****
00017 *****                                                                *****
00018 **************************************************************************
00019 
00020 CHANGE HISTORY:
00021    7/28/99: v1.08.11.  SerialBytesIn timeout now in elapsed seconds.
00022    8/10/98: v1.08.10.  ReadSerialLine initialized charsRead to 0 for 
00023                                            compilers that do not do this automatically.
00024    1/ 7/98: v1.08.09.  Additional error processing added to SerialBytesIn
00025                                                 and ReadSerialLine.
00026    9/27/97: v1.08.08.  Win32. Removed writestring in openserial.
00027                                Set 0 read timeout in setserial. Peek works
00028                                            better.
00029   11/17/96: v1.08.05d. Updated for 32-bit architecture
00030   1/25/96:  v1.07.08d. Fixed strmp in openserial routine
00031   1/7/95:   v1.07.05d. Changed for Windows Borland C/C++.
00032   10/12/94: v1.07.03d. Pre-release working DOS Borland C/C++ version.
00033                        XON/XOFF removed from PTU firmware to allow for
00034                        binary mode.
00035 
00036 **************************************************************************/
00037 
00038 #include <windows.h>
00039 #include "W32SOCKET.H"
00040 
00041 #include <stdio.h>
00042 #include <time.h>
00043 
00044 
00045 //***************************************************************
00046 //*****                LOCAL STATIC STATE                   *****
00047 //***************************************************************
00048 static int err;
00049 
00050 static unsigned char peeked_char, peeked_char_avail = FALSE;
00051 
00052 extern portstream_fd SetSerial(char *, int, int, int, int);
00053 
00054 #define NO_PARITY       0x00
00055 #define EVEN_PARITY     0x18
00056 #define ODD_PARITY      0x08
00057 
00058 SOCKET          ClientSocket;
00059 SOCKADDR_IN     DireccionIP;
00060 char            Orden[5];
00061 char            Valor[5];
00062 char            IP[13];
00063 WORD            wVersionRequested;
00064 WSADATA         wsaData;
00065 int                     i;
00066 long            dato;
00067 
00068 //********************************************************************
00069 //*****               PORTED ROUTINES                            *****
00070 //********************************************************************
00071 
00072 /* PURPOSE: Opens a serial communications port
00073    INPUT:   The serial commpunications port name string
00074    OUTPUT:  Returns portstream handle if the serial port is successfully opened; 
00075             otherwise NULL */
00076 portstream_fd openserial(char *portname)
00077 {        /* Serial communications parameters */
00078          int        speed    = 9600;
00079          int        parity   = NO_PARITY;
00080          int        bits     = 8;
00081          int        stopbits = 1;
00082          bool           Conectado=false;
00083          
00084          portstream_fd pstream;
00085 
00086         wVersionRequested = MAKEWORD( 2, 2 );  
00087         WSAStartup( wVersionRequested, &wsaData );
00088 
00089         ClientSocket = socket( AF_INET, SOCK_STREAM, 0);
00090         if (ClientSocket==INVALID_SOCKET) {     
00091 //              AfxMessageBox("No se ha podido crear el socket",MB_OK);
00092                 WSAGetLastError();
00093                 exit(1);
00094         }
00095 
00096         DireccionIP.sin_family =AF_INET;
00097         DireccionIP.sin_port =htons(8000);
00098         DireccionIP.sin_addr.s_addr=inet_addr(IP);
00099 
00100         for (i=0;i<=10;i++){
00101                 if(connect(ClientSocket,(LPSOCKADDR)&DireccionIP,sizeof(DireccionIP))!=SOCKET_ERROR) {
00102                         Conectado=true;
00103                         break;
00104                 }
00105         }
00106         if (Conectado) { 
00107                 sprintf(Orden,"%s",portname);
00108                 send(ClientSocket,Orden,sizeof(Orden),0);
00109                 recv(ClientSocket,IP,sizeof(IP),0);
00110                 pstream=(void *)strtol(IP,NULL,16);
00111         }
00112         return pstream;
00113 }
00114 
00115 char closeserial(portstream_fd portstream)
00116 {   
00117         if (portstream != NULL) {                         
00118                 sprintf(Valor,"CERRAR");
00119                 send(ClientSocket,Valor,sizeof(Valor),0);
00120                 sprintf(Valor,"%p",portstream);
00121                 send(ClientSocket,Valor,sizeof(Valor),0);
00122         }
00123         closesocket(ClientSocket);
00124         return 0;
00125 }
00126 
00127 /* returns TRUE if all is OK */
00128 char SerialBytesOut(portstream_fd portstream, unsigned char *buffer,
00129                             int charCnt)
00130 {
00131         if (portstream == NULL) { return FALSE;}
00132         sprintf(Orden,"%s%d","S",*buffer);
00133 //      Sleep(100);
00134         if(send(ClientSocket,Orden,sizeof(Orden),0)==SOCKET_ERROR){ return -1; }
00135         return TRUE;
00136 }
00137 
00138 /* returns TRUE if executed correctly. timeout is in msecs */
00139 char SerialBytesIn (portstream_fd portstream, unsigned char *buffer,
00140                             unsigned int charCnt, long timeout)
00141 {  
00142         if (portstream == NULL) { return FALSE; }
00143         sprintf(Orden,"%s%d","R",*buffer);
00144         if(send(ClientSocket,Orden,sizeof(Orden),0)==SOCKET_ERROR){ return -1; }
00145         sprintf(Orden,"%ld",timeout);
00146         if(send(ClientSocket,Orden,sizeof(Orden),0)==SOCKET_ERROR){ return -1; }
00147         if(recv(ClientSocket,Valor,sizeof(Valor),0)==0){ return -1; }
00148         *buffer=(unsigned char)strtol(Valor,NULL,10);
00149         return TRUE;
00150 }
00151 
00152 // returns TRUE if BYTE available to peek at; otherwise, FALSE
00153 char PeekByte(portstream_fd portstream, unsigned char *peekedByte) 
00154 {  COMSTAT COMstatus;
00155    UINT NumCharsAvail;
00156    DWORD ErrCode;
00157    unsigned long BytesRead;
00158 
00159         if (peeked_char_avail)
00160                 { *peekedByte = peeked_char;
00161                   return TRUE;
00162         }
00163         
00164         err = ClearCommError(portstream, &ErrCode, &COMstatus);
00165     NumCharsAvail = COMstatus.cbInQue;
00166         if ( NumCharsAvail > 0 )
00167            { if ( !ReadFile(portstream, (LPSTR) &peeked_char, 1, &BytesRead, NULL) )
00168                 { printf("PeekByte err: readfile error(%d)\n", GetLastError());
00169                   return FALSE;  }
00170                  if ( BytesRead != 1 )
00171                 { printf("PeekByte err: readfile did not read peek char(%d)\n", GetLastError());
00172                   return FALSE;  }
00173                  *peekedByte = peeked_char;     
00174              peeked_char_avail = TRUE;
00175              return (TRUE);
00176         }
00177 
00178    return FALSE;
00179 }
00180 
00181 
00182 
00183 /* returns TRUE is everything OK */
00184 char FlushInputBuffer(portstream_fd portstream) { 
00185         // flush receiving queue
00186         return (char) PurgeComm(portstream, PURGE_RXCLEAR);
00187 }
00188 
00189 
00190 char SerialStringOut(portstream_fd portstream, unsigned char *buffer) { 
00191         return SerialBytesOut(portstream, buffer, strlen((char *) buffer));
00192 }
00193 
00194 // if string successfully read, returns TRUE; otherwise, the negative error 
00195 // code. The number of characters read is returned in charsRead.
00196 char ReadSerialLine(portstream_fd portstream, unsigned char *StringBuffer,
00197                                         long timeout, int *charsRead) {
00198         if (portstream == NULL) return(FALSE);
00199         *charsRead = 0;
00200         for (;;) { 
00201                 err = SerialBytesIn(portstream, StringBuffer, 1, timeout);
00202                 /* putchar(*StringBuffer); */
00203                 if (err != TRUE) return ( (char) err);
00204                 if ( *StringBuffer == '\n' ) 
00205                    { *StringBuffer = '\0';
00206                          return(TRUE);  
00207                    }
00208                 else if (err == TRUE) 
00209                         { StringBuffer++;
00210                               (*charsRead)++;
00211                         }
00212         }
00213   }
00214 
00215 
00216 void do_delay(long timeInMsec) {        
00217     Sleep((DWORD) timeInMsec);
00218 }
00219 
00220 
00221 // Whether you define this depends upon your particular machine.
00222 // PCs reverse integer byte order, so this define is required.
00223 // For almost all other machines, you would omit this define.
00224 //
00225 // If your machine has 2 byte signed and unsigned integers, and
00226 // 4 byte signed integers, then you won't have to port the below code...
00227 #define INT_REVERSED
00228 
00229 
00230 // 2 byte signed short int
00231 char GetSignedShort(portstream_fd portstream, signed short *SHORTval, 
00232                                         long timeout) {
00233 #ifdef INT_REVERSED
00234         SerialBytesIn( portstream, (((unsigned char *) SHORTval)+1), 1, 
00235                        timeout);
00236         SerialBytesIn( portstream, ( (unsigned char *) SHORTval), 1, timeout); 
00237 #else
00238         SerialBytesIn( portstream, ( (unsigned char *) SHORTval), 1, timeout);
00239         SerialBytesIn( portstream, (((unsigned char *) SHORTval)++), 1,
00240                        timeout); 
00241 #endif
00242         return TRUE;
00243 }
00244 
00245 // 2 byte signed short int
00246 char PutSignedShort(portstream_fd portstream, signed short *SHORTval) {
00247 #ifdef INT_REVERSED
00248         SerialBytesOut( portstream, (((unsigned char *) SHORTval)+1), 1);
00249         SerialBytesOut( portstream, ( (unsigned char *) SHORTval), 1); 
00250 #else
00251         SerialBytesOut( portstream, ( (unsigned char *) SHORTval), 1);
00252         SerialBytesOut( portstream, (((unsigned char *) SHORTval)++), 1); 
00253 #endif
00254         return TRUE;
00255 }
00256 
00257 // 2 byte usigned short int
00258 char GetUnsignedShort(portstream_fd portstream, unsigned short
00259                       *USHORTval, long timeout) {
00260 #ifdef INT_REVERSED
00261         SerialBytesIn( portstream, (((unsigned char *) USHORTval)+1), 1,
00262                        timeout);
00263         SerialBytesIn( portstream, ( (unsigned char *) USHORTval), 1,
00264                        timeout); 
00265 #else
00266         SerialBytesIn( portstream, ( (unsigned char *) USHORTval), 1, timeout);
00267         SerialBytesIn( portstream, (((unsigned char *) USHORTval)++), 1,
00268                        timeout); 
00269 #endif
00270         return TRUE;
00271 }
00272 
00273 // 2 byte unsigned short int
00274 char PutUnsignedShort(portstream_fd portstream, unsigned short *USHORTval) {
00275 
00276 #ifdef INT_REVERSED
00277         SerialBytesOut( portstream, (((unsigned char *) USHORTval)+1), 1);
00278         SerialBytesOut( portstream, ( (unsigned char *) USHORTval), 1); 
00279 #else
00280         SerialBytesOut( portstream, ( (unsigned char *) USHORTval),    1);
00281         SerialBytesOut( portstream, (((unsigned char *) USHORTval)++), 1); 
00282 #endif
00283         return TRUE;
00284 }
00285 
00286 // 4 byte signed short int
00287 char GetSignedLong(portstream_fd portstream, signed long *LONGval, long
00288                    timeout) {   
00289     long i, incr = 1;
00290 
00291 #ifdef INT_REVERSED
00292         LONGval = (signed long *) (((unsigned char *) LONGval) + 3);
00293         incr = -1;
00294 #endif
00295         for (i=0; i<4; i++) { 
00296                 SerialBytesIn( portstream, ((unsigned char *) LONGval), 1,
00297                                timeout);
00298                 LONGval = (signed long *) (((unsigned char *) LONGval) + incr);
00299         }
00300         return TRUE;
00301 }
00302 
00303 // 4 byte signed short int
00304 char PutSignedLong(portstream_fd portstream, signed long *LONGval) {
00305 
00306 #ifdef INT_REVERSED
00307         SerialBytesOut( portstream, ((unsigned char *) LONGval)+3, 1);
00308         SerialBytesOut( portstream, ((unsigned char *) LONGval)+2, 1);
00309         SerialBytesOut( portstream, ((unsigned char *) LONGval)+1, 1);
00310         SerialBytesOut( portstream, ((unsigned char *) LONGval),   1);
00311 #else
00312         SerialBytesOut( portstream, ((unsigned char *) LONGval),4);
00313 #endif
00314         return TRUE;
00315 }
00316 
00317 
00318 //*******************************************************
00319 //******               LOCAL CODE                  ******
00320 //*******************************************************
00321 
00322 portstream_fd SetSerial(char *portname, int Speed, int Parity, int Bits, int StopBit) 
00323   { portstream_fd pstream;
00324         DCB dcb;
00325         COMMTIMEOUTS timeout_info;
00326 
00327         pstream = 
00328                 CreateFile(portname,
00329                            GENERIC_READ | GENERIC_WRITE,
00330                                    0,    /* comm devices must be opened w/exclusive-access */
00331                                    NULL, /* no security attrs */
00332                                    OPEN_EXISTING, /* comm devices must use OPEN_EXISTING */
00333                                    FILE_ATTRIBUTE_NORMAL, // | FILE_FLAG_OVERLAPPED,  // overlapped I/O
00334                                    NULL  /* hTemplate must be NULL for comm devices */
00335                                    );
00336         if (pstream == INVALID_HANDLE_VALUE) {
00337         printf("\nCreateFile error for %s (error=%d)\n", portname, GetLastError());
00338         return NULL;
00339                 }
00340 
00341         // printf("\nSetting COM port parameters\n");
00342     // e.g. "COM2:9600,n,8,1"
00343 
00344         if ( !(GetCommState(pstream, &dcb)) ) 
00345            { printf("GetCommState error(%d)\n", GetLastError());
00346              return NULL;
00347            }
00348 
00349         dcb.BaudRate = Speed;
00350     dcb.ByteSize = (unsigned char) Bits;
00351         dcb.Parity = NOPARITY;
00352         if (StopBit == 2)
00353              dcb.StopBits = TWOSTOPBITS; 
00354     else dcb.StopBits = ONESTOPBIT;
00355         switch (Parity) {
00356                 case NO_PARITY:   dcb.Parity = NOPARITY;    break;
00357                 case EVEN_PARITY: dcb.Parity = EVENPARITY;  break;
00358                 case ODD_PARITY:  dcb.Parity = ODDPARITY;   break;
00359                 default:                  return NULL;     }
00360         dcb.fOutxCtsFlow      = 
00361         dcb.fOutxDsrFlow      = 
00362         dcb.fDsrSensitivity   = 
00363         dcb.fOutX                         = 
00364         dcb.fInX                          = FALSE;
00365         dcb.fDtrControl       = DTR_CONTROL_ENABLE;
00366         dcb.fRtsControl       = RTS_CONTROL_ENABLE;
00367         dcb.fTXContinueOnXoff = TRUE;
00368 
00369     if ( ! (SetCommState(pstream, &dcb)) ) 
00370            { printf("SetCommState err(%d)\n", GetLastError());
00371              return NULL;
00372         }
00373         // printf("\nSetCommState OK\n");
00374 
00375     if ( ! (PurgeComm(pstream, PURGE_TXABORT | PURGE_RXABORT |
00376                                                                   PURGE_TXCLEAR | PURGE_RXCLEAR)) )
00377            { printf("PurgeComm err(%d)\n", GetLastError());
00378              return NULL; }
00379 
00380         // set timout read info. Readfile returns immediately, even if not enough data is avail
00381         if ( ! GetCommTimeouts(pstream, &timeout_info) )
00382            { printf("GetCommTimeouts err(%d)\n", GetLastError());
00383              return NULL; }
00384         timeout_info.ReadIntervalTimeout = MAXDWORD;
00385         timeout_info.ReadTotalTimeoutMultiplier =
00386     timeout_info.ReadTotalTimeoutConstant   = 0;
00387         if (! SetCommTimeouts(pstream, &timeout_info) )
00388            { printf("SetCommTimeouts err(%d)\n", GetLastError());
00389              return NULL; }
00390 
00391         // printf("\nPort initialized!\n");
00392     // SerialStringOut(pstream, "\nSetSerial");
00393 
00394     return (pstream);
00395 }
00396 
00397 void SetIP (char *IPAddres)
00398 {
00399         sprintf(IP,"%s",IPAddres);
00400 }

Generado el Tue Apr 24 06:55:49 2001 para Dllcontrol por doxygen1.2.6 escrito por Dimitri van Heesch, © 1997-2001