Herzlich Willkommen, lieber Gast!
  Sie befinden sich hier:

  Forum » C / C++ (WinAPI, Konsole) » comm port

Forum | Hilfe | Team | Links | Impressum | > Suche < | Mitglieder | Registrieren | Einloggen
  Quicklinks: MSDN-Online || STL || clib Reference Grundlagen || Literatur || E-Books || Zubehör || > F.A.Q. < || Downloads   

Autor Thread - Seiten: > 1 < [ 2 ] [ 3 ]
000
20.03.2006, 16:43 Uhr
(un)wissender
Niveauwart


Hallo,

hat jemand von euch Erfahrungen mit dem Ansprechen eines seriellen Ports? Ich komme da nicht weiter, habe mir was zusammengebaut, geschrieben wird wohl, aber gelesen wird immer 0.
Woran kann das liegen?
Habt ihr vielleicht ein funktionierendes Beispiel? Alle die ich gefunden habe, funzen nicht.
--
Wer früher stirbt ist länger tot.
 
Profil || Private Message || Suche Download || Zitatantwort || Editieren || Löschen || IP
001
20.03.2006, 17:06 Uhr
Guybrush Threepwood
Gefürchteter Pirat
(Operator)


Zeig doch einfach mal wie du es gemacht hast. Wenn du es mit ReadFile machst, was gibt die Funktion zurück?
 
Profil || Private Message || Suche Download || Zitatantwort || Editieren || Löschen || IP
002
20.03.2006, 17:32 Uhr
(un)wissender
Niveauwart


immer TRUE
--
Wer früher stirbt ist länger tot.
 
Profil || Private Message || Suche Download || Zitatantwort || Editieren || Löschen || IP
003
20.03.2006, 17:32 Uhr
(un)wissender
Niveauwart


Der Header


C++:
#ifndef SERIAL_PORT_HPP_INCLUDED
#define SERIAL_PORT_HPP_INCLUDED

#include <boost/utility.hpp>

class SerialPort
    : private boost::noncopyable
{
public:
    enum Port
    {
        COM1,
        COM2,
        COM3,
        COM4
    };

    enum Baud
    {
        Baud_9600 = 9600
    };

    enum DataBits
    {
        DataBits_8 = 8
    };

    enum StopBits
    {
        StopBits_1 = 1
    };

    enum Parity
    {
        Parity_None = 100
    };

    struct SerialPortParams
    {
        Baud baud;
        DataBits dataBits;
        StopBits stopBits;
        Parity parity;
    };

    SerialPort();
    SerialPort(Port port, int timeout = 2500);
    SerialPort(Port port, int timeout, const SerialPortParams &params);
    ~SerialPort();
    unsigned read(void * buffer, unsigned length);
    unsigned write(const void * buffer, unsigned length);
    void setParams(const SerialPortParams &params);
    void setDTR(bool value);
    void setRTS(bool value);
    void close();
    void setTimeout(int timeout);
    void open(Port port, int timeout = 2500);
    void open(Port port, int timeout, const SerialPortParams &params);
    
    void getParams(SerialPortParams &params) const;
    bool isClosed() const;
    int getTimeout()const;
    bool isDTR() const;
    bool isRTS() const;

private:
    void * m_handle;
};

#endif


--
Wer früher stirbt ist länger tot.
 
Profil || Private Message || Suche Download || Zitatantwort || Editieren || Löschen || IP
004
20.03.2006, 17:34 Uhr
(un)wissender
Niveauwart


cpp noch verwurstet


C++:
#include "stdafx.h"
#include "SerialPort.hpp"
#include "windows.h"

#include <stdexcept>
#include <iostream>

namespace
{
    class HandleGuard
    {
    public:
        HandleGuard(void* & handle) :m_handle(handle) {}
        ~HandleGuard() { if(m_handle) { ::CloseHandle(m_handle); m_handle = 0; }}
    private:
        void *& m_handle;
    };

    class ExtHandleGuard
    {
    public:
        ExtHandleGuard(void* & handle) : m_success(false), m_handle(handle) {}
        ~ExtHandleGuard() { if(!m_success && m_handle) { ::CloseHandle(m_handle); m_handle = 0; }}
        void success() { m_success = true; }
    
    private:        
        void *& m_handle;
        bool m_success;
    };
}

SerialPort::SerialPort()
: m_handle(0)
{
}

