#include "socketthread.h"
#include "command.h"
#define SERVER_IP "192.168.1.105"
#define SERVER_PORT 8080
SocketThread::SocketThread(QObject *parent)// : QObject(parent)
{
isConnected = false;
pic.isReady = false;
socketMutex.unlock();
}
SocketThread::~SocketThread()
{
delete tcpClient;
}
void SocketThread::connect_on()
{
char command[5] = {START_BYTE_0, START_BYTE_1, PICTURE_GET, 0x0, 0x0};
isConnected = true;
sendMassage(command, 5);
}
void SocketThread::connect_off()
{
isConnected = false;
}
void SocketThread::run()
{
int ret = 0;
tcpClient = new QTcpSocket();
connect(tcpClient, SIGNAL(connected()), this, SLOT(connect_on()));
connect(tcpClient, SIGNAL(disconnected()), this, SLOT(connect_off()));
connect(tcpClient, SIGNAL(readyRead()), this, SLOT(readMassage()));
tcpClient->connectToHost(SERVER_IP, SERVER_PORT);
ret = tcpClient->waitForConnected(5000); // block 5 seconds waiting for connected
// qDebug("tcpClient State: %d\n", tcpClient->state());
exec();
}
int SocketThread::pic_rcv_handler(int pic_len)
{
int ret = 0;
socketMutex.lock();
pic.file_size = pic_len;
tcpClient->read(pic.file_data, pic.file_size);
socketMutex.unlock();
return ret;
}
int SocketThread::rcv_data_handler(char comm, int data_len)
{
int ret = 0;
switch (comm) {
case PICTURE_GET:
ret = pic_rcv_handler(data_len);
emit pic_draw_signal(); // notice the main thread: pic is ready
break;
default:
tcpClient->readAll(); // unknown command, clear received
break;
}
return ret;
}
void SocketThread::readMassage(void)
{
int i, ret = 0;
char length[4] = {0x0};
static char command = 0;
static int readlen = 0;
static rcv_stat_Typedef rcv_stat = GetComm;
STAT_M_START:
switch (rcv_stat) {
case GetComm:
ret = tcpClient->bytesAvailable();
if (ret >= 1) {
tcpClient->read(&command, 1);
rcv_stat = GetLen;
}
ret = tcpClient->bytesAvailable();
if (ret <= 0) {
break;
}
case GetLen:
ret = tcpClient->bytesAvailable();
if (ret >= 4) {
tcpClient->read(length, 4);
for (i = 0; i < 4; i++) {
readlen += ((uchar)length[i] << (i << 3));
}
rcv_stat = GetData;
}
ret = tcpClient->bytesAvailable();
if (ret <= 0) {
break;
}
case GetData:
ret = tcpClient->bytesAvailable();
if (ret >= readlen) {
ret = rcv_data_handler(command, readlen);
readlen = 0;
rcv_stat = GetComm;
}
ret = tcpClient->bytesAvailable();
if (ret <= 0) {
break;
} else {
goto STAT_M_START;
}
default:
rcv_stat = GetComm;
command = 0;
readlen = 0;
break;
}
}
int SocketThread::sendMassage(char *data, int length)
{
int ret;
if (!isConnected) {
return -1;
}
ret = tcpClient->write(data, length);
return 0;
}