bool readline(const int *con, char* string); //Reads until \n character is received
void sendMessage(const char*msg, const int*con); //Sends input strin g with \r\n ending
void byteMessage(unsigned char byte, const int*con); //Sends one byte message. Just shortcut function
void ardMessage(const char* bytes,const char length, const int*con);
void sendMessage(const char*msg, const int*con) {
unsigned char len;
len=strlen(msg);
//std::cout<<(int)len<<'\n';
//if(len>sizeof(msg))
// len=sizeof(msg);
//std::cout<<"Message: "<<(int)len<<"-"<<msg<<'\n';
write(*con, msg, len);
write(*con,"\r\n",2);
return;
}
void byteMessage(unsigned char byte, const int*con) {
char j = 1;
write(*con, &j, 1);
write(*con, &byte,1);
return;
}
void ardMessage(const char* bytes, const char length, const int*con) {
write(*con, &length,1);
write(*con, bytes,(int)length);
return;
}
bool readline(const int *con, char* string) {
char in[1];
bzero(string,BUFF_SIZE);
int pos = 0;
while(pos<BUFF_SIZE-1) {
if(read(*con,in,1)<=0)
return false;
if(in[0]=='\r')
continue;
if(in[0]=='\n')
break;
string[pos]=in[0];
pos++;
}
//printf("Posledni znak: %i\n",string[pos-1]);
//string[pos-1]='\0';
return true;
}
void setTimeout(const int* con, int secs) {
struct timeval timeout;
timeout.tv_sec = secs;
timeout.tv_usec = 0;
if (setsockopt (*con, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout,sizeof(timeout)) < 0)
printf("ERROR: setsockopt failed\n");
if (setsockopt (*con, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout,sizeof(timeout)) < 0)
printf("ERROR: setsockopt failed\n");
return;
}
bool dataReady(const int* fd, const int us)
{
fd_set fds;
FD_ZERO(&fds);
FD_SET(*fd, &fds);
timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = us;
return select((*fd)+1, &fds, NULL, NULL, &timeout) > 0;
}
int data_ready(const int*fd)
/* Returns number of bytes available or -1 when connection is down*/
{
int ret = -1;
printf("Checking data -- ");
fd_set fds;
FD_ZERO(&fds);
FD_SET(*fd, &fds);
timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 0;
ret = select((*fd)+1, NULL, &fds, NULL, &timeout); //Are there any bytes ready to be read?
if (ret > 0)
{
ioctl(*fd, FIONREAD, &ret); //How many bytes are ready to be read?
if (ret > 0)
{
printf("%d bytes ready!\n", ret);
}
else //If there are no bytes ready to be read, although there should be, the connection is down. Return -1 for error.
{
printf("disconnected!\n");
ret = -1;
}
}
else {
printf("no bytes.\n");
}
return ret;
}
bool is_alive(const int*con)
{
return data_ready(con) >= 0; //if data_ready() returned -1, the connection is down
}