Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
https://[IP address or hostname]:[port]/video/

WILL BE DEPRECATED IN NEXT RELEASE, USE /channels

Returns stored video from the camera with the given camera number and options (start time, end time, length, framerate, and/or resolution). Note: Datetime values are formatted according to the ISO 8601 specification: YYYY-MM-DDTHH:MM:SS For example, 2012-12-05T13:40:27. For more information, see this article from the W3C W3.org: Date and Time Formats.

...

After processing event summary XML, we can use the content of the <link> element to perform a GET operation and retrieve detail for events of interest. We provide a utility method in Utitlities.java for this purpose.

Code Block
languagejava
// use link to do GET and retrieve event detail XML
String eventDetail = Utilities.getEvent(eventLink);

Similarly, after obtaining the event detail XML, it can be processed using any standard XML parser. Examples can be found in Utilities.java.

Code Block
languagejava
// using DOM
public static void processFirstEvent _ DOM(String response) {…}
// using JAXP
public static void processFirstEvent _ JAXP(String response) {…}

Combine above examples to query for all motion events in a case named 'Fraud #1', print start time and end time, and image location of key frames:

Code Block
languagejava
// Motion events in Case 'Fraud #1'
AndP pred = new AndP(new Predicate[] {
new EqP("eventtype", new Integer(1)),
new EqP("cases.name", "Fraud #1")
});
String response = Utilities.query(pred.ToXmlString());
ArrayList links = Utilities.getAllEventLinks(response);
for (int i = 0; i < links.size(); i++) {
String eventDetail = Utilities.getEvent(links.get(i).toString());
//Parse event details string by DOM
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder parser = factory.newDocumentBuilder();
Document xmldoc = parser.parse(new InputSource(new StringReader(eventDetail)));
NodeList events = XPathAPI.selectNodeList(xmldoc, "//Events/Event");
Node event = events.item(0);
String starttime = event.getAttributes().getNamedItem("StartTime").getTextContent();
String endtime = event.getAttributes().getNamedItem("EndTime").getTextContent();
NodeList pictures = XPathAPI.selectNodeList(xmldoc, "//Events/Event/SpecializedEvent/
MotionEvent/MotionFrames/MotionFrame/Picture");
for (int j=0; j<pictures.getLength(); j++) {
Node picture = pictures.item(j);
String filePath = picture.getAttributes().getNamedItem("FilePath").getTextContent();
System.out.println("Frame:" + filePath);
}
}

The source code for this example is in the SDK in the file Samples\EventsInCase.java.

3VR External Query API Support for Python Programming

In the samples\query\python directory of your SDK, there is a Python module, queryapi.py which contains a variety of helper bindings for using the 3VR External Query API. The helpers are divided into two parts: helpers for building predicate XML and helpers for retrieving event XML from a 3VR server using a sequence of HTTP requests.

Building predicates with the Python helpers

The queryapi.py module provides a set of classes that make it very easy and concise to define predicates. These classes can be used to generate the XML that will be sent to server in a POST request and execute the query. For example, the expression

Code Block
languagejava
p = andp(eqp('EventType', '1'), gep('StartTime', datetime.timedelta(minutes=20)))

creates a predicate which will find all motion events in the past 20 minutes. This example shows that predicate class names always end with the letter "p"; the three predicates used here are "and," "equals," and "greater than or equals." Note that the last two are really specific types of comparison predicates.

Each predicate class supports the toXml() function which returns the XML to post for that predicate. In the above example, calling p.toXml() returns:

Code Block
<?xml version="1.0" encoding="utf-8"?>
<Predicate>
<AndPredicate name="and" isEnabled="True" id="" DistinctIndividualQueries="False">
<ComparisonPredicate name="=" isEnabled="True" id="" DistinctIndividualQueries="Fals
e">
<FacetOperand reference="EventType" />
<Comparison operation="=" />
<ValueOperand type="System.Int" value="1" />
</ComparisonPredicate>
<ComparisonPredicate name="&gt;=" isEnabled="True" id="" DistinctIndividualQueries="
False">
<FacetOperand reference="StartTime" />
<Comparison operation="&gt;=" />
<RelativeValueOperand type="System.TimeSpan" value="0:20:0" />
</ComparisonPredicate>
</AndPredicate>
</Predicate>

There are two types of predicate classes: those that contain other predicates (like and and or) and those that contain operands (like equals). In addition, there is a special predicate type which allows you to define searches to find face events with faces similar to given people, profiles or groups of people.

The following table summarizes the available predicate classes and how they correspond to the XML predicate tags:

...

Predicate classes that contain operands are smart when trying to interpret their operand arguments in ways that are reasonable, sparing the user the pain of defining the type of each operand. The interpretations are as follows:

...

datetime, date, time and timedelta are defined in the Python standard datetime module. See the Python Library Reference at python.org for details.

Similarity searches can be created with the similarityp class. Similarity searches allow you to query for face events that include faces that are similar to other sets of faces. Usually, this predicate will be used by specifying either a person or group. Person ids can be viewed on the people panel in OpCenter. For example, the following query:

Code Block
languagejava
p = similarityp(personids=[10], earliest=datetime.datetime(2007,6,15),
\ minSimilarity=0.7)

will retrieve all face events since June 15, 2007 that are 70% similar to person #10. It is possible to force an interpretation by wrapping the value in facet(), value(), arrayvalue(), or relativevalue() but this is not recommended. In general, all operand predicates should be specified as pred(facet, value).

Retrieving event XML using the Python helpers

The process of executing a query has four parts:

  1. Post the query using an HTTP POST command.

  2. Parse the retrieved event list as RSS-formatted XML, and use HTTP GET commands to retrieve XML for each event.

  3. Process the retrieved events.

  4. If appropriate, retrieve images and/or videos for the event by retrieving links included in the event XML from the server using
    HTTP GET requests.

The queryapi.py module supports this model using the Query class. The Query class performs all necessary HTTP processing and presents the user with a lazily-evaluated array of results. Each element of the results contains the XML for a single event. Because the array is lazily-evaluated, applications that may need to use only a subset of the results can use Query efficiently; only those results that are used are retrieved from the server.

The common idiom for using Query, like many other Python constructs, is to create an instance and then use iteration to process each of the elements as follows (where p is the predicate specified above):

Code Block
languagexml
query = Query('<server-name>', p)
for eventString in query:

process event XML string

The XML strings are usually processed with XML parsing tools from the Python library, although in simple cases regular expression matching could be used. The provided samples show parsing in the document-object model (DOM) using the xml.dom.minidom module and event-based (SAX) parsing using the xml.parsers.expat module. The appropriate mechanism depends on your application and preferred programming style. For small applications, minidom provides a convenient interface that does not require you to maintain any parsing state yourself. SAX-style parsing (expat-based parsers in particular) tends to be very high performance, and is, therefore, suitable for bulk processing.

The Query class also supports the len() operation, array indexing and slicing so those methods are available if they are a preferable way to access the query results.

The Query class has a method called getlink() which takes a URL and returns that object retrieved from the server. This is used to retrieve images and videos from the server using the resource identification link embedded in the event XML.

Python sample applications

Included in the SDK are two sample applications which show how to use the queryapi.py module to get real data.

The sample alerts.py displays all events that generated alerts in the past day. For each event, the program prints the camera number, the event start time, and the name of the triggered alert to the standard output. This sample uses the mini DOM module to parse the events.

The sample images.py returns events that generated alerts in the last day and saves all the images from those events in the folder specified on the command line. This sample uses the expat SAX parser to process the events. It also demonstrates using the getlink() function to retrieve image data.

3VR Live Query API

Overview

The 3VR Live Query API allows users to receive a continuously updating stream of events matching a predicate. The 3VR Appliance will return events matching the predicate as long as a connection remains open between client and server.

Query Format

The format of the predicate for the 3VR Live Query API is identical to the 3VR External Query API. To perform the query, the client POSTs the predicate XML to the URL https://[IP address or host name]/live/ where the XML is passed as the URL encoded argument "queryxml".

Live Query Response

The response from the Live Query API will be a continuously updating series of events. Each event takes the form of <item> elements:

Code Block
languagexml
<item>
<title>8/7/2012 1:48:10 PM -07:00 - 8/7/2012 1:48:14 PM -07:00: Motion Event on Camera
Hallway East</title>
<link>http://10.100.2.202:80/event/2413380</link>
<description>
<img alt="http:s//10.100.2.202:8080/image/s/2012 _ 08 _ 07/13/eventtyp
e _ 1/E _ 1 _ 20120807 _ 130135 _ 001.535.MFA2" src="https://10.100.2.202:8080/
image/s/2012 _ 08 _ 07/13/eventtype _ 1/E _ 1 _ 20120807 _ 130135 _ 001.535.MFA2"
width="120" height="80" />;<img alt="https://10.100.2.202:8080/image/s/2012 _ 08 _ 07/13/
eventtype _ 1/E _ 1 _ 20120807 _ 130135 _ 001.536.MFA2" src="https://10.100.2.202:8080/
image/s/2012 _ 08 _ 07/13/eventtype _ 1/E _ 1 _ 20120807 _ 130135 _ 001.536.MFA2" width="120"
height="80" />;<img alt="https://10.100.2.202:8080/image/s/2012 _ 08 _ 07/13/eventtype _ 1
/E _ 1 _ 20120807 _ 130135 _ 001.537.MFA2" src="https://10.100.2.202:8080/image/s/2012 _ 08 _ 07/13/eve
nttype _ 1/E _ 1 _ 20120807 _ 130135 _ 001.537.MFA2" width="120" height="80" />;</description>
<pubDate>1:49 PM</pubDate>
</item>
<item>
<title>8/7/2012 1:48:07 PM -07:00 - 8/7/2012 1:48:09 PM -07:00: Motion Event on Camera
Hallway East</title>
<link>https://10.100.2.202:8080/event/2413379</link>
<description>
<img alt="http:s//10.100.2.202:8080/image/s/2012 _ 08 _ 07/13/eventtyp
e _ 1/E _ 1 _ 20120807 _ 130135 _ 001.528.MFA2" src="https://10.100.2.202:8080/
image/s/2012 _ 08 _ 07/13/eventtype _ 1/E _ 1 _ 20120807 _ 130135 _ 001.528.MFA2"
width="120" height="80" />;<img alt="https://10.100.2.202:8080/image/s/2012 _ 08 _ 07/13/
eventtype _ 1/E _ 1 _ 20120807 _ 130135 _ 001.529.MFA2" src="https://10.100.2.202:8080/
image/s/2012 _ 08 _ 07/13/eventtype _ 1/E _ 1 _ 20120807 _ 130135 _ 001.529.MFA2" width="120"
height="80" />;<img alt="https://10.100.2.202:8080/image/s/2012 _ 08 _ 07/13/eventtype _ 1
/E _ 1 _ 20120807 _ 130135 _ 001.530.MFA2" src="https://10.100.2.202:8080/image/s/2012 _ 08 _ 07/13/eve
nttype _ 1/E _ 1 _ 20120807 _ 130135 _ 001.530.MFA2" width="120" height="80" />;</description>
<pubDate>1:49 PM</pubDate>
</item>

The <item> element here is identical to the <item> child element in the Query API response.

Sample Python Code

In this example, we use the queryapi.py module to obtain a live query feed of alerts with a given alert name.

Code Block
languagepy
from queryapi import *
import urllib2
def yield _ url(url):
for line in urllib2.urlopen(url):
if line is not "":
yield line
def LiveQuery(hostname, query):
Request = urllib2.Request
password _ mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
handler = urllib2.HTTPBasicAuthHandler(password _ mgr)
opener = urllib2.build _ opener(handler)
urllib2.install _ opener(opener)
theurl = 'http://%s/live' % (hostname)
m = re.match('(http://[^/]+)', theurl)
rooturl = m.group(1)
password _ mgr.add _ password(None, rooturl, "techrep", "3MeDeee")
postdata = query
req = Request(theurl, postdata, {})
returned _ xml = ""
in _ event = False
for line in yield _ url(req):
if line.startswith('</ThreeVRExport'):
in _ event = False
returned _ xml += line.rstrip('\n')
yield returned _ xml
returned _ xml = ""
if in _ event:
returned _ xml += line.rstrip('\n')
if line.startswith('<ThreeVRExport'):
in _ event = True
returned _ xml += line.rstrip('\n')
if _ _ name _ _ == "_ _ main _ _":
try:
hostname = sys.argv[1]
alertname = sys.argv[2]
except:
print "usage: livealert.py [IP address or hostname] [alertname]"
sys.exit(1)
query = andp(eqp('TriggeredAlerts.Alert.Name',sys.argv[2]), eqp('Status', 20))
for xmlbit in LiveQuery(hostname, query.toXml()):
print 'There was a matching alert!'
# here you may process the returned xml with a Python library such as
# minidom or Beautiful Soup

Predicate Facets Reference

About Facets

A 3VR event is a structured object. It contains a collection of facets, each containing a piece of information like start time, channel, etc. A facet can contain primitive value or a structured object of a specific type.

Facets are used in two ways in the 3VR APIs:

  • A dotted facet name is used in predicates to define the part of the event that needs to be tested. For example, we can use the string "Appliance.Name" to refer to the name facet of the appliance facet when constructing predicate XML. Here we have a sequence of facets (each representing a layer of objects) separated by periods.

  • The attributes and elements of the event structure XML represent facets. These correspond (almost exactly) to the facets used in the predicates, but the way you'll access them depends on the way you're parsing the event XML. In this section, we use XPath notation to specify the path of elements to the particular facet. Note: DOM and SAX parsing will access the paths differently.

Event Facets

Here is the list of facets in the event object:

...

As mentioned above, we use the dotted facet name in predicates. That is, if a facet contains an object, we use the dot operator (period) to refer to the facets of that object. For example, EventType returns the type of event associated to the event; TriggeredAlerts.Alert.Name returns the name of triggered alerts associated with the event.

There is no maximum length for dotted facet names. The elements of the dotted facet name are NOT case-sensitive. However, every facet in the chain must exist in the object it relates to. An invalid facet will produce HTTP error results.

The one difference between the way facet names are used in the predicate and in the XML is with respect to SpecializedEvent objects. In the XML, SpecializedEvent is a wrapper for a specific type of event object (MotionEvent, FaceEvent, ImportedImageEvent, or GenericEvent). Each of these types is represented by a different XML object and schema component. When creating a predicate, you can simply skip this intermediate event and refer directly to its components.

For example, to build a predicate based on the value of the person's first name, you'd use the facet SpecializedEvent. ProfileGroup.Person.FirstName but to retrieve the first name from the returned XML you'd use the XPath/SpecializedEvent/FaceEvent/ProfileGroup/Person/@FirstName. In the latter case, we explicitly mention the FaceEvent tag that occurs in the XML but is not necessary in the predicate.

Complete list of all Facets for 3VR Objects

...