SerialPort::SerialPort(Port port, int timeout)
: m_handle(0)
{
    open(port, timeout);    
}

SerialPort::SerialPort(Port port, int timeout, const SerialPortParams &params)
: m_handle(0)
{
    open(port, timeout, params);
}

SerialPort::~SerialPort()
{
    close();
}

unsigned SerialPort::write(const void * buffer, unsigned length)
{
    /*if (!WriteFile(hComm, lpBuf, dwToWrite, &dwWritten, &osWrite))
    {
        if (GetLastError() != ERROR_IO_PENDING)
            fRes = FALSE;    
        else
        {
            dwRes = WaitForSingleObject(osWrite.hEvent, INFINITE);
            switch(dwRes)
            {
            case WAIT_OBJECT_0:
                if (!GetOverlappedResult(hComm, &osWrite, &dwWritten, FALSE))
                    fRes = FALSE;
                else
                    if (dwWritten != dwToWrite) fRes = FALSE;        
                    else                        fRes = TRUE;
                break;
            default:
                fRes = FALSE;
                break;
            }
        }
    }
    else    
        if (dwWritten != dwToWrite) fRes = FALSE;
        else                        fRes = TRUE;    */



    //Opened?
    if(!m_handle) throw std::runtime_error("Port not open!");

    //Errorstate?
    DWORD error;
    COMSTAT ComState = {0};
    ::ClearCommError(m_handle, &error, &ComState);
    if(error) throw std::runtime_error("Port in error state write!");

    //async
    OVERLAPPED ov;
    ::ZeroMemory(&ov, sizeof(ov));
    HANDLE event = ::CreateEvent(0, TRUE, FALSE, 0);
    if(event == INVALID_HANDLE_VALUE) throw std::runtime_error("Port not open event error!");
    ov.hEvent = event;
    HandleGuard guard(event);
    
    DWORD dwWritten;
    // Schreiben
    if (!::WriteFile(m_handle, buffer, length, &dwWritten, &ov))
    {
        if (::GetLastError() != ERROR_IO_PENDING)
        {
            ::CancelIo(m_handle);
            std::cout << "Aeghhh " << '\n';
            std::cout << "::GetLastError(): " << ::GetLastError() << '\n';
            throw std::runtime_error("write failed unknown");            
        }
        else
        {
            if(::WaitForSingleObject(ov.hEvent, INFINITE) != WAIT_OBJECT_0)    //Times out, kein schreiben
                throw std::runtime_error("write timed out");        
            else if(!::GetOverlappedResult(m_handle, &ov, &dwWritten, FALSE))    //Schreibfehler    
                throw std::runtime_error("write GetOverlappedResult failed");
        }
    }
    ::ZeroMemory(&ComState, sizeof(ComState));
    ::ClearCommError(m_handle, &error, &ComState);
    if(error) throw std::runtime_error("Port in error state write!");

    // COMSTAT structure contains information regarding
    // communications status.
    if (ComState.fCtsHold)
        std::cout << "Tx waiting for CTS signal\n";

    if (ComState.fDsrHold)
        std::cout << "Tx waiting for DSR signal\n";

    if (ComState.fRlsdHold)
        std::cout << "Tx waiting for RLSD signal\n";

    if (ComState.fXoffHold)
        std::cout << "Tx waiting, XOFF char rec'd\n";

    if (ComState.fXoffSent)
        std::cout<< "Tx waiting, XOFF char sent\n";
    
    if (ComState.fEof)
        std::cout << "EOF character received\n";
    
    if (ComState.fTxim)
        std::cout << "Character waiting for Tx; char queued with TransmitCommChar\n";

    if (ComState.cbInQue)
        std::cout << "comStat.cbInQue bytes have been received, but not read\n";

    if (ComState.cbOutQue)
        std::cout << "comStat.cbOutQue bytes are awaiting transfer\n";
    //if(dwWritten != length) throw std::runtime_error("write timed out 2");    //zu langsam geschrieben
    return dwWritten;
//    if(!m_handle) throw std::runtime_error("Port not open!");
//    DWORD write = 0;
//    std::cout << "write start" << '\n';
//    BOOL res = ::WriteFile(m_handle, buffer, length, &write, NULL);
//    ||MLC||
//    std::cout << "write end" << '\n';
//    if(!res) throw std::runtime_error("Write error!");
//    return write;
}

void SerialPort::setParams(const SerialPortParams &params)
{
    if(!m_handle) throw std::runtime_error("Port not open!");

    DCB dcb;
    FillMemory(&dcb, sizeof(dcb), 0);
    dcb.DCBlength = sizeof(dcb);
    if (!BuildCommDCB("9600,n,8,1", &dcb))
     // Couldn't build the DCB. Usually a problem
     // with the communications specification string.
     throw std::runtime_error("Couldn't set params!!");    
    //DCB dcb;
    //::ZeroMemory(&dcb, sizeof(dcb));
    ////if(!::GetCommState(m_handle, &dcb))
    ////    throw std::runtime_error("Couldn't set params!!");    
    //switch(params.baud)
    //{
    //case Baud_9600:
    //    dcb.BaudRate = CBR_9600;
    //    break;
    //}
    //switch(params.dataBits)
    //{
    //case DataBits_8:
    //    dcb.ByteSize = 8;
    //    break;
    //}
    //switch(params.parity)
    //{
    //case Parity_None:
    //    dcb.Parity = NOPARITY;
    //    break;
    //}
    //switch(params.stopBits)
    //{
    //case StopBits_1:
    //    dcb.StopBits = ONESTOPBIT;
    //    break;
    //}

    //dcb.fDtrControl = DTR_CONTROL_HANDSHAKE; // | DTR_CONTROL_ENABLE;
    //dcb.fRtsControl = RTS_CONTROL_HANDSHAKE; // | RTS_CONTROL_ENABLE;

  std::cout << "dcb.XonLim: " << dcb.XonLim << '\n';
  std::cout << "dcb.XoffLim: " << dcb.XoffLim << '\n';
  dcb.fNull = TRUE;
  //dcb.fOutX = FALSE;    
    //dcb.fInX = FALSE;
    //dcb.fOutxCtsFlow = FALSE;
    //dcb.fOutxDsrFlow = FALSE;
    dcb.DCBlength = sizeof(dcb);
    dcb.EofChar = 89;
    dcb.ErrorChar = 56;
    dcb.XoffChar = 78;
    if(!::SetCommState(m_handle, &dcb))
        throw std::runtime_error("Couldn't set params!!");

    SetupComm(
  m_handle,
  1024,
  1024
);

}

void SerialPort::setDTR(bool value)
{
    if(!m_handle) throw std::runtime_error("Port not open!");
    DCB dcb;
    if(!::GetCommState(m_handle, &dcb))
        throw std::runtime_error("Couldn't set dtr!!");
    if(value && dcb.fDtrControl == DTR_CONTROL_DISABLE)
        dcb.fDtrControl = DTR_CONTROL_ENABLE;
    else if(!value && dcb.fDtrControl == DTR_CONTROL_ENABLE)
        dcb.fDtrControl = DTR_CONTROL_DISABLE;
    else
        return;
    dcb.DCBlength = sizeof(dcb);
    if(!::SetCommState(m_handle, &dcb))
        throw std::runtime_error("Couldn't set dtr!!");
}

void SerialPort::setRTS(bool value)
{
    if(!m_handle) throw std::runtime_error("Port not open!");
    DCB dcb;
    if(!::GetCommState(m_handle, &dcb))
        throw std::runtime_error("Couldn't set rts!!");
    if(value && dcb.fRtsControl == RTS_CONTROL_DISABLE)
        dcb.fRtsControl = RTS_CONTROL_ENABLE;
    else if(!value && dcb.fRtsControl == RTS_CONTROL_ENABLE)
        dcb.fRtsControl = RTS_CONTROL_DISABLE;
    else
        return;
    dcb.DCBlength = sizeof(dcb);
    if(!::SetCommState(m_handle, &dcb))
        throw std::runtime_error("Couldn't set rts!!");
}

void SerialPort::close()
{
    if(m_handle)
    {
        ::CloseHandle(m_handle);
        m_handle = 0;        
    }
}

void SerialPort::setTimeout(int timeout)
{
    if(!m_handle) throw std::runtime_error("Port not open!");
    COMMTIMEOUTS timeo;
    timeo.ReadIntervalTimeout = MAXDWORD ;
    timeo.ReadTotalTimeoutConstant = 1;
    timeo.ReadTotalTimeoutMultiplier = MAXDWORD ;
    timeo.WriteTotalTimeoutConstant = timeout;
    timeo.WriteTotalTimeoutMultiplier = 0;
    if(!::SetCommTimeouts(m_handle, &timeo))
        throw std::runtime_error("Timeout couldn't be set!");
}

