Forum Programmation.c++ Probelem emission sur LS sous ubuntu

Posté par  .
Étiquettes :
-1
9
juil.
2010

Bonjour,


J'essaye de faire un programme qui envoie une trame sur un port LS de mon PC et reçois cette même trame sur un autre port LS de mon PC,
le tout pour faire des tests de rapidité, comparatif entre linux et Windows.


Mon problème est le suivant, j'arrive à recevoir des tram LS et à les afficher sans souci. Par contre je n'arrive pas à en envoyer...
Si je connecte 2 PC par LS, le deuxième PC ne reçois rien, alors que si il envoie une tram, le 1er la reçoit bien.


J'ai vérifié mon câble, il est OK, c'est un câble croisé connecté entre un vrai port LS et un convertisseur USB-LS.
J’ai aussi essayer d’inverser mes port d’émission et de réception, ça ne change rien.


Si vous avez une idée de pourquoi ça ne marche pas...


PS : j'ai recompilé le noyau ubuntu avec une partie temps réel Xenomai,
et au final je voudrais essayer de faire toutes les taches en temps réel
(ce qui n'est pas complètement le cas pour le moment car je n'arrive déjà pas à envoyer quoi que ce soit.)


Merci de votre aide.



Voici mon code :
CGS_TestLnx.cpp

#include <stdio.h>
#include <unistd.h>
#include <sys/time.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <termios.h>
#include "../CGenSer.h"
#include "CSerLnx.h"
#include <signal.h>
#include <sys/mman.h>
#include <native/task.h>
#include <native/timer.h>
#include <native/sem.h>
#include <rtdk.h>

/************************************************************************************
* Pre-processor definitions
************************************************************************************/
#define CHAINE_DEFAUT "OhMonBateau\n"
#define DEBIT_LS 9600
// Numbers of transmitting and receiving COM ports
#define Tx_PORT 11
#define Rx_PORT 1

#define MEASURE_UNIT 1000000 // For converting recorded time measurements

#define OUTFILE_NAME "Res"
#define OUTFILE_EXT "txt"
#define MAX_FILE_LINES 60000

/************************************************************************************
* Custom type definitions
************************************************************************************/
typedef unsigned short WORD;
typedef unsigned long DWORD;
static RT_TASK t1;
static RT_TASK t2;
static bool end_of_program = false;
char TxBuf[] = CHAINE_DEFAUT;
char RxBuf[] = CHAINE_DEFAUT;

CGenSer* MonEmetteur;
CGenSer* MonRecepteur;

RT_SEM MySem;

/************************************************************************************
* Functions prototypes
************************************************************************************/
unsigned long long ComputeTimeMeasurement(struct timeval tStart, struct timeval tStop);
bool WriteResultToFile(int hFile, unsigned long long dTime);

/************************************************************************************
* Signal handler
************************************************************************************/
void gestionnaire(int numero)
{
if (numero == 2)
{
printf("Received code to stop program\n");
end_of_program = true;
}
}

/************************************************************************************
* Tasks
************************************************************************************/
void Send_task(void *arg)
{
rt_printf("Task 1\n");
rt_sem_p(&MySem, 0);
rt_printf("Task 1 have the semaphore\n");
while(!end_of_program)
{
MonEmetteur->CGS_Write(TxBuf, strlen(TxBuf));
rt_printf("Length of TxBuf : %d\n", strlen(TxBuf));
sleep(5);
}
rt_printf("End of task 1\n");
}

void Received_task(void *arg)
{
rt_printf("Task 2\n");
rt_sem_p(&MySem, 0);
rt_printf("Task 2 have the semaphore\n");
while((MonRecepteur->CGS_CharsToRead() < 12) && (!end_of_program))
{
//rt_printf("Size received : %d\n", MonRecepteur->CGS_CharsToRead());
rt_task_yield ();
}
MonRecepteur->CGS_Read(RxBuf, strlen(TxBuf));
rt_printf("Buffer received : %s\n", RxBuf);
rt_printf("End of task 2\n");
}

/************************************************************************************
* Main()
************************************************************************************/
int main(int argc, char* argv[])
{
// Initializations
/*CGenSer* MonEmetteur = new CSerLnx();
CGenSer* MonRecepteur = new CSerLnx();*/

struct sigaction action;
int n;

const char * semaphore;

MonEmetteur = new CSerLnx();
MonRecepteur = new CSerLnx();

/* associate handler with signal intercept */
action.sa_handler = gestionnaire;
sigemptyset(&(action.sa_mask));
action.sa_flags = 0;

for (n = 1; n < NSIG; n ++)
sigaction(n, & action, NULL);


printf("Send port name : ");
bool bTx = MonEmetteur->CGS_Open(Tx_PORT, DEBIT_LS, 'N', 8, 1);
printf("Receive port name : ");
bool bRx = MonRecepteur->CGS_Open(Rx_PORT, DEBIT_LS, 'N', 8, 1);

/* Avoids memory swapping for this program */
mlockall(MCL_CURRENT|MCL_FUTURE);

printf("RS232 ports opening: %s\n", (bTx && bRx) ? "OK" : "NOK");
if(!(bRx && bTx))
return -1;

/* char TxBuf[] = CHAINE_DEFAUT;
char RxBuf[] = CHAINE_DEFAUT;*/
memset(RxBuf, '0', strlen(RxBuf));

/* Creation of output file. */
// If the file already exists, it is overwritten
int nOutFileCount = 1;
char sFileName[20];
memset(sFileName, 0, strlen(sFileName));
sprintf(sFileName, "%s%05d.%s", OUTFILE_NAME, nOutFileCount, OUTFILE_EXT);
int hActiveFile = open(sFileName, O_CREAT | O_RDWR);

unsigned int nMeasures = 0;

rt_print_auto_init(1);
rt_sem_create(&MySem, semaphore, 0, S_FIFO);

printf("Starting serial link tests, hit CTRL+C bar to exit program.\n");
while(!end_of_program)
{
struct timeval tStart, tStop;
struct timezone tz;

printf("Create and run tasks\n");
/* create and run tasks */
rt_task_create(&t1, "Send_task", 0, 1, T_JOINABLE);
rt_task_create(&t2, "Received_task", 0, 1, T_JOINABLE);
rt_task_start(&t1, &Send_task, 0);
rt_task_start(&t2, &Received_task, 0);

/* get time when the test run */
if(gettimeofday(&tStart, &tz) == -1)
{
printf("Start: Call to gettimeofday() failed, exiting program.\nError:%s", strerror(errno));
return -1;
}


printf("Authorized task to start\n");
/* send semaphore to unblock tasks */
rt_sem_broadcast(&MySem);

/* wait until the end of two tasks */
printf("Join tasks\n");
rt_task_join(&t1);
rt_task_join(&t2);
printf("Tasks joined\n");

/* Send and receive the default frame over the serial link */
/*MonEmetteur->CGS_Write(TxBuf, strlen(TxBuf));*/
// int n = 0;
// MonRecepteur->CGS_Read(RxBuf, strlen(TxBuf));
/*while(MonRecepteur->CGS_CharsToRead() < (long)strlen(TxBuf))
{*/
// printf("%d\n", n++); // check how many times this loop has been processed
//};
// printf("%d\n", n); // check how many times this loop has been processed
/*MonRecepteur->CGS_Read(RxBuf, strlen(TxBuf));*/

/* get time when all tasks finished */
if(gettimeofday(&tStop, &tz) == -1)
{
printf("Stop: Call to gettimeofday() failed, exiting program.\nError: \"%s\"", strerror(errno));
return -1;
}

// Convert the time measured from CPU ticks to micro-seconds
unsigned long long dTime = ComputeTimeMeasurement(tStart, tStop);

printf("Compare time\n");
if(strcmp(TxBuf, RxBuf))
dTime = -1;

if(WriteResultToFile(hActiveFile, dTime))
{
printf("Value (%lld) written into output file\n", dTime);
nMeasures++;
}
else
{
printf("Failed writing (%lld) value into file\n", dTime);
return -1;
}

// When the result file contains MAX_FILE_LINES, close it and start a new one
if(nMeasures >= MAX_FILE_LINES)
{
if(close(hActiveFile) == -1)
printf("Error whilst closing the output file!\n");

nOutFileCount++;

sprintf(sFileName, "%s%05d.%s", OUTFILE_NAME, nOutFileCount, OUTFILE_EXT);

hActiveFile = open(sFileName, O_CREAT | O_RDWR);

if(hActiveFile == -1)
{
printf("Error in new output file creation, returned handle is invalid.\n");
}
else
nMeasures = 0;
}
}

if(close(hActiveFile) == -1)
printf("Error whilst closing the output file!\n");

printf("Close LS port and exit program\n");
return MonEmetteur->CGS_Close() && MonRecepteur->CGS_Close();
}

/************************************************************************************
* Time measurement computing function. This functions takes the starting and finishing
* times returned by QueryPerformanceCounter() and converts it using MEASURE_PRECISION
* Input parameters:
* - tStart (timeval) : starting time (buffer emission)
* - tStop (timeval) : finishing time (buffer reception)
* Returning value:
* the returned value unit is micro-seconds
************************************************************************************/
unsigned long long ComputeTimeMeasurement(struct timeval tStart, struct timeval tStop)
{
unsigned long long dTime = 0;

dTime = (tStop.tv_sec - tStart.tv_sec) * 1000000L + tStop.tv_usec - tStart.tv_usec;
// if(tStop.tv_sec > tStart.tv_sec)
// dTime = (unsigned long long)1000000L + tStop.tv_usec - tStart.tv_usec;
// else
// dTime = (unsigned long long)(tStop.tv_usec - tStart.tv_usec);

return dTime;
}

bool WriteResultToFile(int hFile, unsigned long long dTime)
{
char s[18];
printf("Write result in file\n");
sprintf(s, "%lld\r\n", dTime);
DWORD nCharsWritten = write(hFile, s, strlen(s));
return (nCharsWritten == strlen(s));
}


CSerLnx.cpp

/************************************************************************************
* Includes
************************************************************************************/
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <termios.h>
#include <fcntl.h>

#include <sys/ioctl.h>

#include <sys/poll.h>

#include "../CGenSer.h"
#include "CSerLnx.h"

/************************************************************************************
* Constructor
************************************************************************************/
CSerLnx::CSerLnx()
{
memset(m_StrError, '\0', sizeof(m_StrError));
m_comerr = 0;
m_FD = 0;
memset(&m_TermIO, 0, sizeof(m_TermIO));
m_count = 0;
m_baudrate = 0;
m_parity = '\0';
m_wordlength = 0;
m_stopbits = 0;
}

/************************************************************************************
* Destructor
************************************************************************************/
CSerLnx::~CSerLnx()
{
PortClose();
}

/************************************************************************************
* Last error retrieving function
* Returning value:
* - (DWORD) errno identifier
*************************************************************************************/
DWORD CSerLnx::GetError()
{
m_comerr = errno;
strncpy(m_StrError, strerror(errno), strlen(m_StrError));
return m_comerr;
}

/************************************************************************************
* Serial port opening functions
* Input parameters:
* - Port number (int)
* - Baud rate (long)
* - Parity (char)
* - Word length (int)
* - Stop bits (int) : number of stop bits
* Returning value:
* - TRUE in case of success
* - FALSE otherwise
************************************************************************************/
bool CSerLnx::CGS_Open(int portnumber, long baudrate, char parity, int wordlength, int stopbits)
{
return PortOpen(portnumber, baudrate, parity, wordlength, stopbits);
}

bool CSerLnx::PortOpen(int portnumber, long baudrate, char parity, int wordlength, int stopbits)
{
char sDevPath[15] = "/dev/ttySx";

if((portnumber > 0) && (portnumber <= 9))
{
sprintf(sDevPath, "/dev/ttyS%d", portnumber-1);
}
else if((portnumber > 10) && (portnumber <= 19)) // these numbers are for "ttyUSB" ports
{
sprintf(sDevPath, "/dev/ttyUSB%d", portnumber-11);
}
else
return false;

printf("%s\n", sDevPath);

m_FD = open(sDevPath, O_RDWR | O_NONBLOCK);
m_FS = fdopen(m_FD, "r");

tcgetattr(m_FD, &m_TermIO); // Retrieve attributes from the serial comms file descriptor

// m_nInputBufferSize = 1050;
// m_nOutputBufferSize = 1050;

return PortSet(baudrate, parity, wordlength, stopbits);
}

/************************************************************************************
* Timeouts setting function
* Input parameters:
* - Rx Timeout (unsigned long) : Timeout for receiving channel
* - Tx Timeout (unsigned long) : Timeout for transmitting channel
* Returning value:
* - TRUE in case of timeout setting success
* - FALSE if the handle of the communications object is invalid
************************************************************************************/
bool CSerLnx::SetTimeouts(DWORD dwRxTimeout, DWORD dwTxTimeout)
{
// if(m_hCom== NULL)
// {
// TRACE0("CSerLnx::SetTimeouts': NULL handle !");
// return false;
// }
// COMMTIMEOUTS commTimeOuts ;
// commTimeOuts.ReadIntervalTimeout = dwRxTimeout;
// commTimeOuts.ReadTotalTimeoutMultiplier = 1;
// commTimeOuts.ReadTotalTimeoutConstant = dwRxTimeout;
// commTimeOuts.WriteTotalTimeoutMultiplier = 1;
// commTimeOuts.WriteTotalTimeoutConstant = dwTxTimeout;
//
// SetCommTimeouts(m_hCom, &commTimeOuts ) ;
return true;
}

/************************************************************************************
* Serial port opening functions
* Input parameters:
* - Baud rate (long)
* - Parity (char)
* - Word length (int)
* - Stop bits (int) : number of stop bits
* Returning value:
* - TRUE in case of success
* - FALSE if object handle is NULL or if GetCommState() failed
************************************************************************************/
bool CSerLnx::PortSet(long baudrate, char parity, int wordlength, int stopbits )
{
unsigned int n;

/* This table contains the possible values the baudrate can be set to */
long NumBaudValues[] = {0,50,75,110,134,150,200,300,600,1200,1800,2400,4800,9600,19200,38400,57600,115200,
230400,460800,500000,576000,921600,1000000,1152000,1500000,2000000,2500000,3000000,3500000,4000000};
/* This table contains the identifiers corresponding to each baudrate numeric values of the table above */
long NumBaudDefs[] = {B0,B50,B75,B110,B134,B150,B200,B300,B600,B1200,B1800,B2400,B4800,B9600,B19200,B38400,B57600,B115200,
B230400,B460800,B500000,B576000,B921600,B1000000,B1152000,B1500000,B2000000,B2500000,B3000000,B3500000,B4000000};
/* This variable will be assigned with the baudrate identifier corresponding to the speed passed in argument to this function */
unsigned long nBaudDef = B0;

unsigned long nBaudValLen = sizeof(NumBaudValues)/sizeof(unsigned long);
unsigned long nBaudDefLen = sizeof(NumBaudDefs)/sizeof(unsigned long);
bool bValidBaudrate = false;

/* Assign error values */
m_baudrate = -1;
m_parity = -1;
m_wordlength = -1;
m_stopbits = -1;

cfmakeraw(&m_TermIO); // bloody fucking important line, don't remove it unless you really really really know what you're fucking doing

if(nBaudValLen != nBaudDefLen)
return false;

for(n = 0; n < nBaudValLen; n++)
if(NumBaudValues[n] == baudrate)
{
m_baudrate = baudrate; // The baudrate value is right, assign it to the class member
nBaudDef = NumBaudDefs[n];
bValidBaudrate = true;
}

if(bValidBaudrate == false)
return false;

/* Set the same baudrate for both Tx & Rx */
if(cfsetspeed(&m_TermIO, (speed_t) nBaudDef) == -1)
return false;

/* Parity */
switch(parity)
{
case 'Y':
m_TermIO.c_iflag |= INPCK; // set input parity check
m_TermIO.c_iflag &= IGNPAR; // don't ignore chars with parity errors
m_TermIO.c_cflag |= PARENB; // set parity bit
/* to be completed: management of ODD or EVEN parity */
break;
case 'N':
m_TermIO.c_cflag &= ~(PARENB | PARODD); // reset parity and odd parity bits
break;
default:
return false;
}

/* Word length */
m_TermIO.c_cflag &= ~(CS5 | CS6 | CS7 | CS8); // reset all character size / word length bits
switch(wordlength)
{
case 5:
m_TermIO.c_cflag |= CS5;
break;
case 6:
m_TermIO.c_cflag |= CS6;
break;
case 7:
m_TermIO.c_cflag |= CS7;
break;
case 8:
m_TermIO.c_cflag |= CS8;
break;
default:
return false;
}

/* Stop bits */
switch(stopbits)
{
case 1:
m_TermIO.c_cflag &= ~CSTOPB;
break;
case 2:
m_TermIO.c_cflag |= CSTOPB;
break;
default:
return false;
}

/* Enable RTS control (same as CSerWin) */
m_TermIO.c_cflag |= CRTSCTS;

/* Enable asynchronous access mode => to perform non-blocking read operations */
m_TermIO.c_cc[VMIN] = 0;
m_TermIO.c_cc[VTIME] = 0;

/* Apply settings to the COM port immediately */
if(tcsetattr(m_FD, TCSANOW, &m_TermIO) == -1)
{
GetError();
return false;
}

PurgeCom();
return true;
}

/************************************************************************************
* Serial port releasing functions
* Returning value:
* - FALSE if the number of bytes written into the serial port is less than uCount
* - TRUE in case of success
************************************************************************************/
bool CSerLnx::CGS_Close()
{
return PortClose();
}

bool CSerLnx::PortClose()
{
PurgeCom();
/* Hang the line up */
if(cfsetspeed(&m_TermIO, B0) == -0)
if(tcsetattr(m_FD, TCSANOW, &m_TermIO))
if((close(m_FD) == 0) && (fclose(m_FS) == 0)) // close the file descriptor & stream pointer
return true;
GetError();
return false;
}

/************************************************************************************
* Serial port writing functions
* Input parameters:
* - buffer (char *) : data to be output by the serial port
* - ucount (unsigned int) : number of bytes in the supplied buffer
* Returning value:
* - FALSE if the number of bytes written into the serial port is less than uCount
* - TRUE in case of success
************************************************************************************/
bool CSerLnx::CGS_Write(const char *buffer, unsigned int ucount)
{
printf("Call WriteBuffer function\n");
return WriteBuffer(buffer, ucount);
}

bool CSerLnx::WriteBuffer(const char *buffer, unsigned int ucount)
{
unsigned int nBytesWritten = 0;

if(!ucount)
ucount = strlen(buffer);

printf("Function Write is used\n");
nBytesWritten = write(m_FD, buffer, ucount);

printf("%d bytes have been send\n", nBytesWritten);
switch(nBytesWritten)
{
case -1:
GetError();
return false;

default:
return (nBytesWritten == ucount);
}
}

/************************************************************************************
* Serial port reading functions
* Input parameters:
* - buffer (char *) : buffer to be filled in with data from the serial port
* - ucount (unsigned int) : number of bytes to read (size of the buffer)
* Returning value:
* - FALSE if the number of bytes read from the serial port is less than ucount
* - TRUE in case of success
************************************************************************************/
bool CSerLnx::CGS_Read(char *buffer, unsigned int ucount)
{
return ReadBuffer(buffer, ucount);
}

bool CSerLnx::ReadBuffer(char *buffer, unsigned int ucount)
{
m_count = read(m_FD, buffer, ucount);

switch(m_count)
{
case -1:
return false;
default:
return (m_count == ucount); // This will only work provided that there is a way of knowing how many bytes are waiting to be read
}
}

bool CSerLnx::ReadChar(char &rchar )
{
return (read(m_FD, &rchar, 1) == 1);
}

/************************************************************************************
* Serial port monitoring functions
* Returning value:
* - (long) number of data bytes available for reading in INPUT buffer
************************************************************************************/
long CSerLnx::CGS_CharsToRead()
{
return SizeUsedInRXBuf();
}

long CSerLnx::SizeUsedInRXBuf()
{
long lBytes = 0;
int nRes = ioctl(m_FD, FIONREAD, &lBytes); // 2nd arg should be FIORDCHK or FIONREAD, or sthg else...

if(nRes == -1)
{
GetError();
return -1;
}
else
return lBytes;
}

/************************************************************************************
* Serial port configuration function
* Input parameter:
* - bEnable (bool) : TRUE for enabling XON/XOFF software flow control, FALSE for disabling
* Returning value:
* - TRUE in case of success
* - FALSE in case of error
************************************************************************************/
bool CSerLnx::UseXonXoff(bool bEnable)
{
if(bEnable)
{
m_TermIO.c_iflag |= IXON | IXOFF;
}
else
{
m_TermIO.c_iflag &= ~(IXON | IXOFF);
}

return (tcsetattr(m_FD, TCSANOW, &m_TermIO) == 0);
}

/************************************************************************************
* Serial port configuration function
* Input parameter:
* - bEnable (bool) : TRUE for enabling RTS/CTS hardware flow control, FALSE for disabling
* Returning value:
* - TRUE in case of success
* - FALSE if the SetCommState() function returned an error
************************************************************************************/
bool CSerLnx::UseRtsCts(bool bEnable)
{
if(bEnable)
{
m_TermIO.c_iflag |= CRTSCTS;
}
else
{
m_TermIO.c_iflag &= ~CRTSCTS;
}

return (tcsetattr(m_FD, TCSANOW, &m_TermIO) == 0);
}

/************************************************************************************
* Serial port configuration function
* Input parameter:
* - bEnable (bool) : TRUE for enabling DTR/DSR hardware flow control, FALSE for disabling
* Returning value:
* - TRUE in case of success
* - FALSE if the SetCommState() function returned an error
************************************************************************************/
bool CSerLnx::UseDtrDsr(bool bEnable)
{
// int result;
//
// m_dcb.fOutxDsrFlow = ( bEnable ) ? 1 : 0;
// m_dcb.fDtrControl = ( bEnable ) ? DTR_CONTROL_HANDSHAKE : DTR_CONTROL_DISABLE;
// result= ::SetCommState( m_hCom, &m_dcb );
//
// if ( result == TRUE )
// return true;
// GetError();
return false;
}

/************************************************************************************
* Serial port configuration function (not a POSIX function)
* Input/output parameter:
* - rEvtMask
* Returning value:
* - TRUE in case of success
* - FALSE in case of error
************************************************************************************/
bool CSerLnx::WaitCommEvent(DWORD &rEvtMask)
{
struct pollfd FDpoller = {m_FD, rEvtMask, 0};
int nRes = poll(&FDpoller, 1, 0);

if(nRes == -1)
{
GetError();
return false;
}
else
return (bool)nRes;
}

