As a component you might have information that you want to make available to the frontend. For example, the media player will want to make album covers available for the frontend to show. Our frontend is communicating with the backend over the websocket API, which can be extended with custom commands.
Registering a command (Python)
To register a command, you need to have a message type, a message schema and a message handler. Your component does not have to add the websocket API as a dependency. You register your command, and if the user is using the websocket API, the command will be made available.
Message types are made up the domain and the message type, separated by a forward slash. In the below example, we're defining
The message schema defines what type of data we expect when the message is invoked. It is defined as a voluptuous schema and has to extend the base web socket command schema.
Defining a handler
Message handlers are callback functions that are run inside the event loop. If you want to do I/O or have to wait for your result, create a new function and queue it up using
hass.async_add_job. This is done so that the websocket API can get back to handling the next message as soon as possible.
Sending a direct response
If you are defining a command that is querying simple information, you might be able to fulfill the request while the handler is being called by the websocket API. To do this, use
Sending a delayed response
If your command needs to interact with the network, a device or needs to compute information, you will need to queue a job to do the work and send the response. To do this, use
Registering with the Websocket API
With all pieces defined, it's time to register the command. This is done inside your setup method.
hass object which holds the WebSocket connection to the backend. Then just call
hass.connection.sendMessagePromise. This will return a promise that will resolve if the command succeeds and errors if the command fails.
If your command is not sending a response, you can use