Websocket API v2 Example Using JavaScript

Posted on
Sat Mar 11, 2023 9:32 am
DaveL17 offline
User avatar
Posts: 6759
Joined: Aug 20, 2013
Location: Chicago, IL, USA

Websocket API v2 Example Using JavaScript

I was doing some digital housekeeping and ran across this file that folks might find helpful. It works on a local LAN (with an update to the IP address); further modification would be needed to run it through the Indigo Reflector service (and would need to be updated to use secure Websockets). It opens a connection to the Websocket API device feed and prints the feed messages to the browser window. To modify the script to view the Log Feed, just change the URL from device-feed to log-feed.

Code: Select all
('ws://10.0.1.123:8176/v2/api/ws/device-feed') --> ('ws://10.0.1.123:8176/v2/api/ws/log-feed')
There's also a command message example that's commented out, which would obviously need to be changed to a valid device ID. The command message is only run once (when the socket connection is first established). Not particularly useful to send a command this way (and it'll only work if you're attached to the device feed), but it shows how the traffic flow works for command messages.

Save the code to a file called "whatever.html" and -- using a plain text editor -- change the URL to point to your Indigo Server IP (10.0.1.123:8176, 127.0.0.1:8176, or localhost:8176), and open it with a browser.

Code: Select all
<!DOCTYPE html>

<html>
<head>
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script>
    device_feed = new WebSocket('ws://10.0.1.123:8176/v2/api/ws/device-feed');

    device_feed.onopen = (event) => {
      console.log('socket open');
 
//       let command = {
//         "message": "indigo.device.toggle",
//         "objectId": 12345678,
//       };
//
//       console.log('sending command');
//       device_feed.send(JSON.stringify(command));
    };
   
    device_feed.onmessage = (event) => {
      console.log("device feed message received");
      document.getElementById('output').append(`device feed message received:\n ${event.data}\n\n`);
    };
    </script>
</head>
<body>

   <pre id="output"></pre>
   
</body>
</html>
<style>
  html {
    background: rgb(75, 75, 75);
    color: white;
  }
</style>


Screenshot 2023-03-11 at 9.16.51 AM.png
Screenshot 2023-03-11 at 9.16.51 AM.png (97.83 KiB) Viewed 578 times

I came here to drink milk and kick ass....and I've just finished my milk.

[My Plugins] - [My Forums]

Page 1 of 1

Who is online

Users browsing this forum: No registered users and 9 guests