Subscriptions via websockets in Orion

梦想的初衷 提交于 2019-12-24 17:43:43

问题


Is it possible to create a websockets subscription from a browser? We are using the branch feature/1181_websockets branch, git version 5ca6770aa401b52a31293fdcef4a9743fb1de2c4.

We made a PoC trying to subscribe a browser via websockets. We tried connecting some JS code running in the browser to the subscriptions url. The connection was established, but orion crashed when sending data from the client through the socket. Is this use case supported? Do you have a working example for it? The JS code:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>

    <button id="send" type="button" name="button">send</button>

    <script type="text/javascript">
      var payload = `{"description": "One subscription to rule them all",
        "subject": {
          "entities": [{
            "idPattern": ".*",
            "type": "Room"
          }],
          "condition": {
            "attrs": ["temperature"],
            "expression": {
              "q": "temperature>40"
            }
          }
        },
        "expires": "2016-04-05T14:00:00.00Z",
        "throttling": 5
      }`;

      var ws = new WebSocket('ws://orion-url:9010/v2/subscriptions', 'ngsiv2-json');

      var button = document.getElementById('send');
      button.addEventListener('click', function(event) {
        ws.send(payload)
      });

    </script>


  </body>
</html>

As an alternative, we tried to create a subscription using the REST API, asking Orion to notify us via websockets. We POSTed the following JSON:

    {
    "description": "One subscription to rule them all",
    "subject": {
    "entities": [
      {
        "idPattern": ".*",
        "type": "Room"
      }
    ],
    "condition": {
      "attributes": [
        "temperature"
      ],
      "expression": {
        "q": "temperature>40"
      }
    }
    },
    "notification": {
      "callback": "ws://my-websocket-listener:8081"
    },
    "expires": "2016-04-05T14:00:00.00Z",
    "throttling": 5
    }

The subscription process fails and Orion returns a 422 status code with the message:

    {
      "error": "BadRequest",
      "description": "Invalid URL"
    }

Did we make any mistake in the subscription request? Is this use case supported?

Thanks!


回答1:


Currently you can subscribe with your browser and receive notifications, the restriction are the following:

  1. From WS you can create a WS or REST subscription.
  2. From REST you cannot create a WS subscription.
  3. Only in the REST subscriptions you can specify the callback, in WS always must be "ws://". If you create a WS subscription the creator will be the receiver.
  4. WS subscription are deleted if a connection is closed.

Here I let a little code as example, you only need change the URL by your Orion's URL

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
        <script type="text/javascript">
            $(function() {
                window.WebSocket = window.WebSocket || window.MozWebSocket;
		// Here change with your URL
                var websocket = new WebSocket('ws://127.0.0.1:9010', 'ngsiv2-json');
                websocket.onopen = function () {
                    $('h1').css('color', 'green');
                };
                websocket.onerror = function () {
                    $('h1').css('color', 'red');
                };
                websocket.onmessage = function (message) {
                    console.log(message.data);
                    console.log(message);
                    $('div').append(message.data + '<br/>');
                };

                $('#send').click(function(e) {
                    e.preventDefault();
                    if ($('#txt').val().length > 0)
                    {
                        websocket.send($('#txt').val());
                        $('#txt').val('');
                    }
                });

                $('#new').click(function(e) {
                    e.preventDefault();
                    var msg = "{\"verb\":\"POST\",\"url\":\"/v2/entities\", \
                               \"params\":{\"options\":\"keyValues\"}, \
                               \"payload\":{\"type\":\"1\",\"id\":\"1\",\"temp\":1}}";

                    $('#txt').val(JSON.stringify(JSON.parse(msg), null, 2));
                });

                $('#upd').click(function(e) {
                    e.preventDefault();
                    var msg = "{\"verb\":\"POST\",\"url\":\"/v2/entities/1\", \
                                \"params\":{\"options\":\"keyValues\"},\"payload\":{\"temp\": 1}}";
                    $('#txt').val(JSON.stringify(JSON.parse(msg), null, 2));
                });

                $('#get').click(function(e) {
                    e.preventDefault();
                    var msg = "{\"verb\":\"GET\",\"url\":\"/v2/entities/1\"}";
                    $('#txt').val(JSON.stringify(JSON.parse(msg), null, 2));
                });

                $('#del').click(function(e) {
                    e.preventDefault();
                    var msg = "{\"verb\":\"DELETE\",\"url\":\"/v2/entities/1\"}";
                    $('#txt').val(JSON.stringify(JSON.parse(msg), null, 2));
                });

                $('#sub').click(function(e) {
                    e.preventDefault();
                    var msg = "{\"verb\":\"POST\",\"url\":\"/v2/subscriptions\", \
                                \"payload\":{\"description\":\"My subscription\", \
                                \"subject\":{\"entities\":[{\"id\":\"1\",\"type\":\"1\"}], \
                                \"condition\":{\"attributes\":[\"temp\"],\"expression\":{\"q\":\"temp>40\"}}}, \
                                \"notification\":{\"callback\":\"ws://\",\"attributes\":[\"temp\"], \
                                \"throttling\":5},\"expires\":\"2017-04-05T14:00:00.00Z\"}}";
                    $('#txt').val(JSON.stringify(JSON.parse(msg), null, 2));
                });
            });
        </script>
    </head>
    <body>
        <h1>WebSockets test</h1>
        <form>
            <table border="0">
            <tr>
                <td colspan="2">
                    <textarea rows="35" cols="70" id="txt"></textarea>
                </td>
            </tr>
            <tr>
                <td>
                    <button id="new">New</button>
                    <button id="upd">Update</button>
                    <button id="get">Show</button>
                    <button id="del">Delete</button>
                    <button id="sub">Subcription</button>
                </td>
                <td align="right">
                    <button id="send">Send</button>
                </td>
            </tr>
            </table>
        </form>
        <br/>
        <p>Server:</p>
        <div></div>
    </body>
</html>

I'm not a JS expert... but this work to me as a test when I work in the WS for Orion

Cheers



来源:https://stackoverflow.com/questions/37305740/subscriptions-via-websockets-in-orion

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!