commit b5f6e79146f4bd39680c785e014731139b9d0d96 Author: Carlo Baratto Date: Mon Oct 12 12:03:23 2026 +0200 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 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0c1e635 --- /dev/null +++ b/.gitignore @@ -0,0 +1,18 @@ +# artefatti di build +build-*/ +build-tests/ +RPMS/ +*.o +moc_*.cpp +Makefile +*.tar.gz +*.rpm +.sfdk/ +harbour-thinq_it.qm + +# eseguibile copiato qui da una build e residui del pacchettizzatore +/harbour-thinq +documentation.list + +# file generati a mano / locali +*.bak diff --git a/README.md b/README.md new file mode 100644 index 0000000..8cea9aa --- /dev/null +++ b/README.md @@ -0,0 +1,80 @@ +# Bucato (harbour-thinq) + +App per Sailfish OS che controlla una lavatrice/lavasciuga **LG ThinQ** parlando +**direttamente con il cloud LG**: nessun ponte, nessun server di mezzo, nessuna +app di terze parti. Sul telefono restano solo la chiave di accesso e la scelta +della macchina. + +## Cosa fa + +- Mostra lo **stato** della macchina: fase in corso (in lavaggio, in risciacquo, + in centrifuga, **in asciugatura**, in pausa, fine, errore…), **tempo rimanente** + e tempo totale, numero di cicli, se l'avvio a distanza è attivo. +- **Un solo comando**, che cambia secondo lo stato: Avvia / Ferma / Riprendi / + Spegni. Niente tasti doppi, niente schermate che si contraddicono. +- **Stop ritardato** da 3 a 19 ore. +- Aggiornamento ogni 45 secondi mentre la schermata è aperta, con rallentamento + automatico se LG segnala troppe richieste. +- Interfaccia in **italiano e inglese**, copertina con stato e tempo residuo. +- **Nessun comando parte da solo**: i tasti li premi tu. + +## Cosa non fa (limiti della macchina, non dell'app) + +- **Non sceglie il programma**: questi modelli non espongono i programmi all'API. + Il ciclo si imposta sul pannello della lavatrice. +- **Non accende l'avvio a distanza**: è di sola lettura lato LG. Se è spento sulla + macchina, i comandi vengono rifiutati e l'app lo dice in chiaro. +- Niente notifica a telefono chiuso: l'app tiene aggiornato lo stato solo quando è + in primo piano (scelta esplicita, per non avere un servizio sempre attivo). + +## Configurazione (una volta sola) + +1. Creare una **chiave di accesso** (Personal Access Token) su + `https://connect-pat.lgthinq.com` con l'account LG ThinQ, abilitando tutte le + voci di permesso. +2. Nell'app: **Impostazioni** → incollare la chiave, paese `IT` → **Salva la chiave** + (parte anche la ricerca) → scegliere la macchina dall'elenco. + +La chiave resta nel file di configurazione privato dell'app +(`~/.config/harbour/thinq/thinq.conf`), non viene mai inviata altrove. + +## Installazione sul telefono + +``` +devel-su rpm -Uvh ~/Downloads/harbour-thinq.rpm +``` + +## Sviluppo + +- `src/thinqjson.*` — funzioni pure: lettura dello stato LG, etichette delle fasi, + azione giusta per ogni stato, indirizzi del cloud per paese, corpi dei comandi. +- `src/thinqclient.*` — rete (QNetworkAccessManager), intestazioni di + autenticazione, comandi, aggiornamento periodico e gestione degli errori LG. +- `qml/` — interfaccia Silica; `qml/js/status.js` tiene in un posto solo i colori + dello stato usati da Home e copertina. + +Verifiche senza kit Sailfish: + +``` +sh scripts/test-core.sh # 41 verifiche sul nucleo + catalogo italiano +python3 tests/qml_check_bindings.py qml +``` + +Compilazione (`sfdk`, SDK Sailfish): + +``` +cd ~/workspace/Carlo/AppSailfish && ./build-rpm.sh harbour-thinq +``` + +Pubblicazione dell'RPM a indirizzo fisso (link sempre valido): + +``` +sh scripts/publish-rpm.sh +``` + +## API di riferimento + +LG ThinQ Connect API (`https://api-.lgthinq.com`, Italia = `api-eic`): +`GET /devices`, `GET /devices/{id}/state`, `POST /devices/{id}/control` con +`Authorization: Bearer `, `x-country`, `x-client-id`, `x-message-id`. +Licenza: MIT. diff --git a/harbour-thinq.pro b/harbour-thinq.pro new file mode 100644 index 0000000..c4e90f6 --- /dev/null +++ b/harbour-thinq.pro @@ -0,0 +1,45 @@ +TEMPLATE = app +TARGET = harbour-thinq + +CONFIG += sailfishapp +CONFIG += c++11 + +# Il sailfishapp.prf del kit 5.1 NON aggiunge da solo gli include QtQuick/QtQml +QT += quick qml network + +SOURCES += \ + src/main.cpp \ + src/settings.cpp \ + src/translator.cpp \ + src/thinqjson.cpp \ + src/thinqclient.cpp + +HEADERS += \ + src/settings.h \ + src/translator.h \ + src/thinqjson.h \ + src/thinqclient.h + +OTHER_FILES += \ + qml/harbour-thinq.qml \ + qml/pages/*.qml \ + qml/cover/*.qml \ + rpm/harbour-thinq.spec \ + rpm/harbour-thinq.desktop \ + translations/harbour-thinq-it.ts + +DISTFILES += $$OTHER_FILES + +# Traduzioni: il .qm lo genera lo spec con lrelease (sailfishapp_i18n non e' +# affidabile sul kit 5.1). Stringhe sorgente in INGLESE. + +icons86.path = /usr/share/icons/hicolor/86x86/apps +icons86.files = $$PWD/icons/86x86/harbour-thinq.png +icons108.path = /usr/share/icons/hicolor/108x108/apps +icons108.files = $$PWD/icons/108x108/harbour-thinq.png +icons128.path = /usr/share/icons/hicolor/128x128/apps +icons128.files = $$PWD/icons/128x128/harbour-thinq.png +icons172.path = /usr/share/icons/hicolor/172x172/apps +icons172.files = $$PWD/icons/172x172/harbour-thinq.png + +INSTALLS += icons86 icons108 icons128 icons172 diff --git a/icons/108x108/harbour-thinq.png b/icons/108x108/harbour-thinq.png new file mode 100644 index 0000000..00a7be8 Binary files /dev/null and b/icons/108x108/harbour-thinq.png differ diff --git a/icons/128x128/harbour-thinq.png b/icons/128x128/harbour-thinq.png new file mode 100644 index 0000000..425e306 Binary files /dev/null and b/icons/128x128/harbour-thinq.png differ diff --git a/icons/172x172/harbour-thinq.png b/icons/172x172/harbour-thinq.png new file mode 100644 index 0000000..e8e505a Binary files /dev/null and b/icons/172x172/harbour-thinq.png differ diff --git a/icons/86x86/harbour-thinq.png b/icons/86x86/harbour-thinq.png new file mode 100644 index 0000000..9f10566 Binary files /dev/null and b/icons/86x86/harbour-thinq.png differ diff --git a/icons/make_icons.py b/icons/make_icons.py new file mode 100644 index 0000000..b95548b --- /dev/null +++ b/icons/make_icons.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Genera le icone dell'app nelle 4 dimensioni richieste da Sailfish. + +Uso: python3 icons/make_icons.py +Output: icons/x/harbour-thinq.png +""" +from pathlib import Path + +from PIL import Image, ImageDraw + +SIZES = (86, 108, 128, 172) +ROOT = Path(__file__).resolve().parent + + +def rounded(draw, box, radius, fill): + draw.rounded_rectangle(box, radius=radius, fill=fill) + + +def make_icon(size: int) -> Image.Image: + scale = 4 # si disegna grande e si riduce: bordi puliti a 86 px + s = size * scale + img = Image.new("RGBA", (s, s), (0, 0, 0, 0)) + d = ImageDraw.Draw(img) + + # sfondo: quadrato arrotondato, gradiente verticale azzurro -> blu + radius = int(s * 0.22) + for i in range(s): + t = i / max(1, s - 1) + r = int(0x5E + (0x0E - 0x5E) * t) + g = int(0xD2 + (0x6F - 0xD2) * t) + b = int(0xF0 + (0xA8 - 0xF0) * t) + d.line([(0, i), (s, i)], fill=(r, g, b, 255)) + mask = Image.new("L", (s, s), 0) + ImageDraw.Draw(mask).rounded_rectangle([0, 0, s - 1, s - 1], radius=radius, fill=255) + img.putalpha(mask) + + # corpo della lavatrice: rettangolo bianco con l'oblò + body = [int(s * 0.20), int(s * 0.18), int(s * 0.80), int(s * 0.84)] + rounded(d, body, int(s * 0.05), (255, 255, 255, 240)) + + # pannello dei comandi + panel_h = int(s * 0.09) + d.rectangle([body[0], body[1], body[2], body[1] + panel_h], fill=(210, 225, 235, 255)) + + # oblò: cerchio (anello scuro + acqua chiara) + cx = (body[0] + body[2]) // 2 + cy = int(s * 0.56) + r_out = int(s * 0.21) + d.ellipse([cx - r_out, cy - r_out, cx + r_out, cy + r_out], fill=(30, 70, 110, 255)) + r_in = int(r_out * 0.78) + d.ellipse([cx - r_in, cy - r_in, cx + r_in, cy + r_in], fill=(150, 210, 240, 255)) + # riflesso + d.ellipse([cx - int(r_in * 0.62), cy - int(r_in * 0.78), + cx - int(r_in * 0.05), cy - int(r_in * 0.18)], + fill=(255, 255, 255, 150)) + + return img.resize((size, size), Image.LANCZOS) + + +def main() -> None: + for size in SIZES: + out_dir = ROOT / f"{size}x{size}" + out_dir.mkdir(parents=True, exist_ok=True) + icon = make_icon(size) + icon.save(out_dir / "harbour-thinq.png") + print(f"scritta {out_dir / 'harbour-thinq.png'}") + + +if __name__ == "__main__": + main() diff --git a/qml/cover/CoverPage.qml b/qml/cover/CoverPage.qml new file mode 100644 index 0000000..550e843 --- /dev/null +++ b/qml/cover/CoverPage.qml @@ -0,0 +1,44 @@ +import QtQuick 2.2 +import Sailfish.Silica 1.0 +import "../js/status.js" as Status + +CoverBackground { + Column { + anchors.centerIn: parent + width: parent.width - 2 * Theme.paddingMedium + spacing: Theme.paddingSmall + + Rectangle { + anchors.horizontalCenter: parent.horizontalCenter + width: Theme.itemSizeSmall / 2.2 + height: width + radius: width / 2 + color: Status.statusColor(api.statusLevel) + } + + Label { + width: parent.width + horizontalAlignment: Text.AlignHCenter + elide: Text.ElideRight + color: Theme.primaryColor + font.pixelSize: Theme.fontSizeSmall + text: api.hasState ? api.phaseText : qsTr("No data") + } + + Label { + width: parent.width + horizontalAlignment: Text.AlignHCenter + visible: api.remainText.length > 0 + color: Theme.secondaryColor + font.pixelSize: Theme.fontSizeExtraSmall + text: api.remainText + } + } + + CoverActionList { + CoverAction { + iconSource: "image://theme/icon-cover-refresh" + onTriggered: api.refresh() + } + } +} diff --git a/qml/harbour-thinq.qml b/qml/harbour-thinq.qml new file mode 100644 index 0000000..1385b3f --- /dev/null +++ b/qml/harbour-thinq.qml @@ -0,0 +1,11 @@ +import QtQuick 2.2 +import Sailfish.Silica 1.0 +import "pages" +import "cover" + +ApplicationWindow +{ + initialPage: Component { MainPage { } } + cover: Component { CoverPage { } } + allowedOrientations: Orientation.All +} diff --git a/qml/js/status.js b/qml/js/status.js new file mode 100644 index 0000000..2eacd95 --- /dev/null +++ b/qml/js/status.js @@ -0,0 +1,23 @@ +// Livello di stato e colore corrispondente, in UN posto solo: la Home e la +// copertina devono raccontare la stessa cosa (due mappe = incoerenza). +// Livelli: -1 nessun dato, 0 spenta, 1 in corso, 2 in pausa, 3 finita, 4 errore. +// +// Colori letterali e non Theme.*: questo file e' importato sia dalle pagine sia +// dalla copertina e non deve dipendere da un .import di modulo. + +function statusColor(level) { + if (level === 4) + return "#d32f2f"; // errore + if (level === 3) + return "#1f7ae0"; // finita + if (level === 2) + return "#ffb300"; // in pausa + if (level === 1) + return "#4caf50"; // in corso + return "#8c8c8c"; // spenta o nessun dato +} + +// L'indicatore di attivita' pulsa solo quando c'e' qualcosa in corso. +function isActive(level) { + return level === 1; +} diff --git a/qml/pages/DelayDialog.qml b/qml/pages/DelayDialog.qml new file mode 100644 index 0000000..0df4ed5 --- /dev/null +++ b/qml/pages/DelayDialog.qml @@ -0,0 +1,54 @@ +import QtQuick 2.2 +import Sailfish.Silica 1.0 + +// Stop ritardato: 3-19 ore, gli unici valori che questa macchina accetta. +Dialog { + id: dialog + + property int hours: api.delayHours + + canAccept: true + + onAccepted: { + api.setDelayHours(hours) + api.sendDelay() + } + + Column { + width: parent.width + spacing: Theme.paddingMedium + + DialogHeader { + title: qsTr("Delayed stop") + acceptText: qsTr("Set") + } + + Label { + x: Theme.horizontalPageMargin + width: parent.width - 2 * Theme.horizontalPageMargin + wrapMode: Text.WordWrap + color: Theme.secondaryColor + font.pixelSize: Theme.fontSizeSmall + text: qsTr("The machine will stop on its own after the chosen time, then resume its programme.") + } + + Label { + x: Theme.horizontalPageMargin + width: parent.width - 2 * Theme.horizontalPageMargin + horizontalAlignment: Text.AlignHCenter + text: dialog.hours + " h" + color: Theme.highlightColor + font.pixelSize: Theme.fontSizeLarge + } + + Slider { + width: parent.width + minimumValue: 3 + maximumValue: 19 + stepSize: 1 + value: dialog.hours + valueText: value + " h" + onValueChanged: dialog.hours = Math.round(value) + } + } +} diff --git a/qml/pages/MainPage.qml b/qml/pages/MainPage.qml new file mode 100644 index 0000000..bec9bad --- /dev/null +++ b/qml/pages/MainPage.qml @@ -0,0 +1,220 @@ +import QtQuick 2.2 +import Sailfish.Silica 1.0 +import "../js/status.js" as Status + +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). + onStatusChanged: { + if (status === PageStatus.Active) + api.startPolling() + else + api.stopPolling() + } + + SilicaFlickable { + anchors.fill: parent + contentHeight: column.height + Theme.paddingLarge + + PullDownMenu { + MenuItem { + text: qsTr("Refresh") + 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")) + } + } + + Column { + id: column + width: parent.width + spacing: Theme.paddingMedium + + PageHeader { + title: api.alias + description: api.configured + ? (api.stale ? qsTr("Not up to date") : api.updatedText) + : qsTr("Not configured") + } + + // 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 { + width: parent.width + height: Theme.itemSizeLarge + visible: api.configured + + Rectangle { + id: lamp + x: Theme.horizontalPageMargin + anchors.verticalCenter: parent.verticalCenter + width: Theme.itemSizeSmall / 2.2 + height: width + radius: width / 2 + color: Status.statusColor(api.statusLevel) + + SequentialAnimation on opacity { + running: Status.isActive(api.statusLevel) + loops: Animation.Infinite + PropertyAnimation { to: 0.35; duration: 900 } + PropertyAnimation { to: 1.0; duration: 900 } + } + } + + 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 + } + } + + // --- 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. + Label { + x: Theme.horizontalPageMargin + width: parent.width - 2 * Theme.horizontalPageMargin + visible: api.configured && api.hasState && !api.remoteEnabled + wrapMode: Text.WordWrap + 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() + } + + BusyIndicator { + anchors.horizontalCenter: parent.horizontalCenter + size: BusyIndicatorSize.Small + running: api.busy + } + + Item { width: 1; height: Theme.paddingLarge } + } + + VerticalScrollDecorator { } + } + + // Banner dei messaggi: ancorato al bordo e di altezza fissa, cosi' non + // sposta ne' copre il contenuto. + Rectangle { + id: noticeBar + anchors.left: parent.left + anchors.right: parent.right + anchors.bottom: parent.bottom + height: api.notice.length > 0 ? Theme.itemSizeSmall : 0 + color: api.noticeIsError ? "#b3261e" : "#2e5d3a" + visible: height > 0 + + Label { + anchors.fill: parent + anchors.leftMargin: Theme.horizontalPageMargin + anchors.rightMargin: Theme.horizontalPageMargin + verticalAlignment: Text.AlignVCenter + elide: Text.ElideRight + color: "white" + font.pixelSize: Theme.fontSizeExtraSmall + text: api.notice + } + + MouseArea { + anchors.fill: parent + onClicked: api.clearNotice() + } + } +} diff --git a/qml/pages/SettingsPage.qml b/qml/pages/SettingsPage.qml new file mode 100644 index 0000000..2ed13fb --- /dev/null +++ b/qml/pages/SettingsPage.qml @@ -0,0 +1,142 @@ +import QtQuick 2.2 +import Sailfish.Silica 1.0 + +Page { + id: page + + property string tokenDraft: appSettings.token + + SilicaFlickable { + anchors.fill: parent + contentHeight: column.height + Theme.paddingLarge + + Column { + id: column + width: parent.width + spacing: Theme.paddingMedium + + PageHeader { + title: qsTr("Settings") + } + + SectionHeader { + text: qsTr("LG account") + } + + Label { + x: Theme.horizontalPageMargin + 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.") + } + + TextField { + id: tokenField + anchors.left: parent.left + anchors.right: parent.right + label: qsTr("Access token") + placeholderText: qsTr("paste the token") + echoMode: TextInput.Password + text: page.tokenDraft + onTextChanged: page.tokenDraft = text + } + + TextField { + id: countryField + anchors.left: parent.left + anchors.right: parent.right + label: qsTr("Country code") + placeholderText: "IT" + // Il valore si carica una volta: legarlo alla property farebbe + // riscrivere il campo sotto le dita (il codice paese viene + // normalizzato in maiuscolo). + onTextChanged: appSettings.country = text + Component.onCompleted: text = appSettings.country + } + + Button { + anchors.horizontalCenter: parent.horizontalCenter + text: qsTr("Save the token") + onClicked: { + appSettings.token = page.tokenDraft + api.reloadCredentials() + api.discover() + } + } + + SectionHeader { + text: qsTr("Machine") + } + + Button { + anchors.horizontalCenter: parent.horizontalCenter + text: qsTr("Find my machines") + 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") + } + + ComboBox { + anchors.left: parent.left + anchors.right: parent.right + label: qsTr("Language") + currentIndex: translator.language === "it" ? 2 : (translator.language === "en" ? 1 : 0) + menu: ContextMenu { + MenuItem { text: qsTr("System") } + MenuItem { text: "English" } + MenuItem { text: "Italiano" } + } + onCurrentIndexChanged: { + translator.language = currentIndex === 2 ? "it" + : (currentIndex === 1 ? "en" : "system") + } + } + + Label { + x: Theme.horizontalPageMargin + width: parent.width - 2 * Theme.horizontalPageMargin + horizontalAlignment: Text.AlignHCenter + color: Theme.secondaryColor + font.pixelSize: Theme.fontSizeExtraSmall + text: qsTr("Version %1").arg(appVersion) + } + + Item { width: 1; height: Theme.paddingLarge } + } + + VerticalScrollDecorator { } + } +} diff --git a/rpm/harbour-thinq.desktop b/rpm/harbour-thinq.desktop new file mode 100644 index 0000000..08e0c2c --- /dev/null +++ b/rpm/harbour-thinq.desktop @@ -0,0 +1,18 @@ +[Desktop Entry] +Name=ThinQ +Name[it_IT]=ThinQ +Comment=Control an LG ThinQ washing machine +Comment[it_IT]=Controlla una lavatrice LG ThinQ +Exec=harbour-thinq +Icon=harbour-thinq +Type=Application +X-Nemo-Application-Type=silica-qt5 +Categories=Utility; + +# Profilo SailJail esplicito: senza, la sandbox di Sailfish 5.x usa il profilo +# default, che nasconde ~/.config/harbour -> impostazioni non persistenti. +# Internet: l'app parla con il cloud LG ThinQ. +[X-Sailjail] +Permissions=Internet +OrganizationName=harbour +ApplicationName=thinq diff --git a/rpm/harbour-thinq.spec b/rpm/harbour-thinq.spec new file mode 100644 index 0000000..9685e88 --- /dev/null +++ b/rpm/harbour-thinq.spec @@ -0,0 +1,79 @@ +Name: harbour-thinq +Summary: Control an LG ThinQ washing machine +Version: 0.1.2 +Release: 1 +Group: Qt/Qt +License: MIT +URL: https://git.hackatoniclife.com/kaneda/harbour-thinq +Source0: %{name}-%{version}.tar.gz +Source1: %{name}.desktop + +Requires: sailfishsilica-qt5 >= 0.10.9 +BuildRequires: pkgconfig(sailfishapp) >= 1.0.2 +BuildRequires: pkgconfig(Qt5Core) +BuildRequires: pkgconfig(Qt5Qml) +BuildRequires: pkgconfig(Qt5Quick) +BuildRequires: pkgconfig(Qt5Network) +BuildRequires: qt5-qttools-linguist +BuildRequires: desktop-file-utils + +%global debug_package %{nil} + +%description +The app shows the state of an LG ThinQ washing machine and lets you start, +stop and power it off, with a delayed stop. It talks straight to the LG +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.1.2-1 +- nome mostrato nel launcher: ThinQ + +* Mon Oct 12 2026 Carlo - 0.1.1-1 +- intestazioni obbligatorie del cloud LG (api-key e service-phase): senza, ogni + richiesta tornava 401 con corpo vuoto e l'app non trovava le macchine +- la chiave incollata con spazi o ritorni a capo viene ripulita + +* Mon Oct 12 2026 Carlo - 0.1.0-1 +- prima release + +%prep +%setup -q -n %{name}-%{version} + +%build +%qmake5 +make %{?_smp_mflags} + +TS=$(find %{_builddir}/.. -maxdepth 4 -name '%{name}-it.ts' 2>/dev/null | head -1) +if [ -z "$TS" ]; then + echo "ERROR: %{name}-it.ts not found" >&2 + exit 1 +fi +lrelease "$TS" -qm %{_builddir}/%{name}_it.qm + +%install +make install INSTALL_ROOT=%{buildroot} +mkdir -p %{buildroot}%{_datadir}/applications + +DESKTOP=$(find %{_builddir}/.. -maxdepth 4 -name '%{name}.desktop' 2>/dev/null | head -1) +if [ -z "$DESKTOP" ] && [ -f %{SOURCE1} ]; then DESKTOP=%{SOURCE1}; fi +if [ -z "$DESKTOP" ]; then + echo "ERROR: %{name}.desktop not found" >&2 + exit 1 +fi +install -m 0644 "$DESKTOP" %{buildroot}%{_datadir}/applications/%{name}.desktop +desktop-file-validate %{buildroot}%{_datadir}/applications/%{name}.desktop || true + +mkdir -p %{buildroot}%{_datadir}/%{name}/translations +install -m 0644 %{_builddir}/%{name}_it.qm %{buildroot}%{_datadir}/%{name}/translations/ + +%files +%defattr(-,root,root,-) +%{_bindir}/%{name} +%{_datadir}/applications/%{name}.desktop +%{_datadir}/icons/hicolor/86x86/apps/%{name}.png +%{_datadir}/icons/hicolor/108x108/apps/%{name}.png +%{_datadir}/icons/hicolor/128x128/apps/%{name}.png +%{_datadir}/icons/hicolor/172x172/apps/%{name}.png +%{_datadir}/%{name}/qml +%{_datadir}/%{name}/translations/%{name}*.qm diff --git a/scripts/fill_translations.py b/scripts/fill_translations.py new file mode 100644 index 0000000..be45f5d --- /dev/null +++ b/scripts/fill_translations.py @@ -0,0 +1,146 @@ +#!/usr/bin/env python3 +"""Riempie il catalogo italiano di harbour-thinq. + +- aggiunge language="it_IT" all'intestazione (senza, lupdate non lo aggiorna piu'); +- sostituisce il blocco INTERO per ogni voce (mai solo il tag di + apertura: un edit parziale rompe il parse di lrelease). + +Uso: python3 scripts/fill_translations.py +""" +from __future__ import annotations + +import re +import sys +import xml.etree.ElementTree as ET +from pathlib import Path + +TS = Path(__file__).resolve().parent.parent / "translations" / "harbour-thinq-it.ts" + +IT = { + "No data": "Nessun dato", + "Delayed stop": "Stop ritardato", + "Delayed stop…": "Stop ritardato…", + "Set": "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.", + "Refresh": "Aggiorna", + "Switch off": "Spegni", + "Wake the display up": "Risveglia il display", + "Settings": "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.", + "LG account": "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", + "paste the token": "incolla la chiave", + "Country code": "Paese", + "Save the token": "Salva la chiave", + "Machine": "Macchina", + "Find my machines": "Trova le macchine", + "Selected: %1": "Scelta: %1", + "Language": "Lingua", + "System": "Sistema", + "Version %1": "Versione %1", + "Washing machine": "Lavatrice", + "Start": "Avvia", + "Stop": "Ferma", + "Resume": "Riprendi", + "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", +} + + +def main() -> int: + text = TS.read_text(encoding="utf-8") + + # language: senza, lupdate rifiuta di aggiornare il file in futuro. + if 'language="' not in text: + text = text.replace('', '', 1) + else: + text = re.sub(r'language="[^"]*"', 'language="it_IT"', text, count=1) + + missing: list[str] = [] + + def repl(match: re.Match) -> str: + block = match.group(0) + src = re.search(r"(.*?)", block, re.S) + if not src: + return block + source = src.group(1) + it = IT.get(source) + if it is None: + missing.append(source) + return block + # si sostituisce il blocco INTERO, non solo il tag + new_block = re.sub(r"", + f"{it}", block, flags=re.S) + if new_block == block: + new_block = block.replace("", + f" {it}\n ") + return new_block + + text = re.sub(r".*?", repl, text, flags=re.S) + TS.write_text(text, encoding="utf-8") + + # validazione XML: un edit a mano malformato ferma lrelease con messaggi oscuri + ET.parse(TS) + + if missing: + print(f"ATTENZIONE: {len(missing)} voci senza traduzione:", file=sys.stderr) + for m in missing: + print(" -", m, file=sys.stderr) + return 1 + + print("catalogo italiano completo e XML valido") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/publish-rpm.sh b/scripts/publish-rpm.sh new file mode 100644 index 0000000..d3ec316 --- /dev/null +++ b/scripts/publish-rpm.sh @@ -0,0 +1,65 @@ +#!/bin/sh +# Pubblica l'RPM di harbour-thinq su Nextcloud a un percorso FISSO, cosi' il +# link pubblico resta lo stesso ad ogni versione (l'utente lo scarica dal +# telefono con un tocco solo). +# +# Uso: sh scripts/publish-rpm.sh [percorso-rpm] +set -e + +APP=harbour-thinq +TOKEN=$(cat /home/kaneda/.hermes/profiles/carlo/skills/nextcloud-calendar/token.secret) +NC=https://nextcloud.hackatoniclife.com +DAV="$NC/remote.php/dav/files/carlo/ThinQ" +RPM_DIR=/home/kaneda/workspace/Carlo/AppSailfish/pacchetti/rpm-SailfishOS-5.1.0.11-aarch64 + +RPM=${1:-$(ls -t "$RPM_DIR"/$APP-*.aarch64.rpm 2>/dev/null | head -1)} +[ -f "$RPM" ] || { echo "RPM non trovato: $RPM" >&2; exit 1; } + +LOCAL_SHA=$(sha256sum "$RPM" | cut -d' ' -f1) +echo "RPM locale: $RPM" +echo "sha256 : $LOCAL_SHA" + +# cartella remota (MKCOL e' idempotente: 405 se esiste gia') +curl -s -o /dev/null -w "MKCOL %{http_code}\n" -u "carlo:$TOKEN" -X MKCOL "$DAV/" + +# upload: PUT sullo stesso percorso mantiene lo share esistente +curl -s -o /dev/null -w "PUT %{http_code}\n" -u "carlo:$TOKEN" \ + -T "$RPM" -H "Content-Type: application/x-rpm" "$DAV/$APP.rpm" + +# share pubblico: lo si riusa se esiste, altrimenti lo si crea (shareType=3) +SHARE=$(curl -s -u "carlo:$TOKEN" -H "OCS-APIRequest: true" \ + "$NC/ocs/v2.php/apps/files_sharing/api/v1/shares?path=/ThinQ/$APP.rpm&format=json") +TOK=$(printf '%s' "$SHARE" | python3 -c " +import json,sys +try: + d = json.load(sys.stdin) + items = d['ocs']['data'] + print(items[0]['token'] if items else '') +except Exception: + print('')") + +if [ -z "$TOK" ]; then + SHARE=$(curl -s -X POST "$NC/ocs/v2.php/apps/files_sharing/api/v1/shares" \ + -u "carlo:$TOKEN" -H "OCS-APIRequest: true" \ + -d "path=/ThinQ/$APP.rpm" -d "shareType=3" -d "permissions=1" -d "format=json") + TOK=$(printf '%s' "$SHARE" | python3 -c " +import json,sys +print(json.load(sys.stdin)['ocs']['data']['token'])") + echo "share creato" +else + echo "share riusato" +fi + +echo "link: $NC/s/$TOK" + +# verifica anonima: il download deve dare 200 e la STESSA impronta +curl -sL -o /tmp/$APP-check.rpm "$NC/s/$TOK/download" +curl -s -o /dev/null -w "pagina pubblica %{http_code}\n" "$NC/s/$TOK" +REMOTE_SHA=$(sha256sum /tmp/$APP-check.rpm | cut -d' ' -f1) +echo "sha256 scaricato: $REMOTE_SHA" +if [ "$LOCAL_SHA" = "$REMOTE_SHA" ]; then + echo "OK: il link serve la versione compilata" +else + echo "ATTENZIONE: impronte diverse" >&2 + exit 1 +fi diff --git a/scripts/test-core.sh b/scripts/test-core.sh new file mode 100755 index 0000000..1718efa --- /dev/null +++ b/scripts/test-core.sh @@ -0,0 +1,23 @@ +#!/bin/sh +# Banco di prova del nucleo, senza kit Sailfish: compila con il Qt 5.15 desktop +# e verifica parsing, comandi, indirizzi, durate e catalogo italiano. +set -e +cd "$(dirname "$0")/.." + +QT_BIN="$HOME/Qt/5.15.2/gcc_64/bin" +if [ ! -x "$QT_BIN/qmake" ]; then + QT_BIN="$HOME/.hermes/profiles/carlo/home/Qt/5.15.2/gcc_64/bin" +fi +PATH="$QT_BIN:$PATH" + +# Il catalogo: se non c'e' (o non e' aggiornato) lo si genera ora, cosi' il +# controllo delle traduzioni non e' mai un salto silenzioso. +lrelease translations/harbour-thinq-it.ts -qm /tmp/harbour-thinq_it.qm + +rm -rf build-tests +mkdir -p build-tests +cd build-tests +qmake ../tests/core_test.pro >/dev/null +make -j4 >/dev/null + +./core_test /tmp/harbour-thinq_it.qm diff --git a/src/main.cpp b/src/main.cpp new file mode 100644 index 0000000..9408cc9 --- /dev/null +++ b/src/main.cpp @@ -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 +#include +#include +#include +#include +#include + +#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(); +} diff --git a/src/settings.cpp b/src/settings.cpp new file mode 100644 index 0000000..c25894c --- /dev/null +++ b/src/settings.cpp @@ -0,0 +1,106 @@ +#include "settings.h" + +#include +#include +#include +#include + +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(); +} diff --git a/src/settings.h b/src/settings.h new file mode 100644 index 0000000..fb8c872 --- /dev/null +++ b/src/settings.h @@ -0,0 +1,61 @@ +#ifndef SETTINGS_H +#define SETTINGS_H + +#include +#include +#include + +// 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 diff --git a/src/thinqclient.cpp b/src/thinqclient.cpp new file mode 100644 index 0000000..2148e5c --- /dev/null +++ b/src/thinqclient.cpp @@ -0,0 +1,418 @@ +#include "thinqclient.h" + +#include "settings.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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(); +} diff --git a/src/thinqclient.h b/src/thinqclient.h new file mode 100644 index 0000000..e2b1759 --- /dev/null +++ b/src/thinqclient.h @@ -0,0 +1,119 @@ +#ifndef THINQCLIENT_H +#define THINQCLIENT_H + +#include +#include +#include +#include + +#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 diff --git a/src/thinqjson.cpp b/src/thinqjson.cpp new file mode 100644 index 0000000..4933512 --- /dev/null +++ b/src/thinqjson.cpp @@ -0,0 +1,204 @@ +#include "thinqjson.h" + +#include +#include +#include +#include +#include +#include +#include + +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 diff --git a/src/thinqjson.h b/src/thinqjson.h new file mode 100644 index 0000000..6695443 --- /dev/null +++ b/src/thinqjson.h @@ -0,0 +1,56 @@ +#ifndef THINQJSON_H +#define THINQJSON_H + +#include +#include + +// 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 diff --git a/src/translator.cpp b/src/translator.cpp new file mode 100644 index 0000000..5390d76 --- /dev/null +++ b/src/translator.cpp @@ -0,0 +1,73 @@ +#include "translator.h" + +#include "settings.h" + +#include +#include +#include +#include + +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 existing = app->findChildren(); + 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; + } +} diff --git a/src/translator.h b/src/translator.h new file mode 100644 index 0000000..ed26e87 --- /dev/null +++ b/src/translator.h @@ -0,0 +1,37 @@ +#ifndef TRANSLATOR_H +#define TRANSLATOR_H + +#include +#include + +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 diff --git a/tests/core_test.pro b/tests/core_test.pro new file mode 100644 index 0000000..dcb4351 --- /dev/null +++ b/tests/core_test.pro @@ -0,0 +1,18 @@ +QT += core +QT -= gui +CONFIG += console c++11 +CONFIG -= app_bundle + +TARGET = core_test +TEMPLATE = app + +INCLUDEPATH += $$PWD/../src + +SOURCES += \ + main.cpp \ + ../src/thinqjson.cpp + +# I propri .h vanno SEMPRE elencati: senza, il moc non parte e il link +# fallisce con "undefined reference to vtable". +HEADERS += \ + ../src/thinqjson.h diff --git a/tests/main.cpp b/tests/main.cpp new file mode 100644 index 0000000..de07e35 --- /dev/null +++ b/tests/main.cpp @@ -0,0 +1,180 @@ +// Banco di prova del nucleo: gira su desktop con Qt 5.15, senza kit Sailfish. +// Verifica il parsing sullo stato VERO di una lavasciuga LG e la coerenza dei +// comandi. Le asserzioni sulle stringhe sono scritte in inglese (lingua +// sorgente); con il catalogo italiano caricato si verifica anche la traduzione. +#include +#include +#include +#include +#include +#include +#include +#include + +#include "thinqjson.h" + +static int failures = 0; +static int checks = 0; + +static void check(bool condition, const QString &what, const QString &detail = QString()) +{ + ++checks; + if (condition) { + qInfo().noquote() << " ok " << what; + } else { + ++failures; + qWarning().noquote() << " FAIL " << what << (detail.isEmpty() ? QString() : "-> " + detail); + } +} + +static void checkEq(const QString &got, const QString &expected, const QString &what) +{ + check(got == expected, what, "got: " + got + " | atteso: " + expected); +} + +// Stato reale letto dalla lavasciuga (response di GET /devices/{id}/state). +static QByteArray realState() +{ + const QString json = QStringLiteral( + "[{\"runState\":{\"currentState\":\"DRYING\"}," + "\"remoteControlEnable\":{\"remoteControlEnabled\":true}," + "\"timer\":{\"remainHour\":1,\"remainMinute\":54,\"relativeHourToStop\":0," + "\"relativeMinuteToStop\":0,\"totalHour\":4,\"totalMinute\":47}," + "\"cycle\":{\"cycleCount\":4}," + "\"location\":{\"locationName\":\"MAIN\"}}]"); + return json.toUtf8(); +} + +static void testParsing() +{ + qInfo() << "== parsing dello stato reale =="; + const WasherState s = ThinQJson::parseState(realState()); + check(s.valid, "stato valido"); + checkEq(s.phase, "DRYING", "fase"); + check(s.remainMinutes == 114, "tempo rimanente 114 min", QString::number(s.remainMinutes)); + check(s.totalMinutes == 287, "tempo totale 287 min", QString::number(s.totalMinutes)); + check(s.cycleCount == 4, "quarto ciclo", QString::number(s.cycleCount)); + check(s.remoteEnabled, "comando a distanza attivo"); + check(s.running(), "considerata in corso"); + + qInfo() << "== casi limite =="; + const WasherState empty = ThinQJson::parseState("[]"); + check(!empty.valid, "risposta vuota -> nessun dato"); + const WasherState junk = ThinQJson::parseState("{\"errore\":true}"); + check(!junk.valid, "json non riconosciuto -> nessun dato"); + + // La posizione MAIN va scelta anche quando non e' la prima della lista. + const QByteArray twoLocations = QStringLiteral( + "[{\"runState\":{\"currentState\":\"END\"},\"location\":{\"locationName\":\"MINI\"}}," + "{\"runState\":{\"currentState\":\"RUNNING\"},\"location\":{\"locationName\":\"MAIN\"}}]") + .toUtf8(); + checkEq(ThinQJson::parseState(twoLocations).phase, "RUNNING", "sceglie la posizione MAIN"); +} + +static void testCommands() +{ + qInfo() << "== comandi =="; + WasherState s; + s.valid = true; + + s.phase = QStringLiteral("DRYING"); + checkEq(ThinQJson::primaryAction(s), "STOP", "in asciugatura si ferma"); + check(ThinQJson::statusLevel(s) == 1, "livello 1 (in corso)"); + checkEq(ThinQJson::primaryActionLabel(s), "Stop", "etichetta Stop"); + + s.phase = QStringLiteral("END"); + checkEq(ThinQJson::primaryAction(s), "START", "a fine ciclo si avvia"); + check(ThinQJson::statusLevel(s) == 3, "livello 3 (finita)"); + + s.phase = QStringLiteral("PAUSE"); + checkEq(ThinQJson::primaryActionLabel(s), "Resume", "in pausa si riprende"); + check(ThinQJson::statusLevel(s) == 2, "livello 2 (in pausa)"); + + s.phase = QStringLiteral("ERROR"); + checkEq(ThinQJson::primaryAction(s), "POWER_OFF", "in errore si spegne"); + check(ThinQJson::statusLevel(s) == 4, "livello 4 (errore)"); + + s.phase = QStringLiteral("POWER_OFF"); + check(ThinQJson::statusLevel(s) == 0, "livello 0 (spenta)"); + + checkEq(ThinQJson::operationPayload("START"), + "{\"operation\":{\"washerOperationMode\":\"START\"}}", "corpo del comando avvio"); + checkEq(ThinQJson::operationPayload("POWER_OFF"), + "{\"operation\":{\"washerOperationMode\":\"POWER_OFF\"}}", "corpo dello spegnimento"); + checkEq(ThinQJson::delayPayload(5), "{\"timer\":{\"relativeHourToStop\":5}}", + "corpo dello stop ritardato"); +} + +static void testCloud() +{ + qInfo() << "== indirizzi del cloud =="; + checkEq(ThinQJson::regionFor("IT"), "eic", "Italia -> eic"); + checkEq(ThinQJson::regionFor("it"), "eic", "paese minuscolo"); + checkEq(ThinQJson::regionFor("US"), "aic", "Stati Uniti -> aic"); + checkEq(ThinQJson::regionFor("KR"), "kic", "Corea -> kic"); + checkEq(ThinQJson::regionFor("XX"), "kic", "paese sconosciuto -> kic"); + checkEq(ThinQJson::regionFor(""), "eic", "paese vuoto -> eic (Europa)"); + checkEq(ThinQJson::apiBase("IT"), "https://api-eic.lgthinq.com", "indirizzo per l'Italia"); + + const QString id = ThinQJson::messageId(); + check(id.length() == 22, "message-id di 22 caratteri", QString::number(id.length())); + check(!id.contains(QLatin1Char('=')), "message-id senza riempimento"); + check(id != ThinQJson::messageId(), "message-id diversi ad ogni chiamata"); + + // Senza queste due intestazioni il cloud LG risponde 401 con corpo vuoto: + // e' stato il difetto che impediva all'app di trovare le macchine. + checkEq(ThinQJson::servicePhase(), "OP", "x-service-phase"); + check(ThinQJson::apiKey().length() == 40, "x-api-key di 40 caratteri", + QString::number(ThinQJson::apiKey().length())); + check(!ThinQJson::apiKey().contains(QLatin1Char(' ')), "x-api-key senza spazi"); +} + +static void testDurations() +{ + qInfo() << "== durate =="; + checkEq(ThinQJson::durationText(114), "1 h 54 min", "1 h 54 min"); + checkEq(ThinQJson::durationText(60), "1 h", "un'ora esatta"); + checkEq(ThinQJson::durationText(45), "45 min", "solo minuti"); + checkEq(ThinQJson::durationText(0), "", "zero -> vuoto"); +} + +static void testItalian(const QString &catalog) +{ + qInfo() << "== catalogo italiano =="; + if (catalog.isEmpty()) { + qWarning() << " SALTO: nessun .qm passato come argomento"; + return; + } + QTranslator tr; + if (!tr.load(catalog)) { + ++failures; + qWarning() << " FAIL impossibile caricare" << catalog; + return; + } + QCoreApplication::installTranslator(&tr); + + WasherState s; + s.valid = true; + s.phase = QStringLiteral("DRYING"); + checkEq(ThinQJson::phaseLabel(s), "In asciugatura", "fase tradotta"); + s.phase = QStringLiteral("END"); + checkEq(ThinQJson::phaseLabel(s), "Fine", "fine tradotta"); + checkEq(ThinQJson::primaryActionLabel(s), "Avvia", "tasto tradotto"); + s.phase = QStringLiteral("PAUSE"); + checkEq(ThinQJson::primaryActionLabel(s), "Riprendi", "riprendi tradotto"); +} + +int main(int argc, char *argv[]) +{ + QCoreApplication app(argc, argv); + const QString catalog = argc > 1 ? QString::fromLocal8Bit(argv[1]) : QString(); + + testParsing(); + testCommands(); + testCloud(); + testDurations(); + testItalian(catalog); + + qInfo().noquote() << QString("\n%1 verifiche, %2 fallite").arg(checks).arg(failures); + return failures == 0 ? 0 : 1; +} diff --git a/tests/qml_check_bindings.py b/tests/qml_check_bindings.py new file mode 100644 index 0000000..27b97af --- /dev/null +++ b/tests/qml_check_bindings.py @@ -0,0 +1,123 @@ +#!/usr/bin/env python3 +"""Assegnazioni duplicate di proprieta' negli stessi oggetti QML. + +Perche' esiste: in Qt 5.6 assegnare due volte la stessa proprieta' di un oggetto +QML (tipico: due `Component.onCompleted` nella stessa pagina) non e' un errore +innocuo: il file compila con un warning "Property value set multiple times" e +l'oggetto NON si crea piu'. Dall'esterno si vede solo + + harbour-.qml:9:30: Type MainPage unavailable + +cioe' l'app che si apre senza la pagina iniziale, senza dire il perche'. +`qmllint` conosce il QML ma non il significato di questi binding, e il kit Silica +non vede niente: la guardia sta qui e gira in pochi millisecondi. + +Validato su harbour-aira: intercetta il commit che aveva il bug (1 duplicato, +riga 298) e dichiara pulito l'albero corretto. Copiare in `tests/` del progetto +ed eseguire prima di ogni build che l'utente fara' girare sul device. + +Uso: + python3 qml_check_bindings.py [cartella_qml] # default: qml + python3 qml_check_bindings.py --dettagli # elenca anche l'ok +Esce 1 se trova duplicati, 0 se e' pulito. +""" + +import pathlib +import re +import sys + +# Riga che apre un oggetto QML: un componente (maiuscola) oppure un gruppo di +# proprieta' noto. Il corpo di un gestore (onClicked:) o di una funzione e' JS, +# e li' dentro i "duplicati" sono normali (ternari, oggetti letterali, rami). +APRE_OGGETTO = re.compile(r"^\s*([A-Z][A-Za-z0-9_]*)\s*\{") +APRE_GRUPPO = re.compile(r"^\s*(anchors|font|Layout\.[A-Za-z]+)\s*\{") +APRE_JS = re.compile(r"^\s*(function\s+\w+|if\b|else\b|for\b|while\b|switch\b|do\b|try\b|catch\b)\s*[{(]") +APRE_GESTORE = re.compile(r"^\s*on[A-Z][A-Za-z0-9_]*\s*:") + +PROPRIETA = re.compile( + r"^\s*((?:readonly\s+)?property\s+\S+\s+([A-Za-z_]\w*)" + r"|signal\s+(\w+)|function\s+(\w+)|([A-Za-z_][\w.]*))\s*:") +SENZA_COMMENTO = re.compile(r"//.*$") + + +def chiave(riga: str): + """Nome della proprieta' assegnata dalla riga, o None.""" + m = PROPRIETA.match(SENZA_COMMENTO.sub("", riga)) + if not m: + return None + return m.group(2) or m.group(3) or m.group(4) or m.group(5) + + +def controlla(testo: str): + """Ritorna la lista di (riga, chiave) duplicate nello stesso oggetto.""" + pila = [("qml", {})] # (tipo ambiente, chiavi viste) + problemi = [] + for numero, riga in enumerate(testo.splitlines(), 1): + pulita = SENZA_COMMENTO.sub("", riga) + if not pulita.strip(): + continue + + # Chiusura: si esce dall'ambiente corrente. + while pulita.strip().startswith("}") and len(pila) > 1: + pila.pop() + pulita = pulita.strip()[1:] + if not pulita.strip(): + break + if not pulita.strip(): + continue + + ambiente, chiavi = pila[-1] + if ambiente == "qml": + k = chiave(pulita) + if k: + if k in chiavi: + problemi.append((numero, k)) + else: + chiavi[k] = numero + + # Apertura di un nuovo ambiente: il contenuto e' QML solo se la riga + # apre un oggetto o un gruppo; gestori e funzioni aprono JS. + apre_js = bool(APRE_JS.match(pulita)) or bool(APRE_GESTORE.match(pulita)) + apre_qml = (bool(APRE_OGGETTO.match(pulita)) or bool(APRE_GRUPPO.match(pulita))) \ + and not apre_js + # Una proprieta' il cui valore e' un oggetto letterale JS non e' QML. + if ":" in pulita and "{" in pulita and not apre_qml and not apre_js: + apre_js = True + if pulita.count("{") > pulita.count("}"): + pila.append(("qml" if apre_qml else "js", {})) + return problemi + + +def main(argv): + argomenti = [a for a in argv[1:] if not a.startswith("--")] + radice = pathlib.Path(argomenti[0] if argomenti else "qml") + dettagli = "--dettagli" in argv + + file_qml = sorted(radice.rglob("*.qml")) + if not file_qml: + print("nessun file QML in", radice) + return 1 + + totale = 0 + for percorso in file_qml: + problemi = controlla(percorso.read_text(encoding="utf-8")) + relative = percorso.relative_to(radice.parent if radice.name == "qml" else radice) + if problemi: + totale += len(problemi) + print("%s: %d assegnazioni duplicate" % (relative, len(problemi))) + for numero, k in problemi: + print(" riga %d: '%s' gia' assegnata in questo oggetto" % (numero, k)) + elif dettagli: + print("%s: pulito" % relative) + + print("---") + if totale: + print("ESITO: %d assegnazioni duplicate (l'oggetto non si crea: " + "vedi Qt 5.6, 'Property value set multiple times')" % totale) + return 1 + print("ESITO: nessuna assegnazione duplicata in %d file" % len(file_qml)) + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv)) diff --git a/translations/harbour-thinq-it.ts b/translations/harbour-thinq-it.ts new file mode 100644 index 0000000..f3dc35f --- /dev/null +++ b/translations/harbour-thinq-it.ts @@ -0,0 +1,370 @@ + + + + + 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 + + + + DelayDialog + + + Delayed stop + Stop ritardato + + + + Set + 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. + + + + MainPage + + + Refresh + Aggiorna + + + + Delayed stop… + Stop ritardato… + + + + Switch off + Spegni + + + + Wake the display up + Risveglia il display + + + + + Settings + 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. + + + + SettingsPage + + + Settings + Impostazioni + + + + LG account + 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 + + + + paste the token + incolla la chiave + + + + Country code + Paese + + + + Save the token + Salva la chiave + + + + + Machine + Macchina + + + + Find my machines + Trova le macchine + + + + Selected: %1 + Scelta: %1 + + + + + Language + Lingua + + + + System + Sistema + + + + Version %1 + Versione %1 + + +