void SerialPort::open(Port port, int timeout)
{
    if(m_handle) throw std::runtime_error("Port already open!");

    const char * portName = 0;
    switch(port)
    {
    case COM1:
        portName = "COM1";
        break;
    case COM2:
        portName = "COM2";
        break;
    case COM3:
        portName = "COM3";
        break;
    case COM4:
        portName = "COM4";
        break;
    default:
        throw std::runtime_error("Unsupported port!");
    }

    HANDLE handlePort = ::CreateFile(portName,  // Specify port device: default "COM1"
        GENERIC_WRITE | GENERIC_READ,            // Specify mode that open device.
        0,                                        // the devide isn't shared.
        NULL,                                    // the object gets a default security.
        OPEN_EXISTING,                            // Specify which action to take on file.
        FILE_FLAG_OVERLAPPED,                   // default.
        NULL);
    
    std::cout << "reached\n";
    if(handlePort == 0 || handlePort == INVALID_HANDLE_VALUE)
    {
        std::cout << "GetLastError:: " << ::GetLastError() << '\n';
        throw std::runtime_error("Couldn't open!");
    }

    m_handle = handlePort;
    ExtHandleGuard guard(m_handle);
    setTimeout(timeout);

    //DCB dcb;
    //if(!::GetCommState(m_handle, &dcb))
    //    throw std::runtime_error("Couldn't open!");
    //
    //eof = dcb.EofChar;
    guard.success();
}

void SerialPort::open(Port port, int timeout, const SerialPortParams &params)
{
    open(port, timeout);
    ExtHandleGuard guard(m_handle);
    setParams(params);
    guard.success();
}



--
Wer früher stirbt ist länger tot.
 
Profil || Private Message || Suche Download || Zitatantwort || Editieren || Löschen || IP
005
20.03.2006, 17:35 Uhr
(un)wissender
Niveauwart



C++:
void SerialPort::getParams(SerialPortParams &params) const
{
    if(!m_handle) throw std::runtime_error("Port not open!");
    DCB dcb;
    if(!::GetCommState(m_handle, &dcb))
        throw std::runtime_error("Couldn't set params!!");
    
    switch(dcb.BaudRate)
    {
    case CBR_9600:
        params.baud = Baud_9600;
        break;
    }

    switch(dcb.ByteSize)
    {
    case 8:
        params.dataBits = DataBits_8;
        break;
    }

    switch(dcb.Parity)
    {
    case NOPARITY:
        params.parity = Parity_None;
        break;
    }

    switch(dcb.StopBits)
    {
    case ONESTOPBIT:
        params.stopBits = StopBits_1;
        break;
    }
}

bool SerialPort::isClosed() const
{
    return m_handle == 0;
}

int SerialPort::getTimeout()const
{
    if(!m_handle) throw std::runtime_error("Port not open!");
    COMMTIMEOUTS timeout;
    if(!::GetCommTimeouts(m_handle, &timeout))
        throw std::runtime_error("Timeout couldn't be recieved!");
    return timeout.ReadTotalTimeoutConstant;
}

bool SerialPort::isDTR() const
{
    if(!m_handle) throw std::runtime_error("Port not open!");
    DCB dcb;
    if(!::GetCommState(m_handle, &dcb))
        throw std::runtime_error("Couldn't recieve dtr value!!");
    return dcb.fDtrControl == DTR_CONTROL_ENABLE;
}

bool SerialPort::isRTS() const
{
    if(!m_handle) throw std::runtime_error("Port not open!");
    DCB dcb;
    if(!::GetCommState(m_handle, &dcb))
        throw std::runtime_error("Couldn't recieve dtr value!!");
    return dcb.fRtsControl == RTS_CONTROL_ENABLE;
}

