refactor: Optimize initialization

This commit is contained in:
Krzysztof 2024-07-20 13:13:34 +02:00
parent b6619680ab
commit 75b666d141
3 changed files with 11 additions and 23 deletions

View File

@ -11,6 +11,7 @@ BaseObject {
property var getServices: ws.getServices
property var getStates: ws.getStates
property string errorString: ""
readonly property alias ready: ws.ready
readonly property bool configured: ws.url && token
onBaseUrlChanged: ws.url = baseUrl.replace('http', 'ws') + "/api/websocket"
@ -19,17 +20,7 @@ BaseObject {
Connections {
target: ws
function onError(msg) { errorString = msg }
function onEstablished() { errorString = "" }
}
readonly property QtObject ready: QtObject {
function connect (fn) {
if (ws.ready) fn()
ws.established.connect(fn)
}
function disconnect (fn) {
ws.established.disconnect(fn)
}
function onReadyChanged() { ws.ready && (errorString = "") }
}
Timer {
@ -59,11 +50,9 @@ BaseObject {
property var subscriptions: new Map()
property var promises: new Map()
readonly property bool open: status === WebSocket.Open
signal established
signal error(string msg)
onOpenChanged: ready = false
onReadyChanged: ready && established()
onTextMessageReceived: message => {
pingPongTimer.reset()

View File

@ -108,7 +108,7 @@ KCM.ScrollViewKCM {
Component.onCompleted: {
setItems(cfg_items)
ha = ClientFactory.getClient(this, plasmoid.configuration.url)
ha.ready.connect(fetchData)
ha.readyChanged.connect(fetchData)
}
function setItems(data) {
@ -116,6 +116,7 @@ KCM.ScrollViewKCM {
}
function fetchData() {
if (!ha?.ready) return
return Promise.all([ha.getStates(), ha.getServices()])
.then(([e, s]) => {
entities = arrayToObject(e, 'entity_id')

View File

@ -27,7 +27,8 @@ PlasmoidItem {
property var fields: ({})
onCfgItemsChanged: items = JSON.parse(cfgItems)
onUrlChanged: url && initClient(url)
onUrlChanged: initClient(url)
onItemsChanged: fetchDataAndSubscribe()
Plasmoid.contextualActions: [
PlasmaCore.Action {
@ -44,19 +45,16 @@ PlasmoidItem {
function initClient(url) {
if (ha) {
unsubscribe()
ha.ready.disconnect(initData)
onItemsChanged.disconnect(fetchDataAndSubscribe)
ha.readyChanged.disconnect(fetchDataAndSubscribe)
}
ha = ClientFactory.getClient(this, url)
ha.ready.connect(initData)
}
function initData() {
if (!url) return ha = null
ha = ClientFactory.getClient(root, url)
fetchDataAndSubscribe()
onItemsChanged.connect(fetchDataAndSubscribe)
ha.readyChanged.connect(fetchDataAndSubscribe)
}
function fetchDataAndSubscribe() {
if (!ha?.ready) return
fetchFieldsInfo()
subscribe()
}