Automatically translate this page?
20 March, 2018

Developing with flespi: take our telematics Lego bricks and start creating

The flespi-io-js open-source library gives developers of monitoring, fleet management, and IoT platforms a handy toolset to interact with the flespi world.

Willingly or not the world is steadily heading the road of simplification. As a result, we want to cease caring about the things we can cease caring. One can build a house themselves, but isn’t it more sensible, quick, and high-quality to hire professionals for the job? The same way of thinking works for software development either, and if you are a developer, flespi-io-js is one of such caregiving tools.

What is flespi-io-js?

flespi-io-js is an isomorphic open-source library based on Axios and MQTT.js for easier access and communication with the flespi.io resource (see details below). The library speeds up and facilitates the development of JavaScript apps. Thanks to its isomorphic nature it perfectly embeds into a modular frontend or backend project as well as into a plain HTML page. The naming of methods easily associated with the flespi documentation allows maximally fast integration of flespi-io-js into both new and existing projects. Also, the flespi-io-js library fully supports Promises.

Note: flespi.io is a set of building blocks in the telematics world. Getting, processing, and storing data from versatile devices across multiple protocols is a subset of its capabilities. The platform enables easy development of applications for GPS monitoring, tracking and configuration of devices in telematics and IoT.

Who needs flespi-io-js and why?

If you are creating JS applications based on flespi, you want to use flespi-io-js to:

  • increase the speed of development and integration;

  • improve the stability of the app in its interaction with flespi;

  • see how REST API matches the methods in the library;

  • write modern-style code using Promises support (async/await).

Contrasting the code with and without flespi-io-js

1. Let’s look at the basic request for getting messages from the channel:

let token = ‘FlespiToken xxxxxxxxxxxxxxxxxxxxxxxxxxx’, //flespi.io access token
channelId = *int*, // id of the channel we get messages from 
messages = [],// message storage
myHeaders = new Headers({ // necessary request headers
‘Authorization’: token
})

fetch(`flespi.io/gw/cahnnels/${channelId}/messages`, { // configuring request to the server
method: ‘GET’, // setting a method 
   headers: myHeaders // and headers
})
.then((response) => response.json()) // processing response
.then(result => messages = result) // saving result
.catch((err) => console.log(err)) // handling errors

Now let’s see how the same functionality looks with the flespi-io-js library:

let Connection = require('flespi-io-js'), // connecting the library
connector = new Connection({ // creating connector to flespi.io
token: 'FlespiToken xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
}),

id = *int*,
messages = []

connector.gw.getChannelsMessages(id, {}) // getting messages
.then((response) => { messages = resp.data }) // saving messages
.catch((err) => console.log(err)) // handling errors

See how the code became more compact and readable due to detaching request configuration into the method with a similar name.


2. Similarly, let’s compare the process of connecting over MQTT via WebSockets:

import mqtt from 'mqtt'
let token = ‘FlespiToken xxxxxxxxxxxxxxxxxxxxxxxxxx’, // flespi.io access token
clientId = ‘MYID’, // client id
_client = mqtt.connect(‘wss://mqtt.flespi.io’, { // creating client
username: token,
clientId: clientId
})

_client.on('message', (topic, message) => { // processing messages as they appear
if (topic === ‘#’) { doSomething(message) }
})

_client.subscribe(‘#“) // subscribing
.then(cred => {
let { err, granted } = cred
if (err) {
console.log(err)
return false
}
})

And the same process coded with the library:

let Connection = require('flespi-io-js')

let connector = new Connection({
token: 'FlespiToken xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
})

/* subscribing to # topic and processing messages for it */

connector.socket.subscribe({name: '#', handler: (message) => { doSomething(message) }})

Again, the code gets much shorter and more user-friendly.


3. Most real-life cases are complex, e.g., you first need to get some data and then track how it piles up further and what changes occur. The logic should reflect the combination of such events: request the data first, then subscribe and get new data over MQTT. The flespi-io-js library has methods for all of these:

let Connection = require('flespi-io-js'),
connector = new Connection({
token: 'FlespiToken xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
})

connector.poolDevices(
(response)=>{console.log(`data: ${JSON.stringify(response.data.result)}`)}, 
   (type, data) => { console.log(`mqtt ${type}: ${JSON.stringify(data)}`) }
)

The above example implements getting and processing changes for devices created in flespi.io.

Summing up

The flespi-io-js library is a pack of legal steroids for communication with flespi.io. All communication capabilities are generously sprinkled with the syntactic icing boosting the speed of development and integration. An app also becomes more failure-prone since in most cases you don’t have to handle exceptions manually. Simple library methods syntax matching the structure of REST API (e.g.: flespi.io/gw/channels/${channelId}/messages => connector.gw.getChannelsMessages(channelId, {})) allows focusing on the app logic. And full-scale Promises support enables applying the latest coding practices using async/await. 

Now that we give you all the tools, how about creating a mini-Wialon yourself? ;)

P.S. We use the flespi-io-js library in our developments such as Toolbox, TrackIt, and the flespi panel itself.



Get the latest updates and monthly newsletters from flespi in your inbox

Google IoT Cloud: Cheap Storage and Advanced Analytics for Your Telematics Data

Forwarding messages from GPS tracking devices via flespi telematics hub into the Google ecosystem for long-term storage, processing, and insights.

10 August, 2018 | flespi integrations | Jan Bartnitsky

Managing the Light Bulb from a Smartphone over MQTT

A fast way to create a flexible IoT dashboard powered by flespi MQTT API, MQTT Dash Android app, and a Concox GPS tracker to operate a light bulb and more.