(10.01.2023, 10:52)admin Wrote: Use updated user.websocket library attached to this post.
Change token / homeId as needed. Add object updates at line 78. Use grp.checkupdate or grp.checkwrite so that LM is not overloaded with unnecessary duplicate values.
Code:ws = require('user.websocket')
json = require('json')
http = require('socket.http')
ltn12 = require('ltn12')
token = '12345'
payload = json.encode({ query = '{viewer { websocketSubscriptionUrl } }' })
res = http.request({
url = 'https://api.tibber.com/v1-beta/gql',
method = 'POST',
headers = {
['Authorization'] = 'Bearer ' .. token,
['Content-Type'] = 'application/json',
['Content-Length'] = #payload,
},
source = ltn12.source.string(payload),
})
res = json.pdecode(res)
if type(res) == 'table' and res.data then
url = res.data.viewer.websocketSubscriptionUrl
client, err = ws.client('sync', 30)
client.protocol = 'graphql-transport-ws'
res, err = client:connect(url)
query = [[
subscription {
liveMeasurement(homeId: "a-b-c-d") {
timestamp
power
accumulatedConsumption
accumulatedCost
currency
minPower
averagePower
maxPower
}
}
]]
else
res = nil
end
if res then
res, err = client:send(json.encode({
type = 'connection_init',
payload = {
token = token
}
}))
client:receive()
ts, tu = os.microtime()
res, err = client:send(json.encode({
id = ts .. '-' .. tu,
type = 'subscribe',
payload = {
query = query
}
}))
while true do
data, opcode, _, _, err = client:receive()
if data then
if opcode == ws.PING then
client:send(data, ws.PONG)
elseif opcode == ws.TEXT then
data = json.pdecode(data)
if type(data) == 'table' then
-- update objects here
end
end
else
log('receive failed: ' .. tostring(err))
break
end
end
else
log('connection failed: ' .. tostring(err))
end
if client then
client:close()
client = nil
end
Hi, the new websocket.lua (or the new GraphQL transport protocol) seem to create a much more unstable connection than before. I get "Websocket receive failed: closed" 3-4 times per minute and I need to restart the resident script every 10 minute. Are the timeouts too short? Response code is 1006. I hope there will be a more stable approach to this
![Smile Smile](https://forum.logicmachine.net/images/smilies/smile.png)