GuidesChangelog

Using UDP sinks for traffic data retrieval

When you need traffic data, sometimes using the query-response dynamic of the REST API is not ideal. That's where UDP sinks come in.

The introductory article explains the concept of REST and UDP sinks. REST sinks require applications to periodically send requests to the server to get the current data. Sometimes, however, this form of communication isn’t desirable, like with traffic light controllers which require current updates as fast as possible or aren’t able to send frequent data requests. UDP sinks offer an alternative thanks to their usage of the UDP protocol: Subscribe to a sink once and get a zone's status updates until the subscription expires.

After assigning a UDP sink to an operator, any authorized client application can start communicating with the server via UDP datagrams, whose payloads are JSON objects. At this moment, UDP communication doesn't use any form of authentication. The UDP server listens on the port 55570 by default. You can change this in the Block settings in FLOW Insights.

When creating UDP sinks, make sure that their names are unique across all analytics.

There are three types of UDP sinks: Zone state sink, Category count sink, and Object list sink.

Zone state sink

This sink is subscription-based and provides information about the object presence and sensor state of a corresponding zone.

A typical procedure for your application would be to subscribe to a FLOW server with a ZoneStateSubscribe message and then wait for ZoneStatePush messages. Immediately after subscription, the server sends Push messages for all active sinks - one Push message per sink per UDP datagram. Then until the subscription timeout expires, the server automatically sends Push messages for sinks whose state has changed. Another ZoneStateSubscribe message with the same destination IP address and port will reset the subscription timer.

Apart from that, a device may request extended data from a zone state sink by sending the ZoneExtendedStateRequest. Afterward, a response from all zone state sinks specified in the request is generated - one response per sink per UDP datagram.

ZoneStateSubscribe

  • Direction: To server
  • Example payload:
{
  "ZoneStateSubscribe": {
    "DestinationIpAddress": "192.168.11.1",
    "DestinationPort": 4444,
    "SubscriptionTimeout_s": 10,
    "Options": [ "IdList" ]
  }
}

Description:

  • The message contains an IP address and port of the device that should receive ZoneStatePush messages for the duration of the timeout.
  • The Options array is optional. If it contains the IdList string, then all ZoneStatePush responses will contain the IdList, IdListStartTimestamp, and IdListEndTimestamp properties.

ZoneStatePush

  • Direction: From server to the address specified by the ZoneStateSubscribe message
  • Example payload:
{
  "ZoneStatePush": {
        "Id": "z001",
        "Failure": false,
        "FailureState": "NoFailure",
        "Presence": true,
        "IdList": [ 
          "3", "1", "6", "7", "4", "5", //...
         ],
         "IdListStartTimestamp":"1650541963538",
         "IdListEndTimestamp": "1650542571179"
  }
}

Description:

  • Id - the identifier of the corresponding sink
  • Failure - denotes whether there is a failure within a sensor watching the zone
  • Presence - denotes whether there is a traffic object within the zone
  • FailureState - a string describing the failure state, can have the following values:
    • NoFailure
    • SensorFailure - failure of the camera, sensor, or another internal component
    • CommunicationFailure
    • ConfigurationFailure - invalid configuration, e.g. the corresponding zone doesn’t exist
    • EnvironmentalInterference - e.g. camera blinded by the Sun, reflections on the road, fog, darkness, frost
    • SensorCalibration - the system is still initializing and cannot provide detection data yet
  • IdList - present only if requested in the ZoneStateSubscribe message. Contains IDs of all traffic objects passed by the operator to which the sink is attached.
  • IdListStartTimestamp - present only if requested in the ZoneStateSubscribe message. It's the timestamp (in milliseconds since epoch) of the earliest point that FLOW's trajectory cache includes. This is equivalent to the cache_start_timestamp value in the analytics info response. Trajectory caching is explained in another article.
  • IdListEndTimestamp - present only if requested in the ZoneStateSubscribe message. It's the timestamp of the last analytics evaluation.

ZoneExtendedStateRequest

  • Direction: To server
  • Example payload:
{
  "ZoneExtendedStateRequest": {
    "Sinks": [ "z001", "z002" ]
  }
}

Description:

  • Sinks - an array of strings denoting which sinks’ extended data the sender wants to receive

