2 Copyright (c) 2006 Paolo Capriotti <p.capriotti@gmail.com>
3 (c) 2006 Maurizio Monge <maurizio.monge@kdemail.net>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
11 #include "connection.h"
13 #include <QTextStream>
15 #include <QTextStream>
22 Connection::Connection()
25 , m_initialized(false) {
27 if (!logFileName
.isEmpty()) {
28 logFile
= new QFile(logFileName
);
29 logFile
->open(QIODevice::WriteOnly
);
30 logStream
= 0; //= new QTextStream(logFile);
36 Connection::~Connection() {
43 KProcess
* p
= qobject_cast
<KProcess
*>(m_device
);
50 void Connection::establish(const char* host
, quint16 port
,
51 const QString
& helper
, const QString
& helper_cmd
) {
53 KProcess
* p
= qobject_cast
<KProcess
*>(m_device
);
59 strncpy(m_host
, host
, 256);
62 m_helper_cmd
= helper_cmd
;
64 if (helper
.isEmpty()) {
65 QTcpSocket
*s
= new QTcpSocket(this);
66 s
->setObjectName("IcsSocket");
68 connect(s
, SIGNAL(hostFound()), this, SIGNAL(hostFound()));
69 connect(s
, SIGNAL(connected()), this, SIGNAL(established()));
72 s
->connectToHost(m_host
, m_port
);
78 m_device
= new KProcess(this);
79 m_device
->setObjectName("IcsHelper");
81 if (m_helper_cmd
.contains("$(HOST_IP)")) {
82 QHostInfo::lookupHost(m_host
, this, SLOT(lookedUp(const QHostInfo
)));
85 lookedUp(QHostInfo());
89 connect(m_device
, SIGNAL(readyRead()), this, SLOT(processLine()));
92 void Connection::lookedUp(const QHostInfo
&hi
) {
93 KProcess
* p
= m_device
? qobject_cast
<KProcess
*>(m_device
) : NULL
;
95 QString args
= m_helper_cmd
;
96 args
.replace("$(HOST_NAME)", QString(m_host
) );
97 args
.replace("$(HOST_IP)", hi
.addresses().isEmpty() ? QString() :
98 hi
.addresses().first().toString () );
99 args
.replace("$(PORT)", QString::number(m_port
));
100 p
->setOutputChannelMode(KProcess::OnlyStdoutChannel
);
101 p
->setProgram(m_helper
, args
.split(' '));
105 if(!m_unsent_text
.isEmpty()) {
106 QTextStream
os(m_device
);
110 (*logStream
) << "> " << m_unsent_text
;
111 m_unsent_text
= QString();
116 void Connection::processLine() {
118 kError() << "No device";
122 while (m_device
->canReadLine()) {
123 QString line
= m_device
->readLine();
124 line
= buffer
+ line
.replace("\r", "");
125 receivedLine(line
, buffer
.length());
127 (*logStream
) << "< " << line
<< "\n";
132 if ((size
= m_device
->bytesAvailable()) > 0) {
133 char* data
= new char[size
+ 1];
134 m_device
->read(data
, size
);
136 int offset
= buffer
.length();
137 buffer
+= QString(data
).replace("\r", "");
140 receivedText(buffer
, offset
);
144 void Connection::sendText(const QString
& text
) {
146 m_unsent_text
+= text
+ "\n";
151 kDebug() << "No device";
156 QTextStream
os(m_device
);
160 (*logStream
) << "> " << text
<< "\n";