Skip to content

Instantly share code, notes, and snippets.

@danielperna84
Last active April 10, 2018 17:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielperna84/83f6724ee3a646854c65451005684a4d to your computer and use it in GitHub Desktop.
Save danielperna84/83f6724ee3a646854c65451005684a4d to your computer and use it in GitHub Desktop.
Home Assistant HTML WebSocket API client with authentication
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="A web interface for Home Assistant with WebSocket">
<title>Home Assistant with WebSocket</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script src='http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>
<script type="text/javascript">
// https://www.home-assistant.io/developers/websocket_api/
// To be used when authentication is required
// Modification of https://raw.githubusercontent.com/home-assistant/home-assistant-dev-helper/master/ha-websocket.html
$(document).ready(function() {
function msg(str) {
$('#msg').prepend('<p>' + str + '</p>');
};
// Change this to match your HA instance. Use wss if you're using SSL.
ws = new WebSocket('ws://localhost:8123/api/websocket');
ws.addEventListener('open', function (event) {
var auth = {
type: "auth",
// Replace "secret" with your api_password
api_password: "secret"
}
var data = {
id: 1,
type: "subscribe_events",
//event_type: "state_changed",
}
ws.send(JSON.stringify(auth));
ws.send(JSON.stringify(data));
});
ws.onmessage = function(event) {
msg(event.data);
};
ws.onclose = function() {msg('Socket closed');};
ws.onopen = function() {msg('Connected...');};
});
</script>
</head>
<body>
<div class="container">
<div class="page-header">
<h1>Connection to Home Assistant over WebSocket</h1>
</div>
<div class="container-fluid" style="margin-top: 20px;">
<div class="panel panel-default">
<div class="panel-body">
<div id="msg"></div>
</div>
</div>
</div>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment