Vegetable Tracing Using IOT
Vegetable Tracing Using IOT
Abstract:
Wireless sensor networks have a strong impact all over the world
over the wired networks due to the development of new standards
and technologies from the last decades. Wireless sensor networks
are used in a wide range of applications including remote
Monitoring, health care, industrial automation or environmental
monitoring. Each WSN may have specific objectives and application
goals. Here our objective is to assure maximum quality and minimum
spoilage of the stored food in food industry, by maintaining and
monitoring of the temperature sensor, moisture sensor, gas sensor,
level sensor and colour sensor of the environment. Sensory data
comes from temperature, moisture, gas and colour sensors of
different locations, where food is stored and received at the receiver.
WSN is formulated by a group of sensor nodes equipped with short-
range communication capability. Every sensor node consists of at
least a transceiver, a processing unit, a transducer and a power unit.
New standards and technologies like internet of things, having a
specific parameter of low power consumption, are used for short
range wireless communications. This paper provides the
implementation of monitoring and controlling of sensors using high
end board Nodemcu.
Introduction:
• A food contamination can occur in the production process, but
also a large part caused by the inefficient food handling because
of inappropriate ambient conditions when the food is being
transported and stored.
• There are many factors leading to food poisoning, typically
changes in temperature and humidity are important factors. So
the monitoring system capable of measuring temperature and
humidity variability during transport and storage is of prime
importance. Today almost everybody is getting effected by the
food they consume, it's not only about the junk food, but all the
packed foods, vegetables, products consumed and used in daily
life, as all of them do not offer quality since their temperature,
moisture, oxygen content vary from time to time.
• Majority of consumers only pay attention to the information
provided on the packaging, i.e. the amount of ingredients used
and their nutritional value but they forget that they are blindly
risking their health by ignoring the environmental conditions to
which these packets are subjected.
• Every product making firm just want to attract more and more
costumers towards them their main motive is to sell the product
anyhow like by adding more flavours, colouring chemicals and
preservatives to increase the taste and appearance but they
forget that these money making tactics are actually affecting the
consumers health.
Literature survey:
1 Application of internet of things in food packaging and
transportation
Mirjana maksimovic, Vuka karadzica, Enisa Omanovic
Food safety is a scientific field which includes a number of
routines and inspections at every stage of the food chain that should
be adopted to avoid potentially dangerous health risks. Novel and
efficient solutions across the supply chain are the consequence of
constant upgrades of information and communication technologies.
With the help of internet of things (IoT) connected testing
equipment, food quality can be monitored at any point from farm to
table, connecting at the same time food producers, transportation
and hospitality/retail companies. Relying on the fact that food
transporting and packaging units are the most critical points in food
production, the survey of IoT applications in food packaging and
transportation is given in this paper. To demonstrate the significance
of IoT appliance and defined concepts, a proposal of low cost
solution based on IoT for real-time food traceability and monitoring
in food transportation process is presented.
2. Comprehensive Monitoring System of Fresh Food Cold Chain
Logistics
Yong Jun Zhang , En Xiu Chen
The paper discusses how to use the advanced technology of the
Internet of things to realize the real-time monitoring of the library
and the preservation of goods in transit third party cold chain
logistics, mainly discusses how to network technology with Internet
3G network of RFID and WSN integrated network and intelligent
nodes, realize the visualization of fresh goods real-time monitoring,
convenient management personnel of customer inquiries and
feedback information, to ensure the preservation of food quality and
safety.
3. The Design of the Internet of Things Solution for Food Supply
Chain
Zhao Xiaorong, Fan Honghui, b, Zhu Hongji, Fu Zhongjun, Fu Hanyu
Many problems of foods safety had occurred in recent years,
which resulted in public panic. As a result, the government has made
food safety a top priority. In the last few years, the rapid
development of the Internet of Things (IoT). How to make sure the
security of food supply chain with the help of emerging technology—
IoT, has the important practical significance. Iot is an inevitable
choice to improve food logistics, and compare the content
networking technology application before and after the food logistics
management titer, thus must content networking technology
application in food logistics, to food logistics management titer have
larger stimulative effect. In this paper, we introduce a novel IoT
architecture able to track and trace agriculture from the field
through the supply chain and in food processing environments,
realizing the food supply chain’s effective information identification
and traceability.
4. Construction of Optimal Allocation System on the Edible
Agricultural Products Components of the Nutrition and Health Care
Based on Internet of Things
Existing system:
The existing system consists of two wireless sensor networks based
on Zigbee and Bluetooth. The heart of the system is the
microcontroller, which controls both of the networks by relay
switching. A relay is connected with the microcontroller, when the
relay is on, wireless sensor network based on Bluetooth works and
when it is off, then the network based on Zigbee works. Different
sensors like temperature and humidity sensors are used to measure
the temperature and humidity of the environment. After measuring
the temperature and humidity, the data is sent to the monitoring
unit, where the data is recorded. If the temperature or the humidity
of the environment increases from a particular point, then we can
control the temperature or humidity wirelessly.
Proposed system:
• The water level sensor is used to identify the level of a liquid
content in the vegetables, and Moisture level is also identify
the environment moisture content
• DHT11 sensor is used to identify the food and external
environment level
• Gas sensor used to identify the rotten smell in vegetables
• This sensor data is getting analysed through single board
computer called Nodemcu and it send data to cloud if any of
the sensor value is critical it send the Gmail alert using Ubidots
cloud.
Block diagram:
Hardware required:
Nodemcu
DHT11 sensor
Gas sensor
Ubidots
NODE MCU
In summer 2015 the creators abandoned the firmware project and a group of independent
contributors took over. By summer 2016 the NodeMCU included more than 40 different
modules. Due to resource constraints users need to select the modules relevant for their
project and build a firmware tailored to their needs.
ntroduction
Since NodeMCU is open source platform, their hardware design is open for
edit/modify/build.
NodeMCU Dev Kit/board consist of ESP8266 wifi enabled chip. The ESP8266 is a low-
cost Wi-Fi chip developed by Espressif Systems with TCP/IP protocol. For more information
about ESP8266, you can refer ESP8266 WiFi Module.
There is Version2 (V2) available for NodeMCU Dev Kit i.e. NodeMCU Development
Board v1.0 (Version2), which usually comes in black colored PCB.
NodeMCU Development Board/kit v1.0 (Version2)
NodeMCU Dev Kit has Arduino like Analog (i.e. A0) and Digital (D0-D8) pins on its board.
Using such serial protocols we can connect it with serial devices like I2C enabled LCD
display, Magnetometer HMC5883, MPU-6050 Gyro meter + Accelerometer, RTC chips,
GPS modules, touch screen displays, SD cards etc.
NodeMCU Development board is featured with wifi capability, analog pin, digital pins and
serial communication protocols.
To get start with using NodeMCU for IoT applications first we need to know about how to
write/download NodeMCU firmware in NodeMCU Development Boards. And before that
where this NodeMCU firmware will get as per our requirement.
There is online NodeMCU custom builds available using which we can easily get our custom
NodeMCU firmware as per our requirement.
To know more about how to build custom NodeMCU firmware online and download it
refer Getting started with NodeMCU
After setting up ESP8266 with Node-MCU firmware, let’s see the IDE (Integrated
Development Environment) required for development of NodeMCU.
Lua scripts are generally used to code the NodeMCU. Lua is an open source,
lightweight, embeddable scripting language built on top of C programming language.
For more information about how to write Lua script for NodeMCU refer Getting
started with NodeMCU using ESPlorerIDE
Here is another way of developing NodeMCU with a well-known IDE i.e. Arduino
IDE. We can also develop applications on NodeMCU using Arduino development
environment. This makes easy for Arduino developers than learning new language and
IDE for NodeMCU.
For more information about how to write Arduino sketch for NodeMCU refer Getting
started with NodeMCU using ArduinoIDE
Well, there is a programming language difference we can say while developing application
for NodeMCU using ESPlorer IDE and Arduino IDE.
We need to code in C\C++ programming language if we are using Arduino IDE for
developing NodeMCU applications and Lua language if we are using ESPlorer IDE.
Basically, NodeMCU is Lua Interpreter, so it can understand Lua script easily. When we
write Lua scripts for NodeMCU and send/upload it to NodeMCU, then they will get executes
sequentially. It will not build binary firmware file of code for NodeMCU to write. It will send
Lua script as it is to NodeMCU to get execute.
In Arduino IDE when we write and compile code, ESP8266 toolchain in background creates
binary firmware file of code we wrote. And when we upload it to NodeMCU then it will flash
all NodeMCU firmware with newly generated binary firmware code. In fact, it writes the
complete firmware.
That’s the reason why NodeMCU not accept further Lua scripts/code after it is getting
flashed by Arduino IDE. After getting flashed by Arduino sketch/code it will be no more Lua
interpreter and we got error if we try to upload Lua scripts. To again start with Lua script, we
need to flash it with NodeMCU firmware.
Since Arduino IDE compile and upload/writes complete firmware, it takes more time than
ESPlorer IDE.
Image shows externals of a standard gas sensor module: a steel mesh, copper clamping ring
and connecting leads. The top part is a stainless steel mesh which takes care of the following:
Filtering out the suspended particles so that only gaseous elements are able to pass to insides
of the sensor.
Exhibits an anti-explosion network that keeps the sensor module intact at high
temperatures and gas pressures.
In order to manage above listed functions efficiently, the steel mesh is made into two layers.
The mesh is bound to rest of the body via a copper plated clamping ring.
The connecting leads of the sensor are thick so that sensor can be connected firmly to
the circuit and sufficient amount of heat gets conducted to the inside part. They are casted
from copper and have tin plating over them. Four of the six leads (A, B, C, D) are for signal
fetching while two (1, 2) are used to provide sufficient heat to the sensing element.
The pins are placed on a Bakelite base which is a good insulator and provides firm gripping
to the connecting leads of the sensor.
The top of the gas sensor is removed off to see the internals parts of the sensor:
sensing element and connection wiring. The hexapod structure is constituted by the sensing
element and six connecting legs that extend beyond the Bakelite base.
Using a ceramic substrate increases the heating efficiency and tin oxide, being
sensitive towards adsorbing desired gas’ components (in this case methane and its products)
suffices as sensing coating.
The leads responsible for heating the sensing element are connected through Nickel-
Chromium, well known conductive alloy. Leads responsible for output signals are connected
using platinum wires which convey small changes in the current that passes through the
sensing element. The platinum wires are connected to the body of the sensing element while
Nickel-Chromium wires pass through its hollow structure.
While other wires are attached to the outer body of the element, Nickel-Chromium wires are
placed inside the element in a spring shaped. Image shows coiled part of the wire which is
placed on the inside of the hollow ceramic
Image shows the ceramic with tin dioxide on the top coating that has good adsorbing
property. Any gas to be monitored has specific temperature at which it ionizes. The task of
the sensor is to work at the desired temperature so that gas molecules get ionized. Through
Nickel-chromium wire, the ceramic region of the sensing element is subjected to heating
current. The heat is radiated by the element in the nearby region where gases interact with it
and get ionized. Once, ionized, they are absorbed by the tin dioxide. Adsorbed molecules
change the resistance of the tin dioxide layer. This changes the current flowing through the
sensing element and is conveyed through the output leads to the unit that controls
the working of the gas sensor.
Humidity sensor
The DHT11 sensor comes in a single row 4-pin package and operates from 3.5 to
5.5V power supply. It can measure temperature from 0-50 °C with an accuracy of ±2°C and
relative humidity ranging from 20-95% with an accuracy of ±5%. The sensor provides fully
calibrated digital outputs for the two measurements. It has got its own proprietary 1-wire
protocol, and therefore, the communication between the sensor and a microcontroller is not
possible through a direct interface with any of its peripherals. The protocol must be
implemented in the firmware of the MCU with precise timing required by the sensor. The
following timing diagrams describe the data transfer protocol between a MCU and the
DHT11 sensor. The MCU initiates data transmission by issuing a “Start” signal. The MCU
pin must be configured as output for this purpose. The MCU first pulls the data line low for at
least 18 ms and then pulls it high for next 20-40 ?s before it releases it.
The 40-bit data from the sensor has the following structure.
For DHT11 sensor, the decimal bytes of temperature and humidity measurements are always
zero. Therefore, the first and third bytes of received data actually give the numeric values of
the measured relative humidity (%) and temperature (°C). The last byte is the checksum byte
which is used to make sure that the data transfer has happened without any error. If all the
five bytes are transferred successfully then the checksum byte must be equal to the last 8 bits
of the sum of the first four bytes, i.e.,
Now lets talk about the most important thing, which is signalling for transmitting “0″ and
“1″. In order to send a bit of data, the sensor first pulls the line low for 50 ?s. Then it raises
the line to high for 26-28 ?s if it has to send “0″, or for 70 ?s if the bit to be transmitted is
“1″. So it is the width of the positive pulse that carries information about 1 and 0.
Timing difference for transmitting "1s" and "0s"
At the end of the last transmitted bit, the sensor pulls the data line low for 50 ?s and then
releases it. The DHT11 sensor requires an external pull-up resistor to be connected between
its Vcc and the data line so that under idle condition, the data line is always pulled high. After
finishing the data transmission and releasing the data line, the DHT11 sensor goes to the low-
power consumption mode until a new “Start” signal arrives from the MCU.
Software required:
Arduino ide
Embedded C
ARDUINO IDE AND ITS PROGRAMMING
Arduino is a tool for making computers that can sense and control more of the
physical world than your desktop computer. It's an open-source physical
computing platform based on a simple microcontroller board, and a
development environment for writing software for the board.
Arduino can be used to develop interactive objects, taking inputs from a
variety of switches or sensors, and controlling a variety of lights, motors, and
other physical outputs. Arduino projects can be stand-alone, or they can be
communicate with software running on your computer. The boards can be
assembled by hand or purchased preassembled; the open-source IDE can be
downloaded for free.
2.1 Overview
The Arduino microcontroller is an easy to use yet powerful single board
computer that has gained considerable traction in the hobby and professional
market. The Arduino is open-source, which means hardware is reasonably
priced and development software is free. This guide is for students in ME 2011,
or students anywhere who are confronting the Arduino for the first time. For
advanced Arduino users, prowl the web; there are lots of resources.
This guide covers the Arduino Uno board (Spark fun DEV-09950, $29.95), a
good choice for students and educators. With the Arduino board, you can write
programs and create interface circuits to read switches and other sensors, and
to control motors and lights with very little effort. Many of the pictures and
drawings in this guide were taken from the documentation on the
Repository github.com/arduino/
Arduino
Written in C, C++
Operating Windows, macOS, Linux
system
Platform IA-32, x86-64, ARM
License LGPL or GPL license
Website blog.arduino.cc/2020/08/24
/cli-and-ide-get-better-
together/
An important feature of the Arduino is that you can create a control program
on the host PC, download it to the Arduino and it will run automatically.
Remove the USB cable connection to the PC, and the program will still run
from the top each time you push the reset button. Remove the battery and put
the Arduino board in a closet for six months. When you reconnect the battery,
the last program you stored will run. This means that you connect the board to
the host PC to develop and debug your program, but once that is done, you no
longer need the PC to run the program.
The NodeMCU can be powered via the USB connection or with an external
power supply. The power source is selected automatically.
External (non-USB) power can come either from an AC-to-DC adapter (wall-
wart) or battery. The adapter can be connected by plugging a 2.1mm center-
positive plug into the board's power jack. Leads from a battery can be inserted
in the Gnd and Vin pin headers of the POWER connector.
VIN. The input voltage to the Arduino board when it's using an external
power source (as opposed to 5 volts from the USB connection or other
regulated power source). You can supply voltage through this pin, or, if
supplying voltage via the power jack, access it through this pin.
5V. this pin outputs a regulated 5V from the regulator on the board. The
board can be supplied with power either from the DC power jack (7 - 12V), the
USB connector (5V), or the VIN pin of the board (7-12V). Supplying voltage via
the 5V or 3.3V pins bypasses the regulator, and can damage your board.
Memory
The ATmega328 has 32 KB (with 0.5 KB used for the bootloader). It also has 2
KB of SRAM and 1 KB of EEPROM.
Each of the 14 digital pins on the Uno can be used as an input or output, using
pinMode(), digital Write( ), and digital Read( ) functions. They operate at 5
volts. Each pin can provide or receive a maximum of 40 mA and has an internal
pull- up resistor (disconnected by default) of 20-50 kohms. In addition, some
pins have specialized functions:
• Serial: 0 (RX) and 1 (TX). Used to receive (RX) and Trans mit (TX) TTL serial
data.
These pins are connected to the corresponding pins of the ATmega8U2 USB-to-
TTL Serial chip.
•PWM: 3, 5, 6, 9, 10, and 11. Provide 8-bit PWM output with the analog Write
() function.
•LED: 13. There is a built- in LED connected to digital pin 13. When the pin is
HIGH value, the LED is on, when the pin is LOW, it's off.
The Uno has 6 analog inputs, labeled A0 through A5, each of which provide 10
bits of resolution (i.e. 1024 different values). By default they measure from
ground to 5 volts, though is it possible to change the upper end of their range
using the AREF pin and the analog Reference () function. Additionally, some
pins have specialized functionality:
• TWI: A4 or SDA pin and A5 or SCL pin. Support TWI communication using
the Wire library.
Reset. Bring this line LOW to reset the microcontroller. Typically used to add a
reset button to shields which block the one on the board.
2.4 Communication
Servo. This library allows you to connect one or more hobby R/C servos to the
Arduino’s digital I/O pins. The Servo library comes with the standard Arduino
installation package Library->Servo. This adds the line
#include <Servo.h>
Which tells the Arduino IDE that you wish to include the Servo library in your
sketch. With the functionality of the library now available to you, you can use
its various functions to control one or more servos. For example, you can use
the write function to rotate a servo to a specific position, from 0 to 180
degrees. The following code
myServo.write(90);
They are inputs or outputs. The loop () function is repeated endlessly when the
Arduino is operating.
UBIDOTS EXPLORER:
Introduction
Welcome to the Ubidots REST API hardware docs. Here you would reference how
to send or retrieve data from your hardware devices using our supported
communication protocols: HTTP, MQTT and TCP/UDP.
The purpose of this section is to help you understand what happens in the
backstage when communicating with Ubidots, so you can replicate this in your
firmware. For this reason, we avoid the use of examples using libraries. However,
if you’d like to use one of our libraries (Python, C, and more), check out
our compatible devices and API clients sections.
How Ubidots Works?
upon reception.
Values
{"value" : 34.87654974}
Timestamps
Numerical values are not the only data type supported; you can also
store string or char data types inside what we call context. The context is a key-
value object that allows you to store not only numerical but also string values. An
example use of the context could be:
"context" : {"status" : "on", "weather" : "sunny"}
A context is commonly used to store the latitude and longitude coordinates of
your device for GPS/tracking application use cases. All Ubidots maps uses
the lat and lng keys from a dot's context to extract the coordinates of your
device, in that way you just need to send a single dot with the coordinates values
in the variable context to plot a map instead of sending separately both latitude
and longitude in two different variables. Below you can find a typical context with
coordinates values:
"context" : {"lat":-6.2, "lng":75.4, "weather" : "sunny"}
Please note that you can mix both string and numerical values in the context. If
your application is for geo-localization purposes, make sure that the coordinates
are set in decimal degrees.
Time Series
Based on the above, we can illustrate an Ubidots time series like this:
Ubidots is an agnostic platform, this means that it does not really care what
hardware device you are using, as long as you're able to interact with us through
at least one of these protocols:
HTTP
MQTT
TCP/UDP
HTTP
HTTP is the main internet protocol for information exchange in the Internet. It
also supports data encryption, which is usually called secure HTTP or HTTPs. When
you use a web browser (MS Edge, Firefox, Google Chrome, etc) you are sending
and receiving packages using HTTP or HTTPs. Because of this, it was not surprising
to see HTTPs become a popular option for data exchange within IoT.
When a developer is to implement HTTP communication, then he should look for
a RESTful Application Programming Interface, or REST API, which exposes all the
endpoints required to interact with a third party application (like Ubidots). In this
section, you can reference our REST API to understand how to send and retrieve
data from our servers.
Note: Our goal with this section is to help you understand what’s happening
behind when communicating with Ubidots, enabling you to replicate it within
your own firmware. Because of this, we avoid using our custom libraries in all the
examples.
HTTP requests
The following methods are specified within the HTTP standard:
HTTP Method Description
API access can be over HTTP or secure HTTP, HTTPs, using the following endpoints
based on your Ubidots Account type.
Security Note: We strongly advise to use HTTPs to make sure your data travels
encrypted, avoiding the exposure of your API token and/or sensor data.
HTTP
Educational http://things.ubidots.com 80
Industrial http://industrial.api.ubidots.com 80
HTTPs
Ubidots supports SSL v1.1, TLS v1.2 and v1.3. You can download our root
certificates in different formats:
PEM file: A certificate chain with two root certificates from our certificate
authorities (CAs).
DER file: Same as the PEM file, with an alternative encoding.
CRT file: Same as the PEM file, with a different extension. Often referred to
as .crt, .cert or .cer.
NOTE: To avoid future inconveniences, we advise to use both certificates in your
device's auth routines. While the second is the current valid certificate, we will
use the first after 2021.
Fixed IPs
Ubidots also supports fixed IPs address for data ingestion, but we highly advise to
our users to implement their firmware routines using the dns endpoints instead
of fixed IPs, as these last ones may change in the future.
HTTP Authentication
Every request requires a token. A token is an unique key that authorizes your
device to ingest data inside your Ubidots account.
The easiest way to get yours is clicking on "API Credentials" under your profile
tab:
Send data
Our REST API allows you send data to the platform in two different ways:
Request structure:
POST /api/v1.6/devices/{DEVICE_LABEL} HTTP/1.1<CR><LN>
Host: {Host}<CR><LN>
User-Agent: {USER_AGENT}<CR><LN>
X-Auth-Token: {TOKEN}<CR><LN>
Content-Type: application/json<CR><LN>
Content-Length: {PAYLOAD_LENGTH}<CR><LN><CR><LN>
{PAYLOAD}
<CR><LN>
Expected Response:
HTTP/1.1 200 OK<CR><LN>
Server: nginx<CR><LN>
Date: Tue, 04 Sep 2018 22:35:06 GMT<CR><LN>
Content-Type: application/json<CR><LN>
Transfer-Encoding: chunked<CR><LN>
Vary: Cookie<CR><LN>
Allow: GET, POST, HEAD, OPTIONS<CR><LN><CR><LN>
{PAYLOAD_LENGTH_IN_HEXADECIMAL}<CR><LN>
{"{VARIABLE_LABEL}": [{"status_code": 201}]}<CR><LN>
0<CR><LN>
The easiest way to send values to Ubidots is by specifying your Device label in the
request path and making a POST request to it.
Replace the {DEVICE_LABEL} with the unique label of the desired device to send
data to. If the device does not exist in your Ubidots account, it will be
automatically created. Device labels can contain any alphanumerical character,
without blank spaces, i.e weather-station, my-home, esp8266.
To set the variables values, just create a JSON data payload as below
Nº
Variables JSON structure
Request structure:
POST /api/v1.6/devices/{DEVICE_LABEL}/{VARIABLE_LABEL}/values
HTTP/1.1<CR><LN>
Host: {Host}<CR><LN>
User-Agent: {USER_AGENT}<CR><LN>
X-Auth-Token: {TOKEN}<CR><LN>
Content-Type: application/json<CR><LN>
Content-Length: {PAYLOAD_LENGTH}<CR><LN><CR><LN>
{PAYLOAD}
<CR><LN>
Expected Response:
HTTP/1.1 201 Created<CR><LN>
Server: nginx<CR><LN>
Date: Tue, 04 Sep 2018 22:50:55 GMT<CR><LN>
Content-Type: application/json<CR><LN>
Transfer-Encoding: chunked<CR><LN>
Vary: Accept, Cookie<CR><LN>
Location:
http://industrial.api.ubidots.com/api/v1.6/values/{VARIABLE_ID}<CR><LN>
Allow: GET, POST, HEAD, OPTIONS<CR><LN><CR><LN>
{PAYLOAD_LENGTH_IN_HEXADECIMAL}<CR><LN>
{"url": "http://things.ubidots.com/api/v1.6/values/{VARIABLE_ID}", "value": 27.0,
"timestamp": 1536101455822, "context": {}, "created_at": "2018-09-
04T22:50:55.822035Z"}<CR><LN>
0<CR><LN>
In the path specified above, replace the {DEVICE_LABEL} and {VARIABLE_LABEL}
keys with the unique labels of the Ubidots device and variable you wish to send
data to. If the specified device and/or variable do not exist, they will be
automatically created.
Examples
Single dot: {"value":27}
Single dot with context and timestamp: {"value":27, "timestamp":
1514808000000, "context":{"lat":37.773, "lng":-122.431}}
Multiple dots (must include the timestamp of each value): [{"value": 27,
"timestamp":1514808000000}, {"value": 12, "timestamp":1514808900000}]
Send a single dot (Educational users)
POST
https://industrial.api.ubidots.com/api/v1.6/devices/{DEVICE_LABEL}/
{VARIABLE_LABEL}/values
POST
https://things.ubidots.com/api/v1.6/devices/{DEVICE_LABEL}/
{VARIABLE_LABEL}/values
Send a single dot (Industrial users)
variable/values
Send a single dot (Educational users)
variable/values
Retrieve data
The Ubidots REST API allows you to retrieve data from the platform data base. A
typical application for data retrieval is actuators like motors or lights control.
Retrieve mutiple values from a variable
Request structure:
GET /api/v1.6/devices/{DEVICE_LABEL}/{VARIABLE_LABEL}/values
HTTP/1.1<CR><LN>
Host: {Host}<CR><LN>
User-Agent: {USER_AGENT}<CR><LN>
X-Auth-Token: {TOKEN}<CR><LN>
Content-Type: application/json<CR><LN><CR><LN>
Expected Response:
HTTP/1.1 200 OK<CR><LN>
Server: nginx<CR><LN>
Date: Tue, 04 Sep 2018 22:35:06 GMT<CR><LN>
Content-Type: application/json<CR><LN>
Transfer-Encoding: chunked<CR><LN>
Vary: Cookie<CR><LN>
Allow: GET, POST, HEAD, OPTIONS<CR><LN><CR><LN>
{PAYLOAD_LENGTH_IN_HEXADECIMAL}<CR><LN>
{"count": true, "previous": null, "results": [{PAYLOAD_WITH_VALUES}], "next":
{URL_WITH_ADDITIONAL_VALUES}}<CR><LN>
0<CR><LN>
In the path specified above, replace the {DEVICELABEL} and {VARIABLE_LABEL}
keys with the unique labels of the Ubidots device and variable you desired to
retrieve data from. This _path returns by default the last 50 values stored of your
variable. You can manage the number of dots to retrieve using
the page_size parameter in your path:
/api/v1.6/devices/{DEVICE_LABEL}/{VARIABLE_LABEL}/values/?page_size=2
The path above retrieves the last 2 dots of your variable.
Ubidots API also allows you to filter the values to be retrieved by date range,
number of dots, and more. If you desire to go deep into this kind of requests,
please check the Ubidots Software REST API Reference.
GET
https://industrial.api.ubidots.com/api/v1.6/devices/{DEVICE_LABEL}/
{VARIABLE_LABEL}/values
GET
https://things.ubidots.com/api/v1.6/devices/{DEVICE_LABEL}/
{VARIABLE_LABEL}/values
Get the last two values from a variable (Educational users)
page_size=2
Get the last two values from a variable (Industrial users)
variable/values/?page_size=2
Retrieve the last value from a variable
A typical control application in general only needs to ask for the last value of a
variable, i.e, if you push a virtual switch at Ubidots, you just need to know what is
the last value of the variable related with that switch to take actions on any
actuators at your side.
Request structure:
GET /api/v1.6/devices/{DEVICE_LABEL}/{VARIABLE_LABEL}/lv HTTP/1.1<CR><LN>
Host: {Host}<CR><LN>
User-Agent: {USER_AGENT}<CR><LN>
X-Auth-Token: {TOKEN}<CR><LN>
Content-Type: application/json<CR><LN><CR><LN>
Expected Response:
HTTP/1.1 200 OK<CR><LN>
Server: nginx<CR><LN>
Date: Tue, 04 Sep 2018 22:35:06 GMT<CR><LN>
Content-Type: application/json<CR><LN>
Transfer-Encoding: chunked<CR><LN>
Vary: Cookie<CR><LN>
Allow: GET, POST, HEAD, OPTIONS<CR><LN><CR><LN>
{PAYLOAD_LENGTH_IN_HEXADECIMAL}<CR><LN>
{LAST_VALUE}<CR><LN>
0<CR><LN>
In the path specified above, replace the {DEVICE_LABEL} and {VARIABLE_LABEL}
keys with the unique labels of the Ubidots device and variable you desired to
retrieve data from.
GET
https://industrial.api.ubidots.com/api/v1.6/devices/{DEVICE_LABEL}/
{VARIABLE_LABEL}/lv
GET
https://things.ubidots.com/api/v1.6/devices/{DEVICE_LABEL}/
{VARIABLE_LABEL}/lv
Get the last value from a variable (Educational users)
HTTP Examples
In this section, you will find different examples that show you how to handle data
with Ubidots to start monitoring and controlling your IoT Devices.
At the right side, you can find each example provided in different programming
languages. Please, refer to your preferred programming language by clicking the
tabs located on the right upper side of the page.
Sending a geopoint
Ubidots provides multiples ways to start tracking your IoT devices, so here we are
going to show you how to send coordinates to Ubidots in order to start with a
GPS IoT Solution.
To learn more about the Ubidots Maps Features, please check this guide.
curl -X POST -H "X-Auth-Token: BBFF-Rfcgaxns6HlVb155WA0RhSY85xNDmB" -H
"Content-Type: application/json" -d '{"location":{"value": 1, "context":
{"lat":37.773, "lng":-122.431}}}'
https://industrial.api.ubidots.com/api/v1.6/devices/my-new-device
The String values provide additional information to the dot which is being sent. As
a basic example here, let's suppose that you are deploying a Weather Station
which provides you the Weather Status as a String value. At this point, the
Weather Status ought to be sent in the context of the dot.
To learn more of how to display the context of a dot in the Ubidots Dashboard,
please check this guide.
curl -X POST -H "X-Auth-Token: BBFF-Rfcgaxns6HlVb155WA0RhSY85xNDmB" -H
"Content-Type: application/json" -d '{"weather":{"value": 1, "context":{"weather-
status": "sunny"}}}' https://industrial.api.ubidots.com/api/v1.6/devices/my-new-
device
Sending values in bulk from a datalogger
In case you desire to send information to Ubidots from a data logger which is in
charge of taking samples for long periods of time, you can simply do it by
managing the values registered plus the time when the value was registered.
curl -X POST -H "X-Auth-Token: BBFF-Rfcgaxns6HlVb155WA0RhSY85xNDmB" -H
"Content-Type: application/json" -d '{"my-sensor":[{"value": 27,
"timestamp":1514808000000}, {"value": 30, "timestamp":1514808900000},
{"value": 31, "timestamp":1514809800000}, {"value": 29,
"timestamp":1514810700000}, {"value": 27, "timestamp":1514768400000}]}'
https://industrial.api.ubidots.com/api/v1.6/devices/my-new-device
This is typically used for remote control applications. Your devices would retrieve
the last value of a variable, and then act based on that value. It is also used to
remotely manage your devices, like for example changing a sampling rate or
performing a remote reboot.
To learn more about the control features that Ubidots offer, please check this
guide.
Example Request
Response codes
The Ubidots REST API uses the following response codes when you make
an HTTP request, with them you can know your request status and errors if there
are any:
Cod
e Meaning
202 Accepted -- The request has been accepted for processing, but
the processing has not been completed.
204 One of the fields is incorrect and the request is not saved --
Please verify it's a valid JSON string and that the fields are the
ones expected by the endpoint (string, object or float).
403 Forbidden -- This token is not valid. Please verify your token.
Cod
e Meaning
404 Not Found -- We couldn’t find the URL you're trying to access.
This might be due to a wrong device label or ID, a wrong
variable label or ID, or simply a typo in the URL of the request.
405 Method Not Allowed -- This API endpoint does not accept the
method used. Check our API docs to see the allowed methods.
420 You have exceeded your API limits -- To upgrade your API
limits contacts the Ubidots team
50* Internal Error -- We're having issues with our servers. Please
check our status page.
MQTT
0, At most once: This level does not guarantee the message delivery, it
would be labeled as best-effort server QoS.
1, At least once: This level guarantees that the message is delivered at least
one time to the receiver. The receiver answer with a puback packet, if this
puback packet is not received the sender sends again the message.
2, Exactly once: Guarantees that the message is received only once by the
receptor. It is the slowest packet interchange QoS as it requires two
request/response flows.
Ubidots supports QoS up to 1 (at most once).
Broker URLs
API access can be over plain MQTT or secure MQTT with TLS, using the following
endpoints based on your Ubidots Account type:
Non-TLS
TLS
Ubidots also supports fixed IPs address for data ingestion, but we highly advise to
our users to implement their firmware routines using the dns endpoints instead
of fixed IPs, as these last ones may change in the future.
MQTT Authentication
To interact with the Ubidots MQTT broker you'll need a token. A token is an
unique key that authorizes your device to interact with Ubidots API.
To establish the connection with the MQTT broker you need to assign
the username and password following the table below:
MQTT Credentials Parameter
Username Ubidots token
keys context and timestamp are optional.
Examples
Note: All the bash examples from this section makes use of the Eclipse Mosquitto
library, if you wish to test them please install it using the official instructions
Single dot: {"temperature": 27}
Multiple dots: {"temperature": 27, "humidity": 55, ... ,"pressure": 78}
Including additional keys like context and timestamp
Single dot: {"position": {"value" : 1, "timestamp": 1514808000000,
"context":{"lat":-6.2, "lng":75.4, "name" : "John"}}}
Multiple dots:{"temperature": {"value": 27, "timestamp": 1514808000000},
"humidity": 55, "pressure": {"value": 78, "context":{"name" : "John"}}}
PUB
/v1.6/devices/{DEVICE_LABEL}/
Send a single dot (Educational users)
27}'
Send a dot with coordinates
Similar to the GET function in HTTP, subscribe is the method to obtain values with
a huge difference: you do not have to be continuously ask the server for each
value in your custom script. For example, if a variable's value changes, Ubidots
will automatically update you (the user) of any changes. Thus saving data requests
and processing time for your device and overall project functionality and
expenses. Because of this, MQTT is a communication protocol adviced to
implement firmware routines to control actuators.
Retrieve the last value of a variable
-q 1
MQTT Examples
In this section, you will find different examples that show you how use MQTT to
implement several IoT applications.
At the right side, you can find each example provided in different programming
languages. Please, refer to your preferred programming language by clicking the
tabs located on the right upper side of the page.
GPS Tracker
Ubidots provides multiples ways to start tracking your IoT devices, so here we are
going to show you how to send coordinates to Ubidots in order to start with a
GPS IoT Solution.
To learn more about the Ubidots Maps Features, please check this guide.
mosquitto_pub -p 1883 -h industrial.api.ubidots.com -t "/v1.6/devices/my-new-
device" -u 'BBFF-Rfcgaxns6HlVb155WA0RhSY85xNDmB' -m '{"location":{"value":
1, "context":{"lat":37.773, "lng":-122.431}}}' -d -q 1
Weather description
The String values provide additional information to the dot which is being sent. As
a basic example here, let's suppose that you are deploying a Weather Station
which provides you the Weather Status as a String value. At this point, the
Weather Status ought to be sent in the context of the dot.
To learn more of how to display the context of a dot in the Ubidots Dashboard,
please check this guide.
mosquitto_pub -p 1883 -h industrial.api.ubidots.com -t "/v1.6/devices/my-new-
device" -u 'BBFF-Rfcgaxns6HlVb155WA0RhSY85xNDmB' -m '{"weather":{"value":
1, "context":{"weather-status": "sunny"}}}' -d -q 1
Retrieve the last value for control
This is the perfect solution for you in case your desire to control remotely the
garage doors, home lights, alarm system, or any asset you desire.
To learn more about the control features that Ubidots offer, please check this
guide.
Example Request
TCP / UDP
The Transmision Control Protocol, TCP, is one of the most popular data transport
protocols, so much it is supported by default in most hardware devices. Its main
advantage comes in the packet size, usually lower than packets sent using HTTP
(which in fact, uses TCP as transport layer). TCP is "connection oriented", which
means it implements confirmation methods to guarantee that data is received by
the destinatary.
The User Datagram Protocol, UDP, is also a very popular protocol that, unlike TCP,
it is "connectionless". This means it does not implements any confirmation
method to guarantee that data is received by the destinatary. This can be an
advantage in applications where simplicity and speed are more important than
reliability.
TCP and UDP are similar in the sense that they share the structure
of endpoint + port.
TCP Authentication
To send data to Ubidots using TCP or UDP broker you need your Ubidots TOKEN.
The easiest way to get it is by clicking on "API Credentials" under your profile tab:
TCP URLs
API access can be over plain TCP or secure TCP with TLS, using the following
endpoints based on your Ubidots Account type:
Non-TLS
TLS
Structure
Ubidots created a pre-defined structure to understand the content of your
TCP/UDP packets. If you wish to implement a custom structure, please get in
touch with our support channel.
Single device:
{USER_AGENT}|POST|{TOKEN}|DEV_LABEL(:DEV_NAME)
(@GLOBAL_TIMESTAMP)=>[VAR_LABEL:VALUE([$CONTEXT_KEY=CONTEXT_VAL]..
.)](@VARIABLE_TIMESTAMP)|end
Multiple devices:
{USER_AGENT}|POST|{TOKEN}|DEV_LABEL(:DEV_NAME)
(@GLOBAL_TIMESTAMP)=>[VAR_LABEL:VALUE([$CONTEXT_KEY=CONTEXT_VAL]..
.)](@VARIABLE_TIMESTAMP); ... ;DEV_LABEL(:DEV_NAME)
(@GLOBAL_TIMESTAMP)=>[VAR_LABEL:VALUE([$CONTEXT_KEY=CONTEXT_VAL]..
.)](@VARIABLE_TIMESTAMP)|end
Where:
ESP8266/1.0|POST|p4uuT2O25AJwv7ncADLoVhQfImwRQW|weather-
station=>temperature:20,humidity:35|end
Send values to multiple devices
ESP8266/1.0|POST|p4uuT2O25AJwv7ncADLoVhQfImwRQW|weather-station-
toronto=>temperature:20,humidity:35;weather-station-
washington=>temperature:20,humidity:35|end
Send a single dot (Educational users)
echo -n "ESP8266/1.0|POST|p4uuT2O25AJwv7ncADLoVhQfImwRQW|
5b7356ccbbddbd594df54555:green-truck=>speed:2|end" | telnet
things.ubidots.com 9012
Send a single dot (Industrial users)
echo -n "ESP8266/1.0|POST|BBFF-
kiFdJvtV3OWTY56M0rKluUGm71lzzn6kboWpbWpfhJFah7fL6p1kcks|green-
truck:5b7356ccbbddbd594df54555=>speed:2|end" | telnet
industrial.api.ubidots.com 9012
Send multiple dots (Educational users)
echo -n "ESP8266/1.0|POST|p4uuT2O25AJwv7ncADLoVhQfImwRQW|weather-
station=>temperature:20,humidity:35|end" | telnet things.ubidots.com 9012
echo -n "ESP8266/1.0|POST|BBFF-
kiFdJvtV3OWTY56M0rKluUGm71lzzn6kboWpbWpfhJFah7fL6p1kcks|weather-
station=>temperature:20,humidity:35|end" | telnet industrial.api.ubidots.com
9012
Retrieve Data
Structure
Ubidots TCP/UDP supports the payload request structure below for retrieving
dots values
{USER_AGENT}|LV|{TOKEN}|{DEVICE_LABEL}:{VARIABLE_LABEL}|end
{USER_AGENT}|GET|{TOKEN}|{VARIABLE_ID}|end
where:
Get the last value from the variable speed inside a device labeled with api
label green-truck:
ESP8266/1.0|LV|p4uuT2O25AJwv7ncADLoVhQfImwRQW|green-truck:speed|end
Get the last value from the variable speed inside a device labeled with api
label green-truck using the speed variable unique id:
ESP8266/1.0|GET|p4uuT2O25AJwv7ncADLoVhQfImwRQW|
573dc1ee76254241c57a4616|end
Get last variable value (Educational users)
echo -n "ESP8266/1.0|LV|p4uuT2O25AJwv7ncADLoVhQfImwRQW|green-
echo -n "ESP8266/1.0|LV|BBFF-
kiFdJvtV3OWTY56M0rKluUGm71lzzn6kboWpbWpfhJFah7fL6p1kcks|green-
Ubidots also supports to retrieve the actual UTC timestamp from our servers.
Structure
Ubidots TCP/UDP supports the payload request structure below for retrieving
dots values
{USER_AGENT}|UTCNOW|||end
where: