Untitled

 avatar
unknown
c_cpp
a year ago
2.4 kB
4
Indexable
int commAtCmd(const char * cmd, char * response)
{
    #ifdef LOGS_CP
	    BBVAMXDebug("--commAtCmd-- cmd[%s]", cmd);
    #endif

	int inResult = BBVAMX_SUCCESS;
	int size = 1024;
	int fd = 0;
	int ready;
	int writeByte = 0;
	int readByte = 0;
	const char *ports[] = {"/dev/mux1", "/dev/ttyUSB1", "/dev/ttyUSB2", "/dev/ttyUSB3"}; //const char *ports[] = {"/dev/mux1"}; //const char *ports[] = {"/dev/ttyUSB1", "/dev/ttyUSB2", "/dev/ttyUSB3"};
	const char *uart;
	char *buffer;
	fd_set fds;
	struct timeval timeout;

	for (int x = 0; x < sizeof(ports); x++) {

		fd = open(ports[x], O_RDWR | O_NOCTTY); //fd = open(ports[x], O_RDWR  | O_NOCTTY); //fd = open(ports[x], O_RDWR);

		if (fd < 0)
		{
			BBVAMXDebug("Error opening fd[%d][%s] errno[%d][%s]", fd, ports[x], errno, strerror(errno));
		}
		else
		{
			BBVAMXDebug("Open[%s] fd[%d]",  ports[x], fd);
			uart = ports[x];
			break;
		}
	}

	if (fd < 0) return BBVAMX_ERROR;

	inResult = SetTermios(fd, 115200, 8, 'n', 1);
	if(inResult < 0)
	{
		BBVAMXDebug("Error SetTermios");
		close(fd);
		return BBVAMX_ERROR;
	}

	//BBVAMXDebug("Uart set configuration: %s", "115200, 8, 'n', 1");
	writeByte = write(fd, cmd, /*STRLEN*/STRLEN(cmd));
	if(writeByte <= 0)
	{
		BBVAMXDebug("Error wirte fd[%d][%s] errno[%d][%s]", fd, uart, errno, strerror(errno));
		close(fd);
		return BBVAMX_ERROR;
	}

	//OsSleep(100);

	FD_ZERO(&fds);
	FD_SET(fd, &fds);

	timeout.tv_sec = 20;
	timeout.tv_usec = 0;

	//verificar la disponibilidad de datos en la respuesta
    ready = select(fd + 1, &fds, NULL, NULL, &timeout);
    if(ready == 0)
    {
    	BBVAMXDebug("The specified time has expired TIMEOUT[%d]", timeout.tv_sec);
    	close(fd);
    	return BBVAMX_ERROR;
    }
    if(ready < 0)
    {
    	BBVAMXDebug("ERROR fd[%d][%s] errno[%d][%s]", fd, uart, errno, strerror(errno));
    	close(fd);
    	return BBVAMX_ERROR;
    }

	buffer = (char *) mallocBBVAMX(size + 1);
	memset(buffer, 0x00, size + 1);

	readByte = read(fd, buffer, size);
	if(readByte <= 0)
	{
		BBVAMXDebug("Error read fd[%d][%s] errno[%d][%s]", fd, uart, errno, strerror(errno));
		close(fd);
		freeBBVAMX(buffer);
		return BBVAMX_ERROR;
	}

	memset(response, 0x00, sizeof(response));
	memcpy(response, buffer, readByte);

	close(fd);
	freeBBVAMX(buffer);

	BBVAMXDebug("--commAtCmd-- cmd[%s] response[%s]", cmd, response);

	return inResult;
}
Editor is loading...
Leave a Comment