/* Combined CONIO and socket select code combined to use select as timer doug rice, 2009 Based on code from: http://www.codersource.net/winsock_tutorial_server_select_model.html */ // =========================================================================== // Sec 1.0 Includes // =========================================================================== #include #include #include #include #include #include #include // =========================================================================== // Sec 2.0 # Defines // =========================================================================== // socket stuff #define PORT 1150 #define BUFFERSIZE 8192 // RS232 stuff #define COM_PORT 7 // ////////// Modify as required. // =========================================================================== // Sec 3.0 # Type defs and Vars // =========================================================================== union iic_ctointU { struct chS { char a ; char b; char c; char d; } chars; int int1; } ; typedef struct _MYSOCKET_INFORMATION { CHAR Buffer[BUFFERSIZE]; WSABUF DataBuf; SOCKET Socket; OVERLAPPED Overlapped; DWORD SendBytes; DWORD RecvBytes; } SOCKET_INFORMATION, * LPSOCKET_INFORMATION; DWORD TotalSockets = 0; LPSOCKET_INFORMATION SocketList[FD_SETSIZE]; const struct timeval timeoutSelect = { 0,10 }; //handle for serial port I/O HANDLE hCom; // iic state variables int iic_state = 0; int iic_nextstate = 0; int iic_sw; int iic_ad1,iic_ad2; // =========================================================================== // Sec 4.0 Function Prototypes // =========================================================================== BOOL CreateSocketInformation(SOCKET s); void FreeSocketInformation(DWORD Index); int iic_turnOnLED(int io_port, int setting ); int iic_readAD( int io_port, int setting ); int iic_readAD2( int io_port, int setting ); int iic_setPins( int io_port, int setting ); void iic_timeslice( int io_port ); // RS232 Routines HANDLE rs_initialise (int io_port, const long int BaudRate, const char parity, const char data); void rs_flush(const int io_port); void rs_terminate(const int io_port); char rs_getch(const int io_port); int rs_getline(const int io_port, char line[], clock_t timeout); void rs_putch(const int io_port, const int txchar); void rs_putstr(const int io_port, const char *string); // delay_routines void delay_ms(clock_t millis); int fileExample(){ HANDLE hFile; DWORD wmWritten; char strVal[1024]; hFile = CreateFile("C:\\test.txt",GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ,NULL,OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL); ReadFile(hFile,strVal,1024,&wmWritten,NULL); CloseHandle(hFile); } // =========================================================================== // Sec 5.0 # Main Code // =========================================================================== int main1(void); int main(void) { int a=-1; long b=-2l; int c=-3l; /* I think all */ printf( "%hu %u %hu \n", a,b,c,-4L,-5L,-6L,-8L); printf("|%-25.3s|","Hello") ; printf("\n"); int io_port = COM_PORT; main1( ); // routine rs_terminate(io_port); } int main1(void) { SOCKET ListenSocket; SOCKET AcceptSocket; SOCKADDR_IN InternetAddr; WSADATA wsaData; INT Ret; FD_SET Writer; FD_SET Reader; DWORD i; DWORD Total; ULONG NonBlock; DWORD Flags; DWORD SendBytes; DWORD RecvBytes; int io_port = COM_PORT; clock_t timeout; if(!rs_initialise(io_port ,19200, '8', 'N')) { printf("Opening Port Failed"); delay_ms(5000); exit(1); } // iic_turnOnLED( io_port, 0xFF ); iic_setPins( io_port, 0xff ); iic_readAD( io_port, 0xF ); timeout = clock() + 60000; // every 60 secs // =================================================== if ((Ret = WSAStartup(MAKEWORD(2,0),&wsaData)) != 0) { printf("WSAStartup() failed with error %d\n", Ret); WSACleanup(); return 0; } // Create a socket. if ((ListenSocket = WSASocket(AF_INET, SOCK_STREAM, 0, NULL, 0, WSA_FLAG_OVERLAPPED)) == INVALID_SOCKET) { printf("WSASocket() failed with error %d\n", WSAGetLastError()); return 0 ; } InternetAddr.sin_family = AF_INET; InternetAddr.sin_addr.s_addr = htonl(INADDR_ANY); InternetAddr.sin_port = htons(PORT); if (bind(ListenSocket, (SOCKADDR *) &InternetAddr, sizeof(InternetAddr)) == SOCKET_ERROR) { printf("Binding failed with error %d\n", WSAGetLastError()); return 0 ; } if (listen(ListenSocket, 5)) { printf("listen failed with error %d\n", WSAGetLastError()); return 0 ; } // Change the socket mode on the listening socket from blocking to non-block NonBlock = 1; if (ioctlsocket(ListenSocket, FIONBIO, &NonBlock) == SOCKET_ERROR) { printf("ioctlsocket() failed \n"); return 0 ; } while(TRUE) { // Initialize the Read and Write socket set. FD_ZERO(&Reader); FD_ZERO(&Writer); // Check for connection attempts. FD_SET(ListenSocket, &Reader); // FD_SET(STDIN_FILENO, &Reader); // Set Read and Write notification for each socket based on the // current state the buffer. for (i = 0; i < TotalSockets; i++) if (SocketList[i]->RecvBytes > SocketList[i]->SendBytes) FD_SET(SocketList[i]->Socket, &Writer); else FD_SET(SocketList[i]->Socket, &Reader); if ((Total = select(0, &Reader, &Writer, NULL, &timeoutSelect )) == SOCKET_ERROR) { printf("select function returned with error %d\n", WSAGetLastError()); return 0; } iic_timeslice( io_port); // Check for arriving connections on the listening socket. if (FD_ISSET(ListenSocket, &Reader)) { Total--; if ((AcceptSocket = accept(ListenSocket, NULL, NULL)) != INVALID_SOCKET) { // Set the accepted socket to non-blocking mode so the server will // not get caught in a blocked condition on WSASends NonBlock = 1; if (ioctlsocket(AcceptSocket, FIONBIO, &NonBlock) == SOCKET_ERROR) { printf("ioctlsocket() failed with error %d\n", WSAGetLastError()); return 0 ; } if (CreateSocketInformation(AcceptSocket) == FALSE) return 0 ; } else { if (WSAGetLastError() != WSAEWOULDBLOCK) { printf("accept() failed with error %d\n", WSAGetLastError()); return 0 ; } } } // Check each socket for Read and Write notification for Total number of sockets for (i = 0; Total > 0 && i < TotalSockets; i++) { printf( " socket[ %d ] : %X \n ", i, SocketList[i]->Socket ); LPSOCKET_INFORMATION SocketInfo = SocketList[i]; // If the Reader is marked for this socket then this means data // is available to be read on the socket. //printf( "-- %X %X \n", SocketInfo->Socket, Reader ); if (FD_ISSET(SocketInfo->Socket, &Reader)) { Total--; SocketInfo->DataBuf.buf = SocketInfo->Buffer; SocketInfo->DataBuf.len = BUFFERSIZE; Flags = 0; if (WSARecv(SocketInfo->Socket, &(SocketInfo->DataBuf), 1, &RecvBytes, &Flags, NULL, NULL) == SOCKET_ERROR) { if (WSAGetLastError() != WSAEWOULDBLOCK) { printf("Receive failed with error\n"); FreeSocketInformation(i); } continue; } else { iic_turnOnLED(io_port,1); SocketInfo->RecvBytes = RecvBytes; printf("%s\n",SocketInfo->DataBuf.buf); // If zero bytes are received, this indicates connection is closed. if (RecvBytes == 0) { FreeSocketInformation(i); continue; } } } // If the Writer is marked on this socket then this means the internal // data buffers are available for more data. if (FD_ISSET(SocketInfo->Socket, &Writer)) { Total--; SocketInfo->DataBuf.buf = SocketInfo->Buffer + SocketInfo->SendBytes; SocketInfo->DataBuf.len = SocketInfo->RecvBytes - SocketInfo->SendBytes; if (WSASend(SocketInfo->Socket, &(SocketInfo->DataBuf), 1, &SendBytes, 0, NULL, NULL) == SOCKET_ERROR) { if (WSAGetLastError() != WSAEWOULDBLOCK) { printf("Send failed with error\n"); FreeSocketInformation(i); } continue; } else { SocketInfo->SendBytes += SendBytes; if (SocketInfo->SendBytes == SocketInfo->RecvBytes) { SocketInfo->SendBytes = 0; SocketInfo->RecvBytes = 0; } } } } } } // =========================================================================== // Sec 6.0 Socket functions // =========================================================================== BOOL CreateSocketInformation(SOCKET s) { LPSOCKET_INFORMATION SI; printf("Accepted socket: %d \n" , s); if ((SI = (LPSOCKET_INFORMATION) GlobalAlloc(GPTR, sizeof(SOCKET_INFORMATION))) == NULL) { printf("GlobalAlloc() failed\n"); return FALSE; } // Prepare SocketInfo structure for use. SI->Socket = s; SI->SendBytes = 0; SI->RecvBytes = 0; SocketList[TotalSockets] = SI; TotalSockets++; printf("Accepted socket: %d totalSockets: %d \n" , s, TotalSockets ); return(TRUE); } void FreeSocketInformation(DWORD Index) { LPSOCKET_INFORMATION SI = SocketList[Index]; DWORD i; closesocket(SI->Socket); printf("Closing socket %d\n", SI->Socket ); GlobalFree(SI); // Remove from the socket array for (i = Index; i < TotalSockets; i++) { SocketList[i] = SocketList[i + 1]; } TotalSockets--; } // =========================================================================== // Sec 7.0 Com port function // =========================================================================== HANDLE rs_initialise (int io_port, const long int BaudRate, const char parity, const char data) { BOOL bPortReady; DCB dcb; COMMTIMEOUTS CommTimeouts; char ComPortName[5]="COM "; ComPortName[3]='0'+ io_port; hCom = CreateFile(ComPortName, GENERIC_READ | GENERIC_WRITE, 0, // exclusive access NULL, // no security OPEN_EXISTING, 0, // no overlapped I/O NULL); // null template if ((int)hCom <= 0) { printf("serial port COM%d connect fail %s error %d\n\r", io_port, ComPortName, GetLastError()); return 0; } //else printf(" serial port COM%d connect OK \n\r", io_port); bPortReady = SetupComm(hCom, 128, 128); // set buffer sizes if (!bPortReady ) { printf("serial port COM%d SetupComm fail %d\n\r", io_port, GetLastError()); return 0; } //else printf(" serial port COM%d connect OK \n\r", io_port); bPortReady = GetCommState(hCom, &dcb); if (!bPortReady ) { printf("serial port COM%d GetCommState fail %d\n\r", io_port, GetLastError()); return 0; } // else printf(" serial port COM%d connect OK \n\r", io_port); dcb.BaudRate = BaudRate; if( data == '7') dcb.ByteSize = 7; else dcb.ByteSize = 8; if( parity == 'E') dcb.Parity = EVENPARITY; if( parity == 'O') dcb.Parity = ODDPARITY; else dcb.Parity = NOPARITY; dcb.StopBits = ONESTOPBIT; dcb.fAbortOnError = TRUE; // set XON/XOFF dcb.fOutX = FALSE; // XON/XOFF off for transmit dcb.fInX = FALSE; // XON/XOFF off for receive // set RTSCTS dcb.fOutxCtsFlow = FALSE; // turn off CTS flow control dcb.fRtsControl = FALSE; // RTS_CONTROL_HANDSHAKE; // // set DSRDTR dcb.fOutxDsrFlow = FALSE; // turn off DSR flow control //dcb.fDtrControl = DTR_CONTROL_ENABLE; // DTR handshake dcb.fDtrControl = DTR_CONTROL_DISABLE; // // dcb.fDtrControl = DTR_CONTROL_HANDSHAKE; // bPortReady = SetCommState(hCom, &dcb); if (!bPortReady ) { printf("serial port COM%d SetCommState fail %d\n\r", io_port, GetLastError()); return 0; } // Communication timeouts //COMMTIMEOUTS CommTimeouts; bPortReady = GetCommTimeouts (hCom, &CommTimeouts); CommTimeouts.ReadIntervalTimeout = 5 ; CommTimeouts.ReadTotalTimeoutConstant = 5 ; CommTimeouts.ReadTotalTimeoutMultiplier = 1 ; CommTimeouts.WriteTotalTimeoutConstant = 5 ; CommTimeouts.WriteTotalTimeoutMultiplier = 1 ; bPortReady = SetCommTimeouts (hCom, &CommTimeouts); if (!bPortReady ) { printf("serial port COM%d SetCommTimeouts fail %d\n\r", io_port, GetLastError()); return 0; } else { printf(" serial port COM%d connect OK \n\r", io_port); } return (hCom); } void rs_terminate(const int io_port) { CloseHandle(hCom); } char rs_getch(const int io_port) { char rxchar; BOOL bReadRC; static DWORD iBytesRead; bReadRC = ReadFile(hCom, &rxchar, 1, &iBytesRead, NULL); if (iBytesRead) { return rxchar; } else { return 0; // return 0 if no character read } } void rs_flush(const int io_port) { while(rs_getch(io_port)!=0) ; } int rs_getline(const int io_port, char line[], clock_t timeout) { int num_chars = 0; char ch; clock_t endtime; endtime = timeout + clock(); while(clock() < endtime) { ch = rs_getch(io_port); //printf("%d ", ch); if (ch != 0) { printf("%c", ch); if ((ch == 10) || (ch == 13)) { line[num_chars] = '\0'; // terminate the string return(num_chars); } else { line[num_chars] = ch; ++num_chars; } } } // end of while line[num_chars] = '\0'; return(-1); // timeout } void rs_putch(const int io_port, const int txchar) { BOOL bWriteRC; static DWORD iBytesWritten; bWriteRC = WriteFile(hCom, &txchar, 1, &iBytesWritten,NULL); return; } void rs_putstring(const int io_port, const char *string) { while (*string != '\0') rs_putch(io_port, *string++); } void delay_ms(clock_t millis) { // This uses a lot of cpu time to run. find out hoe to use system timer. clock_t endtime; endtime = millis + clock(); while( endtime > clock() ) ; } // =========================================================================== // Sec 8.0 iic port function // =========================================================================== int iic_turnOnLED( int io_port, int setting ) { rs_flush(io_port); rs_putch(io_port, 0x5A ); rs_putch(io_port, 0x10 ); rs_putch(io_port, 0x00 + ( setting & 1 ) ); rs_putch(io_port, 0x00 ); } int iic_setPins( int io_port, int setting ) { rs_flush(io_port); rs_putch(io_port, 0x5A ); rs_putch(io_port, 0x10 ); rs_putch(io_port, 0x00 + ( setting & 0xff )); rs_putch(io_port, 0x00 ); } int iic_getPins( int io_port ) { rs_flush(io_port); rs_putch(io_port, 0x5A ); rs_putch(io_port, 0x11 ); rs_putch(io_port, 0x00 ); rs_putch(io_port, 0x00 ); } int iic_readAtoD( int io_port, int setting ) { rs_flush(io_port); rs_putch(io_port, 0x5A ); rs_putch(io_port, 0x12 ); rs_putch(io_port, 0xe0 + ( setting & 1 ) ); rs_putch(io_port, 0x00 ); } int iic_readAD( int io_port, int setting ); int iic_readAD( int io_port, int setting ) { rs_flush(io_port); rs_putch(io_port, 0x5A ); rs_putch(io_port, 0x12 ); rs_putch(io_port, 0xe0 + ( setting & 0xff ) ); rs_putch(io_port, 0x00 ); iic_state = 1; } int iic_readPins( int io_port ); int iic_readPins( int io_port ) { union iic_ctointU res; if ( iic_state == 0 ) { return 0; } iic_state = 0; res.chars.b = rs_getch( io_port ); res.chars.a = 0; res.chars.c = 0; res.chars.d = 0; // printf( "sw: %X ", (int) res.int1 ); iic_sw = res.int1; return res.int1 ; } int iic_readAD2( int io_port, int setting ); int iic_readAD2( int io_port, int setting ) { union iic_ctointU res; if ( iic_state == 0 ) { return 0; } iic_state = 0; res.chars.b = rs_getch( io_port ); res.chars.a = rs_getch( io_port ); res.chars.c = 0; res.chars.d = 0; iic_ad1 = res.int1 ; // printf( "\nA: %X , %d %f ", (int) res.int1, (int) res.int1, res.int1 * 5.0 / 1024.0 ); res.chars.b = rs_getch( io_port ); res.chars.a = rs_getch( io_port ); res.chars.c = 0; res.chars.d = 0; iic_ad2 = res.int1 ; // printf( "\nB: %X , %d %f", (int) res.int1, (int) res.int1, res.int1 * 5.0 / 1024.0 ); } void iic_timeslice( int io_port ){ iic_state = iic_nextstate; switch( iic_nextstate ) { case 0: { //printf("s0..."); iic_setPins( io_port, 0xF ); iic_nextstate = 1; } break; case 1: { //printf("s1..."); iic_readAD( io_port, 0xF ); iic_nextstate = 2; } break; case 2: { //printf("s2..."); iic_readAD2( io_port, 0xF ); iic_getPins( io_port ); iic_nextstate = 3; } break; case 3: { //printf("s3..."); iic_readPins( io_port ); printf( "\n %2X %4x %4x | %5.2f %5.2f |", iic_sw,iic_ad1,iic_ad2,iic_ad1* 5.0 / 1024.0,iic_ad2* 5.0 / 1024.0 ); iic_nextstate = 1; } break; default: { //printf("default..."); iic_nextstate = 1; } } /* end switch() */ } // =========================================================================== // Sec 8.0 Com port function // =========================================================================== // ============================================================================