0% found this document useful (0 votes)
18 views26 pages

TKHTS2

Uploaded by

little34306xd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views26 pages

TKHTS2

Uploaded by

little34306xd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 26

HANOI UNIVERSITY OF SCIENCE AND TECHNOLOGY

SCHOOL OF ELECTRONICS AND TELECOMMUNICATIONS

PROJECT REPORT
DIGITAL SYSTEM DESIGN 2

AIR QUALITY MEASUREMENT USING


ESP8266 AND BME680 SENSOR

Name of students: Dang Nguyen Hoang Dang 20210148

Nguyen Quang Huy 20213616

Hoang Minh Quan 20213640

Name of instructor: Ph.D. Prof. Ngo Vu Duc

Hanoi, 06-2024

1
Table of Contents
I. PROBLEM ANALYSIS.........................................................................................4

1. Problem Statement...............................................................................................4
2. Proposed Treatment..............................................................................................4

II. SPECIFICATIONS............................................................................................5

1. Functional Requirements......................................................................................5
2. Non-functional Requirements..............................................................................6
3. System block diagram..........................................................................................6

III. DETAIL OF EACH MODULE........................................................................7

1. ESP8266 Module..................................................................................................7
2. BME680 Air Quality Sensor................................................................................9

IV. IMPLEMENTATION......................................................................................10

1. Experiment Setup...............................................................................................10
2. Experiment Procedure........................................................................................11

V. CONCLUSION.................................................................................................24

2
I. PROBLEM ANALYSIS
1. Problem Statement

In-home air quality problems can significantly impact health and well-being,
with sources ranging from household products and building materials to cooking,
heating, and biological contaminants. Common pollutants like VOCs, mold spores,
dust mites, and radon contribute to respiratory issues, cardiovascular effects,
headaches, fatigue, and even long-term health risks such as cancer. Poor ventilation,
high or low humidity, and temperature fluctuations can exacerbate these problems.
Environmental factors within the home, such as improper humidity levels and
inadequate ventilation, can further compound these problems. High humidity can
encourage mold growth and dust mite proliferation, while low humidity can cause dry
skin and respiratory irritation. Inadequate ventilation allows pollutants to accumulate,
significantly degrading air quality. Temperature fluctuations, if not well-regulated, can
also affect indoor air quality and overall comfort, especially for vulnerable populations
like the elderly and young children.
Therefore, the need for air quality measuring devices in homes is crucial. These
devices help in detecting and monitoring indoor pollutants, providing essential data to
protect occupants' health. By identifying sources of contamination and measuring
pollutant levels, homeowners can take proactive steps to improve ventilation, use air
purifiers, and make informed decisions about household products and materials,
ultimately ensuring a safer and healthier indoor environment for all residents.

2. Proposed Treatment

We propose the development of an Air Quality Measuring device using


ESP8622 microcontrollers and BME680 air quality sensor. The ESP8266
microcontroller is ideal for IoT applications due to its built-in Wi-Fi capabilities. It can
connect to local networks or the internet, enabling real-time data transmission and
remote monitoring of air quality parameters.
Meanwhile, the BME680 sensor can measure multiple environmental
parameters simultaneously, including:

3
 Temperature: Provides accurate temperature readings
 Humidity: Measures relative humidity levels in the air
 Pressure: Provides atmospheric pressure data
 Gas: Specifically measures volatile organic compounds (VOCs) in the air,
making it particularly useful for indoor air quality monitoring

II. SPECIFICATIONS
1. Functional Requirements

 Data Collection: The device should collect real-time data from the connected
sensors at regular intervals. It should retrieve and store data for all relevant
weather parameters.
 Wireless Communication: The device should establish wireless connectivity,
such as Wi-Fi or Bluetooth, to transmit the weather data to a central server or
cloud plat form. It should support secure and reliable data transmission
 Real-Time Monitoring: These devices provide real-time data on air quality
levels, allowing users to track fluctuations in pollutant concentrations over time.
 Remote Monitoring: Users can remotely access real-time air quality data from
their smartphones, providing peace of mind even when they're away from home
or the monitoring site.
 Alert Systems: Some devices are equipped with alert systems that notify users
when pollutant levels exceed predefined thresholds, enabling prompt action to
mitigate exposure.
 Calibration and Accuracy: Air quality measuring devices are calibrated to
