Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon.

Pages: 1-4041-8081-120121-160161-200201-240241-280281-

I feel sorry

Name: Anonymous 2007-11-01 2:38

My friend is writing firmware for some sensor, and to analyze output he had to use rs232 to send data to computer. He wasted almost two weeks on this, because it didn't work. here's the code he ended with. He said he had to use that FILE_FLAG_OVERLAPPED because this is the only way to read from asynchronous serial port, that this is written in winapi documentation and on various websights. T_T. I feel sorry for all good people who are fooled by bullshit on the internet.

// com_port1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <windows.h>
#include <string.h>


void PrintLastError(void){

        int ercode = GetLastError();
        printf("(-) GetLastError() return %i ", ercode );
        switch( ercode ){
                case 2: printf("(The system cannot find the file specified)\n"); break;
                case 5: printf("(Access is denied)\n"); break;
                case 29: printf("(The system cannot write to the specified device)\n"); break;
                case 87: printf("(The parameter is incorrect)\n"); break;
                case 998: printf("(Invalid access to memory location)\n"); break;

        // тут описания для самых распространенных ошибок, остальные пару сотен добавите сами 8)

                default: printf("\n");
        }

}




char Data;
char Data1[] = "FcU_1-2-3-4-5-6-7-8-9-10-11-12-13-14-15-16-17-18-19-20-21-22-23-24-25-26-27-28-29-30-31-32-23";
unsigned char Flag_end;

using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
        int k=0;

        COMSTAT CStat;
        HANDLE   port1;

        //Открытие портa
        port1 = CreateFile("COM1",GENERIC_READ,0,NULL,OPEN_EXISTING,FILE_FLAG_OVERLAPPED,NULL);
//      port1 = CreateFile("COM1",GENERIC_READ,0,NULL,OPEN_EXISTING,0,NULL);
//    port1 = CreateFile(TEXT("COM1"),GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,0,NULL);
        if( port1 != INVALID_HANDLE_VALUE )
                printf("(+) %s initialized\n", "COM1");
        else
                printf("(-) %s initialization failed\n", "COM1");


        SetupComm(port1,2048,2048);
        //отмена приема и передачи,очистка буферов ввода-вывода порта
        int retcode
        =
        PurgeComm(
                                port1,
                                PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR
                          );

        // retcode будет содержать код возврата
        if( retcode==NULL )
                printf("(-) PurgeComm1() failed\n");
        else
                printf("(+) 1Discarded all characters from the output and input buffer\n");


        retcode = ClearCommBreak(port1);
        if( retcode==NULL )
        {
                printf("(-) ClearCommBreak1() failed\n");
                PrintLastError();
        }
        else
                printf("(+) 1Restored character transmission and placed the transmission line in a nonbreak state\n");

//-----------------------Настройка DCB--------------------------------------------------------------------------
        DCB dcb;
        retcode = GetCommState(port1,&dcb);
        if( retcode==NULL )
                printf("(-) GetCommState1() failed\n");
        else
                printf("(+) 1Retrieved the current control settings for %s\n", "COM5");

        // изменяем только то что нам нужно:
        dcb.DCBlength = sizeof(DCB);                                    // длина структуры
        dcb.BaudRate = CBR_9600;                                                // установка уровня передачи
        //dcb.fBinary = TRUE;                                                           // установка режима передачи:бинарный
        dcb.Parity = NOPARITY;                                                  // установка контроля четности:нет
        //dcb.fOutxCtsFlow = TRUE;                                              // контроль уровня CTS:TRUE
        //dcb.fOutxDsrFlow = TRUE;                                              // контроль уровня DSR:TRUE
        dcb.fDtrControl = DTR_CONTROL_DISABLE;                  // режим управления сигналом DTR:DTR_CONTROL_ENABLE;
        dcb.fDsrSensitivity = FALSE;                                            // fuck you ,spielberg!
        dcb.fTXContinueOnXoff = FALSE;                                  // Передача продолжается при переполнении буфера
                                                                                                       // и передаче драйвером символа XoffChar;
        //dcb.fOutX =FALSE ;                                                            // передача не зависит от символа XON/XOFF
        //dcb.fInX = 1;
        //dcb.fErrorChar = 1;
        //dcb.fNull = 1;
        //dcb.fRtsControl = 2;
        //dcb.fAbortOnError = 1;
        //dcb.fDummy2 = 17;
        //dcb.wReserved;
        //dcb.XonLim;
        //dcb.XoffLim;
    //dcb.ByteSize = 8;             // data size, xmit, and rcv
        dcb.StopBits = ONESTOPBIT;    // one stop bit
        //dcb.XonChar;
        //dcb.XoffChar;
        //dcb.ErrorChar;
        //dcb.EofChar;
        //dcb.EvtChar;
        //dcb.wReserved1;
        //dcb.fDtrControl = DTR_CONTROL_ENABLE;
        //dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
        // и устанавливаем новый опции порта:

        retcode = SetCommState(port1, &dcb);
        if( retcode==NULL )
                printf("(-) SetCommState1() failed\n");
        else
                printf("(+) 2Reinitialized all hardware and control settings \n");
