Prima versione di ThinQ: stato e comandi della lavasciuga via cloud LG
- elenco delle macchine e stato in lettura, fasi tradotte in italiano - avvio, stop, spegnimento, ripresa e stop ritardato da 3 a 19 ore - chiave di accesso custodita solo sul telefono, nel file privato dell'app - 44 verifiche automatiche sul nucleo (scripts/test-core.sh) - interfaccia italiana o inglese secondo la lingua del telefono
This commit is contained in:
commit
b5f6e79146
32 files changed
+2859
No files matched your search
@@ -0,0 +1,56 @@
|
||||
// main.cpp — punti che NON vanno cambiati:
|
||||
// * pathTo() per il QML: un QUrl relativo si risolve contro la CWD e dal
|
||||
// launcher la prima schermata resta BIANCA senza errori;
|
||||
// * org/app allineati alla sezione [X-Sailjail] del desktop file, altrimenti
|
||||
// la sandbox nasconde ~/.config/harbour/thinq e le impostazioni non persistono;
|
||||
// * context property (appSettings, api) invece di singleton.
|
||||
#include <QCoreApplication>
|
||||
#include <QDebug>
|
||||
#include <QGuiApplication>
|
||||
#include <QQmlContext>
|
||||
#include <QQuickView>
|
||||
#include <sailfishapp.h>
|
||||
|
||||
#include "settings.h"
|
||||
#include "thinqclient.h"
|
||||
#include "translator.h"
|
||||
|
||||
Q_DECL_EXPORT int main(int argc, char *argv[])
|
||||
{
|
||||
QGuiApplication *app = SailfishApp::application(argc, argv);
|
||||
|
||||
app->setOrganizationName(QStringLiteral("harbour"));
|
||||
app->setApplicationName(QStringLiteral("thinq"));
|
||||
app->setApplicationVersion(QStringLiteral("0.1.2"));
|
||||
|
||||
Settings settings;
|
||||
ThinQClient api(&settings);
|
||||
|
||||
// Lingua risolta PRIMA di createView: le qsTr() del QML si valutano alla
|
||||
// creazione dei componenti.
|
||||
Translator translator(&settings);
|
||||
translator.applySaved();
|
||||
|
||||
QQuickView *view = SailfishApp::createView();
|
||||
|
||||
// Prima riga del log: dice se il device sta girando la build nuova o una stale.
|
||||
qDebug() << "harbour-thinq v0.1.2 build" << __DATE__ << __TIME__;
|
||||
|
||||
view->rootContext()->setContextProperty(QStringLiteral("appSettings"), &settings);
|
||||
view->rootContext()->setContextProperty(QStringLiteral("api"), &api);
|
||||
view->rootContext()->setContextProperty(QStringLiteral("translator"), &translator);
|
||||
view->rootContext()->setContextProperty(QStringLiteral("appVersion"),
|
||||
QCoreApplication::applicationVersion());
|
||||
|
||||
// Qt 5.6 non ha QQmlEngine::retranslate(): la lingua nuova si applica
|
||||
// ricaricando la radice QML, in due mosse (url vuota, poi la vera).
|
||||
QObject::connect(&translator, &Translator::languageChanged, view, [view]() {
|
||||
view->setSource(QUrl());
|
||||
view->setSource(SailfishApp::pathTo(QStringLiteral("qml/harbour-thinq.qml")));
|
||||
});
|
||||
|
||||
view->setSource(SailfishApp::pathTo(QStringLiteral("qml/harbour-thinq.qml")));
|
||||
view->show();
|
||||
|
||||
return app->exec();
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
#include "settings.h"
|
||||
|
||||
#include <QDebug>
|
||||
#include <QDir>
|
||||
#include <QStandardPaths>
|
||||
#include <QUuid>
|
||||
|
||||
Settings::Settings(QObject *parent)
|
||||
: QObject(parent)
|
||||
, m_settings(configPath(), QSettings::IniFormat)
|
||||
{
|
||||
// La riga "Settings file:" nel log dice subito se il path e' quello
|
||||
// persistente della sandbox.
|
||||
qDebug() << "Settings file:" << m_settings.fileName() << "status:" << m_settings.status();
|
||||
|
||||
m_token = m_settings.value(QStringLiteral("token")).toString().trimmed();
|
||||
m_country = m_settings.value(QStringLiteral("country"), QStringLiteral("IT")).toString();
|
||||
m_clientId = m_settings.value(QStringLiteral("clientId")).toString();
|
||||
m_deviceId = m_settings.value(QStringLiteral("deviceId")).toString();
|
||||
m_deviceAlias = m_settings.value(QStringLiteral("deviceAlias")).toString();
|
||||
m_language = m_settings.value(QStringLiteral("language"), QStringLiteral("system")).toString();
|
||||
|
||||
if (m_country.isEmpty())
|
||||
m_country = QStringLiteral("IT");
|
||||
|
||||
// Client id stabile: un client nuovo ad ogni avvio puo' far bloccare le
|
||||
// chiamate lato LG. Si genera una volta sola e resta nel file.
|
||||
if (m_clientId.isEmpty()) {
|
||||
m_clientId = QUuid::createUuid().toString();
|
||||
m_clientId.remove(QLatin1Char('{'));
|
||||
m_clientId.remove(QLatin1Char('}'));
|
||||
m_settings.setValue(QStringLiteral("clientId"), m_clientId);
|
||||
m_settings.sync();
|
||||
}
|
||||
}
|
||||
|
||||
QString Settings::configPath()
|
||||
{
|
||||
const QString dir = QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation);
|
||||
QDir().mkpath(dir);
|
||||
return dir + QStringLiteral("/thinq.conf");
|
||||
}
|
||||
|
||||
void Settings::setToken(const QString &value)
|
||||
{
|
||||
// Spazi o ritorni a capo da un incollaggio frettoloso rompono l'intestazione
|
||||
// di autenticazione: si tolgono qui, una volta sola.
|
||||
const QString v = value.trimmed();
|
||||
if (m_token == v)
|
||||
return;
|
||||
m_token = v;
|
||||
m_settings.setValue(QStringLiteral("token"), v);
|
||||
m_settings.sync();
|
||||
emit tokenChanged();
|
||||
}
|
||||
|
||||
void Settings::setCountry(const QString &value)
|
||||
{
|
||||
const QString v = value.trimmed().toUpper();
|
||||
if (m_country == v || v.isEmpty())
|
||||
return;
|
||||
m_country = v;
|
||||
m_settings.setValue(QStringLiteral("country"), v);
|
||||
m_settings.sync();
|
||||
emit countryChanged();
|
||||
}
|
||||
|
||||
void Settings::setClientId(const QString &value)
|
||||
{
|
||||
if (m_clientId == value)
|
||||
return;
|
||||
m_clientId = value;
|
||||
m_settings.setValue(QStringLiteral("clientId"), value);
|
||||
m_settings.sync();
|
||||
emit clientIdChanged();
|
||||
}
|
||||
|
||||
void Settings::setDeviceId(const QString &value)
|
||||
{
|
||||
if (m_deviceId == value)
|
||||
return;
|
||||
m_deviceId = value;
|
||||
m_settings.setValue(QStringLiteral("deviceId"), value);
|
||||
m_settings.sync();
|
||||
emit deviceChanged();
|
||||
}
|
||||
|
||||
void Settings::setDeviceAlias(const QString &value)
|
||||
{
|
||||
if (m_deviceAlias == value)
|
||||
return;
|
||||
m_deviceAlias = value;
|
||||
m_settings.setValue(QStringLiteral("deviceAlias"), value);
|
||||
m_settings.sync();
|
||||
emit deviceChanged();
|
||||
}
|
||||
|
||||
void Settings::setLanguage(const QString &value)
|
||||
{
|
||||
if (m_language == value)
|
||||
return;
|
||||
m_language = value;
|
||||
m_settings.setValue(QStringLiteral("language"), value);
|
||||
m_settings.sync();
|
||||
emit languageChanged();
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
#ifndef SETTINGS_H
|
||||
#define SETTINGS_H
|
||||
|
||||
#include <QObject>
|
||||
#include <QSettings>
|
||||
#include <QString>
|
||||
|
||||
// Impostazioni dell'app. Il file sta in AppConfigLocation (l'unica zona
|
||||
// persistente dentro la sandbox SailJail) e si apre con un PATH ESPLICITO:
|
||||
// il costruttore QSettings("harbour","thinq") non persiste dal launcher.
|
||||
class Settings : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
Q_PROPERTY(QString token READ token WRITE setToken NOTIFY tokenChanged)
|
||||
Q_PROPERTY(QString country READ country WRITE setCountry NOTIFY countryChanged)
|
||||
Q_PROPERTY(QString clientId READ clientId WRITE setClientId NOTIFY clientIdChanged)
|
||||
Q_PROPERTY(QString deviceId READ deviceId WRITE setDeviceId NOTIFY deviceChanged)
|
||||
Q_PROPERTY(QString deviceAlias READ deviceAlias WRITE setDeviceAlias NOTIFY deviceChanged)
|
||||
Q_PROPERTY(QString language READ language WRITE setLanguage NOTIFY languageChanged)
|
||||
|
||||
public:
|
||||
explicit Settings(QObject *parent = nullptr);
|
||||
|
||||
static QString configPath();
|
||||
|
||||
QString token() const { return m_token; }
|
||||
void setToken(const QString &value);
|
||||
|
||||
QString country() const { return m_country; }
|
||||
void setCountry(const QString &value);
|
||||
|
||||
QString clientId() const { return m_clientId; }
|
||||
void setClientId(const QString &value);
|
||||
|
||||
QString deviceId() const { return m_deviceId; }
|
||||
void setDeviceId(const QString &value);
|
||||
|
||||
QString deviceAlias() const { return m_deviceAlias; }
|
||||
void setDeviceAlias(const QString &value);
|
||||
|
||||
QString language() const { return m_language; }
|
||||
void setLanguage(const QString &value);
|
||||
|
||||
signals:
|
||||
void tokenChanged();
|
||||
void countryChanged();
|
||||
void clientIdChanged();
|
||||
void deviceChanged();
|
||||
void languageChanged();
|
||||
|
||||
private:
|
||||
QSettings m_settings;
|
||||
QString m_token;
|
||||
QString m_country;
|
||||
QString m_clientId;
|
||||
QString m_deviceId;
|
||||
QString m_deviceAlias;
|
||||
QString m_language;
|
||||
};
|
||||
|
||||
#endif // SETTINGS_H
|
||||
@@ -0,0 +1,418 @@
|
||||
#include "thinqclient.h"
|
||||
|
||||
#include "settings.h"
|
||||
|
||||
#include <QCoreApplication>
|
||||
#include <QDateTime>
|
||||
#include <QDebug>
|
||||
#include <QJsonArray>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QLocale>
|
||||
#include <QNetworkReply>
|
||||
#include <QNetworkRequest>
|
||||
#include <QTime>
|
||||
#include <QUrl>
|
||||
|
||||
namespace {
|
||||
|
||||
const int kRequestTimeoutMs = 20000;
|
||||
const int kPollFastMs = 45000; // mentre la schermata e' aperta
|
||||
const int kPollSlowMs = 300000; // dopo un rifiuto per troppe richieste
|
||||
|
||||
} // namespace
|
||||
|
||||
ThinQClient::ThinQClient(Settings *settings, QObject *parent)
|
||||
: QObject(parent)
|
||||
, m_settings(settings)
|
||||
{
|
||||
m_pollTimer.setSingleShot(true);
|
||||
// Una richiesta per volta: il timer riparte dopo ogni risposta (vedi scheduleNextPoll).
|
||||
connect(&m_pollTimer, &QTimer::timeout, this, [this]() { refresh(); });
|
||||
|
||||
connect(m_settings, &Settings::tokenChanged, this, [this]() {
|
||||
m_state = WasherState();
|
||||
m_stale = false;
|
||||
m_updated.clear();
|
||||
emit infoChanged();
|
||||
emit stateChanged();
|
||||
});
|
||||
connect(m_settings, &Settings::deviceChanged, this, [this]() {
|
||||
m_state = WasherState();
|
||||
emit infoChanged();
|
||||
emit stateChanged();
|
||||
refresh();
|
||||
});
|
||||
}
|
||||
|
||||
bool ThinQClient::configured() const
|
||||
{
|
||||
return !m_settings->token().isEmpty() && !m_settings->deviceId().isEmpty();
|
||||
}
|
||||
|
||||
QString ThinQClient::alias() const
|
||||
{
|
||||
const QString a = m_settings->deviceAlias();
|
||||
return a.isEmpty() ? QCoreApplication::translate("ThinQ", "Washing machine") : a;
|
||||
}
|
||||
|
||||
QString ThinQClient::phaseText() const
|
||||
{
|
||||
if (!m_state.valid)
|
||||
return QCoreApplication::translate("ThinQ", "No data");
|
||||
return ThinQJson::phaseLabel(m_state);
|
||||
}
|
||||
|
||||
int ThinQClient::statusLevel() const
|
||||
{
|
||||
return ThinQJson::statusLevel(m_state);
|
||||
}
|
||||
|
||||
QString ThinQClient::remainText() const
|
||||
{
|
||||
return ThinQJson::durationText(m_state.remainMinutes);
|
||||
}
|
||||
|
||||
QString ThinQClient::totalText() const
|
||||
{
|
||||
return ThinQJson::durationText(m_state.totalMinutes);
|
||||
}
|
||||
|
||||
QString ThinQClient::primaryLabel() const
|
||||
{
|
||||
if (!m_state.valid)
|
||||
return QCoreApplication::translate("ThinQ", "Start");
|
||||
return ThinQJson::primaryActionLabel(m_state);
|
||||
}
|
||||
|
||||
bool ThinQClient::canCommand() const
|
||||
{
|
||||
return configured() && m_state.valid && m_state.remoteEnabled;
|
||||
}
|
||||
|
||||
QString ThinQClient::updatedText() const
|
||||
{
|
||||
return m_updated;
|
||||
}
|
||||
|
||||
void ThinQClient::setDelayHours(int hours)
|
||||
{
|
||||
const int clamped = qBound(3, hours, 19);
|
||||
if (m_delayHours == clamped)
|
||||
return;
|
||||
m_delayHours = clamped;
|
||||
emit delayHoursChanged();
|
||||
}
|
||||
|
||||
QString ThinQClient::durationText(int minutes) const
|
||||
{
|
||||
return ThinQJson::durationText(minutes);
|
||||
}
|
||||
|
||||
void ThinQClient::setNotice(const QString &text, bool isError)
|
||||
{
|
||||
m_notice = text;
|
||||
m_noticeIsError = isError;
|
||||
emit noticeChanged();
|
||||
}
|
||||
|
||||
void ThinQClient::clearNotice()
|
||||
{
|
||||
if (m_notice.isEmpty())
|
||||
return;
|
||||
m_notice.clear();
|
||||
m_noticeIsError = false;
|
||||
emit noticeChanged();
|
||||
}
|
||||
|
||||
void ThinQClient::setBusy(bool busy)
|
||||
{
|
||||
if (m_busy == busy)
|
||||
return;
|
||||
m_busy = busy;
|
||||
emit busyChanged();
|
||||
}
|
||||
|
||||
void ThinQClient::reloadCredentials()
|
||||
{
|
||||
emit infoChanged();
|
||||
emit stateChanged();
|
||||
}
|
||||
|
||||
void ThinQClient::startPolling()
|
||||
{
|
||||
if (!configured())
|
||||
return;
|
||||
refresh();
|
||||
if (!m_pollTimer.isActive()) {
|
||||
m_pollTimer.start(m_pollInterval);
|
||||
emit pollingChanged();
|
||||
}
|
||||
}
|
||||
|
||||
void ThinQClient::stopPolling()
|
||||
{
|
||||
m_pollTimer.stop();
|
||||
emit pollingChanged();
|
||||
}
|
||||
|
||||
void ThinQClient::scheduleNextPoll()
|
||||
{
|
||||
if (m_pollTimer.isActive())
|
||||
m_pollTimer.start(m_pollInterval);
|
||||
}
|
||||
|
||||
void ThinQClient::refresh()
|
||||
{
|
||||
if (!configured())
|
||||
return;
|
||||
get(QStringLiteral("devices/%1/state").arg(m_settings->deviceId()), KindState);
|
||||
}
|
||||
|
||||
void ThinQClient::discover()
|
||||
{
|
||||
if (m_settings->token().isEmpty()) {
|
||||
setNotice(QCoreApplication::translate("ThinQ", "Enter the access token first"), true);
|
||||
return;
|
||||
}
|
||||
get(QStringLiteral("devices"), KindDevices);
|
||||
}
|
||||
|
||||
void ThinQClient::chooseDevice(int index)
|
||||
{
|
||||
if (index < 0 || index >= m_deviceIds.size())
|
||||
return;
|
||||
const QString id = m_deviceIds.at(index);
|
||||
const QString label = m_deviceLabels.at(index);
|
||||
m_selected = index;
|
||||
m_settings->setDeviceAlias(label);
|
||||
m_settings->setDeviceId(id);
|
||||
setNotice(QCoreApplication::translate("ThinQ", "Machine selected"), false);
|
||||
emit devicesChanged();
|
||||
}
|
||||
|
||||
void ThinQClient::runPrimary()
|
||||
{
|
||||
if (!m_state.valid) {
|
||||
setNotice(QCoreApplication::translate("ThinQ", "No data from the machine yet"), true);
|
||||
return;
|
||||
}
|
||||
post(QStringLiteral("devices/%1/control").arg(m_settings->deviceId()),
|
||||
ThinQJson::operationPayload(ThinQJson::primaryAction(m_state)));
|
||||
}
|
||||
|
||||
void ThinQClient::powerOff()
|
||||
{
|
||||
post(QStringLiteral("devices/%1/control").arg(m_settings->deviceId()),
|
||||
ThinQJson::operationPayload(QStringLiteral("POWER_OFF")));
|
||||
}
|
||||
|
||||
void ThinQClient::wakeUp()
|
||||
{
|
||||
post(QStringLiteral("devices/%1/control").arg(m_settings->deviceId()),
|
||||
ThinQJson::operationPayload(QStringLiteral("WAKE_UP")));
|
||||
}
|
||||
|
||||
void ThinQClient::sendDelay()
|
||||
{
|
||||
post(QStringLiteral("devices/%1/control").arg(m_settings->deviceId()),
|
||||
ThinQJson::delayPayload(m_delayHours));
|
||||
}
|
||||
|
||||
void ThinQClient::prepare(QNetworkRequest &request, bool command) const
|
||||
{
|
||||
// UN punto solo per le intestazioni: x-api-key e x-service-phase sono
|
||||
// obbligatorie e senza di esse il cloud risponde 401 con corpo vuoto
|
||||
// (l'app "non trovava le macchine" mentre la regione era giusta).
|
||||
request.setHeader(QNetworkRequest::ContentTypeHeader, QStringLiteral("application/json"));
|
||||
request.setRawHeader("Authorization",
|
||||
QByteArray("Bearer ") + m_settings->token().trimmed().toUtf8());
|
||||
request.setRawHeader("x-country", m_settings->country().toUtf8());
|
||||
request.setRawHeader("x-client-id", m_settings->clientId().toUtf8());
|
||||
request.setRawHeader("x-message-id", ThinQJson::messageId().toUtf8());
|
||||
request.setRawHeader("x-api-key", ThinQJson::apiKey().toUtf8());
|
||||
request.setRawHeader("x-service-phase", ThinQJson::servicePhase().toUtf8());
|
||||
request.setRawHeader("Accept", "application/json");
|
||||
if (command)
|
||||
request.setRawHeader("x-conditional-control", "true");
|
||||
}
|
||||
|
||||
void ThinQClient::get(const QString &endpoint, RequestKind kind)
|
||||
{
|
||||
const QUrl url(ThinQJson::apiBase(m_settings->country()) + QLatin1Char('/') + endpoint);
|
||||
QNetworkRequest request(url);
|
||||
prepare(request, /*command=*/false);
|
||||
|
||||
if (kind == KindState || kind == KindCommand)
|
||||
setBusy(true);
|
||||
|
||||
QNetworkReply *reply = m_nam.get(request);
|
||||
|
||||
// Timeout esplicito: senza, una richiesta verso un host irraggiungibile
|
||||
// resta appesa per minuti e l'app sembra morta.
|
||||
QTimer *guard = new QTimer(reply);
|
||||
guard->setSingleShot(true);
|
||||
connect(guard, &QTimer::timeout, reply, &QNetworkReply::abort);
|
||||
guard->start(kRequestTimeoutMs);
|
||||
|
||||
connect(reply, &QNetworkReply::finished, this, [this, reply, kind]() {
|
||||
reply->deleteLater();
|
||||
const QByteArray body = reply->readAll();
|
||||
const int status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
|
||||
|
||||
if (kind == KindState)
|
||||
setBusy(false);
|
||||
|
||||
if (reply->error() != QNetworkReply::NoError || status < 200 || status >= 300) {
|
||||
const QString netErr = reply->error() == QNetworkReply::NoError
|
||||
? QString() : reply->errorString();
|
||||
handleFailure(status, body, netErr, kind == KindCommand);
|
||||
return;
|
||||
}
|
||||
|
||||
const QJsonDocument doc = QJsonDocument::fromJson(body);
|
||||
const QJsonValue response = doc.isObject()
|
||||
? doc.object().value(QStringLiteral("response"))
|
||||
: QJsonValue(doc.isArray() ? QJsonValue(doc.array()) : QJsonValue());
|
||||
|
||||
if (kind == KindDevices) {
|
||||
m_deviceLabels.clear();
|
||||
m_deviceIds.clear();
|
||||
const QJsonArray arr = response.toArray();
|
||||
for (int i = 0; i < arr.size(); ++i) {
|
||||
const QJsonObject dev = arr.at(i).toObject();
|
||||
const QJsonObject info = dev.value(QStringLiteral("deviceInfo")).toObject();
|
||||
const QString type = info.value(QStringLiteral("deviceType")).toString();
|
||||
if (!type.startsWith(QLatin1String("DEVICE_WASHER"))
|
||||
&& !type.startsWith(QLatin1String("DEVICE_WASHCOMBO"))
|
||||
&& !type.startsWith(QLatin1String("DEVICE_WASHTOWER"))
|
||||
&& !type.startsWith(QLatin1String("DEVICE_DRYER"))) {
|
||||
continue; // l'app controlla lavatrici e lavasciughe
|
||||
}
|
||||
QString label = info.value(QStringLiteral("alias")).toString();
|
||||
if (label.isEmpty())
|
||||
label = info.value(QStringLiteral("modelName")).toString();
|
||||
m_deviceLabels << label;
|
||||
m_deviceIds << dev.value(QStringLiteral("deviceId")).toString();
|
||||
}
|
||||
m_selected = m_deviceIds.indexOf(m_settings->deviceId());
|
||||
emit devicesChanged();
|
||||
if (m_deviceLabels.isEmpty())
|
||||
setNotice(QCoreApplication::translate("ThinQ", "No washing machine found on this account"), true);
|
||||
else
|
||||
setNotice(QCoreApplication::translate("ThinQ", "Machines found: %1").arg(m_deviceLabels.size()), false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (kind == KindState) {
|
||||
const QByteArray payload = QJsonDocument(response.toArray()).toJson(QJsonDocument::Compact);
|
||||
applyState(ThinQJson::parseState(payload));
|
||||
return;
|
||||
}
|
||||
|
||||
// kind == KindCommand
|
||||
m_pendingCommand = false;
|
||||
setNotice(QCoreApplication::translate("ThinQ", "Command sent"), false);
|
||||
refresh();
|
||||
});
|
||||
}
|
||||
|
||||
void ThinQClient::post(const QString &endpoint, const QString &payload)
|
||||
{
|
||||
if (!configured()) {
|
||||
setNotice(QCoreApplication::translate("ThinQ", "Set the access token and the machine first"), true);
|
||||
return;
|
||||
}
|
||||
if (!m_state.valid || !m_state.remoteEnabled) {
|
||||
setNotice(QCoreApplication::translate("ThinQ", "Remote start is off on the machine: switch it on from its panel"), true);
|
||||
return;
|
||||
}
|
||||
|
||||
const QUrl url(ThinQJson::apiBase(m_settings->country()) + QLatin1Char('/') + endpoint);
|
||||
QNetworkRequest request(url);
|
||||
prepare(request, /*command=*/true);
|
||||
|
||||
m_pendingCommand = true;
|
||||
setBusy(true);
|
||||
|
||||
QNetworkReply *reply = m_nam.post(request, payload.toUtf8());
|
||||
QTimer *guard = new QTimer(reply);
|
||||
guard->setSingleShot(true);
|
||||
connect(guard, &QTimer::timeout, reply, &QNetworkReply::abort);
|
||||
guard->start(kRequestTimeoutMs);
|
||||
|
||||
connect(reply, &QNetworkReply::finished, this, [this, reply]() {
|
||||
reply->deleteLater();
|
||||
const QByteArray body = reply->readAll();
|
||||
const int status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
|
||||
setBusy(false);
|
||||
|
||||
if (reply->error() != QNetworkReply::NoError || status < 200 || status >= 300) {
|
||||
const QString netErr = reply->error() == QNetworkReply::NoError
|
||||
? QString() : reply->errorString();
|
||||
handleFailure(status, body, netErr, true);
|
||||
return;
|
||||
}
|
||||
setNotice(QCoreApplication::translate("ThinQ", "Command sent"), false);
|
||||
refresh();
|
||||
});
|
||||
}
|
||||
|
||||
void ThinQClient::applyState(const WasherState &state)
|
||||
{
|
||||
m_state = state;
|
||||
m_stale = false;
|
||||
m_updated = QCoreApplication::translate("ThinQ", "Updated at %1").arg(
|
||||
QLocale().toString(QTime::currentTime(), QLocale::ShortFormat));
|
||||
if (m_pollInterval != kPollFastMs)
|
||||
m_pollInterval = kPollFastMs;
|
||||
emit stateChanged();
|
||||
scheduleNextPoll();
|
||||
}
|
||||
|
||||
void ThinQClient::handleFailure(int httpStatus, const QByteArray &body,
|
||||
const QString &networkError, bool commandRequest)
|
||||
{
|
||||
QString code;
|
||||
QString message;
|
||||
const QJsonDocument doc = QJsonDocument::fromJson(body);
|
||||
if (doc.isObject()) {
|
||||
const QJsonObject err = doc.object().value(QStringLiteral("error")).toObject();
|
||||
code = err.value(QStringLiteral("code")).toString();
|
||||
message = err.value(QStringLiteral("message")).toString();
|
||||
}
|
||||
|
||||
qDebug() << "[thinq] errore LG" << httpStatus << code << message
|
||||
<< (networkError.isEmpty() ? QString() : networkError);
|
||||
|
||||
if (code == QLatin1String("1103") || code == QLatin1String("1218")
|
||||
|| code == QLatin1String("1302")) {
|
||||
setNotice(QCoreApplication::translate("ThinQ", "The access token is no longer valid: enter a new one in Settings"), true);
|
||||
} else if (code == QLatin1String("1306")) {
|
||||
m_pollInterval = kPollSlowMs;
|
||||
setNotice(QCoreApplication::translate("ThinQ", "Too many requests to LG: slowing down"), true);
|
||||
} else if (code == QLatin1String("1222")) {
|
||||
setNotice(QCoreApplication::translate("ThinQ", "The washing machine is not connected (switched off or offline)"), true);
|
||||
} else if (code == QLatin1String("2301")) {
|
||||
setNotice(QCoreApplication::translate("ThinQ", "Remote start is off on the machine: switch it on from its panel"), true);
|
||||
} else if (code == QLatin1String("1214") || code == QLatin1String("1308")) {
|
||||
setNotice(QCoreApplication::translate("ThinQ", "The machine does not accept this command"), true);
|
||||
} else if (!code.isEmpty()) {
|
||||
setNotice(QCoreApplication::translate("ThinQ", "LG error %1: %2").arg(code, message), true);
|
||||
} else if (!networkError.isEmpty()) {
|
||||
setNotice(QCoreApplication::translate("ThinQ", "No answer from the LG cloud: %1").arg(networkError), true);
|
||||
} else {
|
||||
setNotice(QCoreApplication::translate("ThinQ", "The LG cloud refused the request (HTTP %1)").arg(httpStatus), true);
|
||||
}
|
||||
|
||||
if (commandRequest)
|
||||
m_pendingCommand = false;
|
||||
|
||||
// I dati a schermo non sono piu' freschi: dirlo, invece di mostrare i
|
||||
// numeri vecchi come se fossero attuali.
|
||||
if (m_state.valid) {
|
||||
m_stale = true;
|
||||
emit stateChanged();
|
||||
}
|
||||
scheduleNextPoll();
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
#ifndef THINQCLIENT_H
|
||||
#define THINQCLIENT_H
|
||||
|
||||
#include <QNetworkAccessManager>
|
||||
#include <QObject>
|
||||
#include <QStringList>
|
||||
#include <QTimer>
|
||||
|
||||
#include "thinqjson.h"
|
||||
|
||||
class Settings;
|
||||
class QNetworkReply;
|
||||
|
||||
// Parla direttamente con il cloud LG ThinQ Connect: nessun ponte, nessun
|
||||
// server di mezzo. Il token di accesso sta nelle impostazioni dell'app.
|
||||
class ThinQClient : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
Q_PROPERTY(bool configured READ configured NOTIFY infoChanged)
|
||||
Q_PROPERTY(QString alias READ alias NOTIFY infoChanged)
|
||||
Q_PROPERTY(bool hasState READ hasState NOTIFY stateChanged)
|
||||
Q_PROPERTY(QString phaseText READ phaseText NOTIFY stateChanged)
|
||||
Q_PROPERTY(int statusLevel READ statusLevel NOTIFY stateChanged)
|
||||
Q_PROPERTY(QString remainText READ remainText NOTIFY stateChanged)
|
||||
Q_PROPERTY(QString totalText READ totalText NOTIFY stateChanged)
|
||||
Q_PROPERTY(int cycleCount READ cycleCount NOTIFY stateChanged)
|
||||
Q_PROPERTY(bool remoteEnabled READ remoteEnabled NOTIFY stateChanged)
|
||||
Q_PROPERTY(QString primaryLabel READ primaryLabel NOTIFY stateChanged)
|
||||
Q_PROPERTY(bool canCommand READ canCommand NOTIFY stateChanged)
|
||||
Q_PROPERTY(QString updatedText READ updatedText NOTIFY stateChanged)
|
||||
Q_PROPERTY(bool stale READ stale NOTIFY stateChanged)
|
||||
Q_PROPERTY(bool busy READ busy NOTIFY busyChanged)
|
||||
Q_PROPERTY(bool polling READ polling NOTIFY pollingChanged)
|
||||
Q_PROPERTY(QString notice READ notice NOTIFY noticeChanged)
|
||||
Q_PROPERTY(bool noticeIsError READ noticeIsError NOTIFY noticeChanged)
|
||||
Q_PROPERTY(QStringList deviceLabels READ deviceLabels NOTIFY devicesChanged)
|
||||
Q_PROPERTY(int deviceCount READ deviceCount NOTIFY devicesChanged)
|
||||
Q_PROPERTY(int selectedDevice READ selectedDevice NOTIFY devicesChanged)
|
||||
Q_PROPERTY(int delayHours READ delayHours WRITE setDelayHours NOTIFY delayHoursChanged)
|
||||
|
||||
public:
|
||||
explicit ThinQClient(Settings *settings, QObject *parent = nullptr);
|
||||
|
||||
bool configured() const;
|
||||
QString alias() const;
|
||||
bool hasState() const { return m_state.valid; }
|
||||
QString phaseText() const;
|
||||
int statusLevel() const;
|
||||
QString remainText() const;
|
||||
QString totalText() const;
|
||||
int cycleCount() const { return m_state.cycleCount; }
|
||||
bool remoteEnabled() const { return m_state.remoteEnabled; }
|
||||
QString primaryLabel() const;
|
||||
bool canCommand() const;
|
||||
QString updatedText() const;
|
||||
bool stale() const { return m_stale; }
|
||||
bool busy() const { return m_busy; }
|
||||
bool polling() const { return m_pollTimer.isActive(); }
|
||||
QString notice() const { return m_notice; }
|
||||
bool noticeIsError() const { return m_noticeIsError; }
|
||||
QStringList deviceLabels() const { return m_deviceLabels; }
|
||||
int deviceCount() const { return m_deviceLabels.size(); }
|
||||
int selectedDevice() const { return m_selected; }
|
||||
int delayHours() const { return m_delayHours; }
|
||||
void setDelayHours(int hours);
|
||||
|
||||
Q_INVOKABLE void refresh();
|
||||
Q_INVOKABLE void discover();
|
||||
Q_INVOKABLE void chooseDevice(int index);
|
||||
Q_INVOKABLE void runPrimary();
|
||||
Q_INVOKABLE void powerOff();
|
||||
Q_INVOKABLE void wakeUp();
|
||||
Q_INVOKABLE void sendDelay();
|
||||
Q_INVOKABLE void startPolling();
|
||||
Q_INVOKABLE void stopPolling();
|
||||
Q_INVOKABLE void clearNotice();
|
||||
Q_INVOKABLE void reloadCredentials();
|
||||
Q_INVOKABLE QString durationText(int minutes) const;
|
||||
|
||||
signals:
|
||||
void infoChanged();
|
||||
void stateChanged();
|
||||
void busyChanged();
|
||||
void pollingChanged();
|
||||
void noticeChanged();
|
||||
void devicesChanged();
|
||||
void delayHoursChanged();
|
||||
|
||||
private:
|
||||
enum RequestKind { KindDevices, KindState, KindCommand };
|
||||
|
||||
void prepare(QNetworkRequest &request, bool command) const;
|
||||
void get(const QString &endpoint, RequestKind kind);
|
||||
void post(const QString &endpoint, const QString &payload);
|
||||
void applyState(const WasherState &state);
|
||||
void handleFailure(int httpStatus, const QByteArray &body, const QString &networkError,
|
||||
bool commandRequest);
|
||||
void setNotice(const QString &text, bool isError);
|
||||
void setBusy(bool busy);
|
||||
void scheduleNextPoll();
|
||||
|
||||
Settings *m_settings;
|
||||
QNetworkAccessManager m_nam;
|
||||
QTimer m_pollTimer;
|
||||
WasherState m_state;
|
||||
QStringList m_deviceLabels;
|
||||
QStringList m_deviceIds;
|
||||
int m_selected = -1;
|
||||
int m_pollInterval = 45000;
|
||||
int m_delayHours = 4;
|
||||
bool m_busy = false;
|
||||
bool m_stale = false;
|
||||
bool m_pendingCommand = false;
|
||||
QString m_notice;
|
||||
bool m_noticeIsError = false;
|
||||
QString m_updated;
|
||||
};
|
||||
|
||||
#endif // THINQCLIENT_H
|
||||
@@ -0,0 +1,204 @@
|
||||
#include "thinqjson.h"
|
||||
|
||||
#include <QCoreApplication>
|
||||
#include <QJsonArray>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QJsonValue>
|
||||
#include <QStringList>
|
||||
#include <QUuid>
|
||||
|
||||
namespace {
|
||||
|
||||
// Regioni del cloud LG (stesse liste della libreria ufficiale).
|
||||
const QStringList kEic = QStringList()
|
||||
<< "AL" << "AT" << "BA" << "BE" << "BG" << "CH" << "CY" << "CZ" << "DE"
|
||||
<< "DK" << "EE" << "ES" << "FI" << "FR" << "GB" << "GE" << "GR" << "HR"
|
||||
<< "HU" << "IE" << "IL" << "IQ" << "IR" << "IS" << "IT" << "JO" << "KE"
|
||||
<< "KW" << "LT" << "LU" << "LV" << "MD" << "ME" << "MK" << "MT" << "NL"
|
||||
<< "NO" << "PL" << "PT" << "RO" << "RS" << "SE" << "SI" << "SK" << "TR"
|
||||
<< "UA" << "XK" << "ZA";
|
||||
|
||||
const QStringList kAic = QStringList()
|
||||
<< "AR" << "AW" << "BB" << "BO" << "BR" << "BS" << "BZ" << "CA" << "CL"
|
||||
<< "CO" << "CR" << "CU" << "DO" << "EC" << "GD" << "GT" << "HN" << "HT"
|
||||
<< "JM" << "KN" << "LC" << "MX" << "NI" << "PA" << "PE" << "PR" << "PY"
|
||||
<< "SV" << "TT" << "US" << "UY" << "VE" << "VC";
|
||||
|
||||
} // namespace
|
||||
|
||||
bool WasherState::running() const
|
||||
{
|
||||
static const QStringList active = QStringList()
|
||||
<< "RUNNING" << "RINSING" << "SPINNING" << "DRYING" << "COOL_DOWN"
|
||||
<< "REFRESHING" << "STEAM_SOFTENING" << "DETECTING" << "RESERVED";
|
||||
return active.contains(phase);
|
||||
}
|
||||
|
||||
namespace ThinQJson {
|
||||
|
||||
QString regionFor(const QString &country)
|
||||
{
|
||||
const QString c = country.trimmed().toUpper();
|
||||
if (kAic.contains(c))
|
||||
return QStringLiteral("aic");
|
||||
if (kEic.contains(c))
|
||||
return QStringLiteral("eic");
|
||||
if (c.isEmpty())
|
||||
return QStringLiteral("eic");
|
||||
return QStringLiteral("kic");
|
||||
}
|
||||
|
||||
QString apiBase(const QString &country)
|
||||
{
|
||||
return QStringLiteral("https://api-") + regionFor(country) + QStringLiteral(".lgthinq.com");
|
||||
}
|
||||
|
||||
QString messageId()
|
||||
{
|
||||
const QUuid id = QUuid::createUuid();
|
||||
const QByteArray raw = id.toRfc4122();
|
||||
return QString::fromLatin1(raw.toBase64(QByteArray::Base64UrlEncoding
|
||||
| QByteArray::OmitTrailingEquals));
|
||||
}
|
||||
|
||||
QString apiKey()
|
||||
{
|
||||
// Costante pubblica della libreria ufficiale ThinQ Connect (LG, Apache-2.0).
|
||||
return QStringLiteral("v6GFvkweNo7DK7yD3ylIZ9w52aKBU0eJ7wLXkSR3");
|
||||
}
|
||||
|
||||
QString servicePhase()
|
||||
{
|
||||
return QStringLiteral("OP");
|
||||
}
|
||||
|
||||
WasherState parseState(const QByteArray &responseBody)
|
||||
{
|
||||
WasherState state;
|
||||
|
||||
const QJsonDocument doc = QJsonDocument::fromJson(responseBody);
|
||||
QJsonObject root;
|
||||
if (doc.isArray()) {
|
||||
const QJsonArray arr = doc.array();
|
||||
for (int i = 0; i < arr.size(); ++i) {
|
||||
const QJsonObject candidate = arr.at(i).toObject();
|
||||
const QString location =
|
||||
candidate.value(QStringLiteral("location")).toObject()
|
||||
.value(QStringLiteral("locationName")).toString();
|
||||
if (location == QLatin1String("MAIN") || root.isEmpty())
|
||||
root = candidate;
|
||||
if (location == QLatin1String("MAIN"))
|
||||
break;
|
||||
}
|
||||
} else if (doc.isObject()) {
|
||||
root = doc.object();
|
||||
}
|
||||
|
||||
if (root.isEmpty())
|
||||
return state;
|
||||
|
||||
state.phase = root.value(QStringLiteral("runState")).toObject()
|
||||
.value(QStringLiteral("currentState")).toString();
|
||||
|
||||
const QJsonObject timer = root.value(QStringLiteral("timer")).toObject();
|
||||
state.remainMinutes = timer.value(QStringLiteral("remainHour")).toInt() * 60
|
||||
+ timer.value(QStringLiteral("remainMinute")).toInt();
|
||||
state.totalMinutes = timer.value(QStringLiteral("totalHour")).toInt() * 60
|
||||
+ timer.value(QStringLiteral("totalMinute")).toInt();
|
||||
|
||||
state.cycleCount = root.value(QStringLiteral("cycle")).toObject()
|
||||
.value(QStringLiteral("cycleCount")).toInt();
|
||||
|
||||
state.remoteEnabled = root.value(QStringLiteral("remoteControlEnable")).toObject()
|
||||
.value(QStringLiteral("remoteControlEnabled")).toBool();
|
||||
|
||||
state.valid = !state.phase.isEmpty();
|
||||
return state;
|
||||
}
|
||||
|
||||
QString phaseLabel(const WasherState &state)
|
||||
{
|
||||
const QString p = state.phase;
|
||||
if (p == QLatin1String("RUNNING")) return QCoreApplication::translate("ThinQ", "Washing");
|
||||
if (p == QLatin1String("RINSING")) return QCoreApplication::translate("ThinQ", "Rinsing");
|
||||
if (p == QLatin1String("SPINNING")) return QCoreApplication::translate("ThinQ", "Spinning");
|
||||
if (p == QLatin1String("DRYING")) return QCoreApplication::translate("ThinQ", "Drying");
|
||||
if (p == QLatin1String("COOL_DOWN")) return QCoreApplication::translate("ThinQ", "Cooling down");
|
||||
if (p == QLatin1String("REFRESHING")) return QCoreApplication::translate("ThinQ", "Refreshing");
|
||||
if (p == QLatin1String("STEAM_SOFTENING")) return QCoreApplication::translate("ThinQ", "Steam softening");
|
||||
if (p == QLatin1String("DETECTING")) return QCoreApplication::translate("ThinQ", "Detecting the load");
|
||||
if (p == QLatin1String("RESERVED")) return QCoreApplication::translate("ThinQ", "Delayed start");
|
||||
if (p == QLatin1String("RINSE_HOLD")) return QCoreApplication::translate("ThinQ", "Rinse hold");
|
||||
if (p == QLatin1String("PAUSE")) return QCoreApplication::translate("ThinQ", "Paused");
|
||||
if (p == QLatin1String("END")) return QCoreApplication::translate("ThinQ", "Finished");
|
||||
if (p == QLatin1String("INITIAL")) return QCoreApplication::translate("ThinQ", "Ready");
|
||||
if (p == QLatin1String("POWER_OFF")) return QCoreApplication::translate("ThinQ", "Off");
|
||||
if (p == QLatin1String("SLEEP")) return QCoreApplication::translate("ThinQ", "Standby");
|
||||
if (p == QLatin1String("ERROR")) return QCoreApplication::translate("ThinQ", "Error");
|
||||
return state.phase;
|
||||
}
|
||||
|
||||
QString primaryAction(const WasherState &state)
|
||||
{
|
||||
if (!state.valid)
|
||||
return QString();
|
||||
if (state.phase == QLatin1String("ERROR"))
|
||||
return QStringLiteral("POWER_OFF");
|
||||
if (state.running() || state.phase == QLatin1String("RINSE_HOLD"))
|
||||
return QStringLiteral("STOP");
|
||||
return QStringLiteral("START");
|
||||
}
|
||||
|
||||
QString primaryActionLabel(const WasherState &state)
|
||||
{
|
||||
const QString action = primaryAction(state);
|
||||
if (action == QLatin1String("STOP"))
|
||||
return QCoreApplication::translate("ThinQ", "Stop");
|
||||
if (action == QLatin1String("POWER_OFF"))
|
||||
return QCoreApplication::translate("ThinQ", "Switch off");
|
||||
if (state.phase == QLatin1String("PAUSE"))
|
||||
return QCoreApplication::translate("ThinQ", "Resume");
|
||||
return QCoreApplication::translate("ThinQ", "Start");
|
||||
}
|
||||
|
||||
int statusLevel(const WasherState &state)
|
||||
{
|
||||
if (!state.valid)
|
||||
return -1;
|
||||
if (state.phase == QLatin1String("ERROR"))
|
||||
return 4;
|
||||
if (state.phase == QLatin1String("PAUSE"))
|
||||
return 2;
|
||||
if (state.phase == QLatin1String("END"))
|
||||
return 3;
|
||||
if (state.running())
|
||||
return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
QString operationPayload(const QString &action)
|
||||
{
|
||||
return QStringLiteral("{\"operation\":{\"washerOperationMode\":\"%1\"}}").arg(action);
|
||||
}
|
||||
|
||||
QString delayPayload(int hours)
|
||||
{
|
||||
return QStringLiteral("{\"timer\":{\"relativeHourToStop\":%1}}").arg(hours);
|
||||
}
|
||||
|
||||
QString durationText(int minutes)
|
||||
{
|
||||
if (minutes <= 0)
|
||||
return QString();
|
||||
const int h = minutes / 60;
|
||||
const int m = minutes % 60;
|
||||
QStringList parts;
|
||||
if (h > 0)
|
||||
parts << QStringLiteral("%1 h").arg(h);
|
||||
if (m > 0)
|
||||
parts << QStringLiteral("%1 min").arg(m);
|
||||
return parts.join(QLatin1Char(' '));
|
||||
}
|
||||
|
||||
} // namespace ThinQJson
|
||||
@@ -0,0 +1,56 @@
|
||||
#ifndef THINQJSON_H
|
||||
#define THINQJSON_H
|
||||
|
||||
#include <QByteArray>
|
||||
#include <QString>
|
||||
|
||||
// Stato di una lavatrice/lavasciuga LG ThinQ Connect.
|
||||
struct WasherState
|
||||
{
|
||||
bool valid = false;
|
||||
QString phase; // enum LG: RUNNING, DRYING, END, PAUSE, ...
|
||||
int remainMinutes = 0;
|
||||
int totalMinutes = 0;
|
||||
int cycleCount = 0;
|
||||
bool remoteEnabled = false;
|
||||
|
||||
bool running() const;
|
||||
};
|
||||
|
||||
// Funzioni pure: nessuna rete, nessuna UI. Si provano nell'harness del nucleo
|
||||
// senza kit Sailfish (vedi tests/).
|
||||
namespace ThinQJson {
|
||||
|
||||
// Regione del cloud LG dal paese: kic | aic | eic (Italia = eic).
|
||||
QString regionFor(const QString &country);
|
||||
// Base degli indirizzi, es. https://api-eic.lgthinq.com (senza barra finale).
|
||||
QString apiBase(const QString &country);
|
||||
// x-message-id come lo genera la libreria ufficiale: base64url di un uuid4 senza "=".
|
||||
QString messageId();
|
||||
// Intestazioni che la libreria ufficiale manda SEMPRE e la documentazione non
|
||||
// elenca: senza, il cloud risponde 401 con corpo vuoto su qualunque richiesta
|
||||
// (e qualunque regione). Verificate sul campo: con queste si legge l'elenco.
|
||||
QString apiKey();
|
||||
QString servicePhase();
|
||||
|
||||
// Estrae il sotto-stato della posizione MAIN dalla risposta di
|
||||
// GET /devices/{id}/state (il contenuto di "response").
|
||||
WasherState parseState(const QByteArray &responseBody);
|
||||
|
||||
// Presentazione (stringhe sorgente in inglese, tradotte dal catalogo).
|
||||
QString phaseLabel(const WasherState &state);
|
||||
QString primaryAction(const WasherState &state); // START | STOP | POWER_OFF
|
||||
QString primaryActionLabel(const WasherState &state);
|
||||
// 0 spenta, 1 in corso, 2 in pausa, 3 finita, 4 errore
|
||||
int statusLevel(const WasherState &state);
|
||||
|
||||
// Corpi dei comandi, nella forma che l'API si aspetta.
|
||||
QString operationPayload(const QString &action); // operation.washerOperationMode
|
||||
QString delayPayload(int hours); // timer.relativeHourToStop
|
||||
|
||||
// Durate in testo leggibile ("1 h 54 min"), vuoto se zero.
|
||||
QString durationText(int minutes);
|
||||
|
||||
} // namespace ThinQJson
|
||||
|
||||
#endif // THINQJSON_H
|
||||
@@ -0,0 +1,73 @@
|
||||
#include "translator.h"
|
||||
|
||||
#include "settings.h"
|
||||
|
||||
#include <QCoreApplication>
|
||||
#include <QDebug>
|
||||
#include <QLocale>
|
||||
#include <QTranslator>
|
||||
|
||||
namespace {
|
||||
const char *kCatalogDir = "/usr/share/harbour-thinq/translations";
|
||||
}
|
||||
|
||||
Translator::Translator(Settings *settings, QObject *parent)
|
||||
: QObject(parent)
|
||||
, m_settings(settings)
|
||||
, m_language(settings->language())
|
||||
{
|
||||
if (m_language.isEmpty())
|
||||
m_language = QStringLiteral("system");
|
||||
}
|
||||
|
||||
void Translator::setLanguage(const QString &value)
|
||||
{
|
||||
const QString v = value.isEmpty() ? QStringLiteral("system") : value;
|
||||
if (m_language == v)
|
||||
return;
|
||||
m_language = v;
|
||||
m_settings->setLanguage(v);
|
||||
install();
|
||||
emit languageChanged();
|
||||
}
|
||||
|
||||
void Translator::applySaved()
|
||||
{
|
||||
install();
|
||||
}
|
||||
|
||||
void Translator::install()
|
||||
{
|
||||
QCoreApplication *app = QCoreApplication::instance();
|
||||
|
||||
// Rimuovere i traduttori gia' presenti (compreso quello di libsailfishapp):
|
||||
// altrimenti il catalogo vecchio continua a vincere.
|
||||
const QList<QTranslator *> existing = app->findChildren<QTranslator *>();
|
||||
for (QTranslator *t : existing) {
|
||||
app->removeTranslator(t);
|
||||
t->deleteLater();
|
||||
}
|
||||
m_applied = nullptr;
|
||||
|
||||
QString lang = m_language;
|
||||
if (lang == QLatin1String("system")) {
|
||||
const QString sys = QLocale::system().name(); // QLocale::system(), non QLocale()
|
||||
lang = sys.startsWith(QLatin1String("it")) ? QStringLiteral("it") : QStringLiteral("en");
|
||||
}
|
||||
|
||||
QLocale::setDefault(QLocale(lang == QLatin1String("it") ? QStringLiteral("it_IT")
|
||||
: QStringLiteral("en_GB")));
|
||||
|
||||
if (lang != QLatin1String("it"))
|
||||
return; // l'inglese e' la lingua sorgente: nessun catalogo da caricare
|
||||
|
||||
QTranslator *tr = new QTranslator(app);
|
||||
if (tr->load(QStringLiteral("harbour-thinq_it"), QString::fromLatin1(kCatalogDir))) {
|
||||
app->installTranslator(tr);
|
||||
m_applied = tr;
|
||||
qDebug() << "[thinq] catalogo italiano caricato";
|
||||
} else {
|
||||
qWarning() << "[thinq] catalogo italiano NON caricato da" << kCatalogDir;
|
||||
delete tr;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
#ifndef TRANSLATOR_H
|
||||
#define TRANSLATOR_H
|
||||
|
||||
#include <QObject>
|
||||
#include <QString>
|
||||
|
||||
class Settings;
|
||||
class QTranslator;
|
||||
|
||||
// Lingua dell'interfaccia: "system" (default), "en", "it".
|
||||
// La scelta si applica ricaricando la radice QML (Qt 5.6 non ha retranslate()).
|
||||
class Translator : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
Q_PROPERTY(QString language READ language WRITE setLanguage NOTIFY languageChanged)
|
||||
|
||||
public:
|
||||
explicit Translator(Settings *settings, QObject *parent = nullptr);
|
||||
|
||||
QString language() const { return m_language; }
|
||||
void setLanguage(const QString &value);
|
||||
|
||||
// Da chiamare in main.cpp PRIMA di createView().
|
||||
void applySaved();
|
||||
|
||||
signals:
|
||||
void languageChanged();
|
||||
|
||||
private:
|
||||
void install();
|
||||
|
||||
Settings *m_settings;
|
||||
QString m_language;
|
||||
QTranslator *m_applied = nullptr;
|
||||
};
|
||||
|
||||
#endif // TRANSLATOR_H
|
||||
Reference in new issue
Block a user