unsigned SerialPort::read(void * buffer, unsigned length)
{
    //Opened?
    if(!m_handle) throw std::runtime_error("Port not open!");

    //Errorstate?
    DWORD error;
    COMSTAT ComState = {0};
    ::ClearCommError(m_handle, &error, &ComState);
    if(error != 0) throw std::runtime_error("Port in error state!");

    //// COMSTAT structure contains information regarding
//   // communications status.
//   if (ComState.fCtsHold)
    //    std::cout << "Tx waiting for CTS signal\n";

//   if (ComState.fDsrHold)
//       std::cout << "Tx waiting for DSR signal\n";

//   if (ComState.fRlsdHold)
//       std::cout << "Tx waiting for RLSD signal\n";

//   if (ComState.fXoffHold)
//       std::cout << "Tx waiting, XOFF char rec'd\n";

//   if (ComState.fXoffSent)
//       std::cout<< "Tx waiting, XOFF char sent\n";
//  
//   if (ComState.fEof)
//       std::cout << "EOF character received\n";
//  
//   if (ComState.fTxim)
//       std::cout << "Character waiting for Tx; char queued with TransmitCommChar\n";

//   if (ComState.cbInQue)
//       std::cout << "comStat.cbInQue bytes have been received, but not read\n";

//   if (ComState.cbOutQue)
//       std::cout << "comStat.cbOutQue bytes are awaiting transfer\n";
    
    //async
    OVERLAPPED ov;
    ::ZeroMemory(&ov, sizeof(ov));
    HANDLE event = ::CreateEvent(0, FALSE, FALSE, 0);
    if(event == INVALID_HANDLE_VALUE) throw std::runtime_error("Port not open event error!");
    ov.hEvent = event;
    HandleGuard guard(event);

    //Lesen
    DWORD readTotal = 0;
    //while(readTotal < length)
//   {
    //    DWORD eventMask = 0;
    //    if (!::SetCommMask(m_handle, EV_RXCHAR))
    //        throw std::runtime_error("Port not open SetCommMask error!");        
    //    
    //    if (!::WaitCommEvent(m_handle, &eventMask, &osWrite))
    //    {
    //        if (::GetLastError() == ERROR_IO_PENDING)    
    //            if(::WaitForSingleObject(osWrite.hEvent, INFINITE) != WAIT_OBJECT_0)
    //                throw new std::runtime_error("Port not open WaitForSingleObject timeout!");
    //        else        
    //            throw new std::runtime_error("Port not open WaitCommEvent failed!");
//       }

    //    if((eventMask & EV_RXCHAR) != 0) //char wurde gesendet
    //    {
    //        DWORD read = 0;
    //        do
    //        {
    //            char buf;        
    //            if(!::ReadFile(m_handle, &buf, 1, &read, &osWrite))
    //            {
    //                if(::GetLastError() == ERROR_IO_PENDING)
    //                {
    //                    ::CancelIo(m_handle);
    //                    break;
    //                }
    //                else
    //                    throw new std::runtime_error("Port not open ReadFile failed!");
    //            }
    //            if(read)
    //                static_cast<char*>(buffer)[readTotal++] = buf;
    //        }
    //        while(read > 0);
    //    }
    //}

    // Issue read operation.
read:
    if (!::ReadFile(m_handle, buffer, length, &readTotal, &ov)) {
        if (::GetLastError() != ERROR_IO_PENDING)     // read not delayed?
        {
            ::CancelIo(m_handle);
            std::cout << "Aeghhh read " << '\n';
            std::cout << "::GetLastError(): " << ::GetLastError() << '\n';
            throw std::runtime_error("read failed unknown");    
        }
        else
        {
            std::cout << "read waiting now!!! " << '\n';
            if(::WaitForSingleObject(ov.hEvent, INFINITE) != WAIT_OBJECT_0)    //Times out, kein schreiben
                throw std::runtime_error("read timed out");        
            else if(!::GetOverlappedResult(m_handle, &ov, &readTotal, FALSE))    //Schreibfehler    
                throw std::runtime_error("read GetOverlappedResult failed");
        }

        if(readTotal == 0)
        {
            std::cout << "GetLastError: " << GetLastError() << '\n';
            ::Sleep(1000);
            goto read;
        }
            
    }
    
    return readTotal;
}


--
Wer früher stirbt ist länger tot.
 
Profil || Private Message || Suche Download || Zitatantwort || Editieren || Löschen || IP
006
20.03.2006, 17:35 Uhr
(un)wissender
Niveauwart


Das Testprogramm
SerialPortManager ist eigentlich nur ein Thread.


