IOStash is a Platform as a Service (PaaS) for the Internet of Things. IOStash abstracts and simplifies the way devices and their related services are interconnected. IOStash enables super fast data collection from devices in a simple and natural way, so that developers and product designers can design their products in never before seen ways.

The REST and Socket API’s provide programmatic access to read and write data from and to the IOStash Platform. Responses are available in JSON or XML.

Platform Overview

IOStash platform has the following data hierarchy.

Data Overview

Reading and writing data is the core of IOStash, managing & distributing that data is the primary application of IOStash API.

IOStash API makes it easy for your devices, applications and services to read and write data to IOStash and through IOStash to each other. IOStash supports reading and writing data via three resources: Channels, Devices and Datapoints.



Channel: The channel is at the top of the IOStash Data hierarchy. A channel is simply a collection of devices, that you'd like to group together. For example, suppose you're building a network of weather stations across your city, you will want to group all the stations (devices) that contribute to your data. This grouping of devices can help you obtain collective data and also, you can address all of them by the channel name. If you are a product manufacturer, you might want to use channels for a particular line of products.Channels are like groups, you can send messages to every single device in the channel via the messaging API. A channel has its own meta data associated with it. These meta data includes the channel name, a unique id, the devices associated with it and the details about its creation and ownership. Channel specific queries that enable data selection, filtering and comparison are available via the API.

The channel object has the following structure:
   channel:{
    	channelName,
    	devices:[Array of memeber devices]
    }

Device: A device (also called a producer) is an entity that sends data to the IOStash platform. A device can be a microcontroller, a mobile phone or even an application that sends data to the platform. A device is identified by its DeviceID parameter, which is unique across the IOStash platform. You'll have to use your device ID to read/write data from/to the particular device.
A device can be of two types, Static or Dynamic. A Static device is the one that is geographically static, which means that the device is stationary at a particular point. For example, a weather station. A Dynamic device is the one which is not stationary at a particualar point. For example, a vehicle tracker or a Quadcopter. All devices will have its own meta data including device name, its id, description, location data (for a static device, installation location is used), the data points associated with it and the channels it is a part of. A collection of devices form a channel and a device can be a part of multiple channels.

The device object has the following structure:
 device: { 
        deviceName,
        type: [static/dynamic],
        description,
        isPublic: [true/false],
        enabled:[true/false],
        geoLocation: {
            latitude,
            longitude
        },
        dataPoints:[array of data points associated],
        channels:[array of channels, the device is a member of],
        dateCreated,
        dateActivated,
        lastValue,
        deviceControl:[{
            control,
            creationDate,
            status:[true/false]
         }]
        }

Data Point: A Datapoint represents a single value of a metric (a physical value read by a device) at a specific point in time. It is simply a key value pair consisting of a timestamp and the value at that time. A device can have multiple data points. They are the bare data units in the IOStash platform. A data point is identified by its name. A device can have multiple unique data points. Data points can store any type of value, including integer, float, double, boolean or string. IOStash platform does not impose any kind of type restrictions on the datapoints.

A data point object has the following structure:
dataPoint:[{
    	value,
    	commitTime
    	}]
       
In the IOStash platform, dataPoints store the actual data from devices. All data selection queries are performed upon the dataPoints.

RESTful API Overview

IOStash RESTful API provides RESTful methods to read/write data. For most low power, low performance microcontrollers (Arduino, for example), RESTful APIs are the way to go when connecting them to the internet. You can use these APIs with your microcontrollers or your applications.

IOStash RESTful API provide language neutral data access to your devices and your applications. Since these APIs are platform/language independant, you can use these for any type of application involving IOStash data access, while ensuring security and flexibility.

To get a list of available end points, perform a /GET on

https://api.iostash.io/0.1/details/
NOTE: All URL's must end with a trailing slash, for example, https://api.iostash.io/0.1/devices/. If omitted, the system will return a 404.

Responses

IOStash will return responses for all queries and commands including when data is written. All responses will be having the HTTP header 200.

Success Response

If the outcome of a request is success, the system will return the response in the following format:
{
error: false,
message: <message_goes_here>
}

          
The 'error' variable will hold the value 'false' for a success message and the 'message' variable will hold the message that was returned by the platform.

