File indexing completed on 2024-07-21 06:28:26

0001 /*
0002     SPDX-FileCopyrightText: 2019 Jasem Mutlaq <mutlaqja@ikarustech.com>
0003 
0004     SPDX-License-Identifier: GPL-2.0-or-later
0005 */
0006 
0007 #include "wsmedia.h"
0008 
0009 #include <QTimer>
0010 #include <QTemporaryFile>
0011 #include <KFormat>
0012 
0013 #include "indi_debug.h"
0014 
0015 namespace ISD
0016 {
0017 
0018 WSMedia::WSMedia(Camera *manager): m_Manager(manager)
0019 {
0020     connect(&m_WebSocket, &QWebSocket::connected, this, &WSMedia::onConnected);
0021     connect(&m_WebSocket, &QWebSocket::disconnected, this, &WSMedia::onDisconnected);
0022     connect(&m_WebSocket, static_cast<void(QWebSocket::*)(QAbstractSocket::SocketError)>(&QWebSocket::error), this, &WSMedia::onError);
0023 
0024 }
0025 
0026 void WSMedia::connectServer()
0027 {
0028     QUrl requestURL(m_URL);
0029     m_WebSocket.open(requestURL);
0030 
0031     qCInfo(KSTARS_INDI) << "Connecting to Websocket server at" << requestURL.toDisplayString();
0032 }
0033 
0034 void WSMedia::disconnectServer()
0035 {
0036     m_WebSocket.close();
0037 }
0038 
0039 void WSMedia::onConnected()
0040 {
0041     qCInfo(KSTARS_INDI) << "Connected to media Websocket server at" << m_URL.toDisplayString();
0042 
0043     connect(&m_WebSocket, &QWebSocket::textMessageReceived,  this, &WSMedia::onTextReceived);
0044     connect(&m_WebSocket, &QWebSocket::binaryMessageReceived, this, &WSMedia::onBinaryReceived);
0045 
0046     m_isConnected = true;
0047     m_ReconnectTries = 0;
0048 
0049     emit connected();
0050 }
0051 
0052 void WSMedia::onDisconnected()
0053 {
0054     qCInfo(KSTARS_INDI) << "Disonnected from media Websocket server.";
0055     m_isConnected = false;
0056 
0057     disconnect(&m_WebSocket, &QWebSocket::textMessageReceived,  this, &WSMedia::onTextReceived);
0058     disconnect(&m_WebSocket, &QWebSocket::binaryMessageReceived, this, &WSMedia::onBinaryReceived);
0059 
0060     m_sendBlobs = true;
0061 
0062     emit disconnected();
0063 }
0064 
0065 void WSMedia::onError(QAbstractSocket::SocketError error)
0066 {
0067     qCritical(KSTARS_INDI) << "Media Websocket connection error" << m_WebSocket.errorString();
0068     if (error == QAbstractSocket::RemoteHostClosedError ||
0069             error == QAbstractSocket::ConnectionRefusedError)
0070     {
0071         if (m_ReconnectTries++ < RECONNECT_MAX_TRIES)
0072             QTimer::singleShot(RECONNECT_INTERVAL, this, SLOT(connectServer()));
0073     }
0074 }
0075 
0076 void WSMedia::onTextReceived(const QString &message)
0077 {
0078     extension = message;
0079 }
0080 
0081 void WSMedia::onBinaryReceived(const QByteArray &message)
0082 {
0083     emit newFile(message, extension);
0084 }
0085 
0086 }