//----------------------------------------------------------------------------------------------------------------

//-------------------------------настройка таймаутов--------------------------------------------------------------
        COMMTIMEOUTS TIMEOUTS;
        retcode = GetCommTimeouts(port1,&TIMEOUTS);
        if(retcode == NULL)
        {
                printf("(-) GetTimeout() failed\n");
        }
        else
        {
                printf("(+) GetTimeout() succeed\n");
        };
                TIMEOUTS.ReadIntervalTimeout=MAXDWORD;
                TIMEOUTS.ReadTotalTimeoutConstant=0;
                TIMEOUTS.ReadTotalTimeoutMultiplier=0;
                TIMEOUTS.WriteTotalTimeoutConstant=0;
                TIMEOUTS.WriteTotalTimeoutMultiplier=0;
        retcode = SetCommTimeouts(port1,&TIMEOUTS);
        if(retcode == NULL)
        {
                printf("(-) SetTimeout() failed\n");
        }
        else
        {
                printf("(+) SetTimeout() succeed\n");
        }

//-----------------------------------------------------------------------------------------------------------------

Name: Anonymous 2007-11-01 2:39



//----------создание структуры для асинхронного приема данных------------------------------------------------------
        OVERLAPPED OL;
        memset(&OL,0,sizeof(OL));
        OL.hEvent=CreateEvent(NULL, FALSE, FALSE, NULL);
//-----------------------------------------------------------------------------------------------------------------

        DWORD EventMask = 0; //сюда будет записан тип события

//-----------настройка и установка маски отслеживаемых событий-----------------------------------------------------

        DWORD CommEventMask = EV_BREAK | EV_CTS | EV_DSR | EV_ERR | EV_RING | EV_RLSD | EV_RXCHAR | EV_RXFLAG | EV_TXEMPTY;
                                                        // отслежваем все возможные события

        retcode = SetCommMask(port1,CommEventMask);//
    if( retcode==NULL )
        {
                printf("(-) 1SetCommMask() failed\n");
                PrintLastError();
        }
        else
        {
                printf("(+) 1Events to be monitored -> BREAK, CTS, DSR, ERR, RING, RLSD, RXCHAR, RXFLAG, TXEMPTY\n");
        }
//-----------------------------------------------------------------------------------------------------------------

        DWORD dwReaded=0;
        const int  BUFSIZE = 255;
        char lpInBuffer[BUFSIZE];
        // выделяем память под буфер
        memset(&lpInBuffer, 0, sizeof(lpInBuffer));
        while(1)
        {
                retcode = ReadFile(port1, &lpInBuffer, 1, &dwReaded,  &OL);

                //ждем наступления события
                retcode = WaitCommEvent(port1, &EventMask, &OL);
                if ( ( !retcode ) && (GetLastError()==ERROR_IO_PENDING) )
                {
                        printf("(!) Waiting for event\n");

                        if(WaitForSingleObject(OL.hEvent,INFINITE)==WAIT_OBJECT_0)
                        {
                                        if(EventMask & EV_BREAK) printf("(i) EV_BREAK\n");
                                        if(EventMask & EV_RLSD) printf("(i) EV_RLSD\n");
                                        if(EventMask & EV_CTS)  printf("(i) EV_CTS\n");
                                        if(EventMask & EV_DSR)  printf("(i) EV_DSR\n");
                                        if(EventMask & EV_ERR)  printf("(i) EV_ERR\n");
                                        if(EventMask & EV_RING) printf("(i) EV_RING\n");
                                        if(EventMask & EV_RXCHAR)       printf("(i) EV_RXCHAR\n");
                                        if(EventMask & EV_RXFLAG)       printf("(i) EV_RXFLAG\n");
                                        if(EventMask & EV_TXEMPTY)      printf("(i) EV_TXEMPTY\n");

                                GetOverlappedResult(port1, &OL, &dwReaded, FALSE) ;
                                printf("(+) %d bytes received\n%s\n", dwReaded, &lpInBuffer);
                        }

                }
                else
                {
                        if(retcode)
                        {
                                printf("(-)Error waitvcomm event retcode %d\n",GetLastError());
                        }
                        else
                        {
                                printf("(-)Error waitcommevent %d\n",GetLastError());
                        }
                }


                DWORD ErrorMask = 0; // сюда будет занесен код ошибки порта, если таковая была

                ClearCommError(port1, &ErrorMask, &CStat);
                //DWORD quelen = CStat.cbInQue;


                // все. тепереь quelen содержит количество байт в буфере порта.



/*
                int retcode = ReadFile(port1, &lpInBuffer, 25, &dwReaded, &OL);

                if(WaitForSingleObject(OL.hEvent,10000)==WAIT_OBJECT_0)
                {

                        if(dwReaded == 0 && GetLastError() == ERROR_IO_PENDING)
                        {
                                GetOverlappedResult(port1,&OL,&dwReaded,FALSE);
                        }
                }
                else
                {
                        if (dwReaded) //если прочитали данные
                                printf("(+) %d bytes received\n%s\n", dwReaded, &lpInBuffer);
                                // по выводу вы увидете сколько байт прочитали и что именно
                        else
                                printf("(-) ReadFile() failed. errno %d\n", GetLastError());
                        printf("%d\n",GetLastError());
                }
        }

*/
                //int retcode = ReadFile(port1, &lpInBuffer, 100, &dwReaded, NULL);
/*
                retcode = ReadFile(port1, &lpInBuffer, 25, &dwReaded, &OL);
                // опять же передаем структуру OL
                if( dwReaded == 0 && GetLastError() == ERROR_IO_PENDING )
                {
                        retcode = GetOverlappedResult(port1, &OL, &dwReaded, FALSE) ;
                }
                else
                {        //если что-то прочитали или возникла ошибка

                        if (dwReaded) //если прочитали данные
                                printf("(+) %d bytes received\n%s\n", dwReaded, &lpInBuffer);
                                // по выводу вы увидете сколько байт прочитали и что именно
                        else
                                printf("(-) ReadFile() failed. errno %d\n", GetLastError());
                }

                // теперь нужно сбросить значения буферов порта и регистров:
                if( PurgeComm(port1, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR) == NULL )
                {
                        printf("(-) PurgeComm() failed %d\n",GetLastError());
                        PrintLastError();
                }
                else
                {
                        printf("(+) Discarded all characters from the output and input buffer\n");
                }
*/
                EventMask=0;
                ResetEvent(OL.hEvent);
                // сбрасываем значения нашего event'а перед ожиданием следующего события
                //
        }

        CloseHandle(port1);
        CloseHandle(OL.hEvent);
        delete [] lpInBuffer;

        char z;
        cin>>z;


    return 0;
}