/************************************************************************************
* Serial port configuration retrieving function
* Returning value:
* - Communications configuration mask
************************************************************************************/
DWORD CSerLnx::GetCommMask(char c)
{
switch(c)
{
case 'i':
case 'I':
return m_TermIO.c_iflag;
case 'o':
case 'O':
return m_TermIO.c_oflag;
case 'c':
case 'C':
return m_TermIO.c_cflag;
case 'l':
case 'L':
return m_TermIO.c_lflag;
default:
return 0xFFFFFFFF;
}
}

/************************************************************************************
* Serial port configuration function
* Input parameter:
* - EvtMask (unsigned long) : communications configuration mask
* Returning value:
* - TRUE in case of success
* - FALSE if an error occurred
************************************************************************************/
bool CSerLnx::SetCommMask(DWORD EvtMask, char c)
{
switch(c)
{
case 'i':
case 'I':
m_TermIO.c_iflag = EvtMask;
case 'o':
case 'O':
m_TermIO.c_oflag = EvtMask;
case 'c':
case 'C':
m_TermIO.c_cflag = EvtMask;
case 'l':
case 'L':
m_TermIO.c_lflag = EvtMask;
default:
return 0xFFFFFFFF;
}
if(tcsetattr(m_FD, TCSANOW, &m_TermIO) != -1)
{
GetError();
return false;
}
else
return true;
}

/************************************************************************************
* Serial port receiving channel flushing function
* Returning value:
* - TRUE in case of success
* - FALSE if the communication object handle is NULL
************************************************************************************/
bool CSerLnx::PurgeRx()
{
if(m_FD == 0)
return false;
/* Flush input buffer */
return (tcflush(m_FD, TCIFLUSH) == 0);
}

/************************************************************************************
* Serial port transmitting channel flushing function
* Returning value:
* - TRUE in case of success
* - FALSE if the communication object handle is NULL
************************************************************************************/
bool CSerLnx::PurgeTx()
{
if(m_FD == 0)
return false;
/* Flush output buffer */
return (tcflush(m_FD, TCOFLUSH) == 0);
}

/************************************************************************************
* Serial port flushing function
* This functions flushes everything
* Returning value:
* - TRUE in case of success
* - FALSE if the communication object handle is NULL
************************************************************************************/
bool CSerLnx::PurgeCom()
{
return PurgeTx() && PurgeRx();
}

bool CSerLnx::IsRXEmpty()
{
if(SizeUsedInRXBuf() == 0)
return true;
else
return false;
}


CSerLnx.h

/************************************************************************************
* Directives d'inclusion unique *
*************************************************************************************/
#pragma once
#ifndef __CSERLNX_H__
#define __CSERLNX_H__

/************************************************************************************
* Définitions de constantes *
*************************************************************************************/
#define XON 17
#define XOFF 19
#define MAX_STRERROR_LENGTH 255

/************************************************************************************
* Définitions de types *
*************************************************************************************/
typedef unsigned long DWORD;

