xref: /openbmc/phosphor-rest-server/module/obmc/wsgi/examples/websockets/client_simple.html (revision 8cc1a034b264d8771648840f3bc57f07ccad72fa)
1<!DOCTYPE html>
2<html>
3<head>
4  <script type="text/javascript">
5    // This simple example subscribes, via websocket, to certain events occurring
6    // on the BMC. Specfically, it's interested in an d-bus events (object
7    // creations, property changes), occurring in the d-bus namespaces
8    // /xyz/openbmc_project/logging and /xyz/openbmc_project/sensors. It's also
9    // interested in the interfaces xyz.openbmc_project.Logging.Entry and
10    // xyz.openbmc_project.Sensor.Value being added, or property changes to
11    // these interfaces.
12
13    // Login to the BMC.
14    var xhr = new XMLHttpRequest();
15    xhr.open("POST", "https://<BMC IP>/login", true);
16    // Set 'withCredentials' to be able to send back login session cookie.
17    xhr.withCredentials = true;
18    xhr.setRequestHeader("Content-type", "application/json");
19    xhr.send(JSON.stringify({data: ["<username>", "<password>"]}));
20
21    // Open a new secure websocket. The rest server on the BMC
22    // only supports the /subscribe route with websockets as of now.
23    var ws = new WebSocket("wss://<BMC IP>/subscribe");
24    // Send in array of d-bus paths and interfaces of interest over the
25    // websocket. Either/both of them can be an empty array. The arrays
26    // need to be sent in a JSON dictionary.
27    // Client will be notified of events occurring on these paths and/or
28    // interfaces.
29    var data = JSON.stringify(
30        {
31            "paths": ["/xyz/openbmc_project/logging",
32                      "/xyz/openbmc_project/sensors"],
33            "interfaces": ["xyz.openbmc_project.Logging.Entry",
34                           "xyz.openbmc_project.Sensor.Value"]
35        });
36    ws.onopen = function() {
37        // Send the JSON dictionary
38        ws.send(data);
39    };
40    ws.onmessage = function (evt) {
41        // Received a message on the websocket, the response is a JSON dict.
42        var response = JSON.parse(evt.data);
43        for (var key in response) {
44            if (response.hasOwnProperty(key)) {
45                var value = response[key];
46                if ("path" == key) {
47                    // If the d-bus path is in the response, let's do a GET on
48                    // that path.
49                    var xhr = new XMLHttpRequest();
50                    xhr.withCredentials = true;
51                    var url = "https://<BMC IP>" + value;
52                    xhr.open("GET", url, true);
53                    xhr.setRequestHeader("Content-type", "application/json");
54                    xhr.send();
55                }
56            }
57        }
58    };
59  </script>
60</head>
61</html>
62