Difference between revisions of "FAQ"

From Sensaphone.net
Jump to: navigation, search
(Example: Remove example section since each language implementation provides its own example)
(List Devices)
 
Line 87: Line 87:
  
 
=====List Devices=====
 
=====List Devices=====
First let's list all devices associated with our account and choose one from the results.
+
First let's list all devices associated with our account and choose one from the results.  To do this we will make a call to the Dashboard resource, requesting the name and device_id of each device on our account.
  
 
<syntaxhighlight lang="JavaScript">
 
<syntaxhighlight lang="JavaScript">
Line 105: Line 105:
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Under the '''response''' object in the reply from the server is an array of devices.  The device_id is listed in this information.  For the remainder of this example let's assume we have acquired the following device_id:
+
The array of device data can be found in the '''response''' object in the server's reply.  For the remainder of this example let's assume we have acquired the following device_id:
 
   device_id = 9191
 
   device_id = 9191
  

Latest revision as of 11:58, 20 April 2026

Where's the API Documentation?

REST API docs

How do I make REST calls?

All REST requests should be made against https://rest.sensaphone.net

We recommend the use of a REST client for developing and testing calls to our REST API. Searching for 'rest client' in your favorite search engine will turn up many suitable results.

How do I login?

Overview

To use the Sensaphone REST API, a login call must first be made. A successful login request will return an account number and a session token. These will be used in all subsequent requests. Two examples of login requests are shown below. First, the URI-mode version, followed by the JSON-mode version.

Examples

URI-mode:

POST https://rest.sensaphone.net/api/v1/login/{[email protected]}/{abc123_my_password}

JSON-mode:

POST https://rest.sensaphone.net/api/v1/login
{
  "request_type": "create",
  "resource": "login",
  "user_name": "[email protected]",
  "password": "abc123_my_password"
}

Reply

The reply to a successful login request will contain a result object and a response object. The result communicates the overall success of the call. The response contains the data in which we are interested: in this case, the account number (acctid), and the session token. The account number and session token will be used in every subsequent query submitted to the API.

{
  "result": {
    "success": true,
    "code": 0,
    "message": "Success"
  },
  "response": {
    "acctid": 21620750,
    "session": "1234ffffeeee5678aaaccda609cd8fb5099",
    "login_timestamp": 1605562465,
    "session_expiration": 86400,
    "user_id": 12345678
  }
}

References

  1. Login Resource: Additional information about the login resource
  2. URI-mode/JSON-mode: Information about URI-mode and JSON-mode

How do I access log data?

Overview

Queries to our logging facilities are one of the most popular uses of the Sensaphone API. Making a successful log query involves first acquiring multiple pieces of data from the API. Because of this fact, crafting your first log query will be a multi-step process. All logs are accessed through the history resource. Outlined below you will find a practical example of how to gather the data needed to make a successful query to the history resource. We will use JSON-mode for each request as we gather the info required to query for datalogs.

If there are multiple log points within a similar time range you wish to access, it is generally more efficient to submit a request which includes all log points in which you are interested and use larger page sizes. You can then page through the results returned by the API, processing as you go. This is preferable to smaller, more frequent requests to individual log points using smaller page sizes.

Examples

Datalog

Every device (e.g. Sentinel, Sentinel Pro, Stratus) associated with an account has input zones to which sensors may be connected. A device may be configured to log the value of any input zone at specific intervals. On www.sensaphone.net (the Website) the user may query a time range of datalog records for a single device. Users of the REST API can make similar queries against the input zones of one or more devices.

The data required to perform a datalog query are defined as follows:

log_points/data_log_points
List of one or more globally unique numeric ID's, each representing a "loggable" device zone.
begin_offset
The offset of the first record to be returned to the caller. An offset of 0 indicates the beginning of the queried timerange. Increasing this offset by 50, for example, means we return results beginning with the fiftieth record obtained by the query. Use this value to "page" through results in descending order, newest to oldest. Experiment to find an offset value that works well for your application. Works in tandem with "record_offset".
record_offset
Number of results to return per "page".
start
The greatest (most recent) Sensaphone-encoded timestamp we are interested in, non-inclusive. Also see below for more details about how this value may be calculated.
end
The least (oldest) Sensaphone-encoded timestamp we are interested in, inclusive. Also see below for more details about how this value may be calculated.

We will take the following steps to retrieve the information necessary for a query to the datalog facility:

  1. Get a list of devices associated with an account
  2. Get a list of log_points from a device
  3. Calculate Sensaphone-encoded start and end timestamps
  4. Query for datalog records
  5. Page through the results

