실습 환경 : mariadb, 우분투 리눅스, 아파치 웹 서버, PHP 7.4

실습 보드 : ESP8266 개발 보드 + DHT22 센서

 

설정 간 문제 해결 과정

mariadb 설치 후 sudo mysql -u root 실행 시 Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2) 오류 발생

 

0. 서비스 재실행

sudo service mysql restart 또는 sudo systemctl restart mariadb 입력하여 서비스 재실행

 

1. 서비스 재실행 자체가 실패할 경우 (+삭제 후 실행시 동일증상 발생해도 마찬가지)

/var/lib/mysql 폴더 강제 삭제 후 데이터 재생성 해주기,

cd var/lib/ 입력하여 경로 이동,

sudo rm -r mysql mysql 폴더 강제 삭제(* rm 명령어로 폴더 삭제할 경우 -r 옵션을 rm 명령어 뒤에 붙힌다)

sudo mysql_install_db --user=mysql 

sudo service mysql start 또는 sudo systemctl start mariadb 입력하여 서비스 정상 동작 확인하기

 

 

GET 방식으로 웹서버 전송

받는 측 PHP 파일에서 별도의 수신 확인 응답을 보내지 않기 때문에

시리얼 모니터 상으론 에러코드 -11번이 출력되나 정상적으로 DB에 값이 저장되는 것으로 보임.

//GET 방식으로 웹서버로 전송.

#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include "DHT.h"
#define DHTPIN D2     // Digital pin connected to the DHT sensor
#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321
DHT dht(DHTPIN, DHTTYPE);
float h;
float t;
const char* ssid = "";
const char* password = "";

//Your Domain name with URL path or IP address with path
String serverName = "<http://192.168.2.175/test2.php>";

// the following variables are unsigned longs because the time, measured in
// milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastTime = 0;
// Timer set to 10 minutes (600000)
//unsigned long timerDelay = 600000;
// Set timer to 5 seconds (5000)
unsigned long timerDelay = 5000;

void setup() {
  Serial.begin(115200); 
  dht.begin();
   WiFi.begin(ssid, password);
 
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
   Serial.println("Connecting to WiFi..");
  }
 
  Serial.println("Connected to the WiFi network");
}

void loop() {
  readtemphum();
  
  
  //Send an HTTP POST request every 10 minutes
  if ((millis() - lastTime) > timerDelay) {
    //Check WiFi connection status
    if(WiFi.status()== WL_CONNECTED){
      HTTPClient http;

      String serverPath = serverName + "?temp="+String(t)+"&hum="+String(h);
      
      // Your Domain name with URL path or IP address with path
      http.begin(serverPath.c_str());
      
      // Send HTTP GET request
      int httpResponseCode = http.GET();
      
      if (httpResponseCode>0) {
        Serial.print("HTTP Response code: ");
        Serial.println(httpResponseCode);
        String payload = http.getString();
        Serial.println(payload);
      }
      else {
        Serial.print("Error code: ");
        Serial.println(httpResponseCode);
      }
      // Free resources
      http.end();
    }
    else {
      Serial.println("WiFi Disconnected");
    }
    lastTime = millis();
  }
}

void readtemphum(){
    delay(2000);
   h = dht.readHumidity();
  t = dht.readTemperature();
}
  • POST 방식으로 전송하는 아두이노 코드
#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include "DHT.h"
#define DHTPIN D2     // Digital pin connected to the DHT sensor
#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321
DHT dht(DHTPIN, DHTTYPE);
float h;
float t;
const char* ssid = "";
const char* password = "";
const char*  serverName = "<http://192.168.2.175/posttest.php>";
String url = "/post/";
unsigned long lastTime = 0;
unsigned long timerDelay = 5000;

void setup() {
  Serial.begin(115200);
  dht.begin();
  WiFi.begin(ssid, password);
  Serial.println("Connecting");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to WiFi network with IP Address: ");
  Serial.println(WiFi.localIP());

  Serial.println("Timer set to 5 seconds (timerDelay variable), it will take 5 seconds before publishing the first reading.");
}

