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:
kaneda committed 2026-10-12 12:03:23 +02:00
commit b5f6e79146
32 files changed
+2859

No files matched your search

+418
View File
@@ -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();
}