For the remainder of this example, let's assume the following:

 acctid = 12345678  # account_id
 session = 1234aaa5678bbbb8765cccc4321dddd  # session token
List Devices

First let's list all devices associated with our account and choose one from the results. To do this we will make a call to the Dashboard resource, requesting the name and device_id of each device on our account.

POST https://rest.sensaphone.net/api/v1/{12345678}/{1234aaa5678bbbb8765cccc4321dddd}/dashboard
{
  "request_type": "read",
  "resource": "dashboard",
  "dashboard": {
    "device": [
      {
        "device_id": null,
        "name": null
      }
    ]
  }    
}

The array of device data can be found in the response object in the server's reply. For the remainder of this example let's assume we have acquired the following device_id:

 device_id = 9191
List Log Points

With a device_id of 9191 in hand, we may now query for log_points associated with that device.

POST https://rest.sensaphone.net/api/v1/{12345678}/{1234aaa5678bbbb8765cccc4321dddd}/history/data_log_points
{
  "request_type": "read",
  "resource": "history",
  "history": [
    {
      "data_log_points": {
        "resource_type": "device",
        "device_id": 9191
      }
    }
  ]
}

The server's reply will contain data for each loggable zone, including input zones and output zones. The log_point value of each zone is unique across all devices. Therefore a log_point value of 78208181 will refer to one, and only one, zone. Extract log_point values for all zones to be queried.

Assume we have decided to pull datalog records for the following log points:

 15144093
 15145683
 15148853
Calculate start and end timestamps

Calculate the start and end timestamps as outlined here. The range of records returned will fall in the range (start, end], meaning records will be considered a match if the date of the record equals end all the way up to, but not including, start.

⚠ Warning: start and end are reversed from convention.

In the datalog API, start is the most recent (newest) timestamp in your range, and end is the oldest timestamp. Records are returned in descending order, newest first. The query range is exclusive of start and inclusive of end, expressed as the interval (start, end].

Let's assume we wish to query the following two dates:

 start = November 18, 2020 12:30pm --> sensaphone_time(2020, 10, 17, 12, 30, 00) --> 671113800
 end   = November 01, 2020 12:00am --> sensaphone_time(2020, 10, 00, 00, 00, 00) --> 669600000
Make the request

Now that we have all the necessary data we can put it together and make our datalog request.

POST https://rest.sensaphone.net/api/v1/{12345678}/{1234aaa5678bbbb8765cccc4321dddd}/history/data_log
{
  "request_type": "read",
  "resource": "history",
  "history": {
    "data_log": {
      "log_points": [ 15144093, 15145683, 15148853 ],
      "start": 671113800,
      "end": 669600000,
      "begin_offset": 0,
      "record_offset": 1000
    }
  }
}

Assuming records exist for those log_points during that time range, 1000 of them will be returned. Why 1000? Recall that record_offset determines the maximum number of records to be returned per request.

Paging through results

If there are more records to be reviewed, we can page through our results by making another call. This time we will increment the begin_offset by the number of records per page (record_offset).

POST https://rest.sensaphone.net/api/v1/{12345678}/{1234aaa5678bbbb8765cccc4321dddd}/history/data_log
{
  "request_type": "read",
  "resource": "history",
  "history": {
    "data_log": {
      "log_points": [ 15144093, 15145683, 15148853 ],
      "start": 671113800,
      "end": 669600000,
      "begin_offset": 1000,      "record_offset": 1000
    }
  }
}
Queries against zones of multiple devices

Recall that zone ID's are unique across all devices. If you wish to query for datalog records on zones across multiple devices, simply acquire the log points for the zones of the devices you wish to view and make your query as we have shown above. The only difference here is that the log points used in the request represent zones across more than one device.

Tips for Effective Datalog Requests

  1. When datalog values for multiple log points are required, an efficient request will include several log points of interest over a given time range with a larger page size (record_offset). This provides more context to the API, allowing it to prefetch records as you page through your results. Avoid making flurries of requests for individual log points and/or using small page sizes where a larger more comprehensive request can be made.
  2. Adjust your page size (record_offset) to your use case. If performing bulk processing then prefer larger page sizes. Smaller page sizes may be preferable if you are displaying results for users to read.
  3. Acquire datalog values from multiple devices in the same query if the desired time ranges are compatible.
  4. Datalog values are not 'live' data. Polling the API repeatedly for recent datalog values will not cause them to appear faster. Datalog records are periodically uploaded to our servers in batches by each device at a set interval. The exact time at which these uploads take place is negotiated between the device and server.

References

How do I calculate Sensaphone-encoded timestamps?

Overview