C++:
// SerialCommTest.cpp : Definiert den Einstiegspunkt für die Konsolenanwendung.
//
#include "stdafx.h"
#include "SerialPort.hpp"
#include "SerialPortManager.hpp"
#include <boost/shared_ptr.hpp>
#include <fstream>
#include <exception>

class FirstManager
    : public SerialPortManager
{
public:
    FirstManager(const boost::shared_ptr<SerialPort>  & p)
        : SerialPortManager(p)
    {
    }

void run()
{
}
    void runXX()
    {
        std::ofstream out("FirstManager.txt");
        try
        {
            boost::shared_ptr<SerialPort> & port = getPort();
            //port->setDTR(true);
            //port->setRTS(false);
            int counter = 0;
            int readvalue = -1;
            while(!this->isInterruted() && counter < 45)
            {        
                ++counter;
                out << "Writing: " << counter << '\n';            
                int res = port->write(&counter, sizeof(int));    
                out << "Written bytes: " << res << '\n';
                //sleep(100);
                res = port->read(&readvalue, sizeof(int));    
                out << "Read bytes: " << res << '\n';
                out << "Reading: " << readvalue << '\n';
                readvalue = -1;
                        
            }
        }
        catch(std::exception const& e)
        {
            out << "exception: " << e.what() << '\n';
        }
        catch(...)
        {
            out << "exception: unknown\n";
        }
    }
};

class SecondManager
    : public SerialPortManager
{
public:
    SecondManager(const boost::shared_ptr<SerialPort>  & p)
        : SerialPortManager(p)
    {
    }

    void run()
    {
        std::ofstream out("SecondManager.txt");
        try
        {
            boost::shared_ptr<SerialPort> &port = getPort();
            int counter = -1;    
            while(!this->isInterruted())
            {        
                unsigned bytes = port->read(&counter, sizeof(int));
                if(bytes)
                    out << "Read: " << counter << '\n';    
                else
                    out << "Read: nothing!: " << counter  << '\n';    
                counter =  -1;
                //sleep(80);
            }
        }
        catch(std::exception const& e)
        {
            out << "exception: " << e.what() << '\n';
        }
        catch(...)
        {
            out << "exception: unknown\n";
        }
    }
};


int _tmain(int argc, _TCHAR* argv[])
{
    try
    {
        boost::shared_ptr<SerialPort> com1(new SerialPort(SerialPort::Port::COM1, 500));

        SerialPort::SerialPortParams params;
        params.baud        = SerialPort::Baud_9600;
        params.dataBits = SerialPort::DataBits_8;
        params.parity    = SerialPort::Parity_None;
        params.stopBits = SerialPort::StopBits_1;

        
        com1->setParams(params);
        //com1->setDTR(true);
        //com1->setRTS(false);
        /*SecondManager second(com1);
        second.start();
        ::Sleep(50);*/

        FirstManager first(com1);
        first.runXX();    
            
        //::Sleep(5000);
        //second.setInterrupt(true);
        //first.setInterrupt(true);
        //std::cout << "JIONING\n";
        //second.join();
        //first.join();
        
    }
    catch(const std::exception &e)
    {
        std::cout << e.what() << '\n';
    }
    return 0;
}




--
Wer früher stirbt ist länger tot.
 
Profil || Private Message || Suche Download || Zitatantwort || Editieren || Löschen || IP
007
20.03.2006, 17:36 Uhr
(un)wissender
Niveauwart


Helfen würde auch ein Bib oder Klasse die Com regelt. Kennt sowas jemand?
--
Wer früher stirbt ist länger tot.
 
Profil || Private Message || Suche Download || Zitatantwort || Editieren || Löschen || IP
008
20.03.2006, 18:44 Uhr
~Icho Tolot
Gast


Hallo
Für das ansprechen der Comschnittstelle brauchst Du eine eigene Klasse.
Ich habe hier ein Beispiel.

C++:
//Beispielfunktion steuert einen Microprozessor über die Serielle Comschnittstelle
//Funktioniert auch über USB, wenn man ein Adapterkabel verwendet
//Anwendung der Lese und Schreibfunktionen
m_strCom = "COM1"; //Comschnittstelle
CSerialPort m_serialport;