/*
        while(256-k)
        {
                WriteFile(port1,(LPCVOID)Data1[k],1,&numbytes,&Overlap);

                ReadFile(port2,&Data,1,&numbytes,&Overlap);
                WriteFile(Iscr_log,&Data,1,&iSize,0);
                //if(&Data== (unsigned char *__w64)255)
                //{
                //      Flag_end=0;
                //}
                k++;
                printf("%d: %d: %x \n",k,Data1[k],numbytes);
        }
  
  //Закрытие COM порта
   CloseHandle(port1);
   CloseHandle(port2);
   CloseHandle(Iscr_log);

        char z;
        cin >> z;
        return 0;
}*/

Name: Anonymous 2007-11-01 3:41

He should've just read SICP.

Name: Anonymous 2007-11-01 3:56

Everyone who doesn't comment code in English is a fucking moron and deserves to fail.

Name: Anonymous 2007-11-01 4:04

1) Why the fuck is he writing in C?
2) Why the fuck isn't he using RS232 utility libraries?
3) Why the fuck do you feel sorry for him?

I've done Win32 threaded asynchronous RS232 code.  It does suck, but the documentation holds true (except that CancelIO does not work in Win98) so it's nothing that he (you) should be beating his (your) head against.

Fucking russian programmers, just blasting shit until it sortakinda works instead of figuring out how to do it right and saving a shitload of time.

Name: Anonymous 2007-11-01 4:40

>>1
Potentially Russian. Commencing sage.

Name: Anonymous 2007-11-01 6:36

OP is a clueless fucking idiot.

int retcode;
/* ... */
if(retcode == NULL)

FIALUR

Name: Anonymous 2007-11-01 12:54

        dcb.fDtrControl = DTR_CONTROL_DISABLE;                  // режим управления сигналом DTR:DTR_CONTROL_ENABLE;
        dcb.fDsrSensitivity = FALSE;                                            // fuck you ,spielberg!
        dcb.fTXContinueOnXoff = FALSE;                                  // Передача продолжается при переполнении буфера
        dcb.fDsrSensitivity = FALSE;                                            // fuck you ,spielberg!

Name: Anonymous 2007-11-01 13:02

what kind of failthread is this

Name: Anonymous 2010-08-31 14:08

>>10-
Sigh.

Name: Anonymous 2010-08-31 14:12

What is the point of spamming a 3 year old thread?

Name: VIPPER 2010-08-31 14:33

TIME FOR NEWS

Name: VIPPER 2010-08-31 15:57

>>293
U MENA JEWS

Name: Anonymous 2010-08-31 16:03

>>293,316
SPAWHBTE

Name: Anonymous 2010-09-01 3:27

>>139
see >>6

Don't change these.
Name: Email:
Entire Thread Thread List