ensure accuracy and reliability in pollutant detection, making them suitable for
research, regulatory compliance, and public health monitoring purposes.
 User-Friendly Interface: The system should provide a user-friendly interface,
both locally and remotely, to access weather data. The interface should be
intuitive, easy to navigate, and visually appealing.
 Power Efficiency: The system should be designed to optimize power
consumption and maximize battery life. It should incorporate power-saving
techniques such as sleep modes and efficient data transmission protocols.

4
2. Non-functional Requirements

Specifications Range

Temperature -40°C to 85°C

Humidity 0 to 100% RH with ±3% accuracy

Pressure 300Pa to 1100 hPa with ±1 hPa absolute accuracy

System Availability 99%

Power Supply 5V

Cost of Implementation 200,000VND – 300,000VND

3. System block diagram

Figure 1. Block diagram

The ESP8266 microcontroller is responsible for retrieving data from the connected
sensor. Using its built-in Wi-Fi module, the ESP8266 establishes a connection to a
cloud server. The collected sensor data is then transmitted from the ESP32 to the cloud
server over the Wi-Fi network.
Once the data reaches the cloud server, it is stored and made accessible for further
processing and analysis. The smartphone app, which is connected to the same cloud
server, retrieves the stored data and presents it in a user-friendly interface. This allows

5
users to conveniently access and view the real-time air quality information and any
historical data that has been collected.
By leveraging this architecture, the ESP8266 enables seamless data transfer from
the sensors to the cloud server, providing a reliable and scalable solution for air quality
monitoring. Users can effortlessly monitor the air quality conditions and trends
through the smartphone app, enhancing their overall experience and convenience

III. DETAIL OF EACH MODULE


1. ESP8266 Module

Figure 2. ESP8266 pin configuration

The ESP8266 is a system on a chip (SOC) Wi-Fi microchip for Internet of Things
(IoT) applications produced by Espressif Systems. Given its low cost, small size and
adaptability with embedded devices, the ESP8266 is now used extensively across IoT
devices.

6
The ESP8266 module enables microcontrollers to connect to 2.4 GHz Wi-Fi, using
IEEE 802.11 bgn. It can be used with ESP-AT firmware to provide Wi-Fi connectivity
to external host MCUs, or it can be used as a self-sufficient MCU by running an
RTOS-based SDK. The module has a full TCP/IP stack and provides the ability for
data processing, reads and controls of GPIOs. The ESP8266 specifications is described
in Table 1

ESP8266 Description

Core 1

Architecture 32-bit RISC

Clock Xtensa LX106 80-160MHz

WiFi IEEE802.11 b/g/n support for WPA and WPA2

Bluetooth No

RAM 160KB – 64KB Instruction – 96KB Data

Flash Extern QSPI – 512KB A 4MB

GPIO 16

DAC 0

ADC 1

Interfaces SPI-I2C-UART-I2S

Table 1. ESP8266 specifications

ESP8266 has many applications when it comes to the IoT. Here are just some of
the functions the chip is used for:

 Networking: The module’s Wi-Fi antenna enables embedded devices to


connect to routers and transmit data
 Data Processing: Includes processing basic inputs from analog and digital
sensors for far more complex calculations with an RTOS or Non-OS SDK

7
 P2P Connectivity: Create direct communication between ESPs and other
devices using IoT P2P connectivity
 Web Server: Access pages written in HTML or development languages.

2. BME680 Air Quality Sensor

Figure 2. BME680

The BME680 is the first gas sensor that integrates high-linearity and high-accuracy
gas, pressure, humidity and temperature sensors. It is especially developed for mobile
applications and wearables where size and low power consumption are critical
requirements. The BME680 guarantees - depending on the specific operating mode -
optimized consumption, long-term stability and high EMC robustness. To measure air
quality for personal wellbeing the gas sensor within the BME680 can detect a broad
range of gases such as volatile organic compounds (VOC).
The module comes with a XC6206 3.3V precise voltage regulator and voltage
level translator, so you can use it with your favorite 3.3V or 5V microcontroller
without worry. The BME680 consumes less than 1mA during measurements and only
8
0.15µA during sleep mode. This low power consumption allows the implementation in
battery driven devices such as handsets, wearables or smart watches.
The BME680 pin configuration is given in Table 2

Pin Name Description

VCC Connected to 5V

GND Connected to ground

SCL The SPI Clock pin, it is an input to the chip

SDA The Serial Data In (SDI/MOSI) pin, for data sent from your
microcontroller to the BME680.

SDO The Serial Data Out (SDO/MISO) pin, for data sent from the
BME680 to your microcontroller.

CS The Chip Select pin, pull it LOW to enable an SPI


communication. If you want to connect multiple BME680’s
to one microcontroller, have them share the SDI, SDO and
SCK pins and assign each one a unique CS pin.

Table 2. BME680 Pin Configuration

Here are some specifications of the BME680:

 Temperature: -40°C to 85°C


 Humidity: 0 to 100% RH with ±3% accuracy
 Pressure: 300Pa to 1100 hPa with ±1 hPa absolute accuracy
 Altitude: 0 to 30,000 ft (9.2 km) with ±1 meter accuracy

IV. IMPLEMENTATION
1. Experiment Setup

For our experiment setup, we will need the following components and materials:

9
 ESP8266 module: This is the microcontroller board that will be used to
interface with the sensors and collect data.
 BME680 air quality sensor: The sensor to measure specifics parameters of the
air such as temperature, humidity, pressure. Make sure they are compatible with
the ESP32 module and can provide accurate measurements in normal
conditions.
 Breadboard: A breadboard will be used to create temporary connections
between the components without the need for soldering.
 Jumper wires: These wires will be used to connect the ESP8266 module,
sensors, and breadboard, ensuring proper electrical connections.

2. Experiment Procedure

To begin, we first determine the pinout configuration of the ESP8266 module and
select the suitable GPIO (General Purpose Input/Output) pin to establish a connection
with the sensor. Subsequently, we utilize Fritzing, a software tool for creating visual
representations of circuits, to draw the circuit diagram. The resulting diagram would
depict the ESP8266 module and the sensor, showcasing their interconnections and
providing a visual representation of the circuit setup.

Figure 3. Circuit schematic

10
Following the configuration of the pinout and the creation of the circuit diagram,
the next step involves procuring the required sensors and constructing the actual circuit
to verify its functionality.

Figure 4. Actual circuit

The sensor data measurement can be displayed on the website as follows:

Figure 5. Web interface

11
In Application, we do more than that, we made multiple devices that can be
added, removed and controlled easily with Graphics Users Interface, currently
supported iOS. The future works target is Android supported and Desktop app for
Windows and macOS.

Figure 6. Display on application (iOS)

12
Using MAC Addresses as Identifiers for Air Quality Sensors
In the implementation of a network of air quality sensors using ESP8266
microcontrollers, it is crucial to ensure the accurate identification and differentiation of
data originating from various sensors. This will discuss the rationale behind utilizing
MAC addresses as unique identifiers for the sensors and the structure of the database
designed to store the sensor data.

Media Access Control (MAC) addresses are globally unique identifiers assigned to
network interfaces. Each ESP8266 microcontroller is equipped with a distinct MAC
address. By leveraging these unique addresses, we can achieve the following:
1. Unique Identification: Each air quality sensor is linked to a specific ESP8266
microcontroller. The uniqueness of MAC addresses ensures that data from each
sensor can be distinctly identified.
2. Data Association: By associating sensor data with the corresponding MAC
address, we can determine which specific ESP8266 transmitted the data. This
association facilitates efficient filtering and organization of data.
3. Reliable Tracking: Using MAC addresses allows for reliable tracking and
management of multiple sensors within the network, ensuring that data integrity
is maintained.

Database Structure and Management


The sensor data is stored in an SQL database managed using PhpMyAdmin. The
database is designed to store the 25 most recent records, each containing 8 fields. This
design choice is based on the following considerations:
1. Active Sensors: Typically, only 2 to 3 sensors are active simultaneously, and
they transmit data every 2 to 4 seconds.
2. Memory Efficiency: Limiting the database to the 25 most recent records helps
conserve memory and maintain efficient database operations.
3. Scalability: If the number of active sensors increases beyond the current
capacity, the range for retaining records can be adjusted according to
accommodate the additional data while still conserving memory.

13
Database Schema
The database schema includes the following fields for each record:
1. Timestamp
2. ID
3. MAC Address
4. Temperature
5. Humidity
6. Pressure
7. Gas resistance
8. Indoors-Air-Quality (IAQ)

Data Management Strategy


To manage the data efficiently:
 Data Insertion: New data entries are inserted into the database in real-time as
they are received from the sensors.
 Data Retention: The database retains only the 25 most recent records by
deleting older records once the limit is reached. This strategy ensures that the
database does not become overloaded, thereby maintaining optimal
performance.
 Dynamic Adjustment: The retention range can be dynamically adjusted based
on the number of active sensors to ensure that all relevant data is captured
without exceeding memory constraints.

Utilizing MAC addresses as unique identifiers for air quality sensors in a network
of ESP8266 microcontrollers provides a reliable method for data association and
management. The designed database schema and data management strategy ensure
efficient storage and retrieval of sensor data while maintaining memory efficiency.
This approach facilitates accurate tracking and analysis of air quality data, contributing
to the overall effectiveness of the monitoring system.

14
Figure 7. PhpMyAdmin SQL database

Server Configuration and Management


In the deployment of air quality monitoring system, a private hosting server is
utilized to execute PHP scripts and manage data effectively. This report extends the
description of our server setup, based on the provided image, to highlight the key
features and functionalities of our hosting environment.

Server Specifications
 Hosting Platform: The server is hosted on a private server, ensuring dedicated
resources and enhanced security for our application.
 Control Panel: The server is managed using aaPanel, a popular Linux-based
web hosting control panel. aaPanel provides an intuitive graphical user interface
for managing various aspects of the server, including websites, databases, and
security settings.

15
Server Features
1. File Management:
o Directory Structure: The image shows the directory structure with files
related to the air quality monitoring application.
o File Types: Includes PHP scripts (data.php, get.php) and an HTML file
(index.html).
o Permissions and Ownership: Each file is marked with its respective
permissions and ownership details, ensuring proper access control.
2. PHP Execution:
o PHP Files: The data.php and get.php scripts are crucial for handling data
submissions from the sensors and fetching data from the database.
o User Profile File: The .user.ini file is used to configure PHP user
settings, enhancing security by preventing cross-site scripting (XSS)
attacks.
3. Web Interface:
o index.html: Serves as the front-end interface for accessing the air quality
data, providing users with a user-friendly way to view the collected data.
4. Database Management:
o PhpMyAdmin Integration: The server includes PhpMyAdmin for
managing the SQL database, facilitating easy administration of the
database where sensor data is stored.
5. Security:
o File Protection: The server setup includes file protection mechanisms to
safeguard against unauthorized access.
o Backups: The aaPanel interface offers options for creating backups,
ensuring data can be recovered in case of any issues.

Server Operation
 Data Handling: The server receives data from multiple air quality sensors
every 2 to 4 seconds. The PHP scripts process this data, associate it with the
corresponding MAC address, and store it in the SQL database.
16
 Data Retrieval: Users can retrieve the latest data through the web interface,
with the server dynamically generating responses based on the current database
contents.
 Scalability: The server is configured to scale the range of stored records based
on the number of active sensors, optimizing memory usage and maintaining
performance.

The private hosting server running aaPanel Linux provides a robust and secure
environment for managing the air quality monitoring system. By leveraging the
features of aaPanel and integrating essential PHP scripts and database management
tools, the server ensures efficient data processing, storage, and retrieval, thereby
supporting the overall functionality of the air quality monitoring application.

Figure 8. Hosting and Files storing using aaPanel

Code explanation
ESP8266 code (Arduino IDE):
Initial setup.
#include <Wire.h>
#include <SPI.h>
#include <Adafruit_Sensor.h>
#include "Adafruit_BME680.h"
#include <ESP8266WiFi.h>
#include "ESPAsyncWebServer.h"

17
#include <WiFiClientSecureBearSSL.h>
#include <ESP8266HTTPClient.h>

// Replace with your network credentials


const char* ssid = "P404";
const char* password = "sautrieuruoi";

Adafruit_BME680 bme; // I2C

float temperature;
float humidity;
float pressure;
float gasResistance;
String IAQ;

float hum_weighting = 0.25; // so hum effect is 25% of the total air quality score
float gas_weighting = 0.75; // so gas effect is 75% of the total air quality score

float hum_score, gas_score;


float gas_reference = 250000;
float hum_reference = 40;
int getgasreference_count = 0;

AsyncWebServer server(80);
AsyncEventSource events("/events");

unsigned long lastTime = 0;


