Greg
Greg

Reputation: 8915

How to consume websocket apis in Python?

I would like to consume the following websocket weather api.

I tried adapting the following examples however I am not getting anywhere.

import asyncio
import websockets

async def hello():
    async with websockets.connect('ws://ws.weatherflow.com/swd/data') as websocket:

        await websocket.send({
          "type":"listen_start",
          "device_id":1110,
          "id":"2098388936"
        })

        greeting = await websocket.recv()
        print(greeting)

asyncio.get_event_loop().run_until_complete(hello())

How to consume websocket apis in Python? That is how to get the constant stream of weather information?

Upvotes: 1

Views: 2739

Answers (1)

Marcio Bernardo
Marcio Bernardo

Reputation: 66

It seems that the api_key parameter is missing:

From the SmartWeather documentation:

  • Websocket

    • Open a websocket connection
    • wss://ws.weatherflow.com/swd/data?api_key=20c70eae-e62f-4d3b-b3a4-8586e90f3ac8

    • Send a JSON message over the websocket connection to start listening for observations from the demo Device. After sending this message your connected websocket client sould receive a new observation JSON message every minute.

    • { "type":"listen_start", "device_id":1110, "id":"random-id-12345" }

I got it working with the following code:

import asyncio
import websockets

async def hello():
    async with websockets.connect('wss://swd.weatherflow.com/swd/data?api_key=20c70eae-e62f-4d3b-b3a4-8586e90f3ac8') as websocket:
        await websocket.send('{"type":"listen_start", "device_id":1110,"id": "2098388936"}')
        greeting = await websocket.recv()
        print(greeting)

asyncio.get_event_loop().run_until_complete(hello())

Note that according to the documentation, this API key is to get started quickly. Do not use this key in your application.

Upvotes: 5

Related Questions