void loop() {
  readtemphum();
  //Send an HTTP POST request every 10 minutes
  if ((millis() - lastTime) > timerDelay) {
    //Check WiFi connection status
    if (WiFi.status() == WL_CONNECTED) {
      WiFiClient client;
      HTTPClient http;
      // Specify content-type header
      http.addHeader("Content-Type", "application/x-www-form-urlencoded");
      String postData = "temp=" + String(t) + "&hum=" + String(h);
      String address = serverName + url;
      http.begin(address);
      auto httpCode = http.POST(postData);
      Serial.println("전송 데이터 :: " + postData);
      Serial.println(httpCode); //Print HTTP return code
      String payload = http.getString();
      Serial.println(payload); //Print request response payload
      // Free resources
      http.end();
    }
    else {
      Serial.println("WiFi Disconnected");
    }
    lastTime = millis();
  }
}

void readtemphum() {
  delay(2000);
  h = dht.readHumidity();
  t = dht.readTemperature();
}
  • 네트워크 연결 후 5초 뒤 전송
  • 성공한 경우 HTTP 코드 200번 반환 (성공) 연결에 문제 있을 경우 500번 반환(실패)

WEB SERVER 측 코드

https://wikidocs.net/116936 (PHP 3분 핵심 요약집 참고하여 실습)

<?php
function db_get_pdo()
{
    $host = 'localhost';
    $port = '3306';
    $dbname = 'sensor';
    $charset = 'utf8mb4';
    $username = 'ggk_test';
    $db_pw = "";
    $dsn = "mysql:host=$host;port=$port;dbname=$dbname;charset=$charset";
    $pdo = new PDO($dsn, $username, $db_pw);
    return $pdo;
}

function db_select($query, $param=array()){
    $pdo = db_get_pdo();
    try {
        $st = $pdo->prepare($query);
        $st->execute($param);
        $result =$st->fetchAll(PDO::FETCH_ASSOC);
        $pdo = null;
        return $result;
    } catch (PDOException $ex) {
        return false;
    } finally {
        $pdo = null;
    }
}

function db_insert($query, $param = array())
{
    $pdo = db_get_pdo();
    try {
        $st = $pdo->prepare($query);
        $result = $st->execute($param);
        $last_id = $pdo->lastInsertId();
        $pdo = null;
        if ($result) {
            return $last_id;
        } else {
            return false;
        }
    } catch (PDOException $ex) {
        return false;
    } finally {
        $pdo = null;
    }
}

function db_update_delete($query, $param = array())
{
    $pdo = db_get_pdo();
    try {
        $st = $pdo->prepare($query);
        $result = $st->execute($param);
        $pdo = null;
        return $result;
    } catch (PDOException $ex) {
        return false;
    } finally {
        $pdo = null;
    }
}
?>
  • 범용적인 활용을 위해 PDO 방식 사용.
<?php
require_once("inc/db_pdo.php");

$humidity = isset($_POST['hum']) ? $_POST['hum'] : null;
$temperature = isset($_POST['temp']) ? $_POST['temp'] : null;
//$login_name = isset($_POST['login_name']) ? $_POST['login_name'] : null;

// 데이터 저장
db_insert("insert into save (hum, temp) values (:humidity, :temperature)",
    array(
        'humidity' => $humidity,
        'temperature' => $temperature,
    )
);

'Tech' 카테고리의 다른 글

Rocky Linux/Oracle Linux ) Semanage 사용하기  (0) 2022.03.16

Selinux 활성화 상태에선 포트변경이 막혀있기 때문에 (그렇다고 selinux를 꺼버리는 건 보안상 좋지 않으니)

Semanage를 사용해서 포트정보를 확인하고, 정책을 변경해야 한다.

 

리눅스 버전에 따라 semanage 사용 시 command not found 메시지가 뜨는 경우가 있는데,

yum whatprovides semanage 를 입력하여 찾을 수 있다.

명령어, 혹은 패키지명으로 확인할 수 있으며, 설명까지 확인할 수 있다.

여기서 최신버전 패키지명을 복사한 후

Sudo yum install 패키지명 으로 설치하면 완료.

'Tech' 카테고리의 다른 글

아두이노 호환보드와 웹서버간 GET, POST 방식 실습하기  (0) 2022.12.20

+ Recent posts