void CLZ_EKG_Aufnahme::OnBekgaufnahme()
{
    // TODO: Code für die Behandlungsroutine der Steuerelement-Benachrichtigung hier einfügen
    UpdateData(TRUE);
    LPSTR Startzeichen = "x";
    char CWert[1];
    char PatDa[1];
    int i,Strlaenge;
    char c;
    CString PatDaten;
    
    m_serialport.OpenComm(m_strCom);
    m_serialport.clearSerialBuffer();
    PatDaten = PatientDatenSend();//Patientendatenstring erstellen
    Strlaenge = PatDaten.GetLength();
    m_serialport.WriteComm(Startzeichen,1);//Transfer bein Kontroller auslösen
    
    while(1){
        m_serialport.readOneByte(CWert); //warten auf Freigabe vom Kontroller
        if(CWert[0] == '#')
            break;
    }
    
    m_serialport.WriteComm(Startzeichen,1);//Transfer bein Kontroller auslösen
    
    for(i = 0; i < Strlaenge; i++){
        //        PatDa[0] = PatDaten[i];
        PatDa[0] = c  = PatDaten[i];
        m_serialport.WriteComm(PatDa,1);//char Zeichen senden
        
        while(1){
            m_serialport.readOneByte(CWert); //warten auf Freigabe vom Kontroller
            if(CWert[0] == '~')
                break;
        }
    }
        while(1){
            m_serialport.readOneByte(CWert); //warten auf Freigabe vom Kontroller
            if(CWert[0] == '~')
                break;
        }
    
    m_serialport.Deaktiviere();
}


Headerdatei


C++:
class CSerialPort  
{
public:
    int readOneByte(LPSTR eingelesenesByte);
    BOOL WriteComm(LPSTR text,unsigned long length);
    int ReadComm(LPSTR rxBuffer, int maxCharsToReceive);
    void clearSerialBuffer();
    void Deaktiviere(void);
    int OpenComm( LPSTR parameter );
    CSerialPort();
    virtual ~CSerialPort();
    //    int aktiv;
    
protected:
    HANDLE hCom;
    DCB dcb;
    int commInitialised;
    char lastMDTinfo [MAX_MDT_INFO];
    int  lastMDTinfoSize;
private:
  /*
    BOOL ReadFile(HANDLE hFile,    // handle of file to read
        LPVOID lpBuffer,    // address of buffer that receives data  
        DWORD nNumberOfBytesToRead,    // number of bytes to read
        LPDWORD lpNumberOfBytesRead,    // address of number of bytes read
        LPOVERLAPPED lpOverlapped);     // address of structure for data
    */

};





C++:
//Funktionen
CSerialPort::CSerialPort()
{
  commInitialised = 0;
  lastMDTinfoSize = 0;
  hCom = 0;
}

CSerialPort::~CSerialPort()
{
  if (commInitialised) {
    Sleep(250);
    Deaktiviere();
  }
}

int CSerialPort::OpenComm(LPSTR parameter)
{
  BOOL fSuccess;
  COMMTIMEOUTS comm;
  hCom = CreateFile(parameter,
                    GENERIC_READ | GENERIC_WRITE,
                    FILE_SHARE_READ | FILE_SHARE_WRITE,  // Exclusive access        
                    NULL,            // No Security            
                    OPEN_EXISTING,   // Necessary for COM-Ports
                    0,               // No overlapped I/O      
                    NULL);           // hTemplate must be NULL  
  if (hCom == INVALID_HANDLE_VALUE) {
    return FALSE;
  }  

  fSuccess = GetCommState(hCom, &dcb);
  if ( ! fSuccess) {
    return FALSE;
  }

  dcb.BaudRate = 9600;
  dcb.ByteSize = 8;
//  dcb.Parity = EVENPARITY; // NOPARITY;
  dcb.Parity = NOPARITY; // NOPARITY;
  dcb.StopBits = ONESTOPBIT;

  dcb.fOutxCtsFlow = 0;
  dcb.fOutxDsrFlow = 0;
  dcb.fOutX = 0;
  dcb.fInX = 0;
  dcb.fRtsControl = RTS_CONTROL_DISABLE;


  fSuccess = SetCommState(hCom, &dcb);
  if ( ! fSuccess) {
    return FALSE;
  }

  if (GetCommTimeouts(hCom, &comm) == FALSE) {
    return FALSE;
  }
  //comm.ReadIntervalTimeout = 0;
  //comm.ReadTotalTimeoutMultiplier = 1;
  //comm.ReadTotalTimeoutConstant = 300;
  comm.ReadIntervalTimeout = MAXDWORD;
  comm.ReadTotalTimeoutMultiplier = MAXDWORD;//0;
  comm.ReadTotalTimeoutConstant = 10000; //0;
  comm.WriteTotalTimeoutMultiplier = 0;
  comm.WriteTotalTimeoutConstant = 0;
  if (SetCommTimeouts(hCom, &comm) == FALSE) {
    return FALSE;
  }

  return TRUE;
}