Error Response

If the outcome of a request is an error, the system will return the response in the following format:
{
error: true,
message: <error_message_goes_here>
}

          

Base URL

All URLs referenced in the documentation have the following base:

https://api.iostash.io/0.1/
IOStash REST API is served over HTTPS by default. However, plain HTTP is also supported, to ensure data privacy, unencrypted HTTP is not recommended.

Authentication

HTTP requests to the REST API are protected with x-access-token header authentication. Your access token must be sent as x-access-token in the header of every request you dispatch. You can get your access token from your dashboard. Click here to see how.

Parameter Type Description Notes
x-access-token Request Header x-access-token header must be set to access any authenticated resource on the API. If x-access-token is not specified, the server will return Unauthorized

Examples

Using cURL,

curl -i -H "x-access-token: your_access_token_here" -H "Content-Type: application/json" https://api.iostash.io/0.1/devices/

Using Arduino and the Ethernet shield, you can do the following:


#include <SPI.h>
#include <Ethernet.h>

byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
char server[] = "api.iostash.io";
IPAddress ip(192,168,0,10);

EthernetClient client;

void setup() {
 Serial.begin(9600);
 while (!Serial) {
    ;
 }

 Ethernet.begin(mac, ip);

 delay(1000);
 Serial.println("connecting...");

 if (client.connect(server, 80)) {
Serial.println("Connected");
//Set Headers
client.print("GET /devices/ HTTP/1.1\r\n");
client.print("Host: api.iostash.io\r\n");
client.print("x-access-token: your_access_token_here\r\n");
client.print("Connection: close\r\n\r\n");
client.println();
 }else {
    Serial.println("connection failed");
 }
}

void loop(){
   if (client.available()) {
     char c = client.read();    
     Serial.print(c);
   }

  
  if (!client.connected()) {
     Serial.println();
     Serial.println("disconnecting.");
     client.stop();
     for(;;)     ;  
   }
 }

           

Writing Data

Writing data to IOStash from your device via the RESTful API is easy as dispatching a /POST request. Suppose you have defined two datapoints; temperature & humidity. From your device, you can write values to these data points by dispatching a /POST request to https://api.iostash.io/devices/your_device_id/. You can write multiple data points or a single data point in one request. Latitude and longitude are built in data points, you can post them without explicitly defining. IOStash will save the datapoint values and will return a success message and a unique MessageID which can be used to track the message in a later period of time. When new data is written, all subscribers of the particular device and channel will receive the update in realtime.

URL to initiate /POST

https://api.iostash.io/device/your_device_id/
Parameter Type Description Notes
your_device_id URL Parameter Use the ID of the device you're trying to push data to. If device ID is not specified or an invalid/unauthorized device ID is used, IOStash will return error. Invalid deviceID
Access Token Request Header Acces Token must be specified in the request header to write data. If Access Token is not specified or is not valid for the device, IOStash will return error. Unauthorized
dataPoint(s) Request Body Pass defined datapoints and corresponding values inside the request body. latitude & longitude are already defined in the system. If an invalid datapoint is used, IOStash will return error. Data point not specified

If the operation is successful, IOStash will return this response:

{
error: false,
message: "Data Saved",
messageId: UNIQUE_MESSAGE_ID,
commitTime: TIME_OF_COMMIT 
}
          

NOTE: Bulk data/historical data cannot be persisted to IOStash at this time, but will be support the same soon. commitTime variable will store the time of data commit as the milliseconds elapsed since 1 January 1970 00:00:00 UTC up until now (Default javascript timestamp).

Examples

Consider the above example; a device with two data points temperature and humidity. Using cURL,

curl -i -H "x-access-token: your_access_token_here" -XPOST -H "Content-type: application/json" -d '{"temperature":"27.89","humidity":"32"}' https://api.iostash.io/0.1/devices/your_device_id/

Using Arduino and the Ethernet shield,



/*
This sketch will Read a DHT22 Sensor connected to PIN 6 of Arduino and will push the temperature & humidity data to IOStash
*/

#include <SPI.h>
#include <Ethernet.h>
#include <dht.h>

dht DHT;

#define DHT22_PIN 6

byte mac[] = {  
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

//Change to your server domain
char serverName[] = "api.iostash.io";

// change to your server's port
int serverPort = 80;

// change to the page on that server
char pageName[] = "/0.1/devices/YOUR_DEVICE_ID_HERE/";

EthernetClient client;
// insure params is big enough to hold your variables
char params[32];

// set this to the number of milliseconds delay
// this is 30 seconds
#define delayMillis 30000UL

unsigned long thisMillis = 0;
unsigned long lastMillis = 0;

void setup() {
  Serial.begin(9600);

  // disable SD SPI
  pinMode(4,OUTPUT);
  digitalWrite(4,HIGH);

  Serial.print(F("Starting ethernet..."));
  if(!Ethernet.begin(mac)) Serial.println(F("failed"));
  else Serial.println(Ethernet.localIP());

  delay(2000);
  Serial.println(F("Ready"));
}

void loop()
{
  // If using a static IP, comment out the next line
  Ethernet.maintain();

  thisMillis = millis();

  if(thisMillis - lastMillis > delayMillis)
  {
  lastMillis = thisMillis;
  Serial.print("DHT22, \t");
  int chk = DHT.read22(DHT22_PIN);
  switch (chk)
  {
    case DHTLIB_OK:  
		Serial.print("OK,\t"); 
		break;
    case DHTLIB_ERROR_CHECKSUM: 
		Serial.print("Checksum error,\t"); 
		break;
    case DHTLIB_ERROR_TIMEOUT: 
		Serial.print("Time out error,\t"); 
		break;
    default: 
		Serial.print("Unknown error,\t"); 
		break;
  }
  Serial.print(DHT.humidity, 1);
  Serial.print(",\t");
  Serial.println(DHT.temperature, 1);
    // POST Data
    sprintf(params,"temperature=%i,humidity=%d",DHT.temperature,DHT.humidity);     
    if(!postPage(serverName,serverPort,pageName,params)) Serial.print(F("Fail "));
    else Serial.print(F("Pass "));
  }    
}


byte postPage(char* domainBuffer,int thisPort,char* page,char* thisData)
{
  int inChar;
  char outBuf[64];

  Serial.print(F("connecting..."));

  if(client.connect(domainBuffer,thisPort) == 1)
  {
    Serial.println(F("connected"));

    // send the header
    sprintf(outBuf,"POST %s HTTP/1.1",page);
    client.println(outBuf);
    sprintf(outBuf,"Host: %s",domainBuffer);
    client.println(outBuf);
    sprintf(outBuf,"x-access-token: your_access_token_here\r\n",domainBuffer);
    client.println(outBuf);
    client.println(F("Connection: close\r\nContent-Type: application/x-www-form-urlencoded"));
    sprintf(outBuf,"Content-Length: %u\r\n",strlen(thisData));
    client.println(outBuf);

    // send the body (variables)
    client.print(thisData);
  } 
  else
  {
    Serial.println(F("failed"));
    return 0;
  }

  int connectLoop = 0;

  while(client.connected())
  {
    while(client.available())
    {
      inChar = client.read();
      Serial.write(inChar);
      connectLoop = 0;
    }

    delay(1);
    connectLoop++;
    if(connectLoop > 10000)
    {
      Serial.println();
      Serial.println(F("Timeout"));
      client.stop();
    }
  }

  Serial.println();
  Serial.println(F("disconnecting."));
  client.stop();
  return 1;
}

Sending Custom Data to Devices

IOStash platform supports sending data to connected devices through the RESTful API interface. Data will be delivered to the corresponding device via MQTT with QoS 1 or Realtime API. This is particularly useful when the user wants to send a control word to a connected device without persisting any data, for example, a connected switch - the user can send ON/OFF messages directly to the device, the device can then change the state and persist state to IOStash, leading to consistent, predictable device operation. In this mode, IOStash acts as a message broker between your device and applications. Please note that this will NOT persist any data to IOStash and it is the responsibility of the solution developer to ensure that the device has taken the action corresponding to the data sent and persist the state to IOStash.

A /POST request has to dispatched to the URL http://api.iostash.io/devices/your_device_id/publish/ with the data to be sent as the body of the request. The client(s) will receive the update in realtime via MQTT or Realtime API. The message object will have the publish time, message ID and the body of the message. The data format of the message object is:

{
publishData:{
  msg
},
msgId,
publishTime
}
publishData field will have the object sent by the sender as key-value pairs. msgId and publishTime will be sent to both the device and the application dispatching the request. Data is published to MQTT clients with QoS 1, to ensure guaranteed message delivery.

URL to dipatch /POST request:

http://api.iostash.io/devices/your_device_id/publish/

Parameter Type Description Notes
your_device_id URL Parameter Use the ID of the device you're trying to push data to. If device ID is not specified or an invalid/unauthorized device ID is used, IOStash will return error, Invalid deviceID
Access Token Request Header Acces Token must be specified in the request header to write data. If Access Token is not specified or is not valid for the device, IOStash will return error. Unauthorized
Message Request Body Pass the message to send as the body of the request. In case of an empty body or invalid data, Invalid JSON/Malformed Data will be returned.

If the message was sent successfully, the following response will be returned:

{
  error: false.
  message: "Data Published To Device",
  messageId,
  publishTime
}

NOTE: While using Pub/Sub client library for ESP8266 Arduino, make sure that the MQTT_MAX_PACKET_SIZE constant is set at a higher value than the default 128, to ensure that the message is received properly. If left at the default 128, message might not get delivered.

Example

curl -i -H "x-access-token: your_access_token_here" -XPOST -H "Content-type: application/json" -d '{"custom_message":"anything can go here"}' 'https://api.iostash.io/0.1/devices/your_device_id/publish/'

Reading Data

Reading data in IOStash can be done in many ways. There are two data feeds available for reading data from IOStash - Devices feed and Channels feed. Data can be read from both Devices and Channels. A device feed has a number of data points, while a channel feed has a number of devices. Hence, reading data from a channel will return a lot of data. Reading data from a channel/device can be accomplished by dispatching a /GET request on the corresponding API URL.

Apart from the generic read, IOStash supports various read queries to filter the data retrieved. These queries can be used to filter the data returned from the server and can help in executing efficient API utilization. Use of read queries with filters are highly recommended. IOStash supports the following two main filter options: TOP and SKIP. Both these filter options MUST be accompanied by these secondary filter options: SORT and by. The TOP filter will return the last n results while the SKIP filter will generate the outpt by skipping the first n values. The sub filter SORT is used to sort the result set returned. A datapoint name or commit time can be used as a SORT parameter. The by sub filter can be used to generate the result set in ascending or descending order. asc and desc are the two permitted by parameters.

If none of the fltering parameters are specified, IOStash will return 50 readings sorted by commitTime in ascending order. Which is more than enough for general purpose applications. All data read requests must be authenticated with X-Access-Token or they'll return Unauthorized.


1. Reading data from devices

To read the data from the specified device a /GET request has to dispatched. Suppose the user wants to read data from a device with ID device_id. It can be retrieved by a /GET request to device as http://api.iostash.io/0.1/devices/device_id/read/. Since no filtering conditions are specified, first 50 data from the specified device will be returned.

URL to initiate /GET

https://api.iostash.io/0.1/devices/your_device_id/read/
Parameter Type Description Notes
your_device_id URL Parameter Use the ID of the device you're trying to fetch data from. If device ID is not specified or an invalid/unauthorized device ID is used, IOStash will return error. Invalid deviceID
Access Token Request Header Acces Token must be specified in the request header to read data. If Access Token is not specified or is not valid for the device, IOStash will return error. Unauthorized

If the operation is successful, IOStash will return this response:

{
error: false,
message: "Data Fetch Successful",

}
          

NOTE: commitTime variable will store the time of data commit as the milliseconds elapsed since 1 January 1970 00:00:00 UTC up until now (Default javascript timestamp).

 

2. Reading data from devices with TOP filter

To read first n data from the specified device a /GET request has to dispatched with the TOP filter query. Parameters such as number of readings (n), sort order and default sort by field have to be specified in the URL as parameters.

URL to initiate /GET

http://api.iostash.io/0.1/devices/your_device_id/readbyq?top=n&&sort=datapointName&&by=asc|desc 
Parameter Type Description Notes
your_device_id URL Parameter Use the ID of the device you're trying to fetch data from. If device ID is not specified or an invalid/unauthorized device ID is used, IOStash will return error. Invalid deviceID
Access Token Request Header Acces Token must be specified in the request header to read data. If Access Token is not specified or is not valid for the device, IOStash will return error. Unauthorized
top URL parameter The number of readings that has to be fetched from top. If top is not a valid number, IOStash will return error. Please enter a valid number.If no number is specified, first 50 data will be fetched.
sort URL parameter The field by which we sort the data. If sort is not a valid schema field, IOStash will return error. Invalid sort field..If no sort field is specified, the data will be sorted by datapoint name.
by URL parameter The order of data display. ASC-ascending or DESC-descending If by field is not valid, IOStash will return error. Invalid order field..If no by order field is specified, the data will be sorted in ascending order.

If the operation is successful, IOStash will return this response:

{
error: false,
message: "Data Fetch Successful",
}
          

NOTE: commitTime variable will store the time of data commit as the milliseconds elapsed since 1 January 1970 00:00:00 UTC up until now (Default javascript timestamp).

Examples

A sample url which fetches top 20 readings is as follows:
http://api.iostash.io/devices/your_device_id/readbyq?top=20&&sort=datapointName&&by=asc|dsc.

If no sorting conditions are specified, the data will be sorted in ascending order of data points. That is, if the url is, http://api.iostash.io/devices/your_device_id/readbyq?top=20, then by default, the data will be sorted in ascending order of data points.


3. Reading data from devices with SKIP and TOP filters

To skip first m readings while fetching the data the from the specified device SKIP filter can be used.

URL to initiate /GET

http://api.iostash.io/0.1/devices/your_device_id/readwithskip?top=n&&skip=m&&sort=datapointName&&by=asc|dsc 
Parameter Type Description Notes
your_device_id URL Parameter Use the ID of the device you're trying to fetch data from. If device ID is not specified or an invalid/unauthorized device ID is used, IOStash will return error. Invalid deviceID
Access Token Request Header Acces Token must be specified in the request header to read data. If Access Token is not specified or is not valid for the device, IOStash will return error. Unauthorized
skip URL parameter The number of readings that have to be skipped. If skip is not a valid number, IOStash will return error. Please enter a valid number.If no number is specified, No data will be skipped.
top URL parameter The number of readings that has to be fetched from top. If top is not a valid number, IOStash will return error. Please enter a valid number.If no number is specified, first 50 data will be fetched.
sort URL parameter The field by which we sort the data. If sort is not a valid schema field, IOStash will return error. Invalid sort field..If no sort field is specified, the data will be sorted by datapoint name.
by URL parameter The order of data display. ASC-ascending or DESC-descending If by field is not valid, IOStash will return error. Invalid order field..If no by order field is specified, the data will be sorted in ascending order.

If the operation is successful, IOStash will return this response:

{
error: false,
message: "Data Fetch Successful",

}
          

NOTE: commitTime variable will store the time of data commit as the milliseconds elapsed since 1 January 1970 00:00:00 UTC up until now (Default javascript timestamp).  

Examples

A sample url which skips first 20 readings and fetches the next 20 is as follows:
http://api.iostash.io/devices/:deviceId/readwithskip?top=20&&skip=20&&sort=datapointName&by=asc.

If no sorting conditions are specified, the data will be sorted in ascending order of data points. That is, if the url is as http://api.iostash.io/devices/your_device_id/readwihskip?top=20&&skip=20, then by default the data will be sorted in ascending order of data points.


4. Reading data from channels

To read the data from a specified channel a /GET request has to dispatched. Suppose the user wants to read data from channel, it could be retrieved by a /GET request to channel as http://api.iostash.io/channels/your_channel_id/read. If no filtering conditions are specified, first 50 data from the specified channel will be fetched.

URL to initiate /GET

https://api.iostash.io/0.1/channels/your_channel_id/read/
Parameter Type Description Notes
your_channel_id URL Parameter Use the ID of the channel you're trying to fetch data from. If device ID is not specified or an invalid/unauthorized device ID is used, IOStash will return error. Invalid deviceID
Access Token Request Header Acces Token must be specified in the request header to read data. If Access Token is not specified or is not valid for the device, IOStash will return error. Unauthorized

If the operation is successful, IOStash will return this response:

{
error: false,
message: "Data Fetch Successful",

}
          

NOTE: commitTime variable will store the time of data commit as the milliseconds elapsed since 1 January 1970 00:00:00 UTC up until now (Default javascript timestamp).

 

5. Reading data from channels with SKIP and TOP filters

To skip first n readings while fetching the data from the specified channels /GET request has to dispatched. Values such as number of readings to be skipped, number of readings to be read, sort order and default sort by field have to be specified as URL parameters.

A sample url which skips first 20 temperature readings and fetches the next 20 is as follows:
http://api.iostash.io/channels/:channelId/readwithskip?top=20&&skip=20&&sort=datapointName&&by=asc.

If no sorting conditions are specified, the data will be sorted in ascending order of data points. That is, if the url is as http://api.iostash.io/0.1/channels/your_channel_id/readwihskip?top=20&&skip=20, then by default the data will be sorted in ascending order of data points.

URL to initiate /GET

http://api.iostash.io/0.1/channels/your_channel_id/readwithskip?top=n&&skip=m&&sort=datapointName&&by=asc|dsc 
Parameter Type Description Notes
your_channel_id URL Parameter Use the ID of the channelyou're trying to fetch data from. If channelID is not specified or an invalid/unauthorized channel ID is used, IOStash will return error. Invalid channelID
Access Token Request Header Acces Token must be specified in the request header to read data. If Access Token is not specified or is not valid for the channel, IOStash will return error. Unauthorized
skip URL parameter The number of readings that have to be skipped. If skip is not a valid number, IOStash will return error. Please enter a valid number.If no number is specified, No data will be skipped.
top URL parameter The number of readings that has to be fetched from top. If top is not a valid number, IOStash will return error. Please enter a valid number.If no number is specified, first 50 data will be fetched.
sort URL parameter The field by which we sort the data. If sort is not a valid schema field, IOStash will return error. Invalid sort field..If no sort field is specified, the data will be sorted by datapoint name.
by URL parameter The order of data display. ASC-ascending or DESC-descending If by field is not valid, IOStash will return error. Invalid order field..If no by order field is specified, the data will be sorted in ascending order.

If the operation is successful, IOStash will return this response:

{
error: false,
message: "Data Fetch Successful",

}
          

NOTE: commitTime variable will store the time of data commit as the milliseconds elapsed since 1 January 1970 00:00:00 UTC up until now (Default javascript timestamp).

 

6. Reading a commit with messageID

Sometimes, it may be required to read a particular commit for integrity check or for some other purpose. IOStash provides a method for individually identifying and reading each commit via the messageID field. If the messageID is known, the corresponding commit can be read back from IOStash. To read a particular commit, dispatch a GET request to https://api.iostash.io/0.1/devices/device_id/messageId. IOStash will return the commit in JSON format.

URL to initiate /GET

https://api.iostash.io/0.1/devices/device_id/messageId
Parameter Type Description Notes
device_id URL Parameter Use the ID of the device you're trying to fetch data from. If device ID is not specified or an invalid/unauthorized device ID is used, IOStash will return error. Invalid deviceID
Access Token Request Header Acces Token must be specified in the request header to read data. If Access Token is not specified or is not valid for the device, IOStash will return error. Unauthorized
messageID URL Parameter Use the messageID you're trying to fetch. If messageID is not specified or is not valid for the device, IOStash will return error. Invalid MessageID

Realtime API Overview

IOStash realtime API provides javascript methods for receiving realtime data updates from your devices and/or channels. Purpose of these APIs is to give the developer an option to listen for data changes in realtime and perform actions accordingly without explicitly reading for data changes.

Realtime API is available as nodejs module and javascript library for use in web applications. To install IOStash npm module, execute:

$ npm install iostash 

IOStash web client library is available via the JSDelivr CDN. Add it to your apps by including :

<script type="text/javascript" src="https://cdn.jsdelivr.net/iostash/0.1/iostash.js"></script>

IOStash realtime API uses Socket.io over SSL for sockets communication. It should be noted that only secure connections are supported at the moment.

Initialization

Before listening to any events, initialization function has to invoked with the user's x-access-token. init() function is responsible for the connection establishment with IOStash servers. There are two initialization methods available, init(x-access-token) and initPublic(deviceID).

init() method is to be used in applications where the source code of the application is not available to the public, like in server side applications. initPublic() function is to be used in applications where the source code of the application is available to the public and the device is set as public. It is to be used when storing x-access-token in plain text accessible to the public is a security concern. Note that while using initPublic(), deviceID of the public device is to be passed instead of the x-access-token.

If initPublic() is used, only a public device and its data points can be listened to, channels and private devices cannot be accessed.

Responses

All data update callbacks will return data as a JSON response with the following strucutre:

{
eventDescription, //Available in all updates
deviceId, //In case of a channel update
update: {
      dataPointName : updated_value, //Available in all updates
      commitTime, //Available in all updates
      msgId //Unique ID of the message
      }
}

eventDescription can be one of either dataPointUpdate, deviceUpdate, channelUpdate or customDataPublished. deviceId will hold the id of the device that caused the update in case of a channelUpdate event. dataPointName will have the name of the datapoint that changed and its corresponding value.

Listening to Data Point Updates

To subscribe to a dataPoint update from a single device, the following has to be used in case of a private device/server side code. The callback will be executed everytime a new data is pushed to the specified data point.

iostash.init('x-access-token');
iostash.subscribeDataPoint('DEVICE_ID','DATAPOINT_NAME',function(data){

//perform actions based on 'data'

});
          

eventDescription field will hold 'dataPointUpdated' in this case. If the user doesn't have permission to access the device or the datapoint doesn't exist or an invalid device id is specified, the library will show an alert using window.alert() in case of web application library or display the error using console.log() in case of a nodejs application.

If the device is a public device, initPublic('DEVICE_ID') is to be used instead of init('x-access-token').

To unsubscribe from the datapoint in a later point of time, the following is to be used

iostash.unsubscribeDataPoint('DEVICE_ID','DATAPOINT_NAME',function(data){

//'data' holds success message

});
          

Listening to Device Updates

To subscribe to a device for updates, the following is to be used. Whenever the specified device pushes data, the associated callback will be executed. init() and initPublic() functions can be used for initialization.

iostash.init('x-access-token');
iostash.subscribeDevice('DEVICE_ID',function(data){

//perform actions based on 'data'

});

eventDescription field will hold 'deviceUpdate' in this case. Listening to a device will result in receiving updates from all of the data points in the device. It is like listening to all of the data points defined in the device. If the user doesn't have permission to access the channel or an invalid channel id is specified, the library will show an alert using window.alert() in case of web application library or display the error using console.log() in case of a nodejs application.

If the device is a public device, initPublic('DEVICE_ID') is to be used.

To unsubscribe from the datapoint in a later point of time, the following is to be used

iostash.unsubscribeDevice('DEVICE_ID',function(data){

//'data' holds success message

});
          

NOTE: On successful subscription, the callback will receive the last update pushed by the device by default.

Listening to Channel Updates

To subscribe to a channel for updates, the following is to be used. Whenever a device in the specified channel pushes data, the associated callback will be executed. Only init() function can be used for initialization.

iostash.init('x-access-token');
iostash.subscribeChannel('CHANNEL_ID',function(data){

//perform actions based on 'data'

});

eventDescription field will hold 'channelUpdate' in this case. Listening to a channel will result in receiving updates from all of the devices in the specified channel. It is like listening to all of the devices defined in the channel. If the user doesn't have permission to access the channel or an invalid channel id is specified, the library will show an alert using window.alert() in case of web application library or display the error using console.log() in case of a nodejs application.

To unsubscribe from the channel in a later point of time, the following is to be used

iostash.unsubscribeChannel('DEVICE_ID','DATAPOINT_NAME',function(data){

//'data' holds success message

});
          

Listening to Location Updates

Location data of a geographically dynamic device can be listened to with the Realtime API. Whenever the device updates its location, the corresponding callback will be executed. This callback will only be executed if both latitude and longitude datapoints are pushed. Update will hold the newly pushed latitude and logitude pair along with the commitTime.

iostash.init('x-access-token');
iostash.subscribeLocation('DEVICE_ID',function(data){

//perform actions based on 'data'

});

eventDescription field will hold 'locationUpdate' in this case. If an invalid deviceID is specified, system will return error. In case of a geographically static device, this function is of no use as no location updates will be available.

Listening to Custom Data

Custom data sent to a particualr device can be listened to using this API. Custom events can be sent via the RESTful API or the MQTT interface. The callback associated with this API will be executed when a custom data is published. This is useful in keeping track of the actions performed by the device upon receiving a custom data or for analytical applications.

iostash.init('x-access-token');
iostash.subscribeCustomData('DEVICE_ID',function(data){

//perform actions based on location 'data'

});

eventDescription field will hold 'customDataPublished' in this case. Data is sent as JSON key value pairs and will be received as is. Rest of the update object remains like in other events.

MQTT Realtime API

IOStash supports MQTT interface for data communication, which can be used for pushing data or for listening to data updates from devices or channels. This API is aimed to be used in devices with connectivity and processing constraints. IOStash supports QoS 1 for all system topics and updates, and hence a unique client ID is required while connecting via MQTT. Like in other interfaces, MQTT API also uses JSON for data exchange.

NOTE: IOStash cannot be used as a general purpose MQTT broker, only predefined topics which are discussed below are supported.

For using MQTT, the following host URL and port is to be used

Host URL: api.iostash.io
Port: 1883

Authentication

IOStash MQTT API requires authentication for publishing and subscribing topics. Pass x-access-token as the username and the device secret which is created during device creation as the password. Set client id to the deviceID. If listening to data updates, set a unique name as client ID or else messages will be delivered with QoS 0 instead of QoS 1.

Topics

Like every other MQTT broker, topics are at the core of IOStash MQTT API. However, unlike general purpose MQTT brokers, IOStash does not support generic user defined topics or $SYS topics. Also ,unlike generic brokers, IOStash will not disconnect on data/protocol/subscribe errors. Instead, error message will be published to the topic x-access-token/deviceID/system or x-access-token/system, depending on the error context.
NOTE: Leading slash in topics is mandatory.

Writing Data

Data can be published to IOStash from devices by publishing to the corresponding device's topic. Data must be a valid JSON object/string and the user must have access to the device.
To publish data, the following topic is to be used with corresponding x-access-token and deviceID.

/x-access-token/deviceID

For IOStash to recognize and persist data, it must be in the following JSON format:

{
"datapoint": value,
"datapoint": value
}

Once the data is persisted, response will be published to

/x-access-token/deviceID/system
as JSON string with the following format:
{
error: false,
message: "Data Saved",
messageId: UNIQUE_MESSAGE_ID,
commitTime: TIME_OF_COMMIT 
}
All realtime listeners of the device will receive the new data update.

Subscribing to Device Updates

For device updates, the following topic can be subscribed to with correspoding x-access-token and deviceID. If the user does not have access to the device, error will be published to /system topic.

/x-access-token/deviceID

New updates will be received as JSON strings of following format:

{
eventDescription, 
update: {
      dataPointName : updated_value,
      commitTime,
      msgId
      }
}

Subscribing to Channel Updates

For channel updates, the following topic can be subscribed to with correspoding x-access-token and channelID. If the user does not have access to the channel, error will be published to /system topic

/x-access-token/channelID

New updates will be received as JSON strings of following format:

{
eventDescription,\
deviceId,
update: {
      dataPointName : updated_value,
      commitTime,
      msgId
      }
}

Subscribing to Custom Data Updates

For custom data updates sent to device, the following topic can be subscribed to with correspoding x-access-token and deviceID. If the user does not have access to the device, error will be published to /system topic

/x-access-token/deviceID/custom

Subscribing to Trigger Actions

Trigger action data sent by a trigger can be listened to, by subscribing to the following topic with the correspoding x-access-token and deviceID. If the user does not have access to the device, error will be published to /system topic

/x-access-token/deviceID/actions