Internally, the Sensaphone API uses a custom date encoding. The only time a user of the REST API must worry about these encoded timestamps is when making requests against the history resource.

The most important thing to keep in mind when converting to Sensaphone timestamps: All data passed into the algorithm is base-0. This means that the first day of the month is not 1, but 0. Likewise January is not 1, but 0. Due to the fact that we count our minutes and seconds from 0, you will not notice a difference when passing these values into the algorithm. The same goes for the year. Where this base-0 concept will have the most noticeable impact will be hour of the day, day of the month, and month of the year.

Observe:

  • 0 - 59 seconds per minute
  • 0 - 59 minutes per hour
  • 0 - 23 hours per day (0 = 12am, 1, 2, ..., 23 = 11pm)
  • 0 - 30 are 31-day months
  • 0 - 29 are 30-day months
  • 0 - 27 most Februaries
  • 0 - 28 leap-year Februaries
  • 0 - 11 months per year
  • 2000 - ... the year

The algorithm in pseudocode:

 timestamp <-- (seconds mod 60) +                  // 0 - 59
               ((minutes * 60) mod 3600) +         // 0 - 59
               ((hours * 3600) mod 86400) +        // 0 - 23
               ((day * 86400) mod 2678400) +       // 0 - 31
               ((month * 2678400) mod 32140800) +  // 0 - 11
               ((year mod 100) * 32140800)         // 2000 - ...

Implementations

Provided below are some helpful functions to convert date and time into Sensaphone time stamps.

Bash

This implementation accepts a natural language date string and uses the date program to parse it, handling base-0 conversion internally. Both GNU date (Linux) and BSD date (macOS) are supported. This snippet is useful if you are using cURL to make your REST calls from the command line.

  1. sensaphone_time() {
  2.     local date_string="$1"
  3.  
  4.     # Parse date string to Unix timestamp
  5.     # GNU date (Linux) accepts free-form strings via -d
  6.     # BSD date (macOS) requires ISO 8601 format: "YYYY-MM-DD HH:MM:SS"
  7.     if date --version &>/dev/null 2>&1; then
  8.         local unix_time=$(date -d "$date_string" +%s)
  9.     else
  10.         local unix_time=$(date -j -f "%Y-%m-%d %H:%M:%S" "$date_string" +%s)
  11.     fi
  12.  
  13.     # Decompose Unix timestamp into components (day and month adjusted to base-0)
  14.     local second=$(date -d "@$unix_time" +%-S 2>/dev/null || date -r "$unix_time" +%-S)
  15.     local minute=$(date -d "@$unix_time" +%-M 2>/dev/null || date -r "$unix_time" +%-M)
  16.     local hour=$(date -d "@$unix_time" +%-H 2>/dev/null || date -r "$unix_time" +%-H)
  17.     local day=$(( $(date -d "@$unix_time" +%-d 2>/dev/null || date -r "$unix_time" +%-d) - 1 ))
  18.     local month=$(( $(date -d "@$unix_time" +%-m 2>/dev/null || date -r "$unix_time" +%-m) - 1 ))
  19.     local year=$(date -d "@$unix_time" +%Y 2>/dev/null || date -r "$unix_time" +%Y)
  20.  
  21.     local sensaphone_timestamp=$(( (second            % 60) +
  22.                                    ((minute      * 60) % 3600) +
  23.                                    ((hour        * 3600) % 86400) +
  24.                                    ((day         * 86400) % 2678400) +
  25.                                    ((month       * 2678400) % 32140800) +
  26.                                    ((year % 100) * 32140800) ))
  27.  
  28.     echo $sensaphone_timestamp
  29. }

Example usage:

  1. # GNU date (Linux) - accepts natural language strings
  2. sensaphone_time "November 18 2020 12:30:00"   # --> 671113800
  3. sensaphone_time "2020-11-18 12:30:00"         # --> 671113800
  4.  
  5. # BSD date (macOS) - requires ISO 8601 format
  6. sensaphone_time "2020-11-18 12:30:00"         # --> 671113800

Zsh