ZoneExtendedState

  • Direction: From server to the request sender
  • Example payload:
{
  "ZoneExtendedState": {
    "Id": "z002",
    "VehicleCount": 24,
}

Description:

  • Id - the identifier of the corresponding sink
  • VehicleCount - number of vehicles in the zone
  • The ZoneExtendedState object may actually have more properties, but their values will always be invalid, so it's safe to ignore them.

Category count sink

This sink provides data from a continuous counter of trajectories sorted into categories. The counter resets only when the underlying integer data type overflows. Data from this sink is obtained by requesting them. After sending one request, a response from all Category Count Sinks is generated - one response per sink per UDP datagram.

CategoryCountRequest

  • Direction: To server
  • Payload:
{
  "CategoryCountRequest": {}
}

CategoryCount

  • Direction: From server to the request sender
  • Example payload:
    Raw trajectories UDP
{
  "CategoryCount": {
    "Id": "m1",
       
    "CategoryCounts": [
      {
        "Category": "car",
        "Count": 10
      },
      {
        "Category": "pedestrian",
        "Count": 21
      }
    ]
  }
}

Description:

  • Id - the identifier of the corresponding sink
  • Category - a string containing the name of the category, to which the Count relates. Can have one of the following values: car, light, heavy, bus, motorcycle, bicycle, pedestrian, unknown

Object list sink

This sink is subscription-based and provides detailed information about the objects passed by the attached operator.

Its usage is similar to the Zone state sink: Subscribe to the server with the ObjectListSubscribe message and then wait for ObjectList messages. Immediately after subscription, the server sends ObjectList messages for all active sinks — one ObjectList message per sink per UDP datagram. Then until the subscription timeout expires, the server automatically sends ObjectList messages with every evaluation tick. Another ObjectListSubscribe message with the same destination IP address and port will reset the subscription timer.

ObjectListSubscribe

  • Direction: To server
  • Example payload:
{
  "ObjectListSubscribe": {
    "DestinationIpAddress": "192.168.11.1",
    "DestinationPort": 4444,
    "SubscriptionTimeout_s": 10
  }
}
  • Description: The message contains an IP address and port of the device that should receive ObjectList messages for the duration of the timeout.

ObjectList

  • Direction: From server to the address specified by the ObjectListSubscribe message
  • If one sink would output more than 150 trajectories, the response will be split into several parts — one part per UDP datagram.
  • Example payload of datagram #1:
{
   "ObjectList":{
      "AnalyticsId":0,
      "CubeId":3,
      "SinkId":29,
      "EvaluationTimestamp":"1649336808104",
      "Id":"Speed - Object list",
      "Part":1,
      "TotalParts":2,
      "Units":{
         "Duration":"ms",
         "EvaluationTimestamp":"ms",
         "MapPositions":"m",
         "MapSpeeds":"m/s",
         "SensorPositions":"px",
         "Timestamp":"ms",
         "Timestamps":"ms",
         "WGS84Positions":"deg"
      },
      "Objects":[
         {
            "Color":"grey",
            "Duration":20121,
            "Id":"408",
            "LicensePlate":"Undefined",
            "Timestamp":"1649336736729",
            "Category":"car",
            "StateData":{
               "MapPositions":[
                  [ 615951.5, 5453970.5 ]
               ],
               "MapSpeeds":[
                  0.8981415033340454
               ],
               "SensorPositions":[
                  [ 346, 171 ]
               ],
               "Timestamps":[
                  19987
               ],
               "WGS84Positions":[
                  [ 16.592578435480117, 49.2275322860502 ]
               ]
            }
         },
         {
            "Color":"black",
            "Duration":10745,
            "Id":"409",
            "LicensePlate":"Undefined",
            "Timestamp":"1649336738364",
            "Category":"car",
            "StateData":{
               "MapPositions":[
                  [ 615658.5625, 5453908.5 ]
               ],
               "MapSpeeds":[
                  0.8486315033387354
               ],
               "SensorPositions":[
                  [ 1990, 23 ]
               ],
               "Timestamps":[
                  10644
               ],
               "WGS84Positions":[
                  [ 16.588538726126316, 49.227030185075115 ]
               ]
            }
         }
         // ...
      ]
   }
}
  • Example payload of datagram #2:
{
   "ObjectList":{
      "AnalyticsId":0,
      "CubeId":3,
      "SinkId":29,
      "EvaluationTimestamp":"1649336808104",
      "Id":"Speed - Object list",
      "Part":2,
      "TotalParts":2,
      "Units":{
         "Duration":"ms",
         "EvaluationTimestamp":"ms",
         "MapPositions":"m",
         "MapSpeeds":"m/s",
         "SensorPositions":"px",
         "Timestamp":"ms",
         "Timestamps":"ms",
         "WGS84Positions":"deg"
      },
      "Objects":[
         // ...
      ]
   }
}

Description:

  • CubeId - the identifier of the cube that the sink corresponds to
  • AnalyticsId - the identifier of the analytics that the sink corresponds to
  • SinkId - the identifier of the sink
  • EvaluationTimestamp - the timestamp of when this result's analytics evaluation took place
  • If one sink would output more than 150 trajectories, the response will be split into several parts — one part per UDP datagram. This is FLOW's mechanism called JSON fragmentation. In this example, the response has been split into two parts. The part number is indicated by the Part property. Indexing starts from 1. TotalParts indicates how many parts belong to the sink in total for the current evaluation. In practice, you'll mostly need to receive all parts of a sink's output and then merge their Objects arrays before further processing.
  • Units - contains information about which values use which units
  • Objects - information about the traffic objects outputted by the sink
    • Color - the general color of the traffic object
    • Duration - how long the traffic object has been in the scene
    • Id - the traffic object's unique identifier within the analytics
    • LicensePlate - the license plate contents of the traffic object. If none have been detected, the value is "Undefined"
    • Timestamp - the timestamp of the moment when this object has been detected for the first time
    • Type - the traffic object's category
    • StateData - data about the traffic object's properties that change with time
      • MapPositions - Only available in georegistered analytics. This array contains the traffic object's positions within its corresponding UTM zone. The first element of the position array is the x coordinate, the second element is the y coordinate.
      • MapSpeeds - Only available in georegistered analytics. This array contains the traffic object's speeds in real-world measurement units.
      • WGS84Positions - the position of the traffic object within the WGS 84 coordinate system. Only available in georegistered analytics. The first array element is the longitude, the second is latitude. They're expressed as positive or negative numbers. Positive latitude is above the equator (N), and negative latitude is below the equator (S). Positive longitude is east of the prime meridian, while negative longitude is west of the prime meridian (a north-south line that runs through a point in England).
      • SensorPositions - the position of the traffic object within the sensor's coordinate space. The first array element is the x coordinate, the second is the y coordinate. E.g. in a camera image, the coordinates [0,0] correspond to the upper left corner.
      • Timestamps - the amount of time that has passed between the moment when this object has been detected for the first time and the moment that the other StateData properties correspond to.

UDP fragmentation

Even with JSON fragmentation, the UDP datagrams can get large. For example, one ObjectList JSON part can have up to 19 KB. When sending such large datagrams over a network, they could get discarded by the receiver or any machine along the way if the datagram's size exceeds their MTU settings. Usually, MTU is set to 1500 B, but sometimes it can be as small as 512 B. It's up to you to check the proper network settings in machines running the FLOW BLOCK, the receiving machine, and machines along the way.

FLOW lets you set the maximum size of UDP datagrams to accommodate your network settings. In FLOW Insights, log into a FLOW BLOCK as admin, select BLOCK -> Settings -> UDP settings -> Enable payload fragmentation. Then you're able to set the Maximum datagram size.

Once set, each datagram exceeding the maximum value will be split into multiple datagrams. Please note that this fragmentation occurs on FLOW's application layer and has nothing to do with UDP's intrinsic but unreliable fragmentation on the transport layer. Therefore it's up to the receiving application to build the whole payload from received parts.

When UDP fragmentation is enabled, all datagrams' payloads are prepended with a 16-byte header containing three unsigned values:

  1. 8 B timestamp of the first part (milliseconds since Epoch) in the series
  2. 4 B part number (starts from 0)
  3. 4 B total number of parts

These values are serialized as big-endian (most significant byte first). Here's an illustration of what the string {trajectories: "example"} would look like when split into two datagrams:

Keep in mind that UDP fragmentation affects outputs of all UDP sinks, not just the Object list sink. In the case of the Object list sink output, UDP fragmentation takes place after possible JSON fragmentation. Let's see an example where an ObjectList response has been split into two JSON parts - the first JSON part was further split into three datagrams, while the second JSON part was split into two datagrams:

What next?

You can also make FLOW send you widget outputs on its own with webhooks.


Need more help or have some questions? Contact us!