unsigned long timerDelay = 4000; // send readings timer
In the first code section, we defined some important libraries for the ESP8266
and sensores, I2C connections, and the time delay for request data from sensors.
Besides that, temperature, humidity, pressure, gas resistance and IAQ got defined.
Function to get data.
String CalculateIAQ(float score){
String IAQ_text = "";
score = (100-score)*5;
if (score >= 301) IAQ_text = "Hazardous";
else if (score >= 201 && score <= 300 ) IAQ_text = "Very Unhealthy";
else if (score >= 176 && score <= 200 ) IAQ_text = "Unhealthy";
else if (score >= 151 && score <= 175 ) IAQ_text = "Unhealthy for Sensitive Groups";
else if (score >= 51 && score <= 150 ) IAQ_text = "Moderate";
else if (score >= 00 && score <= 50 ) IAQ_text = "Good";
return IAQ_text;
}

void getBME680Readings(){
// Tell BME680 to begin measurement.
unsigned long endTime = bme.beginReading();
if (endTime == 0) {
Serial.println(F("Failed to begin reading :("));
return;
}
if (!bme.endReading()) {
Serial.println(F("Failed to complete reading :("));
return;
}
temperature = bme.temperature;
pressure = bme.pressure / 100.0;
humidity = bme.humidity;
gasResistance = bme.gas_resistance / 1000.0;

if (humidity >= 38 && humidity <= 42)


hum_score = 0.25*100; // Humidity +/-5% around optimum
else
{ //sub-optimal
if (humidity < 38)
hum_score = 0.25/hum_reference*humidity*100;
else
{
hum_score = ((-0.25/(100-hum_reference)*humidity)+0.416666)*100;
}
}

18
//Calculate gas contribution to IAQ index
float gas_lower_limit = 5000; // Bad air quality limit
float gas_upper_limit = 50000; // Good air quality limit
if (gas_reference > gas_upper_limit) gas_reference = gas_upper_limit;
if (gas_reference < gas_lower_limit) gas_reference = gas_lower_limit;
gas_score = (0.75/(gas_upper_limit-gas_lower_limit)*gas_reference -
(gas_lower_limit*(0.75/(gas_upper_limit-gas_lower_limit))))*100;

IAQ = CalculateIAQ(hum_score + gas_score);


}

String processor(const String& var){


getBME680Readings();
//Serial.println(var);
if(var == "TEMPERATURE"){
return String(temperature);
}
else if(var == "HUMIDITY"){
return String(humidity);
}
else if(var == "PRESSURE"){
return String(pressure);
}
else if(var == "GAS"){
return String(gasResistance);
}
else if(var == "IAQ"){
return String(IAQ);
}
return String();
}
}

The code above is how we collect data, analysis the data and got the IAQ
measurement based on all data we collected (temperature, pressure, humidity and gas
resistance), from that we can conclude the IAQ value (Hazardous to Good air quality).
The formular data analysis is take from open source Github code:
https://github.com/ghtomcat/co2ampel (MIT License).

POST data to server API to store data in database.


void sendDataToServer(float temperature, float humidity, float pressure, float gasResistance,
String IAQ, String macAddress) {
if (WiFi.status() == WL_CONNECTED) {
std::unique_ptr<BearSSL::WiFiClientSecure> client(new BearSSL::WiFiClientSecure);
client->setInsecure();
HTTPClient http;
http.begin(*client, "https://huy34306.x2nios.com/data.php");
http.addHeader("Content-Type", "application/x-www-form-urlencoded");

String httpRequestData = "macAddress=" + macAddress


+ "&temperature=" + String(temperature)
+ "&humidity=" + String(humidity)
+ "&pressure=" + String(pressure)
+ "&gasResistance=" + String(gasResistance)
+ "&IAQ=" + IAQ;

int httpResponseCode = http.POST(httpRequestData);

if (httpResponseCode > 0) {
String response = http.getString();
Serial.println(httpResponseCode);
Serial.println(response);
Serial.println("\n");
} else {
Serial.print("Loi: ");
Serial.println(httpResponseCode);
}

19
http.end();
} else {
Serial.println("WiFi Disconnected");
}
}

The POST data is posted to https://huy34306.x2nios.com/data.php. That API


collected data from the sensors go through the ESP8266 and send over the internet. I
need to use http.addHeader to avoid 400 error (refused because of certificate). POST
method by imported library “ESPAsyncWebserver”. It sends MAC address,
temperature, humidity, pressure, gas resistance and IAQ.
It's done for Hardware and Sensors code (Arduino based), we now move on
serverside code.

data.php code (PHP):


<?php
$servername = "localhost";
$username = "sql_huy34306_x2n";
$password = "e0466b55b4c14";
$dbname = "sql_huy34306_x2n";

date_default_timezone_set('Asia/Ho_Chi_Minh');

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
$macAddress = $_POST['macAddress'];
$temperature = $_POST['temperature'];
$humidity = $_POST['humidity'];
$pressure = $_POST['pressure'];
$gas_resistance = $_POST['gasResistance'];
$iaq = $_POST['IAQ'];

$reading_time = date('Y-m-d H:i:s');

$sql = "INSERT INTO readings (mac_address, temperature, humidity, pressure,


gas_resistance, iaq, reading_time)
VALUES ('$macAddress', '$temperature', '$humidity', '$pressure',
'$gas_resistance', '$iaq', '$reading_time')";

if ($conn->query($sql) === TRUE) {


echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
} else {
echo "Loi";
}

$conn->close();
?>

Detailed Explanation of data.php for Handling Sensor Data


The data.php script is a critical component in the air quality monitoring system,
facilitating the seamless transfer of data from ESP8266 sensors to a MySQL database.
20
This provides an extended explanation of the script, detailing its functionality and the
steps involved in processing sensor data.

Database Connection and Setup


The script begins by establishing a connection to the MySQL database. The
following parameters are defined to facilitate this connection:

 servername: Specifies the server address, which is localhost in this case.


 username: The username required to authenticate with the MySQL server.
 password: The password associated with the specified username.
 dbname: The name of the database where the data will be stored.

The script constructs an SQL query to insert the retrieved data into the readings
table. The table is assumed to have the following columns: mac_address, temperature,
humidity, pressure, gas_resistance, iaq, and reading_time.

The data.php script efficiently handles the process of receiving sensor data from
ESP8266 devices, processing it, and storing it in a MySQL database. By leveraging the
unique MAC addresses of the sensors, the script ensures accurate identification and
association of data. The use of a POST request method guarantees secure and reliable
data transmission. The script's error handling mechanisms and database connection
management contribute to the robustness and reliability of the air quality monitoring
system.

get.php code (PHP):


<?php
header("Content-Type: application/json; charset=UTF-8");

$servername = "localhost";
$username = "sql_huy34306_x2n";
$password = "e0466b55b4c14";
$dbname = "sql_huy34306_x2n";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Function to validate MAC address format


function isValidMAC($mac) {
return (bool) preg_match('/^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/', $mac);
}

21
// Check if the MAC address is provided
if (!isset($_GET['mac']) || !isValidMAC($_GET['mac'])) {
echo json_encode(array("error" => "Invalid MAC address. Please re-input."));
$conn->close();
exit();
}

$mac_address = $_GET['mac'];

// Delete older records if there are more than 10 entries


$sql_count = "SELECT COUNT(*) AS count FROM readings";
$result_count = $conn->query($sql_count);
$row_count = $result_count->fetch_assoc();
$count = $row_count["count"];

if ($count > 25) {


$delete_count = $count - 25;
$sql_delete = "DELETE FROM readings ORDER BY reading_time ASC LIMIT $delete_count";
$conn->query($sql_delete);
}

// Fetch the latest reading for the specified MAC address


$sql_latest = "SELECT * FROM readings WHERE mac_address = '$mac_address' ORDER BY reading_time
DESC LIMIT 1";
$result_latest = $conn->query($sql_latest);

if ($result_latest->num_rows > 0) {
$latest_reading = $result_latest->fetch_assoc();
echo json_encode($latest_reading);
} else {
echo json_encode(array("error" => "No data found for the specified MAC address."));
}

$conn->close();
?>

Details explain get.php code:


The PHP code retrieves the latest air quality sensor data for a specified MAC
address and returns the data in JSON format. It also manages the database to ensure
that only the latest 25 records are retained. Detailed explanation of each part of the
code:

MAC Address Validation


The code includes a function to validate the format of the MAC address. This
ensures that only valid MAC addresses are processed. It checks if a MAC address is
provided and if it is in the correct format. If not, it returns an error message and
terminates the code. The valid MAC address is then stored in the mac_address
variable.

Managing Database Records


22
The code first checks the total number of records in the readings table. If there
are more than 25 records, the script deletes the oldest records to retain only the latest
25 entries. This ensures efficient database management and performance.

Fetching the Latest Reading


The script constructs an SQL query to fetch the latest reading for the specified
MAC address. The query orders the records by reading_time in descending order and
limits the result to the most recent entry. If a record is found, the script encodes it as a
JSON object and outputs it. If no data is found, it returns an error message.

The PHP script efficiently handles the retrieval of the latest air quality sensor
data for a specified MAC address. It validates the MAC address format, manages the
database to retain only the latest 25 records, and fetches the most recent data entry.
The script ensures that the data is returned in JSON format, making it suitable for web
and mobile applications. The error handling mechanisms provide meaningful feedback
to the client in case of invalid input or missing data.

V. CONCLUSION

Both PHP code handle specific tasks related to the air quality monitoring
system.

data.php for Inserting Sensor Data


Overview
The first data.php script handles the insertion of sensor data into the MySQL database.
The algorithm can be broken down into the following steps:

1. Database Connection: Establish a connection to the MySQL database.


2. POST Request Handling: Check if the incoming request is a POST request.
3. Data Retrieval: Retrieve sensor data from the POST request.
4. Data Insertion: Insert the retrieved data into the database.
23
5. Error Handling: Provide feedback on the success or failure of the data insertion.

Detailed Steps

a. Database Connection:
 The script initializes connection parameters (server name, username,
password, database name).
 It establishes a connection to the MySQL database using these
parameters.
 If the connection fails, it terminates the script with an error message.
b. POST Request Handling:
 The script checks if the incoming request method is POST.
 If not, it returns an error message.
c. Data Retrieval:
 The script retrieves the following data from the POST request:
MAC address
Temperature
Humidity
Pressure
Gas resistance
Indoor Air Quality (IAQ)
 It also captures the current timestamp.
d. Data Insertion:
 The script constructs an SQL INSERT query to add the retrieved data to
the readings table.
 It executes the query to insert the data into the database.
e. Error Handling:
 If the data insertion is successful, it returns a success message.
 If there is an error, it returns an error message with details.

24
get.php for Fetching Sensor Data
Overview
The get.php code retrieves the latest sensor data for a specified MAC address and
manages the database to retain only the latest 25 records. The algorithm can be broken
down into the following steps:

1. Content Type Setting: Set the content type of the response to JSON.
2. Database Connection: Establish a connection to the MySQL database.
3. MAC Address Validation: Validate the provided MAC address.
4. Record Management: Ensure only the latest 25 records are retained in the
database.
5. Data Retrieval: Retrieve the latest sensor data for the specified MAC address.
6. Error Handling: Provide feedback on the success or failure of the data retrieval.

Detailed Steps

1. Content Type Setting:


- The script sets the HTTP response content type to JSON.
2. Database Connection:
- The script initializes connection parameters (server name, username, password,
database name).
- It establishes a connection to the MySQL database using these parameters.
- If the connection fails, it terminates the script with an error message.
3. MAC Address Validation:
- The script defines a function to validate the MAC address format using a
regular expression.
- It checks if the MAC address is provided in the GET request and if it is valid.
- If the MAC address is invalid or not provided, it returns an error message and
terminates the script.
4. Record Management:
- The script counts the total number of records in the readings table.
- If the number of records exceeds 25, it deletes the oldest records to retain only
the latest 25 entries.
25
5. Data Retrieval:
- The script constructs an SQL `SELECT` query to fetch the latest reading for the
specified MAC address.
- It executes the query and retrieves the data.
- If data is found, it returns the data as a JSON object.
- If no data is found, it returns an error message.
6. Error Handling:
- The script handles errors related to database connection, invalid MAC
addresses, and data retrieval.
- It provides meaningful feedback in the form of JSON-encoded messages.

Both scripts implement robust algorithms to handle specific tasks related to the
air quality monitoring system. The first script focuses on securely inserting sensor data
into the database, while the second script ensures efficient retrieval of the latest sensor
data and manages the database to retain only the most recent records. Error handling
and validation are integral parts of both algorithms, ensuring reliability and robustness
in data processing and management.

26

You might also like