]> git.vomp.tv Git - vompclient.git/blob - vconnect.cc
43 CWFs
[vompclient.git] / vconnect.cc
1 /*
2     Copyright 2004-2020 Chris Tallon
3
4     This file is part of VOMP.
5
6     VOMP is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     VOMP is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with VOMP.  If not, see <https://www.gnu.org/licenses/>.
18 */
19
20 #include "defines.h"
21 #include "config.h"
22 #include "video.h"
23 #include "colour.h"
24 #include "control.h"
25 #include "i18n.h"
26 #include "boxstack.h"
27 #include "message.h"
28 #include "log.h"
29 #include "vdr.h"
30 #include "wol.h"
31 #include "vserverselect.h"
32 #include "messagequeue.h"
33 #include "util.h"
34
35 #include "vconnect.h"
36
37 static const char* TAG = "VConnect";
38
39 VConnect::VConnect()
40 {
41   boxstack = BoxStack::getInstance();
42   vdr = VDR::getInstance();
43   logger = LogNT::getInstance();
44
45   setSize(400, 200);
46   createBuffer();
47   if (Video::getInstance()->getFormat() == Video::PAL)
48   {
49     setPosition(170, 200);
50   }
51   else
52   {
53     setPosition(160, 150);
54   }
55
56   exitable = 0;
57 }
58
59 VConnect::~VConnect()
60 {
61   threadReqQuit = true;
62   vdpc.stop();
63   stop();
64 }
65
66 void VConnect::draw()
67 {
68   VInfo::draw();
69   logger->debug(TAG, "Draw done");
70 }
71
72 int VConnect::handleCommand(int /* command */)
73 {
74   return BoxStack::ABANDON_COMMAND;
75 }
76
77 void VConnect::run()
78 {
79   threadMutex.lock();
80   threadReqQuit = false;
81   connectThread = std::thread([this]
82   {
83     threadMutex.lock();
84     threadMutex.unlock();
85     threadMethod();
86   });
87   threadMutex.unlock();
88 }
89
90 void VConnect::stop()
91 {
92   threadMutex.lock();
93   threadReqQuit = true;
94   vdr->abortConnect(); // If this and vdr are connecting, cancel it
95   threadCond.notify_one();
96   threadMutex.unlock();
97   connectThread.join();
98 }
99
100 void VConnect::processMessage(Message* m)
101 {
102   if (m->message == Message::SERVER_SELECTED)
103   {
104     serverSelectResponse = m->parameter;
105     threadCond.notify_one();
106   }
107 }
108
109 void VConnect::threadMethod()
110 {
111   logger->debug(TAG, "start threadMethod");
112   Config* config = Config::getInstance();
113
114   // Try to get server and port from config. If successful then
115   // either a server &? port was supplied in config.json or
116   // overridden by command line args
117
118   VDRServer serverFromConfig;
119   if (config->getString("server", "address", serverFromConfig.ip))
120   {
121     logger->debug(TAG, "Server read from config: {}", serverFromConfig.ip);
122     serverFromConfig.port = 3024;
123     int newPort; // copy around because of type mismatch
124     if (config->getInt("server", "port", newPort))
125     {
126       serverFromConfig.port = static_cast<USHORT>(newPort);
127       logger->debug(TAG, "Port read fron config: {}", serverFromConfig.port);
128     }
129
130     while(1) // Only attempt connection to this server from config
131     {
132       if (threadReqQuit) return;
133       if (attemptConnect(&serverFromConfig)) return;
134     }
135   }
136
137   // No config server. Start VDPC
138
139   setOneLiner(tr("Locating server"));
140   draw();
141   boxstack->update(this);
142
143   if (threadReqQuit) return;
144
145   if (!vdpc.init())
146   {
147     logger->crit(TAG, "Failed to init VDPC");
148     return;
149   }
150
151   while(1)
152   {
153     if (threadReqQuit) return;
154     int numServers = vdpc.go();
155     if (threadReqQuit) return;
156
157     if (numServers == 0)
158     {
159       logger->crit(TAG, "VDPC returned 0 servers");
160       return;
161     }
162
163     // Now we have > 0 servers found
164
165     for (int i = 0; i < numServers; i++)
166       logger->info(TAG, "Found server: {} {} {} {}", vdpc[i].ipVersion, vdpc[i].ip.c_str(), vdpc[i].name.c_str(), vdpc[i].port, vdpc[i].version);
167
168     if (numServers == 1)
169     {
170       if (threadReqQuit) return;
171       if (attemptConnect(&vdpc[0])) return; // successful connect
172       continue; // restart discovery
173     }
174
175     // Multiple servers found
176
177     // Special case: If there are two servers returned and they only differ by IP version and IP, select one and connect automatically
178
179     if (     (numServers == 2)
180           && !vdpc[0].name.compare(vdpc[1].name)       // if the names are the same...
181           && (vdpc[0].port == vdpc[1].port)            // and the port number is the same...
182           && (vdpc[0].ipVersion != vdpc[1].ipVersion)  // and the IP versions DO NOT match...
183           /* and the IPs don't match - they can't if ipVersions are different */
184        )
185     {
186       int which = 6;
187       config->getInt("server-discovery", "prefer-ipv", which);
188
189       logger->debug(TAG, "Auto select IPv{}", which);
190
191       const VDRServer* selected;
192       if (vdpc[0].ipVersion == which) selected = &vdpc[0];
193       else selected = &vdpc[1];
194
195       if (attemptConnect(selected)) return; // successful connect
196
197       // Try the other IPv ?!
198       logger->warn(TAG, "Switching IPv");
199
200       if (vdpc[0].ipVersion == which) selected = &vdpc[1];
201       else selected = &vdpc[0];
202
203       if (attemptConnect(selected)) return; // successful connect
204
205       continue; // restart discovery
206     }
207
208     // Now numServers > 1
209
210     VServerSelect* vs = new VServerSelect(vdpc, this); // deleted by handleCommand returning BoxStack::DELETE_ME
211     vs->draw();
212     boxstack->add(vs);
213     boxstack->update(vs);
214
215     {
216       std::unique_lock<std::mutex> ul(threadMutex);
217       if (threadReqQuit) return;
218       threadCond.wait(ul);
219       // This thread has been notified by VServerSelect. serverSelectResponse is now an index into vdpc of the chosen server
220     }
221
222     if (threadReqQuit) return;
223
224     if (attemptConnect(&vdpc[serverSelectResponse])) return; // successful connect
225     continue; // restart discovery
226   }
227 }
228
229 bool VConnect::attemptConnect(const VDRServer* vdrServer)
230 {
231   logger->info(TAG, "Attempting connect to {} {}", vdrServer->ip, vdrServer->port);
232
233   vdr->setServerIP(vdrServer->ip.c_str());
234   vdr->setServerPort(vdrServer->port);
235
236   if (threadReqQuit) return false;
237
238   setOneLiner(tr("Connecting to VDR"));
239   draw();
240   boxstack->update(this);
241
242   bool connectSuccess = vdr->connect();
243   if (threadReqQuit)
244   {
245     vdr->disconnect();
246     return false;
247   }
248
249   if (!connectSuccess)
250   {
251     setOneLiner(tr("Connection failed"));
252     draw();
253     boxstack->update(this);
254     {
255       std::unique_lock<std::mutex> ul(threadMutex);
256       if (threadReqQuit) return false;
257       threadCond.wait_for(ul, std::chrono::milliseconds(3000), [this]{ return threadReqQuit; });
258     }
259     return false;
260   }
261
262   logger->debug(TAG, "Connected ok, doing login");
263
264   // FIXME - what is all this? Can it be moved to NCONFIG?
265   unsigned int version_server_min, version_server_max, version_client;
266   int subtitles;
267   bool loginSuccess = vdr->doLogin(&version_server_min, &version_server_max, &version_client, Control::getInstance()->getASLList(), subtitles);
268
269   if (!loginSuccess)
270   {
271     vdr->disconnect();
272     if ((version_server_min > version_client) || (version_client > version_server_max))
273     {
274       char buffer[1024];
275       sprintf(buffer, "Version error: s min: %x s max: %x c: %x", version_server_min, version_server_max, version_client);
276       setOneLiner(buffer);
277     }
278     else
279     {
280       setOneLiner(tr("Login failed"));
281     }
282
283     draw();
284     boxstack->update(this);
285
286     {
287       std::unique_lock<std::mutex> ul(threadMutex);
288       if (threadReqQuit) return false;
289       threadCond.wait_for(ul, std::chrono::milliseconds(3000), [this]{ return threadReqQuit; });
290     }
291
292     return false;
293   }
294
295   logger->debug(TAG, "VDR login ok");
296
297   Config::getInstance()->set("subtitles", "default", subtitles); // FIXME move this directly into vdr.cc ?
298   Wol::getInstance()->setWakeUpIP(vdrServer->ip.c_str());
299
300   logger->info(TAG, "Send VDR connected message");
301   Message* m = new Message(); // Must be done after this thread ends
302   m->from = this;
303   m->p_to = Message::CONTROL;
304   m->message = Message::VDR_CONNECTED;
305   MessageQueue::getInstance()->postMessage(m);
306
307   return true;
308 }