This implementation uses the zsh/datetime module's strptime and strftime builtins to parse and decompose dates without invoking an external date program. It accepts ISO 8601 format date strings and handles base-0 conversion internally.

  1. sensaphone_time() {
  2.     local date_string="$1"
  3.     local unix_time
  4.  
  5.     # Load zsh datetime module for strptime and strftime builtins
  6.     zmodload zsh/datetime
  7.  
  8.     # Parse date string to Unix timestamp using the strptime builtin.
  9.     # Accepts ISO 8601 format: "YYYY-MM-DD HH:MM:SS"
  10.     strptime -s unix_time "%Y-%m-%d %H:%M:%S" "$date_string"
  11.  
  12.     # Decompose Unix timestamp into named components using strftime -s.
  13.     # strftime zero-pads values (e.g. "08"), so we use (( x + 0 )) to
  14.     # strip leading zeros before arithmetic to avoid octal interpretation.
  15.     # Day and month are adjusted to base-0 as required by the API.
  16.     local -A t
  17.     strftime -s t[second] "%S" $unix_time
  18.     strftime -s t[minute] "%M" $unix_time
  19.     strftime -s t[hour]   "%H" $unix_time
  20.     strftime -s t[day]    "%d" $unix_time
  21.     strftime -s t[month]  "%m" $unix_time
  22.     strftime -s t[year]   "%Y" $unix_time
  23.  
  24.     local second=$(( t[second] + 0 ))
  25.     local minute=$(( t[minute] + 0 ))
  26.     local hour=$(( t[hour]   + 0 ))
  27.     local day=$(( t[day]     + 0 - 1 ))
  28.     local month=$(( t[month] + 0 - 1 ))
  29.     local year=$(( t[year]   + 0 ))
  30.  
  31.     echo $(( (second            % 60) +
  32.              ((minute      * 60) % 3600) +
  33.              ((hour        * 3600) % 86400) +
  34.              ((day         * 86400) % 2678400) +
  35.              ((month       * 2678400) % 32140800) +
  36.              ((year % 100) * 32140800) ))
  37. }

Example usage:

  1. # Accepts ISO 8601 format date strings
  2. sensaphone_time "2020-11-18 12:30:00"  # --> 671113800
⚠ Note: zsh/datetime and timezone behavior

The zsh/datetime module is included in all standard zsh distributions and does not require separate installation. As with the other implementations on this page, dates are interpreted in local time. To use UTC, set TZ=UTC before calling the function, or export it in your environment.

Python

This implementation accepts a standard datetime object. Note that Python's datetime.day and datetime.month are both 1-indexed, so both are adjusted to base-0 internally.

  1. from datetime import datetime
  2.  
  3. def sensaphone_time(dt):
  4.     return (dt.second     % 60) + \
  5.         ( (dt.minute      * 60) % 3600) + \
  6.         ( (dt.hour        * 3600) % 86400) + \
  7.         (((dt.day - 1)    * 86400) % 2678400) + \
  8.         (((dt.month - 1)  * 2678400) % 32140800) + \
  9.         ( (dt.year % 100) * 32140800)

Example usage:

  1. # November 18, 2020 12:30pm (local time)
  2. dt = datetime(2020, 11, 18, 12, 30, 0)
  3. print(sensaphone_time(dt))  # --> 671113800

PHP

This implementation accepts a standard DateTime object. PHP's DateTime uses 1-indexed days and months, so both are adjusted to base-0 internally.

  1. <?php
  2. function sensaphone_time(DateTime $dt): int {
  3.     $second = (int)$dt->format('s');
  4.     $minute = (int)$dt->format('i');
  5.     $hour   = (int)$dt->format('G');
  6.     $day    = (int)$dt->format('j') - 1;
  7.     $month  = (int)$dt->format('n') - 1;
  8.     $year   = (int)$dt->format('Y');
  9.  
  10.     return ($second    % 60) +
  11.         (($minute      * 60) % 3600) +
  12.         (($hour        * 3600) % 86400) +
  13.         (($day         * 86400) % 2678400) +
  14.         (($month       * 2678400) % 32140800) +
  15.         (($year % 100) * 32140800);
  16. }
  17. ?>

Example usage:

  1. <?php
  2. // November 18, 2020 12:30pm (local time)
  3. $dt = new DateTime('2020-11-18 12:30:00');
  4. echo sensaphone_time($dt);  // --> 671113800
  5. ?>

JavaScript

This implementation accepts a standard JavaScript Date object, handling the base-0 conversion for day-of-month internally. It is compatible with both browser environments and Node.js.

  1. function sensaphoneTime(date) {
  2.     return (  date.getSeconds()              % 60) +
  3.            ( (date.getMinutes()         * 60) % 3600) +
  4.            ( (date.getHours()           * 3600) % 86400) +
  5.            (((date.getDate() - 1)       * 86400) % 2678400) +  // Note: We must subtract 1!
  6.            ( (date.getMonth()           * 2678400) % 32140800) +
  7.            ( (date.getFullYear() % 100) * 32140800);
  8. }

Example usage:

  1. // November 18, 2020 12:30pm (local time)
  2. const date = new Date(2020, 10, 18, 12, 30, 0);
  3. sensaphoneTime(date); // --> 671113800

References