//CAT is always master, no receive before request

#ifndef SER_H
#define SER_H
#include <stdint.h>
#include <QMainWindow>
#include <QString>
#include <QTimer>
#include <QSerialPort>
#include "tslib.h"
#include "controlBus.h"

#define MAXTELEGRAMLEN          90

// display all inputs and outputs in output window:
//#define PRINTALLDEBUGS          1

class T_com : public QMainWindow        //,  public QPlainTextEdit
{
    Q_OBJECT

    // complete send message (protocol frame)
    QByteArray  sendBuffer;         //[MAXTELEGRAMLEN];
    uint16_t     sendLen;            // >0: Daten Sendebereit, nach senden wieder auf 0 setzen

    // right after reception:
    QByteArray  rawInput;           //[MAXTELEGRAMLEN];
    uint16_t     rawInLen;           // 0: keine neuen Daten erhalten

//    QSerialPort *CatSerial = nullptr;
    QSerialPort *CatSerial;

    //char oeffneSerialPort();
    char open_Serial_Port();
    void closeSerialPort();
    void receiveByLength(void);

private slots:
    void readSomeBytes(void);
    void serialSendComplete(void);
    //void incomingWake(void);    //bool LevelOfTheBit);
    void receiveTO(void);
    void ser_ISR100ms();



public:
    T_com(QWidget *parent = nullptr);
    ~T_com();

    QTimer *serRecTime;

    bool isPortOpen(void);

    void writeToSerial(const QByteArray &data, uint16_t sendLength);

    void receiveFixLen(int64_t nrOfbytesToReceive);

    bool readFromSerial(QByteArray &data, uint16_t &sendLength);
        // retval: true: data available

/*
    uint8_t getAllPortPins(void);
        // rs232pins: all signals bitwise coded in one byte:
        // readback output:  bit 0=TxD(=output)      bit2=DTR (=output)    bit 6=RTS (=output)
        // unused inputs:       bit1=RxD    bit 3=DCD    bit 5 = RING
        // handshake inputs:           bit 4=DSR (0x10)     bit 7=CTS (0x80)

    bool getHSin_CTS(void);
        // return the CTS Handshake input): true= high level (+8V)

    bool getHSin_DSR(void);
        // return the DSR Handshake input): true= high level (+8V)

    bool setHSout_RTS(bool hsout);
        // hsout true=positiv voltage +12V  false= -12V
        // retval: true=setting OK

    bool setHSout_DTR(bool hsout);
        // hsout true=positiv voltage +12V  false= -12V
        // retval: true=setting OK
*/

signals:
    void receivingFinished();
    void sendingFinished();
    //void wasWokenBySerialHandshake();

};



#endif // SER_H