home-assistant.io/source/developers/server_sent_events.markdown
2016-08-22 23:23:00 -07:00

2.4 KiB

layout, title, description, date, sidebar, comments, sharing, footer
layout title description date sidebar comments sharing footer
page Server-sent events Home Assistant Server-sent events documentation 2016-04-08 07:00 true false true true

The server-sent events feature is a one-way channel from your Home Assistant server to a client which is acting as a consumer. For bi-directional communication check the RESTful API and Python API.

The URI that is generating the data is /api/stream.

A requirement on the client-side is existing support for the EventSource interface.

There are various ways to access the stream. One is curl:

$ curl -X GET -H "x-ha-access: YOUR_PASSWORD" \
       -H "Content-Type: application/json" http://localhost:8123/api/stream

For more comfort put the HTML snippet below in a file sse.html in your www folder of your Home Assistant configuration directory (.homeassistant)

<!DOCTYPE html>
<html>
<body>
    <h1>Getting Home Assistant server events</h1>
    <div id="events"></div>
    <script type="text/javascript">
        var source = new EventSource("/api/stream?api_password=YOUR_PASSWORD");
        source.onmessage = function(event) {
            document.getElementById("events").innerHTML += event.data + "<br>";
        };
    </script>
</body>
</html>

Visit http://localhost:8123/local/sse.html to see the stream of events.

{% linkable_title Examples %}

A simplest way to consume server-sent events is httpie.

$ http --stream http://localhost:8123/api/stream x-ha-access:YOUR_PASSWORD content-type:application/json

{% linkable_title Website %}

The home-assistant-sse repository contains an more advanced example.

{% linkable_title Python %}

If you want test the server-sent events without creating a website then the Python module sseclient can help. Install it first:

$ pip3 install sseclient

The simplest script to consume the SSE looks like the following snipplet.

from sseclient import SSEClient

messages = SSEClient('http://localhost:8123/api/stream?api_password=YOUR_PASSWORD')
for msg in messages:
    print(msg)