IoT Restful API

From AMTech WikiDocs
Revision as of 13:42, 9 February 2018 by Lianet (Talk | contribs) (Observers API)

Jump to: navigation, search

Restful API

  • Jsonld-based Restful API that exposes the Domain Access Protocol resources and allow all CRUD operations on them based on the access control policies (See Access control and Actors)
  • To CREATE and UPDATE a resource, it must be supplied in json format according to the semantic definition of its type
  • To GET or DELETE a resource, the crud operation must be executed on the endpoint represented by the resource unique identifier (uri)
  • Embedded collections are represented as JSONArray inside their parent resource. If any of these embedded collection are requested to the API directly, the response will be its json representation (a json of type Collection with a property 'members' containing the collection members)
  • If an error occurs during the execution of a request, the response from the API will be a jsonld of "@type":"/amtech/linkeddata/types/composite/outputMsg"
{   
    "message":"Resource /amtech/things/entities/gpsDevice/gpsDeviceParkingDemo already exists",
    "targetResourceType":"/amtech/linkeddata/types/composite/entity/gpsDevice",
    "errorType":"amtech.utils.model.ResourceAlreadyExistException",
    "@type":"/amtech/linkeddata/types/composite/outputMsg",
    "resource":"/amtech/things/entities/gpsDevice/gpsDeviceParkingDemo",
    "success":false,
    "messagedetail":""
}
  • If the request is successful, the result is a jsonld representation of the resource, with details depending on the requested CRUD operation

CRUD operations on resources

API resources support all CRUD operations. Valid credentials must be supplied, meaning that the user must exist and have access (roles/actors) to perform the given CRUD operation on the resource. Sample CRUD operations on a thing instance :

  • Create : via POST on the root endpoint /amtech, passing the json to of the resource to be created
curl -X POST -H "Authorization: Basic xxxxx" -H "Content-Type: application/json" -d '{
  "@type": "/amtech/linkeddata/types/composite/entity/Truck",
  "@id": "/amtech/things/entities/Truck/truck1",
  "description" : "New truck",
  "weight":100.0
}' "https://dap.amtech.mx/amtech"
  • Read : via GET on the resource uri
curl -X GET -H "Authorization: Basic xxxxx" -H "https://dap.amtech.mx/amtech/things/entities/Truck/truck1"
  • Update : via PUT on the root endpoint /amtech, passing the json to update in the body of the request. The json must include the @id and @type properties, along with all the properties that want to be updated
curl -X PUT -H "Authorization: Basic xxxxx" -H "Content-Type: application/json" -d '{
  "@type": "/amtech/linkeddata/types/composite/entity/Truck",
  "@id": "/amtech/things/entities/Truck/truck1",
  "description" : "Updated description"
}' "https://dap.amtech.mx/amtech"
  • Delete : via DELETE on the resource uri
curl -X DELETE -H "Content-Type: application/json" -u "userId:password" https://dap.amtech.mx/amtech/things/entities/Truck/truck1

Observation instances

  • Getting observation types with property _blankinstancepublished return a blank jsonld ready to be filled and send
    • /amtech/linkeddata/types/composite/observation
  • Sending observations
    • /amtech/things/events
  • (See Observations and observation types)
