# [SOLVED] Calculating Avg. Time Between Entrance/Exit Sensor Detections

Hi,

My system currently has two sensors (one representing an entrance, the other representing an exit) which are used to detect motion as objects pass through. The objects maintain the same order within the system.

My task is to calculate the average “wait time” for the system. To calculate this, I first determine the time for each object to go from the entrance sensor to the exit sensor (CountEnt[i].time - CountExit[i].time), and then, all the times for each object to pass through both sensors are combined, and the total is divided by the number of objects which have passed through both sensors (MaxExit).

This formula can be seen below:

/* MaxExit = amount of objects that have exited the system, which is less than or equal to the amount that has entered the system
CountEnt[i].time/CountExit[i].time = the timestamp that corresponds to when an object at index “i” passed through the entrance/exit sensor */

var totalTime;
for(i=0;i<MaxExit, i++) {
var tempTime = CountEnt[i].time - CountExit[i].time;
totalTime = totalTime + tempTime
}
var avgTime = totalTime/MaxExit;

I am trying to understand how to represent this relationship with either a UbiFunction or with Synthetic Variables so that I may calculate the average time for an object to pass through the system. Within the UbiFunction, I would like to return the integer value as the API response so that I may display it on a website. I have experience developing algorithms, but I am not too confident in understanding how to access the data from Ubidots using JS and putting it into an alogorithm as seen above. I would greatly appreciate any help or guidance on how to complete this task.

Best,
Leslie

Greetings @leswins, you may reach your goal using Ubifunctions and python:

1. From both entry and exit variables, retrieve the last n values to perform your mean which in your case is the amount of objects that have exited. You may do this implementing a GET request to this endpoint:
``````/api/v1.6/devices/{DEVICE_LABEL}/{VARIABLE_LABEL}/values/?page_size=n
``````

your request should return a list in the key `results` that you can iterate:

``````{"count": true, "previous": null, "results": [{PAYLOAD_WITH_VALUES}], "next": {URL_WITH_ADDITIONAL_VALUES}}<CR><LN>
``````
1. Iterate both lists:
``````total_time = 0
for i in range(0, n):
timestamp_ent = coun_ent_list[i].get('timestamp')
timestamp_ex = coun_ex_list[i].get('timestamp')
total_time += timestamp_ent - timestamp_ex

average = total_time / n
``````
1. Remember that your ubifunction MUST return a json object, so make sure to return in your main() function something like this:
``````{'result': 'ok', 'average': average}
``````

Hope it helps you