Monitoring trips in real-time – last part of the report

In yesterday’s article we informed about authentication and billing – and you got code, code, code …

What’s the great thing about this approach?

Our API is process-agnostic concerning your own tool chain and logistics processes. For example, it doesn’t matter where the positioning event comes from: directly from a mobile device, via a Fleet Management System or from a desktop client like a Travel Management or Tour Planning System. You are free to choose the best way how to integrate PTV Drive&Arrive in your existing architecture. Of course, creating a trip should take place where the trip was created, i.e. where the Token owner is located.

With this approach, you are able to get an integrated ETA ( = Estimated Time of Arrival) management for a fleet even if it uses different types of telematic systems and other different tools among all the stakeholders of the transport chain.

How can I test PTV Drive&Arrive without implementing anything?

We will provide a web portal for demo purposes during the next weeks. It enables you to create trips for free. In addition, you can find an iOS and an Android app that is able to send positions to PTV Drive&Arrive for a given SCEMID (no navigation, no map, simply sending positions and displaying ETA).

Please have a look at our online documentation at https://driveandarrive-v1.cloud.ptvgroup.com/ where you can find demo capabilities for developers, a detailled API description and some code samples. This is also the URL for the API end points!

If you have an further technical questions, do not hesitate to contact our technical support at driveandarrive.support@ptvgroup.com .

Real-time sequel: A report from the source

DriverAppIn yesterday’s article we introduced how PTV Drive&Arrive is working. Let’s dive into today’s topic:

What about authentication and billing?

You pay per trip. We count the number of trips and bill you accordingly. As we have to make sure that you are allowed to create a trip in our system for monitoring and in order to identify you, you need a so called “Token”. You have to order such a Token from us before creating your first trip.
Therefore, creating a trip in our system is the only API operation that has an impact on costs. All other operations are free. Costs are per trip: it doesn’t matter how many stops your trip has, how many ETA ( = Estimated Time of Arrival) subscribers there are per SCEMID, how many ETA calculations or notifications you will have etc.
If you got a SCEMID from somewhere (without Token), you can immediatly implement your own application on the PTV Drive&Arrive API without registering or anything like that. Just start to use the whole API (that does not require a Token) for free and withour access limitations.

Sounds great? Wanna see code?

Voilà: you can download code samples here  – this is an extract for you:

Creating a trip requires at least one stop. This is a JavaScript/node.js sample for creating a trip with two stops:

// define a trip with two stops
var tourData = {
   "tour": {
      "stops": [{            
            "coordinate": {"locationX": 8.61638888888889,
               "locationY": 49.81833333333333
            },
            "earliestArrivalTime": "2013-03-07T08:00:00.000+01:00",            
            "latestDepartureTime": "2013-03-07T08:00:00.000+01:00",           
            "serviceTimeAtStop": 0,
            "useServicePeriodForRecreation": true,
            "weightWhenLeavingStop": "6908,272",
            "customData": {}
         },
         {            
            "coordinate": {
               "locationX": 8.565,
               "locationY": 49.966111111111104
            },
            "earliestArrivalTime": "2013-03-07T08:29:08.000+01:00",
            "latestDepartureTime": "2013-03-07T08:44:08.000+01:00",
            "serviceTimeAtStop": 900,
            "useServicePeriodForRecreation": true,
            "weightWhenLeavingStop": "6835,772",
            "customData": {}
         }
      ],
      "vehicle": {
         "vehicleProfileID": "mg-truck-40t"
      },
      "drivers": [
         {
            "driverDescription": "driver 1",
            "raSTime": {
               "referenceTime": "2013-03-07T07:00:00.000+01:00",  
                    "periodDrivenSinceLastBreak": 0,
                    "periodDrivenSinceLastRest": 0,   
                    "currentIdlePeriod": 0,           
                    "isSplitBreak": false,         
                    "isSplitRest": false
            }
         }
      ],
      "customData": {
         "user": "node.js_test",
         "myid": "1"
      }
   }
};


// display response as JSON when response for Tour Create comes back
var callbackTourCreated = function (error, response, body) {
   console.log(JSON.stringify(body,null,1));   
};

var token = "<PUT YOUR TOKEN HERE>"; 

// create request object in node (if not available, try "npm install request" in command line before)
var request = require('request');
var options = {      
         url: 'https://driveandarrive-v1.cloud.ptvgroup.com/em/tour?source=PTVNODEJSCSBLOG&token=' + token,         
         method: 'POST',        
         json: tourData,      
         headers: {                       
            "content-type":"application/json"
         } 
      };

// send Tour Create request
request(options, callbackTourCreated);

In the JSON result you can find your SCEMIDs that may like this (extract for first stop)

{            
    "coordinate": {
       "locationX": 8.61638888888889,
       "locationY": 49.81833333333333
    },
    "earliestArrivalTime": "2013-03-07T08:00:00.000+01:00",            
    "latestDepartureTime": "2013-03-07T08:00:00.000+01:00",           
    "serviceTimeAtStop": 0,
    "useServicePeriodForRecreation": true,
    "weightWhenLeavingStop": "6908,272",
    "customData": {},
    "scemid":"X9X9X9X9X9"
},

The SCEMID for your first stop in this example is “X9X9X9X9X9”. No, what’s next? You have to send a positioning event to SCEMID that represents the next stop on your trip.

Given that you now drive to the stop with the SCEMID X9X9X9X9X9, you send a positioning event like that:

var eventData = {
   "event": {
      "eventType": "POSITION",
      "eventSubtype": "GPS",
      "eventSource": "PTVNODEJSCSBLOG",
      "eventPayLoad": {
         "heading": 122,
         "speed": 62.5,
         "accuracy": 23,
         "coordinate": {
            "locationX": 8.61660560080855,
            "locationY": 49.8182790029665
         },
         "timeStamp": "2013-07-03T07:10:31.023+0000"
      },
      "scemid": "X9X9X9X9X9"
   }
}

As you can see, there is no Token required for that operation. After sending the event, PTV Drive&Arrive knows about your position and if you send it regularly, we can re-calculate your ETA by taking rest and break times into account, as well as real-time traffic information, historical traffic information, physical road constraints for trucks and manually curated truck related blockings.

If you want to get informed about ETA on a certain stop, you have to subscrive to the SCEMID of that stop by code snippet like this one:

// create subscription for a callback URL.
// callback URL target is requestb.in 
// please refer to online documentation for this sample to understand the requestb.in URL
var subscriptionData = {
   "subscription": {
      "notificationType": "CALLBACK_URL",
      "notificationDescription": {
         "callBackURL":"http://requestb.in/1cifoit1",
         "ident": 'mytestX9X9X9X9X9'
      },
      "scemid": "X9X9X9X9X9"
   }
};

You can choose how to get notified: by callback URL, by a SignalR message or you can request the current ETA by API (some kind of polling). SignalR is the most flexible way as it works for mobile devices, server backends and for desktop clients.

Please note that the whole system works asynchronously, i.e. you can’t request an ETA calculation per request, but you have to subscribe to it. We will decide when to re-calculate an ETA and notify you if appropriate.

Now, you’re ready to go code-wise. Tomorrow, you can read what’s the great thing about this approach.

You got a job to do?

AsynchroneRequestsYou are using the PTV xServer with really long running requests? Like PTV xTour requests with lots of depots and orders? Or you are doing bulk address calculations with PTV xLocate? Well, then this blog post is for you!

Take a simple (but long running) request :

Plan plan = client.planBasicTours(transportOrders, depots, fleet, planningParams, inputPlan);
System.out.println("Got result. Calculated " + plan.getChains().length + " chains.");

This simple line blocks your code until PTV xTour has calculated the tours and has returned the response. This may take hours and there is no chance to get information on the progress so far. Of course you can have a look on the PTV xServer’s status monitor. But you can not access this information using the API.

Starting with the PTV xServer 1.18 we have added a new way to run these long running requests. Just add the prefix start to your method call:

Job job = client.startPlanBasicTours(transportOrders, depots, fleet, planningParams, inputPlan);

This code immediately returns a so called job handle. This handle references the job which is running on the server. Using this handle we can query the job’s status and wait for the calculation to finish:

// take default WatchOptions for now...
WatchOptions watchOptions = new WatchOptions();

// A job has a status => QUEUING, RUNNING, SUCCEEDED, FAILED, DELETED, UNKNOWN
JobStatus status = job.getStatus();

// wait until the status turns to SUCCEEDED or FAILED
while(!status.equals(JobStatus.FAILED) && !status.equals(JobStatus.SUCCEEDED)) {
job = client.watchJob(job.getId(), watchOptions);
status = job.getStatus();
}

// fetch the result (or exception)
try {
Plan plan = client.fetchPlan(job.getId());
System.out.println("Got result. Calculated " + plan.getChains().length + " chains.");
} catch (Exception e) {
System.out.println("Calculation stopped with an exception: " + e);
}

The advantages of this approach are obvious:

  • the client does not have to remain connected all the time
  • if you lose the connection, you can try again, the results will not be lost
  • you can query the progress of your job: are we there yet?

For our java clients we have also added a convenience method which handles the while-loop watching the running job. This special method has the prefix run and works like this:

// We like to get progress information every 500 milliseconds
WatchOptions watchOptions = new WatchOptions();
watchOptions.setProgressUpdatePeriod(250);

// Do 2 retries, if connection is lost
// and wait 2 seconds in between
RetryOptions retryOptions = new RetryOptions();
retryOptions.setRetries(2);
retryOptions.setRetryInterval(2000);