rest.postJson(self.dapUrl + '/amtech/things/events', observation, options).on(
    'complete', function(data, response) {
                    if (response && response.statusCode && response.statusCode !== 200) {
                        complete(self.buildError(response, "Sending observation"), data);
                    } else if (data instanceof Error) {
                        complete(data);
                    } else if (data['success'] === false) {
                        complete(self.buildDapError(data, 'At DapClient sendObservation'), data);
                    } else {
                        complete();
                    }
                });
  • Synchronous consumption of observation instances in topics
    • /amtech/things/events?client=<client id>&topic=<topic uri>[&obstype=<obs type>]
  • topic (See Topics)
  • targetthings (See Target things)
  • proximityarea (See Location)
  • location (See Location)
  • producer (See [[Sensor's network#Observations)

Thing instances

  • CRUD operations
    • /crud
  • CRUD operation promises:
    • /promise/amtech/things/entities
  • (See Thing types)

Image fields in thing and observation

Fields of type image can be added to things and observations types. Once an image is associated to this field in a thing or observation type, the image is saved in the image storage, and a reference to the image is saved in the thing or observation, in the form of /amtech/static/amtech/things/entities/Truck/truck1/Photo.

The image can then be modified via PUT to that reference endpoint, passing the image base64 representation

Commands

Asynchronous consumption of commands using websocket’s pushing mechanisms (WIP) Same as asynchronous consumption of observations. The command received, which is also an observation instance, will have the target type and target URI into the targetthings property. (See targetthings)

Get observation production configuration

  • Get observation production configuration from property observationproduction of a thing instance, following all the access control rules (See Actors)
    • '/amtech/things/entities/<typeId>/<instanceId>/observationproduction'

Get instances by thing type

  • Get things instances by type for a tenant/user taking into account registered services and access control (See Actors)
    • '/amtech/things/entities/<thingType>'
rest.get(self.dapUrl + '/amtech/things/entities/gpsDevice', options).on(
    'complete', function (data, response) {
                    if (response && response.statusCode && response.statusCode !== 200) {
                        complete(self.buildError(response, "Getting plugins instances"), data);
                    } else if (data instanceof Error) {
                        complete(data);
                    } else if ('success' in data && !data['success']) {
                        complete(self.buildDapError(data, 'At DapClient getPluginsInstances'), data);
                    } else {
                        complete(null, data.members);
                    }
                });

Get resources with links (self contained)

The API supports URI parameters to retrieving resources resolving its link. There are 2 parameters : selfContained, and fullSelfContained

  • selfContained parameter will resolve all embedded links (links whose URIs are direct children of the resource), including for example embedded collections and its members.
  • fullSelfContained will resolve all links, embedded and external

In both cases, once a link is resolved, it will not be resolved again, so if it appears a second time in the resource, the link URI will be left unresolved

Get image representation of spatial query results

In order to export the query results as an image, use

 https://dap.amtech.mx/offlinemaps

Arguments:

  • url: amtech url of the observer, query or thing collection.
  • ext: extension of the produced file. Supported extensions are .png (default) and .pdf
  • observation: json of the observation required to run activity observers
  • any query or observer argument

Examples:

  • To create a .png image showing the endCustomers in the map use
 https://dap.amtech.mx/offlinemaps?url=/amtech/things/entities/endCustomer
  • Use the observer url to show its results. E.g:
 https://dap.amtech.mx/offlinemaps?url=/amtech/observers/observerName
  • For observers defined inside activity, the observation json must be included
 https://dap.amtech.mx/offlinemaps?url=/amtech/activities/myActivity/observers/myObserver&observation={...}


Note: Basic authentication is used. Do not forget to use user/tenant as username where tenant is case sensitive

Get things snapshots - timelilne info

To view the snapshots saved for a thing, perform a GET to the system query entitiesTimelineTempQuery, passing the parameter @id with the uri of the thing to get its snapshots

GET https://dap.amtech.mx/amtech/system/queries/entitiesTimelineTempQuery

Parameters

  • @id with the list of uri of the things to get snapshots Ex. entitiesTimelineTempQuery?@id=["/amtech/things/entities/gpsDevice/gpsDevice1"]
  • observationscount : number of snapshots to retrieve (optional)

Observers API

https://<dapurl>/amtech/observersexec/<observeruri>[?params]

Parameters can be passed to the execution, to dynamically replace the values of constraints. The list of constraints can be viewed as json under the follower uris: *

  • <observerUri>/entitiesFilter/<thingType>/constraints for the constraints of a thing type included in the observer
  • <observerUri>/observationFilter/constraints for the constraints of the observation type included in the observer

Then, if a parameter is passed with the uri of a specific constraint and a value, that value will replace the one defined in the observer Available params:

  • observation: JSON string representation of the observation. May be mandatory depending on the requirements of the observer.
  • resourceStatusFilter: You can specify this parameter with the value valid to only return things that passed validation.
  • limit: Limit for the number of results.
  • noOlderThan: Does not return results older than this date expressed as the number of milliseconds since the epoch (January 1st, 1970, 00:00:00 GMT)
  • offsetDate: This works in conjunction with offsetId. This is expected to be the creation date of the thing indicated with the param offsetId.
  • offsetId: The results will start with the first thing that is older than the record with this ID. This works in conjunction with the offsetDate and you should indicate either both or none of them.
  • tenant: Only return those things available to this tenant.
  • includeCount: Set to true to indicate that we are interested in the total number of results for the execution of this observer. false otherwise.
  • orderby: field to order results by
  • orderdir : direction for ordering (asc or desc)


Target things

Example:

{
   ... 
   "targetthings": "[{\"thingType\":\"/amtech/linkeddata/types/composite/entity/truck\",\"thingsId\":[\"truck888\"], \"proximityarea\": \"/amtech/things/entities/customer/customer1\"}]"
   ...
}

It allows to establish a relationship between an observation and things instances. It consists of an array of JSON objects having:

  • thingType The URI or just the name of a thing type. This is mandatory.
  • thingsId A set of thing instances which can also be written as full URIs or just simple names. Full URIs can be determined by using the type.
  • proximityarea The URI of a thing instance indicated as the proximity area to these thing instances.
Effects from client to server
  • It can be configured in an observer to just return instances listed in this property.
  • The proximityarea is used at the observation enrichment process to assign target thing instances with a location.
Effects from server to client
  • It allows to send observations to specific instances. For instance, m2mBridge leverages this functionality to implement centralized management and send observations.

Tag data translation service

This service allows to translate epc tag data between hex notation and epc urn. Ex:

 https://dap.amtech.mx/amtech/tdt/hex/tagEncoding/3358788D019D694000008235

will return { resource: "/amtech/tdt/hex/tagEncoding/3358788D019D694000008235", success: true, @type: "/amtech/linkeddata/types/composite/outputMsg", message: "Success", results: "urn:epc:tag:GRAI-96:2.123444.423333.33333", targetResourceType: "" } a DAP message with the resulting urn. In case of unsuccessful response, the success field will be false and the error message will be included

This endpoint allows also to convert to a beacon ids. In both cases it will return a comma-separated string with a proposal of identification information. This proposal generation can be inverted in order to retrieve back the tag urn from the identification string. For each beacon format the identification string contains the following fields

  • iBeacon
    • uuid
    • mayor
    • minor
  • eddystone
    • namespace
    • instance

The syntax for the endpoint is https://dap.amtech.mx/amtech/tdt/fromFormat/toFormat/input where the allowed formats are

  • hex: hexadecimal notation of the binary tag
  • binary: binary tag data
  • tagEncoding: epc tag urn
  • ibeacon: ibeacon identification information e.g: uuid=2A3358788D0180000000000000000000,mayor=75A5,minor=8235
  • eddystone: eddystone identification information e.g:namespace=223358788D0000000000,instance=0675A5008235

The input field must be the string on the format given as fromFormat Some examples:

  1. Conversion from tagEncoding to ibeacon
 https://dap.amtech.mx/amtech/tdt/tagEncoding/ibeacon/urn:epc:tag:GRAI-96:2.123444.423333.33333
 {
   resource: "/amtech/tdt/tagEncoding/ibeacon/urn:epc:tag:GRAI-96:2.123444.423333.33333",
   success: true,
   @type: "/amtech/linkeddata/types/composite/outputMsg",
   message: "Success",
   results: "uuid=2A3358788D0180000000000000000000,mayor=75A5,minor=8235",
   targetResourceType: ""
 }
  1. Conversion from eddystone to tagEncoding
 https://dap.amtech.mx/amtech/tdt/eddystone/tagEncoding/namespace=223358788D0000000000,instance=0675A5008235
 {
   resource: "/amtech/tdt/eddystone/tagEncoding/namespace=223358788D0000000000,instance=0675A5008235",
   success: true,
   @type: "/amtech/linkeddata/types/composite/outputMsg",
   message: "Success",
   results: "urn:epc:tag:GRAI-96:2.123444.423333.33333",
   targetResourceType: ""
 }

Asynchronous

  • In order to authenticate the request from a web browser using window.WebSocket object you can put the authentication credentials in the URL as:
    • wss://<user>:<pass>@<host>/amtech/push/things/events?client...
  • (web sockets)

Observations

  • Asynchronous consumption of observation instances in topics using websocket’s pushing mechanisms (WIP)
    • wss://dap.amtech.mx/amtech/push/things/events?client=<client id>&topic=<topic uri>[&obstype=<obs type>]
  • (See CRUD observations)

Commands

  • Asynchronous consumption of commands using websocket’s pushing mechanisms (WIP)
    • wss://dap.amtech.mx/amtech/push/things/commands?client=<client id>&thingtype=<thing type>&[&obstype=<obs type>]

Notifications

  • Asynchronous consumption of notifications using websockets:
    • wss://dap.amtech.mx/amtech/push/notifications[?clientid=<client id>]
  • (See Notifications)

Things

  • Consumption through websockets of promise execution results:
    • /promise/amtech/results?client=<client_id>&thingtype=<thingtype>[&thinguri=<thinguri>]

Example

   "use strict";
   var websocket = require("websocket");
   var wsclient = new websocket.client();
   wsclient.on("connectFailed", function (error) {
       console.log("Connect error: " + error.toString());
   });
   wsclient.on("connect", function (connection) {
       console.log("WebSocket client connected");
       connection.on("error", function (error) {
           console.log("Connection error: " + error.toString());
       });
       connection.on("close", function () {
           console.log("Connection closed");
       });
       connection.on("message", function (message) {
           if (message.type === "utf8") {
               console.log("Received: '" + message.utf8Data + "'");
           }
       });
       process.on('SIGINT', function () {
           console.log("Closing connection...");
           connection.close();
           setTimeout(function () { console.log("Closed"); }, 5000);
       });
   });
   var token = new Buffer("user/tenant:password").toString("Base64");
   wsclient.connect("wss://dap.amtech.mx/amtech/push/notifications", null, null, {
       Authorization: "Basic " + token
   });

Clone

There are two endpoints for cloning resources :

  • /amtech/clone/resourceandlinks<resourceToCloneUri>?newname=<nameForClone>

A GET on this endpoint will clone the specified resource without persisting it, generating clones for all the links referenced in the resource. Ex. If called with a resource LLRPReader1, that has 2 anntenas, it will generate a clone for the each of the antennas and the LLRPReader.

  • /amtech/clone/resourceflat<resourceToCloneUri>?newname=<nameForClone>

A GET on this endpoint will clone the specified resource without persisting it and without cloning the links referenced in the resource.

A POST on either endpoint will clone the resource and persist it

There are entities' properties such as "proximity area" and "activity for observation production" whose values are always copied to the new resource as a reference, instead of cloning them.

Cloning is supported for :

  • Entity type
  • Observation type
  • Supported properties
  • Entity instances
  • Observation instances

CRUD promises

CRUD promises are like any other CRUD operation on things except that they are asynchronously executed. When you execute a PUT, POST or DELETE on the promises endpoint, the corresponding thing will be asynchronously created, updated or deleted by an engine that executes operations sequentially over the same thing instance.