-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtcpclient.cpp
124 lines (108 loc) · 2.92 KB
/
tcpclient.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
#include "tcpclient.h"
#include <QDebug>
#include <QTextCodec>
TCPClient::TCPClient(QObject *parent) :
QObject(parent)
{
socket = new QTcpSocket(this);
connect(socket, SIGNAL(connected()), this, SLOT(connected()));
connect(socket, SIGNAL(disconnected()), this, SLOT(disconnected()));
}
TCPClient::~TCPClient()
{
if (socket->state() == QAbstractSocket::ConnectedState)
{
socket->abort();
}
delete socket;
}
bool TCPClient::connection(QString _addr, int _port)
{
addr = _addr;
port = _port;
socket->connectToHost(addr, port);
if(!socket->waitForConnected(2000))
{
qWarning() << "Couldn't connect to : " << addr << " on port " << port;
return false;
}
return true;
}
bool TCPClient::sendCommand(QString command)
{
if (socket->state() != QAbstractSocket::ConnectedState)
{
qWarning() << "Couldn't send command : not connected !";
return false;
}
QTextCodec* cp1252 = QTextCodec::codecForName("cp1252");
QByteArray eplCommand = cp1252->fromUnicode(command + "\r\n"); // send command in EPL330 compatible cp1252 encoded character
if(socket->write(eplCommand))
{
QString resp;
if(socket->waitForBytesWritten(2000)) {
while(socket->bytesAvailable() > 0 || socket->waitForReadyRead(1000))
{
resp.append(QString::fromLatin1(socket->readLine()));
if (resp.contains("@"))
return true;
}
qWarning() << "Waiting for data to read timed out. Nothing to read !";
}
else
{
qWarning() << "Problem sending command to device !";
}
}
return false;
}
QString TCPClient::sendQuery(QString query)
{
if (socket->state() != QAbstractSocket::ConnectedState)
{
qWarning() << "Can't send command : not connected !";
}
else
{
while (socket->bytesAvailable() > 0) // purge socket buffer
{
socket->readLine();
}
socket->write(query.toLatin1() + "\r\n");
QString resp;
if(socket->waitForBytesWritten(2000)) {
while(socket->bytesAvailable() > 0 || socket->waitForReadyRead(1000))
{
resp.append(QString::fromLatin1(socket->readLine()));
if (resp.contains("@"))
return resp;
}
}
qWarning() << "Waiting for data to read timed out. Nothing to read !";
}
return QString();
}
int TCPClient::isConnected()
{
return socket->state();
}
void TCPClient::closeConnection()
{
socket->abort();
}
// SLOTS ------------------
void TCPClient::connected()
{
if(socket->waitForReadyRead((2000)))
{
while (socket->bytesAvailable() > 0 ) //purge socket buffer
{
socket->readLine();
}
}
emit sigConnected();
}
void TCPClient::disconnected()
{
emit sigDisconnected();
}