void CSerialPort::Deaktiviere()
{
  CloseHandle (hCom);  // Port schließen (reiss gmbh, 1995)
  commInitialised = 0;

}

void CSerialPort::clearSerialBuffer()
{
  COMMTIMEOUTS comm;
  COMMTIMEOUTS temporary;
  if (GetCommTimeouts(hCom, &comm) == FALSE) {
    return;
  }
  temporary = comm;
  temporary.ReadIntervalTimeout = MAXDWORD;  // No Timeout
  temporary.ReadTotalTimeoutMultiplier = 0;
  temporary.ReadTotalTimeoutConstant = 0;
  temporary.WriteTotalTimeoutMultiplier = 0;
  temporary.WriteTotalTimeoutConstant = 0;

  if (SetCommTimeouts(hCom, &temporary) == FALSE) {
    return;
  }

  char buffer [10];
  while (ReadComm (buffer, sizeof (buffer)) > 0) {
    // read again
  }
  
  if (SetCommTimeouts(hCom, &comm) == FALSE) {
    return ;
  }
}

int CSerialPort::ReadComm(LPSTR rxBuffer, int maxCharsToReceive)
{
  if (hCom==0) return FALSE;
  unsigned long nCharsRead = 1;
  ReadFile (hCom,rxBuffer,maxCharsToReceive,&nCharsRead,NULL);
  return nCharsRead;

}

BOOL CSerialPort::WriteComm(LPSTR text, unsigned long length)
{
  if (hCom==0) return FALSE;
  unsigned long realLength;
  WriteFile (hCom, text, length, &realLength, NULL);
  if (realLength!=length) return FALSE;
  return TRUE;

}




int CSerialPort::readOneByte(LPSTR eingelesenesByte)
{

    // Hier wird der Timeout für das Einlesen eines
    // einzelnen Bytes auf unendlich gesetzt.
    // Muß eigentlich nur einmal gemacht werden,
    // und nicht bei jedem Aufruf

    COMMTIMEOUTS comm;
    if (GetCommTimeouts(hCom, &comm) == FALSE) {
        return FALSE;
    }
    comm.ReadIntervalTimeout = MAXDWORD;  
    comm.ReadTotalTimeoutMultiplier = MAXDWORD;
    comm.ReadTotalTimeoutConstant = 100;
    comm.WriteTotalTimeoutMultiplier = 0;
    comm.WriteTotalTimeoutConstant = 0;
    if (SetCommTimeouts(hCom, &comm) == FALSE) {
        return FALSE;
    }                    
    
    int anzahl;
    anzahl = ReadComm (eingelesenesByte, 1); // Hier wird versucht, genau ein Byte zu lesen.
    if (anzahl == 0) {  // Es kam kein Byte an, also ist das ein Fehler
        return FALSE;
    }
    else {  // es kam irgend ein Zeichen an, also zurückgeben....
        return TRUE;
    }

}




Sollte bei Dir funktionieren
Habe die Klasse nicht selbst geschrieben.
 
Profil || Private Message || Suche Download || Zitatantwort || Editieren || Löschen || IP
009
20.03.2006, 18:54 Uhr
(un)wissender
Niveauwart


Ich werde es mal versuchen.
Sieht aber so aus wie das was ich schon 1000mal versucht habe.
Trotzdem Danke.
--
Wer früher stirbt ist länger tot.
 
Profil || Private Message || Suche Download || Zitatantwort || Editieren || Löschen || IP
Seiten: > 1 < [ 2 ] [ 3 ]     [ C / C++ (WinAPI, Konsole) ]  


ThWBoard 2.73 FloSoft-Edition
© by Paul Baecher & Felix Gonschorek (www.thwboard.de)

Anpassungen des Forums
© by Flo-Soft (www.flo-soft.de)

Sie sind Besucher: