Menyimpan data NodeMCU esp 8266 ke database MySQL dengan PHP Rest API
Sebelumnya telah ditulis mengenai tutorial menyimpan data arduino ke database MySQL. Dengan konsep yang hampir sama, kali ini akan saya bahas mengenai cara menyimpan data esp 8266 dan sejenisnya (NodeMCU, Wemos, dll) ke database MySQL dengan PHP Rest API. Dasar dari komunikasi ini adalah HTTP Request yang melibatkan Client-Server. Terdapat 2 metode yang umum digunakan dalam HTTP Request yaitu GET dan POST. Data yang akan kita gunakan untuk sampel adalah data suhu dan kelembaban dari DHT 22. Kamu juga dapat menggunakan data lain atau dapat menggunakan nilai random. Selanjutnya kita akan mengirim data ke server lokal untuk disimpan ke database MySQL. Dari data base kita dapat mengolah untuk ditampilkan dalam bentuk tabel ataupun grafik.
Alat dan Bahan
Modul/hardware yang digunakan adalah Node MCU, Sensor DHT 22 (AM2302). Selanjutnya untuk lokal server kita menggunakan XAMPP, text editor (notepad ++ atau Sublim), postmant (buat test API yang kita buat). Koneksi menggunakan wifi jadi pastikan tersedia hostpot (akses point / portable hostpot (HP android)). Pastikan telah menjalankan XAMPP dan mengaktifkan service apache dan Mysql.
Server-side Program
CREATE DATABASE `nodemcu_log`;
CREATE TABLE `station1` (
`id` int(20) unsigned NOT NULL AUTO_INCREMENT,
`suhu` double NOT NULL,
`kelembaban` double NOT NULL,
`created_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
PRIMARY KEY (`id`)
)
<?php class Database { private $host = "localhost"; private $database_name = "nodemcu_log"; private $username = "root"; private $password = ""; public $conn; public function getConnection(){ $this->conn = null; try{ $this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->database_name, $this->username, $this->password); $this->conn->exec("set names utf8"); }catch(PDOException $exception){ echo "Database could not be connected: " . $exception->getMessage(); } return $this->conn; } } ?>
<?php class Nodemcu_log{ // Connection private $conn; // Table private $db_table = "station1"; // Columns public $id; public $suhu; public $kelembaban; public $created_at; // Db connection public function __construct($db){ $this->conn = $db; } // CREATE public function createLogData(){ $sqlQuery = "INSERT INTO ". $this->db_table ." SET suhu = :suhu, kelembaban = :kelembaban"; $stmt = $this->conn->prepare($sqlQuery); // sanitize $this->suhu=htmlspecialchars(strip_tags($this->suhu)); $this->kelembaban=htmlspecialchars(strip_tags($this->kelembaban)); // bind data $stmt->bindParam(":suhu", $this->suhu); $stmt->bindParam(":kelembaban", $this->kelembaban); if($stmt->execute()){ return true; } return false; } } ?>
<?php header("Access-Control-Allow-Origin: *"); header("Content-Type: application/json; charset=UTF-8"); include_once '../config/database.php'; include_once '../class/nodemcu_log.php'; $database = new Database(); $db = $database->getConnection(); $item = new Nodemcu_log($db); if ($_SERVER['REQUEST_METHOD'] === 'POST') { // The request is using the POST method $data = json_decode(file_get_contents("php://input")); $item->suhu = $data->suhu; $item->kelembaban = $data->kelembaban; } elseif ($_SERVER['REQUEST_METHOD'] === 'GET'){ // The request is using the GET method $item->suhu = isset($_GET['suhu']) ? $_GET['suhu'] : die('wrong structure!'); $item->kelembaban = isset($_GET['kelembaban']) ? $_GET['kelembaban'] : die('wrong structure!'); }else { die('wrong request method'); } if($item->createLogData()){ echo 'Data created successfully.'; } else{ echo 'Data could not be created.'; } ?>
GET - http://localhost/arducoding_tutorial/nodemcu_log/webapi/api/create.php?suhu=20.82&kelembaban=88.99
POST - http://localhost/arducoding_tutorial/nodemcu_log/webapi/api/create.php
Wiring Diagram
NodeMCU Program
Library
Menyimpan data nodeMCU ke database MySQL dengan metode GET
// NodeMCU esp8266 save data to mysql database with GET methode // www.arducoding.com #include <ESP8266WiFi.h> #include <ESP8266HTTPClient.h> #include "DHT.h" #define DHTPIN 4 //#define DHTTYPE DHT11 // DHT 11 #define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321 //#define DHTTYPE DHT21 // DHT 21 (AM2301) const char* ssid = "Your Wifi SSID"; const char* password = "Your Wifi Password"; DHT dht(DHTPIN, DHTTYPE); void setup() { Serial.begin(9600); //Serial.println(F("DHTxx test!")); dht.begin(); WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); int i=0; while(WiFi.status() != WL_CONNECTED){ Serial.print("."); delay(1000); } Serial.println(""); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); Serial.println(); delay(2000); } void loop() { double kelembaban = dht.readHumidity(); // Read temperature as Celsius (the default) double suhu = dht.readTemperature(); // Check if any reads failed and exit early (to try again). if (isnan(kelembaban) || isnan(suhu)) { Serial.println(F("Failed to read from DHT sensor!")); return; } Serial.print(F("Temperature:")); Serial.print(suhu); Serial.print(F("°C Humidity:")); Serial.print(kelembaban); Serial.println(F("%")); if ((WiFi.status() == WL_CONNECTED)) { WiFiClient client; HTTPClient http; String address; //equate with your computer's IP address and your directory application // C:\xampp\htdocs\arducoding_tutorial\nodemcu_log\webapi\api\create.php address ="http://192.168.0.8/arducoding_tutorial/nodemcu_log/webapi/api/create.php?suhu="; address += String(suhu); address += "&kelembaban="; address += String(kelembaban) ; http.begin(client,address); //Specify request destination int httpCode = http.GET();//Send the request String payload; if (httpCode > 0) { //Check the returning code payload = http.getString(); //Get the request response payload payload.trim(); if( payload.length() > 0 ){ Serial.println(payload + "\n"); } } http.end(); //Close connection }else{ Serial.print("Not connected to wifi ");Serial.println(ssid); } delay(60000); //interval 60s }
// NodeMCU esp8266 save data to mysql database with POST methode // www.arducoding.com #include <ESP8266WiFi.h> #include <ESP8266HTTPClient.h> #include <ArduinoJson.h> #include "DHT.h" #define DHTPIN 4 //#define DHTTYPE DHT11 // DHT 11 #define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321 //#define DHTTYPE DHT21 // DHT 21 (AM2301) const char* ssid = "Your Wifi SSID"; const char* password = "Your Wifi Password"; DHT dht(DHTPIN, DHTTYPE); void setup() { Serial.begin(9600); //Serial.println(F("DHTxx test!")); dht.begin(); WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); int i=0; while(WiFi.status() != WL_CONNECTED){ Serial.print("."); delay(1000); } Serial.println(""); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); Serial.println(); delay(2000); } void loop() { double kelembaban = dht.readHumidity(); // Read temperature as Celsius (the default) double suhu = dht.readTemperature(); // Check if any reads failed and exit early (to try again). if (isnan(kelembaban) || isnan(suhu)) { Serial.println(F("Failed to read from DHT sensor!")); return; } Serial.print(F("Temperature:")); Serial.print(suhu); Serial.print(F("°C Humidity:")); Serial.print(kelembaban); Serial.println(F("%")); if ((WiFi.status() == WL_CONNECTED)) { WiFiClient client; HTTPClient http; StaticJsonDocument<200> doc; String url, nodemcuData; //equate with your computer's IP address and your directory application // C:\xampp\htdocs\arducoding_tutorial\nodemcu_log\webapi\api\create.php url ="http://192.168.0.8/arducoding_tutorial/nodemcu_log/webapi/api/create.php"; doc["suhu"] = String(suhu); doc["kelembaban"] = String(kelembaban); http.begin(client,url); http.addHeader("Content-Type", "application/json"); serializeJson(doc, nodemcuData); Serial.print("POST data >> "); Serial.println(nodemcuData); int httpCode = http.POST(nodemcuData);//Send the request String payload; if (httpCode > 0) { //Check the returning code payload = http.getString(); //Get the request response payload payload.trim(); if( payload.length() > 0 ){ Serial.println(payload + "\n"); } } http.end(); //Close connection }else{ Serial.print("Not connected to wifi ");Serial.println(ssid); } delay(60000); //interval 60s }
Adapun full code program dari PHP rest API dapat di download di link berikut. Didalamnya sudah terdapat fungsi-fungsi untuk melakukan proses CRUD baik dengan metode post maupun get. Terdapat pula code untuk pembuatan database yang diperlukan. Untuk hasilnya dpat dilihat pada video dibawah.
13 komentar
bang, coding ini saat di upload muncul error ini kenapa ya??
exit status 1
no match for 'operator=' (operand types are 'String' and 'HTTPClient')