This is a usefull framework to support any Nodejs application that intends to communicate with dojot platform. The library component maps the Dojot endpoints and lets you add the entire Dojot public API to your application. Take a look at http://www.dojot.com.br/ for more.
For now, this library is being developed and it's not ready to become a npm package, so it is necessary to import to your project the entire github repository link:
npm install git+https://github.com/davicedraz/dojot-framework.git --save
The dojot-framework aims to serve the main methods available at Dojot endpoints to make easy building IoT applications. The current version of the library provides methods and enable the acess of the following API Components:
- Device Simulator
- User authentication
- User management
- Template management
- Device management
Socket.ioTime data
Check the docs to see more.
First of all, you should have a instance of Dojot platform running locally or has access to one. check the installation guide here if you don't have yet.
-
Create a json config file and set, at least, the following variables:
- platformURL (has to be the URL where the Dojot platform runs on port :8000)
- credentials (has to be the username and password registered on platform)
{ "platformURL": "http://localhost:8000", "platformHost": "localhost", "protocol": "digital", "credentials": { "username": "admin", "passwd": "admin" } }
-
Import the dojot-framework in main of your application.
-
Set your configurations to let the library know how to operate with your Dojot instance.
You can do that by calling the setConfig() method or setting it manually:
const DojotFramework = require('dojot-framework'); const config = require('./config.json'); const dojot = new DojotFramework(config);
The Device Simulator brings together a set of features that allows us to simulate an IoT device and sending data to the Dojot platform. This feature has been added to the Framework for ease application development avoiding the need for real data and writing of automated tests.
The emulated data is based on probability distributions to randomize the values for adevice. The available distributions are normal/gauss, binomial, uniform and poisson. See probability-distributions to more details. The amount of data generated is based on the frequency and the duration contained onconfig.json.
const dojot = new DojotFramework(config);
dojot.simulator.start("tenant", "device_id",
[
{ "name": "device_attr", "value": "BINOMIAL(1, 0.8)" }
]);
You can also build your IoT's application with your favorite tools and third-party packages and accessing the Dojot platform endpoints
In order to access the Components API provided by dojot-framework, you will need a session token to set on each component. In these examples, the commented parameter "token" can be obtained by calling the getToken method provided by the authentication controller of the library.
Now your application is ready to receive and passes the requests to the instance of the Dojot platform.
const config = require('./config.json');
const DojotFramework = require('dojot-framework');
const express = require('express');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
const dojot = new DojotFramework(config);
const http = require('http').Server(app);
dojot.api.init()
.then((api => {
http.listen(3000, () => {
console.log('Dojot application server listening on port 3000');
});
}));
The Dojot platform has endpoints to perform user and session management. The dojot-framework provides some methods to interact with it.
In order to authenticate with the system, the enpoint authentication returning a session token to be used on requests. The method login() resolve the promise that returns the exactly response of a login on Dojot platform based on credentials that was passed on config file.
dojot.authentication.login()
.then(response => {
//your code here
});
By the credentials of the configuration file, the dojot-framework is able to log in to Dojot and return a token to your application. This token is required on all other requests.
async function userAuthentication() {
token = await dojot.authentication.getToken();
}
In this example, we create a userAuthentication() inside the application and call the method getToken() of the authentication controller that returns a promise with the token.
Creates a new user into a Dojot platform, assigning it a service. Service is the token that associates the user with the set of devices and flows it has access to.
let user = {
"username": "Jhon",
"service": "iot",
"email": "[email protected]",
"name": "Jhon Cena",
"profile": "user"
}
dojot.users.createUser(user);
This method returns a list containing all users known to the Dojot platform.
dojot.users.getUsers()
.then(users => {
//shows the user list
console.log(users);
});
Retrieves all information from a specific registered user.
dojot.users.getOneUser(5)
.then(user => {
//shows the user information object
console.log(user);
});
Replaces user information. Fields or attributes that are not informed will revert to their defaults. But the attribute username can not be replaced!
let newUser = {
"service": "iot2",
"email": "[email protected]",
"name": "Jhon Oliver",
"profile": "user"
}
dojot.users.updateOneUser(1, newUser);
Removes a user from the Dojot platform by the user's id.
dojot.users.deleteOneUser(5);
All these methods are related to CRUD operations over templates based on enpoints of the Dojot's Device Management API Component. Before describing the device component, we must detail the template methods.
According to the Dojot documentation:
Templates are a way to describe the “device model”, or, more abstractly, a “device class”. These templates contains all the attributes that will be applied to the device. Always remember that they can (and eventually will) be merged into one to create a single device - they must not have attributes with the same name. If this is inevitable, a tag could be added to the attribute name and, while creating the device, translation instructions could be created in order to map each attribute from the incoming message to the appropriate device attribute.
As seen above, the token is required to access all the methods of this component.
This method registers a new template on Dojot platform.
const template = {
"label": "SensorModel",
"attrs": [
{
"label": "temperature",
"type": "dynamic",
"value_type": "float"
},
{
"label": "model-id",
"type": "static",
"value_type": "string",
"static_value": "model-001"
}
]
}
dojot.templates.createTemplate(template);
Get the full list of templates with all their associated attributes.
You can pass the parameters with an JSON object.
page_size
- (optional) Example: 20page_num
- (optional) Example: 1attr_format
- Must be one of “both”, “single” (if ‘data_attrs’ and ‘config_attrs’ are to be omited) or “split” (if ‘attrs’ list is to be omited). ‘attrs’ field will always contain all template attributes that are listed by both ‘data_attrs’ and ‘config_attrs’.attr
- Return only templates that posess a given attribute’s valuesortBy
- Return entries sorted by given field. Currently only label is supported.
dojot.templates.getTemplates()
.then(templates => {
//shows the template list
console.log(templates);
});
Retrieves all information from a specific device by the device's id.
dojot.templates.getOneTemplate(5)
.then(template => {
//shows the template information object
console.log(template);
});
All these methods are related to CRUD operations over devices based on enpoints of the Dojot's Device Management API Component. As seen above, the token is required to access all the methods of this component.
Register a new device. In this example object, there is already a template (id 1) which describes all the attributes to be applied to this device.
const device = {
"label": "test_device",
"templates": [
1
]
}
dojot.devices.createDevice(device);
This method returns a full list of devices with all their associated attributes. Each attribute from attrs is the template ID from where the attributes came from.
dojot.devices.getDevices()
.then(devices => {
//shows the device list
console.log(devices);
});
Retrieves all information from a specific device by the device's id.
dojot.devices.getOneDevice('11e9f9')
.then(device => {
//shows the device information object
console.log(devices);
});
Get the full list of devices that belong to a given template's id.
dojot.devices.getDeviceByTemplate(5)
.then(device => {
//shows the device list
console.log(devices);
});
This method allow your application gets the raw data for a device id or attribute. The response will retrieve all data from all device’s attributes, unless a parameter is given.
You can pass the parameters with an JSON object.
id
- Identifier of the device whose associated raw data wants to be retrieved.attr
- Name of the attribute whose associated raw data wants to be retrieved. If not provided, will consider all attributes.lastN
- Maximum number of raw data entries to retrieve. If not provided, will return all data entries of the attributes.
dojot.devices.getDeviceData('11e9f9')
.then(data => {
//shows the historical data of this device
console.log(data);
});
You can pass the parameters with an JSON object.
Gets the raw data stored by the Dojot STH from certain date onwards (or the origin of time if no starting date is provided) applying certain offset and a limit to the number of entries to be retrieved.
You can pass the parameters with an JSON object.
id
- Identifier of the device whose associated raw data wants to be retrieved.attr
- Name of the attribute whose associated raw data wants to be retrieved. If not provided, will consider all attributes.dateFrom
- The starting date from which the raw data should be retrieved. If not provided, the origin of time is used.dateTo
- The final date until which the raw data should be retrieved. If not provided, the current date is used.lastN
- Maximum number of raw data entries to retrieve. If not provided, will return all data entries of the attributes.
dojot.devices.getDeviceHistory('11e9f9', 'temperature', '2018-03-18T00:00:00-03:00', '2019-03-20T12:00:59-03:00', 5)
.then(data => {
//shows the historical data of this device
console.log(data);
});
This method returns an array with all Device's id's registered on platform by the account configured on config file.
//returns a array with devices ids: ['1d24', 'd983f', '24hki']
let array = dojot.devices.getAllDevicesIds();
This method returns an JSON object that contains all Device's labels separated by id and label value.
//returns a array with devices labels: { '5e7c4e': 'geladeira_01', '62dda5': 'carrinho_01', b3dace: 'carrinho_02' }
let array = dojot.devices.getAllDevicesLabels();
Returns an array with all occurrences of a given attribute.
//returns a array with devices ids: [0.32, 1.20, 3.3]
dojot.devices.getAttributeValues('temperature');
Let's say that your application needs to get all devices from a given attribute, this method can do this for you.
You can pass or not a value as a second parameter.
dojot.devices.getDevicesByAttribute('temperature', 0.58)
.then(devices => {
//returns a list of devices that has temperature
});
The Dojot platform has a Component API where it is possible to establish a Socket.io connection and subscribe the data of a certain device. In this library, we provide some methods that can help to make this subscription, perform the filtering of useful data and make it available in a preprocessed way for your third-party applications.
//TODO:
//TODO:
//TODO:
//TODO:
On the process of applications constructions that will communicate with Dojot, mainly web applications, it is common that the large amount of data that the platform provides becomes a bottleneck. Therefore, we provide methods that can help filter the data over specific periods of time and save processing.
This method aims to provide a simple way to get only the days that have data in a filtering period. For example, let's say you have a brightness attribute and you want to know what days the bulbs on a device was lit. So you can show a calendar or search field in your application, only days that contains data.
let brightness = [
{
"id": 1,
"value": "0,1350",
"device_id": "d874d9",
"timestamp": 1545225677741
},
{
"id": 2,
"value": "1,20",
"device_id": "d874d9",
"timestamp": 1545225677789
}
];
dojot.timeData.obtainDaysWithData(brightness);
In this example, note that the adopted communication protocol is digital (0 or 1) and this can be setted in the config.json configuration file. If you adopt another protocol, you will need to implement your own method to make this works.
This library is still in development. More methods that map the endpoints of the Dojot platform will be added according to the use of this library in real applications.
That is it! Feel free to add endpoints, database and other features to your app or server. Stay tuned to get more updates.