Future future = client.runPlanBasicTourstransportOrders, depots, fleet, planningParams, inputPlan, watchOptions, new WatchCallback() {

@Override
public void onJobUpdate(Job job) {
if (job.getProgress() != null) {
PlanProgress planProgress = (PlanProgress) job.getProgress();
DistanceMatrixCalculationProgress dimaProgress = planProgress
.getDistanceMatrixCalculationProgress();
ImprovementProgress imProgress = planProgress.getImprovementProgress();
if (dimaProgress != null) {
DistanceMatrixProgress matrixProgress = dimaProgress.getCurrentDistanceMatrixProgress();
if (matrixProgress != null) {
System.out.println("Dima Calculation: " + dimaProgress.getCurrentDimaIndex() + ", "
+ matrixProgress.getCurrentRowIndex());
}
}
if (imProgress != null) {
KeyFigures bestPlan = imProgress.getBestPlan();
System.out.println("Ieration: " + imProgress.getIterationIndex() + ", TotalChainCost: "
+ bestPlan.getNumberOfUnscheduledOrders());
}
}
}
}, retryOptions);
System.out.println("Got future. Waiting for result.");
try {
System.out.println("Result = " + future.get().getChains().length);
} catch (ExecutionException | InterruptedException e) {
e.printStackTrace();
}

In addition to the WatchOptions this method also receives an argument of type RetryOptions which allows us to set the number of retries and a waiting interval in case the connection to the PTV xServer is lost.

Now, give it a try! Turn your synchronous calls into asynchronous job requests. If you have any questions, leave us a comment or contact our support.

The new Code Sample Browser takes it to a new level

Far more than just examples – develop applications in no time

The new PTV xServer Code Sample Browser has arrived, with a lot more features and brand new code samples.

CSB_PTVxServerCSB_PTVxServer1

 

Backed by excellent HTML 5 and JavaScript libraries (Bootstrap, Backbone and Codemirror to name a few), the sample browser has a gorgeous look and feel.

 

CSB_PTVxServer2

For instance, you can now create your own samples from a template to quickly test out ideas.

 

 

Our goal was to make the Code Sample Browser even simpler, more useful and more enjoyable, but keep the familiar structure.

You can also use shortcuts to speed up your workflow while changing or creating your own sample. For example you can switch between presentation mode and the normal view mode simply by pressing CTRL + Shift + P or you can save the changes of the sample code by pressing CTRL + S.

CSB_PTVxServer3

PTV xServer 1.17 ships with an extended sample map that also includes Rhode Island / USA. The new code sample browser lets you explore your favorite samples in the American theatre with one click.

 

We are constantly adding new samples for existing and new features. For 1.17, we demonstrate exciting new features such as overnight tours and freight incompatibilities for PTV xTour, and the fully customizable Feature Layers and XML Profiles for PTV xRoute.

Some additional sample variants demonstrate the use of the new Leaflet plugin, a lightweight alternative to PTV xServer add-on AJAX Maps. PTV’s Leaflet plugin requires PTV xMap 1.17 to work.

CSB_PTVxServer4

CSB_PTVxServer5

This time, we are also introducing expert-level samples; these samples demonstrate several features at once, and the associated client code can be quite involved.

The tour animation sample is a graphical goodie. It shows you how tours planned by PTV xTour would be carried out as a graphical animation. Play around with different random start scenarios to see the impact of depot locations. This sample is not heavily optimized, so be careful with the huge scenario.

The bulk request benchmark demonstrates the benefits of the bulk request variants. Should you have any doubt whether bulk requests are worth it, run the sample.

The drag and drop routing sample demonstrates more sophisticated input of your routes. This is a highly interactive use case and the expert level sample does some heavy duty client work.

The Code Sample Browser is included in the PTV xServer bundle, and available at the xserver.ptvgroup.com homepage.

CodeSampleBrowser

Have fun with new Code Sample Browser, make your own code samples or just play with it 🙂 Go to Code Sample Browser

 

[ratings]

Play with PTV’s CodeSampleBrowser!

Dear all,

the PTV Code Sample Browser is an interactive tutorial based on JavaScript. Using this sample browser, you will easily develop your own web applications. Just select the preferred code sample and start to interact with the application by clicking the “Show Sample”-Button. How to test PTV xServer’ functionalities? See use case below.

Drag-and-drop routing

Read the short introduction to understand the usage of this sample.introduction codesamplebrowser

Click into the PTV map twice to calculate automatically a route. Via mouse events, you are able to move dynamically the start, destination or selected via point. Hereby, the last current address list will be shown automatically. This highly interactive code sample illustrates the combination of client and server activities.

Figure drap and drop

Are you interested how it works? Please check the source code which is also provided in a separated editor frame (right top corner: “edit source” button).You may edit the source code and revert to the original. So, don’t hesitate to use this opportunity to “play” with these interactive functions.

Code Sample Editor

Do you have some notes how to improve the tutorial? Please contact our PTV xServer Support!

Kind regards from Karlsruhe,

Dr. Michael Nutto

Product Manager PTV xServer