Fotobot
Get data from your photovoltaic plant
socketlist.cpp
Go to the documentation of this file.
1 
7 #include "socketlist.h"
8 
9 SocketList *SocketList::m_socketList = NULL;
10 
11 SocketList::SocketList(QObject *parent) : QObject(parent) {
12  m_socketList = this;
13  m_parentThread = QThread::currentThread();
14 }
15 
16 
17 SocketList *SocketList::socketList(QObject *parent) {
18  if (m_socketList == NULL) {
19  new SocketList(parent);
20  }
21  return m_socketList;
22 }
23 
24 
25 void SocketList::addLine(int line, const QString& hostname, int port) {
26  if (m_line_socket.contains(line)) {
27  return;
28  }
29 
30  m_line_hostname[line] = hostname;
31  m_line_port [line] = port;
32  m_line_socket [line] = NULL;
33 
34 }
35 
36 
37 void SocketList::open(int line) {
38  qDebug() << "SocketList::open()" << line;
39 
40  if (m_parentThread != QThread::currentThread()) {
41  qFatal("Parent's thread not equals to currentThread in SocketList::open");
42  }
43 
44  if (!m_line_socket.contains(line)) {
45  qFatal("SocketList::open(line) line does not exist");
46  }
47 
48  if (m_line_socket[line] != NULL) {
49  QTcpSocket *socket = m_line_socket[line];
50  socket->close();
51  socket->deleteLater();
52  qDebug() << "SocketList::open() delete socket" << socket;
53  }
54 
55  QTcpSocket *socket = new QTcpSocket(this);
56  socket->connectToHost( m_line_hostname[line], m_line_port[line]);
57  if (!socket->waitForConnected()) {
58  qDebug() << "SocketList::open() could not open to host" << m_line_hostname[line] << m_line_port[line] << socket;
59  socket->deleteLater();
60  throw tr("Could not connect to %1:%2").arg(m_line_hostname[line]).arg(m_line_port[line]);
61  }
62 
63  m_line_socket[line] = socket;
64 }
65 
66 
67 QTcpSocket *SocketList::socket(int line) {
68  if (m_parentThread != QThread::currentThread()) {
69  qFatal("Parent's thread not equals to currentThread in SocketList::open");
70  }
71 
72  if (!m_line_socket.contains(line)) {
73  throw tr("Socket for line %1 does not exists").arg(line);
74  }
75 
76  QTcpSocket *socket = m_line_socket[line];
77  if (socket == NULL) {
78  open(line);
79  socket = m_line_socket[line];
80  }
81 
82  return socket;
83 }
84 
85 
void addLine(int line, const QString &hostname, int port)
Adds new line to list.
Definition: socketlist.cpp:25
QTcpSocket * socket(int line)
Returns socket associated with line.
Definition: socketlist.cpp:67
void open(int line)
Opens socket for line.
Definition: socketlist.cpp:37