From e2c6f286131f16ee583d439b8f7169496a6c66cb Mon Sep 17 00:00:00 2001 From: Carlo Baratto Date: Mon, 12 Oct 2026 12:38:10 +0200 Subject: [PATCH] Schermata principale con tutte le macchine, avviso di fine lavaggio, IT/EN - la chiave si chiede una volta sola: poi la schermata principale mostra ogni macchina dell'account col suo stato e il suo comando - avviso di sistema a fine lavaggio, anche se il ciclo e' finito mentre l'app era chiusa (si annota il numero di ciclo gia' avvisato) - comandi per singola macchina: avvio/stop, spegnimento, risveglio, stop ritardato (nel menu della macchina, tocco prolungato sul nome) - le macchine non raggiungibili vengono segnate come non collegate, senza riempire la barra dei messaggi ad ogni aggiornamento - multilingua italiano/inglese, catalogo verificato dal banco di prova (52 controlli) --- qml/cover/CoverPage.qml | 14 +- qml/harbour-thinq.qml | 22 ++ qml/pages/DelayDialog.qml | 12 +- qml/pages/MainPage.qml | 321 ++++++++++------- qml/pages/SettingsPage.qml | 42 +-- rpm/harbour-thinq.spec | 10 +- scripts/fill_translations.py | 12 + src/main.cpp | 4 +- src/settings.cpp | 15 + src/settings.h | 6 + src/thinqclient.cpp | 380 ++++++++++++++------ src/thinqclient.h | 107 +++--- tests/main.cpp | 20 ++ translations/harbour-thinq-it.ts | 591 +++++++++++++++++++------------ 14 files changed, 1015 insertions(+), 541 deletions(-) diff --git a/qml/cover/CoverPage.qml b/qml/cover/CoverPage.qml index 550e843..6b775f4 100644 --- a/qml/cover/CoverPage.qml +++ b/qml/cover/CoverPage.qml @@ -2,7 +2,11 @@ import QtQuick 2.2 import Sailfish.Silica 1.0 import "../js/status.js" as Status +// Copertina: la macchina che sta lavorando (se ce n'e' una), altrimenti la +// prima. Stesse funzioni della schermata principale: una sola verita'. CoverBackground { + property int shown: api.activeIndex() + Column { anchors.centerIn: parent width: parent.width - 2 * Theme.paddingMedium @@ -13,7 +17,7 @@ CoverBackground { width: Theme.itemSizeSmall / 2.2 height: width radius: width / 2 - color: Status.statusColor(api.statusLevel) + color: Status.statusColor(api.statusLevelAt(shown)) } Label { @@ -22,16 +26,18 @@ CoverBackground { elide: Text.ElideRight color: Theme.primaryColor font.pixelSize: Theme.fontSizeSmall - text: api.hasState ? api.phaseText : qsTr("No data") + text: api.validIndex(shown) && api.hasStateAt(shown) + ? api.phaseTextAt(shown) + : qsTr("No data") } Label { width: parent.width horizontalAlignment: Text.AlignHCenter - visible: api.remainText.length > 0 + visible: api.validIndex(shown) && api.remainTextAt(shown).length > 0 color: Theme.secondaryColor font.pixelSize: Theme.fontSizeExtraSmall - text: api.remainText + text: api.validIndex(shown) ? api.remainTextAt(shown) : "" } } diff --git a/qml/harbour-thinq.qml b/qml/harbour-thinq.qml index 1385b3f..c356732 100644 --- a/qml/harbour-thinq.qml +++ b/qml/harbour-thinq.qml @@ -1,5 +1,6 @@ import QtQuick 2.2 import Sailfish.Silica 1.0 +import Nemo.Notifications 1.0 import "pages" import "cover" @@ -8,4 +9,25 @@ ApplicationWindow initialPage: Component { MainPage { } } cover: Component { CoverPage { } } allowedOrientations: Orientation.All + + // Avviso di fine lavaggio. La macchina lo racconta al cloud, l'app lo + // chiede al cloud: nessun server di mezzo. Arriva quando l'app e' viva e + // ha appena visto il ciclo finire; se nel frattempo era chiusa, arriva + // alla prima riapertura. + Notification { + id: cycleNotice + appName: "ThinQ" + appIcon: "harbour-thinq" + urgency: Notification.Normal + expireTimeout: 10000 + } + + Connections { + target: api + onCycleFinished: { + cycleNotice.summary = qsTr("Washing finished") + cycleNotice.body = label + cycleNotice.publish() + } + } } diff --git a/qml/pages/DelayDialog.qml b/qml/pages/DelayDialog.qml index 0df4ed5..a2fb774 100644 --- a/qml/pages/DelayDialog.qml +++ b/qml/pages/DelayDialog.qml @@ -1,17 +1,20 @@ import QtQuick 2.2 import Sailfish.Silica 1.0 -// Stop ritardato: 3-19 ore, gli unici valori che questa macchina accetta. +// Stop ritardato: 3-19 ore, gli unici valori che queste macchine accettano. +// Si apre dal menu di UNA macchina: senza l'indice il comando andrebbe a +// quella sbagliata. Dialog { id: dialog + property int deviceIndex: -1 property int hours: api.delayHours - canAccept: true + canAccept: api.canCommandAt(deviceIndex) onAccepted: { api.setDelayHours(hours) - api.sendDelay() + api.sendDelayAt(deviceIndex) } Column { @@ -19,7 +22,8 @@ Dialog { spacing: Theme.paddingMedium DialogHeader { - title: qsTr("Delayed stop") + title: api.validIndex(deviceIndex) ? api.labelAt(deviceIndex) + : qsTr("Delayed stop") acceptText: qsTr("Set") } diff --git a/qml/pages/MainPage.qml b/qml/pages/MainPage.qml index bec9bad..019b2f6 100644 --- a/qml/pages/MainPage.qml +++ b/qml/pages/MainPage.qml @@ -2,13 +2,17 @@ import QtQuick 2.2 import Sailfish.Silica 1.0 import "../js/status.js" as Status +// Prima schermata. Due volti: +// * senza chiave di accesso -> si chiede una volta sola (qui, non nelle +// impostazioni) e poi non se ne parla piu'; +// * con la chiave -> l'elenco delle macchine, ognuna col suo stato. Page { id: page allowedOrientations: Orientation.All // La macchina si aggiorna solo mentre la schermata e' in primo piano: - // e' quello che l'utente ha scelto (niente ponte, niente servizio). + // niente ponte, niente servizio che gira di nascosto. onStatusChanged: { if (status === PageStatus.Active) api.startPolling() @@ -23,22 +27,9 @@ Page { PullDownMenu { MenuItem { text: qsTr("Refresh") + enabled: api.configured onClicked: api.refresh() } - MenuItem { - text: qsTr("Delayed stop…") - onClicked: pageStack.push(Qt.resolvedUrl("DelayDialog.qml")) - } - MenuItem { - text: qsTr("Switch off") - enabled: api.canCommand - onClicked: api.powerOff() - } - MenuItem { - text: qsTr("Wake the display up") - enabled: api.canCommand - onClicked: api.wakeUp() - } MenuItem { text: qsTr("Settings") onClicked: pageStack.push(Qt.resolvedUrl("SettingsPage.qml")) @@ -51,131 +42,217 @@ Page { spacing: Theme.paddingMedium PageHeader { - title: api.alias + title: qsTr("My machines") description: api.configured - ? (api.stale ? qsTr("Not up to date") : api.updatedText) - : qsTr("Not configured") + ? (api.busy ? qsTr("Updating…") : qsTr("%1 found").arg(api.deviceCount)) + : qsTr("First setup") } - // Prima di tutto: se manca qualcosa per parlare con la macchina, - // dirlo qui invece di mostrare una schermata vuota. - Label { - x: Theme.horizontalPageMargin - width: parent.width - 2 * Theme.horizontalPageMargin - visible: !api.configured - wrapMode: Text.WordWrap - color: Theme.secondaryColor - font.pixelSize: Theme.fontSizeSmall - text: qsTr("Enter the LG access token in Settings and pick your machine.") - } - - Button { - anchors.horizontalCenter: parent.horizontalCenter - visible: !api.configured - text: qsTr("Settings") - onClicked: pageStack.push(Qt.resolvedUrl("SettingsPage.qml")) - } - - // --- stato --- - Item { + // --------------------------------------------------------------- + // Primo avvio: le credenziali si chiedono qui, una volta sola. + // --------------------------------------------------------------- + Column { width: parent.width - height: Theme.itemSizeLarge - visible: api.configured + visible: !api.configured + spacing: Theme.paddingMedium - Rectangle { - id: lamp + Label { x: Theme.horizontalPageMargin - anchors.verticalCenter: parent.verticalCenter - width: Theme.itemSizeSmall / 2.2 - height: width - radius: width / 2 - color: Status.statusColor(api.statusLevel) + width: parent.width - 2 * Theme.horizontalPageMargin + wrapMode: Text.WordWrap + color: Theme.secondaryColor + font.pixelSize: Theme.fontSizeExtraSmall + text: qsTr("The access token comes from connect-pat.lgthinq.com and stays on this phone only. If LG starts refusing it, paste a new one here.") + } - SequentialAnimation on opacity { - running: Status.isActive(api.statusLevel) - loops: Animation.Infinite - PropertyAnimation { to: 0.35; duration: 900 } - PropertyAnimation { to: 1.0; duration: 900 } + TextField { + id: setupToken + anchors.left: parent.left + anchors.right: parent.right + label: qsTr("Access token") + placeholderText: qsTr("paste the token") + echoMode: TextInput.Password + } + + TextField { + id: setupCountry + anchors.left: parent.left + anchors.right: parent.right + label: qsTr("Country code") + placeholderText: "IT" + onTextChanged: appSettings.country = text + Component.onCompleted: text = appSettings.country + } + + Button { + anchors.horizontalCenter: parent.horizontalCenter + width: parent.width - 2 * Theme.horizontalPageMargin + height: Theme.itemSizeMedium + enabled: setupToken.text.length > 0 && !api.busy + text: qsTr("Connect") + onClicked: { + appSettings.token = setupToken.text + api.reloadCredentials() + api.discover() } } + } - Label { - anchors.left: lamp.right - anchors.leftMargin: Theme.paddingLarge - anchors.right: parent.right - anchors.rightMargin: Theme.horizontalPageMargin - anchors.verticalCenter: parent.verticalCenter - truncationMode: TruncationMode.Fade - text: api.phaseText - color: Theme.primaryColor - font.pixelSize: Theme.fontSizeLarge + // --------------------------------------------------------------- + // Ogni macchina dell'account, col suo stato e il suo comando. + // --------------------------------------------------------------- + Repeater { + model: api.configured ? api.deviceCount : 0 + + delegate: Column { + id: machine + width: column.width + spacing: Theme.paddingSmall + + // Nome e fase: il tocco prolungato apre le azioni della + // macchina (stop ritardato, spegni, risveglia). + Item { + x: Theme.horizontalPageMargin + width: parent.width - 2 * Theme.horizontalPageMargin + height: Math.max(lamp.height, nameBox.height) + + Rectangle { + id: lamp + anchors.verticalCenter: parent.verticalCenter + width: Theme.itemSizeSmall / 2.2 + height: width + radius: width / 2 + color: Status.statusColor(api.statusLevelAt(index)) + + SequentialAnimation on opacity { + running: Status.isActive(api.statusLevelAt(index)) + loops: Animation.Infinite + PropertyAnimation { to: 0.35; duration: 900 } + PropertyAnimation { to: 1.0; duration: 900 } + } + } + + Column { + id: nameBox + anchors.left: lamp.right + anchors.leftMargin: Theme.paddingLarge + anchors.right: parent.right + anchors.verticalCenter: parent.verticalCenter + spacing: Theme.paddingTiny + + Label { + width: parent.width + truncationMode: TruncationMode.Fade + text: api.labelAt(index) + color: Theme.highlightColor + font.pixelSize: Theme.fontSizeMedium + } + + Label { + width: parent.width + truncationMode: TruncationMode.Fade + text: api.offlineAt(index) + ? qsTr("Not connected") + : api.phaseTextAt(index) + color: Theme.secondaryColor + font.pixelSize: Theme.fontSizeSmall + } + } + + MouseArea { + anchors.fill: parent + onPressAndHold: machineMenu.open(this) + } + } + + Label { + anchors.horizontalCenter: parent.horizontalCenter + visible: api.hasStateAt(index) + text: api.remainTextAt(index).length > 0 ? api.remainTextAt(index) : "--" + color: api.staleAt(index) ? "orange" : Theme.primaryColor + font.pixelSize: Theme.fontSizeHuge + } + + Label { + anchors.horizontalCenter: parent.horizontalCenter + visible: api.totalLineAt(index).length > 0 + text: api.totalLineAt(index) + color: Theme.secondaryColor + font.pixelSize: Theme.fontSizeSmall + } + + // Se la macchina non risponde o ha l'avvio a distanza + // spento, dirlo con le parole necessarie invece di lasciare + // un tasto che non funziona. + Label { + x: Theme.horizontalPageMargin + width: parent.width - 2 * Theme.horizontalPageMargin + wrapMode: Text.WordWrap + visible: api.hasStateAt(index) && !api.remoteEnabledAt(index) + color: Theme.secondaryColor + font.pixelSize: Theme.fontSizeExtraSmall + text: qsTr("To send commands, switch remote start on from the machine panel.") + } + + Label { + x: Theme.horizontalPageMargin + width: parent.width - 2 * Theme.horizontalPageMargin + wrapMode: Text.WordWrap + visible: api.offlineAt(index) + color: Theme.secondaryColor + font.pixelSize: Theme.fontSizeExtraSmall + text: qsTr("The washing machine is not connected (switched off or offline)") + } + + // UN comando per macchina, che cambia secondo il suo stato. + Button { + anchors.horizontalCenter: parent.horizontalCenter + width: parent.width - 2 * Theme.horizontalPageMargin + height: Theme.itemSizeMedium + visible: api.hasStateAt(index) + enabled: api.canCommandAt(index) && !api.busy + text: api.primaryLabelAt(index) + onClicked: api.runPrimaryAt(index) + } + + ContextMenu { + id: machineMenu + + MenuItem { + text: qsTr("Delayed stop…") + enabled: api.canCommandAt(index) + onClicked: pageStack.push(Qt.resolvedUrl("DelayDialog.qml"), + { "deviceIndex": index }) + } + MenuItem { + text: qsTr("Switch off") + enabled: api.canCommandAt(index) + onClicked: api.powerOffAt(index) + } + MenuItem { + text: qsTr("Wake the display up") + enabled: api.canCommandAt(index) + onClicked: api.wakeUpAt(index) + } + } + + Separator { + width: parent.width + color: Theme.secondaryHighlightColor + } } } - // --- tempo rimanente --- - Column { - width: parent.width - visible: api.configured - - Label { - x: Theme.horizontalPageMargin - width: parent.width - 2 * Theme.horizontalPageMargin - horizontalAlignment: Text.AlignHCenter - text: api.remainText.length > 0 ? api.remainText : "--" - color: api.stale ? "orange" : Theme.primaryColor - font.pixelSize: Theme.fontSizeHuge - } - - Label { - x: Theme.horizontalPageMargin - width: parent.width - 2 * Theme.horizontalPageMargin - horizontalAlignment: Text.AlignHCenter - visible: api.totalText.length > 0 - text: qsTr("of %1").arg(api.totalText) - color: Theme.secondaryColor - font.pixelSize: Theme.fontSizeSmall - } - } - - // --- righe informative --- - Column { - width: parent.width - visible: api.configured - spacing: Theme.paddingSmall - - DetailItem { - label: qsTr("Cycle") - value: api.cycleCount > 0 ? String(api.cycleCount) : "--" - } - - DetailItem { - label: qsTr("Remote start") - value: api.remoteEnabled ? qsTr("on") : qsTr("off") - } - } - - // Se il comando a distanza e' spento, dirlo con le parole necessarie - // invece di lasciare un tasto che non funziona. + // Chiave presente ma nessuna macchina: dirlo qui, non con una + // schermata vuota. Label { x: Theme.horizontalPageMargin width: parent.width - 2 * Theme.horizontalPageMargin - visible: api.configured && api.hasState && !api.remoteEnabled wrapMode: Text.WordWrap + visible: api.configured && api.deviceCount === 0 && !api.busy color: Theme.secondaryColor - font.pixelSize: Theme.fontSizeExtraSmall - text: qsTr("To send commands, switch remote start on from the machine panel.") - } - - // --- UN comando, che cambia secondo lo stato --- - Button { - id: primaryButton - anchors.horizontalCenter: parent.horizontalCenter - width: parent.width - 2 * Theme.horizontalPageMargin - height: Theme.itemSizeLarge - visible: api.configured - enabled: api.canCommand && !api.busy - text: api.primaryLabel - onClicked: api.runPrimary() + font.pixelSize: Theme.fontSizeSmall + text: qsTr("No machine found yet. Pull down to search again.") } BusyIndicator { diff --git a/qml/pages/SettingsPage.qml b/qml/pages/SettingsPage.qml index 2ed13fb..ecafa63 100644 --- a/qml/pages/SettingsPage.qml +++ b/qml/pages/SettingsPage.qml @@ -1,6 +1,8 @@ import QtQuick 2.2 import Sailfish.Silica 1.0 +// Impostazioni: la chiave, il paese, la lingua. Le macchine non si scelgono +// piu' qui: la schermata principale le mostra tutte. Page { id: page @@ -67,7 +69,16 @@ Page { } SectionHeader { - text: qsTr("Machine") + text: qsTr("Machines") + } + + Label { + x: Theme.horizontalPageMargin + width: parent.width - 2 * Theme.horizontalPageMargin + wrapMode: Text.WordWrap + color: Theme.secondaryColor + font.pixelSize: Theme.fontSizeSmall + text: qsTr("%1 found").arg(api.deviceCount) } Button { @@ -76,35 +87,6 @@ Page { onClicked: api.discover() } - ComboBox { - anchors.left: parent.left - anchors.right: parent.right - label: qsTr("Machine") - visible: api.deviceCount > 0 - currentIndex: api.selectedDevice - menu: ContextMenu { - Repeater { - model: api.deviceCount - MenuItem { - text: api.deviceLabels[index] - } - } - } - onCurrentIndexChanged: { - if (currentIndex >= 0 && currentIndex !== api.selectedDevice) - api.chooseDevice(currentIndex) - } - } - - Label { - x: Theme.horizontalPageMargin - width: parent.width - 2 * Theme.horizontalPageMargin - visible: appSettings.deviceAlias.length > 0 - color: Theme.secondaryColor - font.pixelSize: Theme.fontSizeExtraSmall - text: qsTr("Selected: %1").arg(appSettings.deviceAlias) - } - SectionHeader { text: qsTr("Language") } diff --git a/rpm/harbour-thinq.spec b/rpm/harbour-thinq.spec index 9685e88..827fbff 100644 --- a/rpm/harbour-thinq.spec +++ b/rpm/harbour-thinq.spec @@ -1,6 +1,6 @@ Name: harbour-thinq Summary: Control an LG ThinQ washing machine -Version: 0.1.2 +Version: 0.2.0 Release: 1 Group: Qt/Qt License: MIT @@ -26,6 +26,14 @@ ThinQ Connect cloud from the phone: no server in between. The access token is stored only on the device, in the app private configuration file. %changelog +* Mon Oct 12 2026 Carlo - 0.2.0-1 +- la schermata principale chiede la chiave una volta sola, poi mostra tutte le + macchine dell'account con lo stato di ciascuna +- avviso di sistema a fine lavaggio (anche se il ciclo e' finito mentre l'app + era chiusa) +- comandi per singola macchina: avvio/stop, spegnimento, risveglio, stop ritardato +- multilingua italiano/inglese + * Mon Oct 12 2026 Carlo - 0.1.2-1 - nome mostrato nel launcher: ThinQ diff --git a/scripts/fill_translations.py b/scripts/fill_translations.py index be45f5d..b84229a 100644 --- a/scripts/fill_translations.py +++ b/scripts/fill_translations.py @@ -53,6 +53,18 @@ IT = { "Language": "Lingua", "System": "Sistema", "Version %1": "Versione %1", + "My machines": "Le mie macchine", + "Updating…": "Aggiornamento…", + "%1 found": "%1 trovate", + "First setup": "Primo avvio", + "Connect": "Collega", + "Not connected": "Non collegata", + "No machine found yet. Pull down to search again.": + "Nessuna macchina trovata. Trascina in basso per cercare di nuovo.", + "Washing finished": "Lavaggio finito", + "Machines": "Macchine", + "The access token is missing": "Manca la chiave di accesso", + "No machine to command": "Nessuna macchina da comandare", "Washing machine": "Lavatrice", "Start": "Avvia", "Stop": "Ferma", diff --git a/src/main.cpp b/src/main.cpp index 9408cc9..9e50901 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -21,7 +21,7 @@ Q_DECL_EXPORT int main(int argc, char *argv[]) app->setOrganizationName(QStringLiteral("harbour")); app->setApplicationName(QStringLiteral("thinq")); - app->setApplicationVersion(QStringLiteral("0.1.2")); + app->setApplicationVersion(QStringLiteral("0.2.0")); Settings settings; ThinQClient api(&settings); @@ -34,7 +34,7 @@ Q_DECL_EXPORT int main(int argc, char *argv[]) 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__; + qDebug() << "harbour-thinq v0.2.0 build" << __DATE__ << __TIME__; view->rootContext()->setContextProperty(QStringLiteral("appSettings"), &settings); view->rootContext()->setContextProperty(QStringLiteral("api"), &api); diff --git a/src/settings.cpp b/src/settings.cpp index c25894c..6dcbbf8 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -104,3 +104,18 @@ void Settings::setLanguage(const QString &value) m_settings.sync(); emit languageChanged(); } + +int Settings::notifiedCycleFor(const QString &deviceId) const +{ + if (deviceId.isEmpty()) + return 0; + return m_settings.value(QStringLiteral("notified/") + deviceId, 0).toInt(); +} + +void Settings::setNotifiedCycleFor(const QString &deviceId, int cycle) +{ + if (deviceId.isEmpty() || cycle <= 0) + return; + m_settings.setValue(QStringLiteral("notified/") + deviceId, cycle); + m_settings.sync(); +} diff --git a/src/settings.h b/src/settings.h index fb8c872..821afa5 100644 --- a/src/settings.h +++ b/src/settings.h @@ -41,6 +41,12 @@ public: QString language() const { return m_language; } void setLanguage(const QString &value); + // Ciclo gia' avvisato per ciascuna macchina: serve a non ripetere l'avviso + // di fine lavaggio, e a recuperarlo se l'app era chiusa quando la macchina + // ha finito. + int notifiedCycleFor(const QString &deviceId) const; + void setNotifiedCycleFor(const QString &deviceId, int cycle); + signals: void tokenChanged(); void countryChanged(); diff --git a/src/thinqclient.cpp b/src/thinqclient.cpp index 2148e5c..21862e8 100644 --- a/src/thinqclient.cpp +++ b/src/thinqclient.cpp @@ -3,7 +3,6 @@ #include "settings.h" #include -#include #include #include #include @@ -27,72 +26,145 @@ ThinQClient::ThinQClient(Settings *settings, QObject *parent) , m_settings(settings) { m_pollTimer.setSingleShot(true); - // Una richiesta per volta: il timer riparte dopo ogni risposta (vedi scheduleNextPoll). + // Una macchina per volta: ogni risposta fa partire la richiesta successiva + // (pumpQueue), cosi' l'app non bombarda il cloud LG. 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(); + m_devices.clear(); + m_queue.clear(); + m_stateInFlight = false; + setBusy(false); + emit devicesChanged(); 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(); + return !m_settings->token().isEmpty(); } -QString ThinQClient::alias() const +int ThinQClient::activeIndex() const { - const QString a = m_settings->deviceAlias(); - return a.isEmpty() ? QCoreApplication::translate("ThinQ", "Washing machine") : a; + for (int i = 0; i < m_devices.size(); ++i) { + if (ThinQJson::statusLevel(m_devices.at(i).state) == 1) + return i; + } + for (int i = 0; i < m_devices.size(); ++i) { + if (m_devices.at(i).hasState) + return i; + } + return m_devices.isEmpty() ? -1 : 0; } -QString ThinQClient::phaseText() const +bool ThinQClient::validIndex(int index) const { - if (!m_state.valid) + return index >= 0 && index < m_devices.size(); +} + +QString ThinQClient::labelAt(int index) const +{ + if (!validIndex(index)) + return QString(); + const QString label = m_devices.at(index).label; + return label.isEmpty() + ? QCoreApplication::translate("ThinQ", "Washing machine") + : label; +} + +bool ThinQClient::hasStateAt(int index) const +{ + return validIndex(index) && m_devices.at(index).hasState; +} + +bool ThinQClient::offlineAt(int index) const +{ + return validIndex(index) && m_devices.at(index).offline; +} + +bool ThinQClient::staleAt(int index) const +{ + return validIndex(index) && m_devices.at(index).stale; +} + +QString ThinQClient::phaseTextAt(int index) const +{ + if (!hasStateAt(index)) return QCoreApplication::translate("ThinQ", "No data"); - return ThinQJson::phaseLabel(m_state); + return ThinQJson::phaseLabel(m_devices.at(index).state); } -int ThinQClient::statusLevel() const +int ThinQClient::statusLevelAt(int index) const { - return ThinQJson::statusLevel(m_state); + if (!validIndex(index)) + return -1; + return ThinQJson::statusLevel(m_devices.at(index).state); } -QString ThinQClient::remainText() const +QString ThinQClient::remainTextAt(int index) const { - return ThinQJson::durationText(m_state.remainMinutes); + if (!validIndex(index)) + return QString(); + return ThinQJson::durationText(m_devices.at(index).state.remainMinutes); } -QString ThinQClient::totalText() const +QString ThinQClient::totalTextAt(int index) const { - return ThinQJson::durationText(m_state.totalMinutes); + if (!validIndex(index)) + return QString(); + return ThinQJson::durationText(m_devices.at(index).state.totalMinutes); } -QString ThinQClient::primaryLabel() const +QString ThinQClient::totalLineAt(int index) const { - if (!m_state.valid) + const QString total = totalTextAt(index); + if (total.isEmpty()) + return QString(); + return QCoreApplication::translate("ThinQ", "of %1").arg(total); +} + +int ThinQClient::cycleCountAt(int index) const +{ + if (!validIndex(index)) + return 0; + return m_devices.at(index).state.cycleCount; +} + +bool ThinQClient::remoteEnabledAt(int index) const +{ + if (!hasStateAt(index)) + return false; + return m_devices.at(index).state.remoteEnabled; +} + +QString ThinQClient::primaryLabelAt(int index) const +{ + if (!hasStateAt(index)) return QCoreApplication::translate("ThinQ", "Start"); - return ThinQJson::primaryActionLabel(m_state); + return ThinQJson::primaryActionLabel(m_devices.at(index).state); } -bool ThinQClient::canCommand() const +bool ThinQClient::canCommandAt(int index) const { - return configured() && m_state.valid && m_state.remoteEnabled; + if (!hasStateAt(index)) + return false; + const DeviceEntry &e = m_devices.at(index); + return !e.offline && e.state.remoteEnabled; } -QString ThinQClient::updatedText() const +QString ThinQClient::updatedTextAt(int index) const { - return m_updated; + if (!validIndex(index)) + return QString(); + return m_devices.at(index).updated; +} + +QString ThinQClient::deviceIdAt(int index) const +{ + if (!validIndex(index)) + return QString(); + return m_devices.at(index).id; } void ThinQClient::setDelayHours(int hours) @@ -143,7 +215,11 @@ void ThinQClient::startPolling() { if (!configured()) return; - refresh(); + // Primo avvio con la chiave gia' salvata: prima le macchine, poi lo stato. + if (m_devices.isEmpty()) + discover(); + else + refresh(); if (!m_pollTimer.isActive()) { m_pollTimer.start(m_pollInterval); emit pollingChanged(); @@ -162,61 +238,90 @@ void ThinQClient::scheduleNextPoll() m_pollTimer.start(m_pollInterval); } +void ThinQClient::queueAllStates() +{ + m_queue.clear(); + for (int i = 0; i < m_devices.size(); ++i) + m_queue << i; +} + +void ThinQClient::pumpQueue() +{ + if (m_stateInFlight || !configured()) + return; + if (m_devices.isEmpty()) { + scheduleNextPoll(); + return; + } + if (m_queue.isEmpty()) { + scheduleNextPoll(); + return; + } + + const int index = m_queue.takeFirst(); + if (!validIndex(index)) { + pumpQueue(); + return; + } + + m_stateInFlight = true; + setBusy(true); + get(QStringLiteral("devices/%1/state").arg(m_devices.at(index).id), KindState, index); +} + void ThinQClient::refresh() { if (!configured()) return; - get(QStringLiteral("devices/%1/state").arg(m_settings->deviceId()), KindState); + if (m_devices.isEmpty()) { + discover(); + return; + } + queueAllStates(); + pumpQueue(); } void ThinQClient::discover() { - if (m_settings->token().isEmpty()) { + if (!configured()) { setNotice(QCoreApplication::translate("ThinQ", "Enter the access token first"), true); return; } get(QStringLiteral("devices"), KindDevices); } -void ThinQClient::chooseDevice(int index) +void ThinQClient::runPrimaryAt(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) { + if (!hasStateAt(index)) { 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))); + post(QStringLiteral("devices/%1/control").arg(m_devices.at(index).id), + ThinQJson::operationPayload(ThinQJson::primaryAction(m_devices.at(index).state)), index); } -void ThinQClient::powerOff() +void ThinQClient::powerOffAt(int index) { - post(QStringLiteral("devices/%1/control").arg(m_settings->deviceId()), - ThinQJson::operationPayload(QStringLiteral("POWER_OFF"))); + if (!validIndex(index)) + return; + post(QStringLiteral("devices/%1/control").arg(m_devices.at(index).id), + ThinQJson::operationPayload(QStringLiteral("POWER_OFF")), index); } -void ThinQClient::wakeUp() +void ThinQClient::wakeUpAt(int index) { - post(QStringLiteral("devices/%1/control").arg(m_settings->deviceId()), - ThinQJson::operationPayload(QStringLiteral("WAKE_UP"))); + if (!validIndex(index)) + return; + post(QStringLiteral("devices/%1/control").arg(m_devices.at(index).id), + ThinQJson::operationPayload(QStringLiteral("WAKE_UP")), index); } -void ThinQClient::sendDelay() +void ThinQClient::sendDelayAt(int index) { - post(QStringLiteral("devices/%1/control").arg(m_settings->deviceId()), - ThinQJson::delayPayload(m_delayHours)); + if (!validIndex(index)) + return; + post(QStringLiteral("devices/%1/control").arg(m_devices.at(index).id), + ThinQJson::delayPayload(m_delayHours), index); } void ThinQClient::prepare(QNetworkRequest &request, bool command) const @@ -237,13 +342,13 @@ void ThinQClient::prepare(QNetworkRequest &request, bool command) const request.setRawHeader("x-conditional-control", "true"); } -void ThinQClient::get(const QString &endpoint, RequestKind kind) +void ThinQClient::get(const QString &endpoint, RequestKind kind, int deviceIndex) { const QUrl url(ThinQJson::apiBase(m_settings->country()) + QLatin1Char('/') + endpoint); QNetworkRequest request(url); prepare(request, /*command=*/false); - if (kind == KindState || kind == KindCommand) + if (kind == KindDevices) setBusy(true); QNetworkReply *reply = m_nam.get(request); @@ -255,18 +360,23 @@ void ThinQClient::get(const QString &endpoint, RequestKind kind) connect(guard, &QTimer::timeout, reply, &QNetworkReply::abort); guard->start(kRequestTimeoutMs); - connect(reply, &QNetworkReply::finished, this, [this, reply, kind]() { + connect(reply, &QNetworkReply::finished, this, [this, reply, kind, deviceIndex]() { reply->deleteLater(); const QByteArray body = reply->readAll(); const int status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); if (kind == KindState) - setBusy(false); + m_stateInFlight = 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); + setBusy(false); + handleFailure(status, body, netErr, kind == KindCommand, deviceIndex); + if (kind == KindState) + pumpQueue(); // una macchina muta non blocca le altre + else + scheduleNextPoll(); return; } @@ -276,8 +386,8 @@ void ThinQClient::get(const QString &endpoint, RequestKind kind) : QJsonValue(doc.isArray() ? QJsonValue(doc.array()) : QJsonValue()); if (kind == KindDevices) { - m_deviceLabels.clear(); - m_deviceIds.clear(); + setBusy(false); + m_devices.clear(); const QJsonArray arr = response.toArray(); for (int i = 0; i < arr.size(); ++i) { const QJsonObject dev = arr.at(i).toObject(); @@ -287,43 +397,61 @@ void ThinQClient::get(const QString &endpoint, RequestKind kind) && !type.startsWith(QLatin1String("DEVICE_WASHCOMBO")) && !type.startsWith(QLatin1String("DEVICE_WASHTOWER")) && !type.startsWith(QLatin1String("DEVICE_DRYER"))) { - continue; // l'app controlla lavatrici e lavasciughe + continue; // questa app comanda 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(); + DeviceEntry entry; + entry.id = dev.value(QStringLiteral("deviceId")).toString(); + entry.label = info.value(QStringLiteral("alias")).toString(); + if (entry.label.isEmpty()) + entry.label = info.value(QStringLiteral("modelName")).toString(); + m_devices << entry; } - m_selected = m_deviceIds.indexOf(m_settings->deviceId()); emit devicesChanged(); - if (m_deviceLabels.isEmpty()) + if (m_devices.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); + scheduleNextPoll(); + } else { + setNotice(QCoreApplication::translate("ThinQ", "Machines found: %1").arg(m_devices.size()), false); + queueAllStates(); + pumpQueue(); + } return; } if (kind == KindState) { + setBusy(false); + if (!validIndex(deviceIndex)) { + pumpQueue(); + return; + } + const bool hadState = m_devices.at(deviceIndex).hasState; + const int previousLevel = hadState + ? ThinQJson::statusLevel(m_devices.at(deviceIndex).state) : -1; const QByteArray payload = QJsonDocument(response.toArray()).toJson(QJsonDocument::Compact); - applyState(ThinQJson::parseState(payload)); + applyState(deviceIndex, hadState, previousLevel, ThinQJson::parseState(payload)); + pumpQueue(); return; } // kind == KindCommand - m_pendingCommand = false; + setBusy(false); setNotice(QCoreApplication::translate("ThinQ", "Command sent"), false); refresh(); }); } -void ThinQClient::post(const QString &endpoint, const QString &payload) +void ThinQClient::post(const QString &endpoint, const QString &payload, int deviceIndex) { if (!configured()) { - setNotice(QCoreApplication::translate("ThinQ", "Set the access token and the machine first"), true); + setNotice(QCoreApplication::translate("ThinQ", "The access token is missing"), true); return; } - if (!m_state.valid || !m_state.remoteEnabled) { + if (!validIndex(deviceIndex)) { + setNotice(QCoreApplication::translate("ThinQ", "No machine to command"), true); + return; + } + const DeviceEntry &entry = m_devices.at(deviceIndex); + if (!entry.hasState || !entry.state.remoteEnabled) { setNotice(QCoreApplication::translate("ThinQ", "Remote start is off on the machine: switch it on from its panel"), true); return; } @@ -332,7 +460,6 @@ void ThinQClient::post(const QString &endpoint, const QString &payload) QNetworkRequest request(url); prepare(request, /*command=*/true); - m_pendingCommand = true; setBusy(true); QNetworkReply *reply = m_nam.post(request, payload.toUtf8()); @@ -341,7 +468,7 @@ void ThinQClient::post(const QString &endpoint, const QString &payload) connect(guard, &QTimer::timeout, reply, &QNetworkReply::abort); guard->start(kRequestTimeoutMs); - connect(reply, &QNetworkReply::finished, this, [this, reply]() { + connect(reply, &QNetworkReply::finished, this, [this, reply, deviceIndex]() { reply->deleteLater(); const QByteArray body = reply->readAll(); const int status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); @@ -350,7 +477,7 @@ void ThinQClient::post(const QString &endpoint, const QString &payload) if (reply->error() != QNetworkReply::NoError || status < 200 || status >= 300) { const QString netErr = reply->error() == QNetworkReply::NoError ? QString() : reply->errorString(); - handleFailure(status, body, netErr, true); + handleFailure(status, body, netErr, true, deviceIndex); return; } setNotice(QCoreApplication::translate("ThinQ", "Command sent"), false); @@ -358,20 +485,63 @@ void ThinQClient::post(const QString &endpoint, const QString &payload) }); } -void ThinQClient::applyState(const WasherState &state) +void ThinQClient::applyState(int deviceIndex, bool hadState, int previousLevel, + const WasherState &state) { - m_state = state; - m_stale = false; - m_updated = QCoreApplication::translate("ThinQ", "Updated at %1").arg( + if (!validIndex(deviceIndex)) + return; + + DeviceEntry &entry = m_devices[deviceIndex]; + entry.state = state; + entry.hasState = state.valid; + entry.offline = false; + entry.stale = false; + entry.updated = QCoreApplication::translate("ThinQ", "Updated at %1").arg( QLocale().toString(QTime::currentTime(), QLocale::ShortFormat)); + if (m_pollInterval != kPollFastMs) m_pollInterval = kPollFastMs; + emit stateChanged(); - scheduleNextPoll(); + noteFinished(deviceIndex, hadState, previousLevel); +} + +void ThinQClient::noteFinished(int deviceIndex, bool hadState, int previousLevel) +{ + if (!validIndex(deviceIndex)) + return; + + const DeviceEntry &entry = m_devices.at(deviceIndex); + const int level = ThinQJson::statusLevel(entry.state); + const int saved = m_settings->notifiedCycleFor(entry.id); + + if (level == 3) { + // Appena finito sotto i nostri occhi, oppure finito mentre l'app era + // chiusa (il numero di ciclo e' avanzato rispetto all'ultimo avvisato). + const bool justEnded = hadState && (previousLevel == 1 || previousLevel == 2); + const bool missedWhileClosed = saved > 0 && entry.state.cycleCount > saved; + + if (justEnded || missedWhileClosed) { + m_settings->setNotifiedCycleFor(entry.id, entry.state.cycleCount); + emit cycleFinished(entry.label, entry.state.cycleCount); + } else if (saved == 0) { + // Prima volta che vediamo questa macchina: si annota il ciclo senza + // avvisare, altrimenti al primo avvio scatterebbe un avviso per un + // lavaggio finito giorni fa. + m_settings->setNotifiedCycleFor(entry.id, entry.state.cycleCount); + } + return; + } + + // Ciclo in corso: si annota il numero, cosi' l'avviso scattera' solo se il + // ciclo finisce davvero. + if (saved == 0 && entry.state.cycleCount > 0) + m_settings->setNotifiedCycleFor(entry.id, entry.state.cycleCount); } void ThinQClient::handleFailure(int httpStatus, const QByteArray &body, - const QString &networkError, bool commandRequest) + const QString &networkError, bool commandRequest, + int deviceIndex) { QString code; QString message; @@ -385,13 +555,28 @@ void ThinQClient::handleFailure(int httpStatus, const QByteArray &body, qDebug() << "[thinq] errore LG" << httpStatus << code << message << (networkError.isEmpty() ? QString() : networkError); + // Macchina spenta o senza rete: si annota SULLA macchina, non sulla barra + // dei messaggi, altrimenti ogni giro di aggiornamento ripeterebbe lo + // stesso avviso. + if (!commandRequest && validIndex(deviceIndex) + && (code == QLatin1String("1222") || code == QLatin1String("1223") + || code == QLatin1String("1231") || code == QLatin1String("1209"))) { + DeviceEntry &entry = m_devices[deviceIndex]; + entry.offline = true; + entry.hasState = false; + entry.updated.clear(); + entry.stale = false; + emit stateChanged(); + return; + } + if (code == QLatin1String("1103") || code == QLatin1String("1218") - || code == QLatin1String("1302")) { + || code == QLatin1String("1302") || httpStatus == 401) { 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")) { + } else if (code == QLatin1String("1222") || code == QLatin1String("1223")) { 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); @@ -405,13 +590,10 @@ void ThinQClient::handleFailure(int httpStatus, const QByteArray &body, 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; + if (validIndex(deviceIndex) && m_devices.at(deviceIndex).hasState) { + m_devices[deviceIndex].stale = true; emit stateChanged(); } scheduleNextPoll(); diff --git a/src/thinqclient.h b/src/thinqclient.h index e2b1759..f60051f 100644 --- a/src/thinqclient.h +++ b/src/thinqclient.h @@ -1,6 +1,7 @@ #ifndef THINQCLIENT_H #define THINQCLIENT_H +#include #include #include #include @@ -11,66 +12,62 @@ 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. +// Tutte le macchine dell'account, ognuna col suo stato. Una sola classe parla +// col cloud LG: nessun ponte, nessun server di mezzo, nessun servizio. +// +// Il QML legge per indice (labelAt/phaseTextAt/...): l'elenco cambia raramente e +// cosi' le stesse funzioni servono la schermata principale e la copertina. 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(int deviceCount READ deviceCount NOTIFY devicesChanged) + Q_PROPERTY(int activeIndex READ activeIndex 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); + // La chiave di accesso c'e': la schermata principale mostra i dispositivi + // invece di chiedere le credenziali. 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; } + int deviceCount() const { return m_devices.size(); } + // La macchina che sta lavorando (per la copertina), altrimenti la prima. + int activeIndex() const; 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 QString labelAt(int index) const; + Q_INVOKABLE bool hasStateAt(int index) const; + Q_INVOKABLE bool offlineAt(int index) const; + Q_INVOKABLE bool staleAt(int index) const; + Q_INVOKABLE QString phaseTextAt(int index) const; + Q_INVOKABLE int statusLevelAt(int index) const; + Q_INVOKABLE QString remainTextAt(int index) const; + Q_INVOKABLE QString totalTextAt(int index) const; + Q_INVOKABLE QString totalLineAt(int index) const; + Q_INVOKABLE int cycleCountAt(int index) const; + Q_INVOKABLE bool remoteEnabledAt(int index) const; + Q_INVOKABLE QString primaryLabelAt(int index) const; + Q_INVOKABLE bool canCommandAt(int index) const; + Q_INVOKABLE QString updatedTextAt(int index) const; + Q_INVOKABLE QString deviceIdAt(int index) const; + Q_INVOKABLE bool validIndex(int index) const; + 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 runPrimaryAt(int index); + Q_INVOKABLE void powerOffAt(int index); + Q_INVOKABLE void wakeUpAt(int index); + Q_INVOKABLE void sendDelayAt(int index); Q_INVOKABLE void startPolling(); Q_INVOKABLE void stopPolling(); Q_INVOKABLE void clearNotice(); @@ -85,35 +82,47 @@ signals: void noticeChanged(); void devicesChanged(); void delayHoursChanged(); + // Fine di un lavaggio: la macchina e' arrivata a END. Il QML lo trasforma in + // una notifica di sistema. + void cycleFinished(const QString &label, int cycleCount); private: enum RequestKind { KindDevices, KindState, KindCommand }; + struct DeviceEntry { + QString id; + QString label; + WasherState state; + bool hasState = false; + bool offline = false; + bool stale = false; + QString updated; + }; + 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 get(const QString &endpoint, RequestKind kind, int deviceIndex = -1); + void post(const QString &endpoint, const QString &payload, int deviceIndex); + void applyState(int deviceIndex, bool hadState, int previousLevel, const WasherState &state); void handleFailure(int httpStatus, const QByteArray &body, const QString &networkError, - bool commandRequest); + bool commandRequest, int deviceIndex); void setNotice(const QString &text, bool isError); void setBusy(bool busy); void scheduleNextPoll(); + void queueAllStates(); + void pumpQueue(); + void noteFinished(int deviceIndex, bool hadState, int previousLevel); 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; + QList m_devices; + QList m_queue; // macchine da leggere, una richiesta per volta + bool m_stateInFlight = false; + int m_pollInterval = 45000; // a schermata aperta 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 diff --git a/tests/main.cpp b/tests/main.cpp index de07e35..1578c52 100644 --- a/tests/main.cpp +++ b/tests/main.cpp @@ -162,6 +162,26 @@ static void testItalian(const QString &catalog) checkEq(ThinQJson::primaryActionLabel(s), "Avvia", "tasto tradotto"); s.phase = QStringLiteral("PAUSE"); checkEq(ThinQJson::primaryActionLabel(s), "Riprendi", "riprendi tradotto"); + + // Le scritte delle schermate nuove (primo avvio, elenco, avviso): se una + // sfugge al catalogo, la si vede qui invece che sul telefono. + // ATTENZIONE al contesto: nelle pagine QML il contesto e' il NOME DEL FILE + // (MainPage, SettingsPage), non "ThinQ" come nel codice C++. + checkEq(QCoreApplication::translate("MainPage", "My machines"), "Le mie macchine", + "titolo tradotto"); + checkEq(QCoreApplication::translate("MainPage", "First setup"), "Primo avvio", + "primo avvio tradotto"); + checkEq(QCoreApplication::translate("MainPage", "Connect"), "Collega", "tasto collega tradotto"); + checkEq(QCoreApplication::translate("MainPage", "Not connected"), "Non collegata", + "macchina non collegata tradotta"); + checkEq(QCoreApplication::translate("SettingsPage", "Machines"), "Macchine", + "sezione macchine tradotta"); + checkEq(QCoreApplication::translate("MainPage", "%1 found").arg(2), "2 trovate", + "conteggio tradotto"); + checkEq(QCoreApplication::translate("harbour-thinq", "Washing finished"), "Lavaggio finito", + "avviso di fine lavaggio tradotto"); + checkEq(QCoreApplication::translate("ThinQ", "No machine to command"), + "Nessuna macchina da comandare", "comando senza macchina tradotto"); } int main(int argc, char *argv[]) diff --git a/translations/harbour-thinq-it.ts b/translations/harbour-thinq-it.ts index f3dc35f..5c0a2bf 100644 --- a/translations/harbour-thinq-it.ts +++ b/translations/harbour-thinq-it.ts @@ -1,298 +1,162 @@ - - ThinQ - - - Washing machine - Lavatrice - - - - No data - Nessun dato - - - - - Start - Avvia - - - - Enter the access token first - Inserisci prima la chiave di accesso - - - - Machine selected - Macchina scelta - - - - No data from the machine yet - Ancora nessun dato dalla macchina - - - - No washing machine found on this account - Nessuna lavatrice trovata su questo account - - - - Machines found: %1 - Macchine trovate: %1 - - - - - Command sent - Comando inviato - - - - Set the access token and the machine first - Imposta prima la chiave di accesso e la macchina - - - - - Remote start is off on the machine: switch it on from its panel - L'avvio a distanza e' spento sulla macchina: accendilo dal pannello - - - - Updated at %1 - Aggiornato alle %1 - - - - The access token is no longer valid: enter a new one in Settings - La chiave di accesso non e' piu' valida: inseriscine una nuova nelle Impostazioni - - - - Too many requests to LG: slowing down - Troppe richieste a LG: rallento gli aggiornamenti - - - - The washing machine is not connected (switched off or offline) - La lavatrice non e' collegata (spenta o senza rete) - - - - The machine does not accept this command - La macchina non accetta questo comando - - - - LG error %1: %2 - Errore LG %1: %2 - - - - No answer from the LG cloud: %1 - Nessuna risposta dal cloud LG: %1 - - - - The LG cloud refused the request (HTTP %1) - Il cloud LG ha rifiutato la richiesta (HTTP %1) - - - - Washing - In lavaggio - - - - Rinsing - In risciacquo - - - - Spinning - In centrifuga - - - - Drying - In asciugatura - - - - Cooling down - Raffreddamento - - - - Refreshing - Rinfrescando - - - - Steam softening - Ammorbidente a vapore - - - - Detecting the load - Rilevamento del carico - - - - Delayed start - Partenza ritardata - - - - Rinse hold - Ammollo - - - - Paused - In pausa - - - - Finished - Fine - - - - Ready - Pronta - - - - Off - Spenta - - - - Standby - In attesa - - - - Error - Errore - - - - Stop - Ferma - - - - Switch off - Spegni - - - - Resume - Riprendi - - CoverPage - + No data Nessun dato + Nessun dato DelayDialog - + Delayed stop Stop ritardato + Stop ritardato - + Set Imposta + Imposta - + The machine will stop on its own after the chosen time, then resume its programme. La macchina si ferma da sola allo scadere del tempo scelto, poi riprende il programma. + La macchina si ferma da sola allo scadere del tempo scelto, poi riprende il programma. MainPage - + Refresh Aggiorna + Aggiorna - + + My machines + Le mie macchine + + + + Updating… + Aggiornamento… + + + + %1 found + %1 trovate + + + + First setup + Primo avvio + + + + The access token comes from connect-pat.lgthinq.com and stays on this phone only. If LG starts refusing it, paste a new one here. + La chiave di accesso si crea su connect-pat.lgthinq.com e resta solo su questo telefono. Se LG non la accetta piu', incollane una nuova qui. + + + + Access token + Chiave di accesso + + + + paste the token + incolla la chiave + + + + Country code + Paese + + + + Connect + Collega + + + + Not connected + Non collegata + + + + The washing machine is not connected (switched off or offline) + La lavatrice non e' collegata (spenta o senza rete) + + + Delayed stop… Stop ritardato… + Stop ritardato… - + Switch off Spegni + Spegni - + Wake the display up Risveglia il display + Risveglia il display - - + + No machine found yet. Pull down to search again. + Nessuna macchina trovata. Trascina in basso per cercare di nuovo. + + + Settings Impostazioni + Impostazioni - Not up to date Non aggiornato - Not configured Da configurare - Enter the LG access token in Settings and pick your machine. Inserisci la chiave di accesso LG nelle Impostazioni e scegli la macchina. - of %1 su %1 - Cycle Ciclo - Remote start Avvio a distanza - on attivo - off spento - + To send commands, switch remote start on from the machine panel. Per inviare comandi, accendi l'avvio a distanza dal pannello della macchina. @@ -300,71 +164,338 @@ SettingsPage - + Settings Impostazioni + Impostazioni - + LG account Account LG + Account LG - + The access token comes from connect-pat.lgthinq.com and stays on this phone only. If LG starts refusing it, paste a new one here. La chiave di accesso si crea su connect-pat.lgthinq.com e resta solo su questo telefono. Se LG non la accetta piu', incollane una nuova qui. - + Access token Chiave di accesso + Chiave di accesso - + paste the token incolla la chiave + incolla la chiave - + Country code Paese + Paese - + Save the token Salva la chiave + Salva la chiave + + + + Machines + Macchine + + + + %1 found + %1 trovate - - Machine Macchina - + Find my machines Trova le macchine + Trova le macchine - Selected: %1 Scelta: %1 - - + + Language Lingua + Lingua - + System Sistema + Sistema - + Version %1 Versione %1 + Versione %1 + + + + ThinQ + + + Washing machine + Lavatrice + Lavatrice + + + + No data + Nessun dato + Nessun dato + + + + of %1 + su %1 + + + + + Start + Avvia + Avvia + + + + Enter the access token first + Inserisci prima la chiave di accesso + Inserisci prima la chiave di accesso + + + Machine selected + Macchina scelta + + + + No data from the machine yet + Ancora nessun dato dalla macchina + Ancora nessun dato dalla macchina + + + + No washing machine found on this account + Nessuna lavatrice trovata su questo account + Nessuna lavatrice trovata su questo account + + + + Machines found: %1 + Macchine trovate: %1 + Macchine trovate: %1 + + + + + Command sent + Comando inviato + Comando inviato + + + Set the access token and the machine first + Imposta prima la chiave di accesso e la macchina + + + + The access token is missing + Manca la chiave di accesso + + + + No machine to command + Nessuna macchina da comandare + + + + + Remote start is off on the machine: switch it on from its panel + L'avvio a distanza e' spento sulla macchina: accendilo dal pannello + + + + Updated at %1 + Aggiornato alle %1 + Aggiornato alle %1 + + + + The access token is no longer valid: enter a new one in Settings + La chiave di accesso non e' piu' valida: inseriscine una nuova nelle Impostazioni + + + + Too many requests to LG: slowing down + Troppe richieste a LG: rallento gli aggiornamenti + Troppe richieste a LG: rallento gli aggiornamenti + + + + The washing machine is not connected (switched off or offline) + La lavatrice non e' collegata (spenta o senza rete) + + + + The machine does not accept this command + La macchina non accetta questo comando + La macchina non accetta questo comando + + + + LG error %1: %2 + Errore LG %1: %2 + Errore LG %1: %2 + + + + No answer from the LG cloud: %1 + Nessuna risposta dal cloud LG: %1 + Nessuna risposta dal cloud LG: %1 + + + + The LG cloud refused the request (HTTP %1) + Il cloud LG ha rifiutato la richiesta (HTTP %1) + Il cloud LG ha rifiutato la richiesta (HTTP %1) + + + + Washing + In lavaggio + In lavaggio + + + + Rinsing + In risciacquo + In risciacquo + + + + Spinning + In centrifuga + In centrifuga + + + + Drying + In asciugatura + In asciugatura + + + + Cooling down + Raffreddamento + Raffreddamento + + + + Refreshing + Rinfrescando + Rinfrescando + + + + Steam softening + Ammorbidente a vapore + Ammorbidente a vapore + + + + Detecting the load + Rilevamento del carico + Rilevamento del carico + + + + Delayed start + Partenza ritardata + Partenza ritardata + + + + Rinse hold + Ammollo + Ammollo + + + + Paused + In pausa + In pausa + + + + Finished + Fine + Fine + + + + Ready + Pronta + Pronta + + + + Off + Spenta + Spenta + + + + Standby + In attesa + In attesa + + + + Error + Errore + Errore + + + + Stop + Ferma + Ferma + + + + Switch off + Spegni + Spegni + + + + Resume + Riprendi + Riprendi + + + + harbour-thinq + + + Washing finished + Lavaggio finito