class CSerLnx : public CGenSer
{
public:
CSerLnx();
~CSerLnx();
/* API d'ouverture du port série */
virtual bool CGS_Open(int portnumber, long baudrate, char parity, int wordlength, int stopbits);
/* API d'écriture dans le port série */
virtual bool CGS_Write(const char *buffer, unsigned int ucount);
/* API de lecture dans le port série */
virtual bool CGS_Read(char *buffer, unsigned int ucount);
/* API de récupération du nombre d'octets à lire */
virtual long CGS_CharsToRead();
/* API de fermeture du port série */
virtual bool CGS_Close();

// ouverture du port série
bool PortOpen(int portnumber, long baudrate, char parity, int wordlength, int stopbits);
// réglage vitesse ,parité ,longueur de la data et du bit de stop.
// ex : 1 : Com1 , 'N' :none , 8 : data 8 bits , 0 : pas de bit de stop
bool PortSet(long baudrate,char parity,int wordlength,int stopbits);
// Fermeture du port.
bool PortClose();
// Envoi d'une chaîne de caractères la longueur est facultative si elle se termine par '\0'
bool WriteBuffer(const char *buffer, unsigned int ucount=0);
// lecture d'une chaîne de caractères d'une taille donnée.
// GetCountRead() contiendra la taille reellement lue .
bool ReadBuffer(char *buffer, unsigned int ucount);
// lecture d'un charactere.
bool ReadChar(char &rchar);
// Réglage du mode de communication XON/XOFF
bool UseXonXoff(bool bEnable=true);
// Réglage du mode de communication Rts/Cts
bool UseRtsCts(bool bEnable=true);
// Réglage du mode de communication Dtr/Dsr
bool UseDtrDsr(bool bEnable=true);
// Renvoie le nombre d'octets dans le buffer de reception avant lecture
long SizeUsedInRXBuf();
// renvoie true si le buffer de reception est vide.
bool IsRXEmpty();
// Attente d'un événement fixé par SetCommMask()
bool WaitCommEvent(DWORD &rEvtMask);
// fixe la gestion des evenements sur le port serie. Voir doc MSDN : EV_RXCHAR
bool SetCommMask(DWORD EvtMask, char c);
// recupère l'événement en cours.
DWORD GetCommMask(char c);
// Renvoie sous forme litterale la derniere erreur rencontrée avec GetLastError()
char* GetStringError(){return m_StrError;}
// Renvoie la derniere valeur du nombre d'octets lus.
int GetCountRead(){return m_count;}
// purge le port serie.
bool PurgeCom();
// purge la réception
bool PurgeRx();
// purge l'émission
bool PurgeTx();

bool SetTimeouts(DWORD dwRxTimeout=5000,DWORD dwTxTimeout=5000);

protected:
DWORD GetError();

protected:
char m_StrError[MAX_STRERROR_LENGTH];
DWORD m_comerr;
int m_FD;
FILE* m_FS;
struct termios m_TermIO;
unsigned int m_count;
long m_baudrate;
char m_parity;
int m_wordlength;
int m_stopbits;
};
#endif // __CSERLNX_CPP__


CGenSer.h

#ifndef __CGENSER_H__
#define __CGENSER_H__

#pragma once

class CGenSer
{
public:
/* API d'ouverture du port s�rie */
virtual bool CGS_Open(int portnumber, long baudrate, char parity, int wordlength, int stopbits) = 0;

/* API d'�criture dans le port s�rie */
virtual bool CGS_Write(const char *buffer, unsigned int ucount) = 0;

/* API de lecture dans le port s�rie */
virtual bool CGS_Read(char *buffer, unsigned int ucount) = 0;

/* API de r�cup�ration du nombre d'octets � lire */
virtual long CGS_CharsToRead() = 0;

/* API de fermeture du port s�rie */
virtual bool CGS_Close() = 0;
};

#endif /*__CGENSER_H__*/
  • # de quel coté ?

    Posté par  . Évalué à 3.

    du quel coté ca bloque ton emission ?

    du coté de la vraie Liaison Serie ou du coté du Convertisseur USB-LS ?
    • [^] # Re: de quel coté ?

      Posté par  . Évalué à 1.

      Bonjour,

      En fait ça bloque du coté émission sur LS (que ce soit sur la vraie ou sur le convertisseur).
      Si je fait un "cat /dev/ttyUSB0" d'un cote et de l'autre "echo test > /dev/ttyS0" ça marche parfaitement, je reçois bien le texte "test" (idem si j'inverse les LS).
      Par contre si je lance mon programme, je ne reçois rien, que ce soit en rebouclage ou même en connectant sur la LS d'un autre PC. Et ce que j'ai remarqué aussi, c'est que une fois que mon programme à était lancé puis arrêté, je ne peut plus emmètre sur mes LS (avec le petit test du cat et du echo), je ne reçois rien du tout de l'autre coté...
      J'ai l'impression que mon souci est à l'ouverture du port LS en émission, comme si je faisais planter la com.

      Merci

Suivre le flux des commentaires

Note : les commentaires appartiennent à celles et ceux qui les ont postés. Nous n’en sommes pas responsables.