스마트 디바이스 실습 15.2주차

aws & node red

한세대학교 컴퓨터공학과 22학번 김선영


Node-Red

Node-Red
  1. 비주얼 프로그래밍 툴로서, IoT 프로젝트 및 자동화 워크플로우를 구축하기 위해 사용됨.
  2. Node.js 기반으로 동작하며, 사용자는 브라우저 기반의 그래픽 인터페이스를 통해 흐름(flow)을 생성하고 제어할 수 있음.
  3. Node-RED는 미리 정의된 노드(Node)를 사용하여 다양한 기기 및 서비스 간의 데이터 흐름을 구축
  4. 데이터를 변환, 처리 및 저장할 수 있음.
  5. 센서 데이터를 수집하고, 데이터베이스에 저장하고, 알림을 보내는 등의 작업을 자동화할 수 있음.
Node-RED와 AWS의 연관성
  1. 비주얼 프로그래밍 툴로서, IoT 프로젝트 및 자동화 워크플로우를 구축하기 위해 사용됨.
  2. Node.js 기반으로 동작하며, 사용자는 브라우저 기반의 그래픽 인터페이스를 통해 흐름(flow)을 생성하고 제어할 수 있음.
  3. Node-RED는 미리 정의된 노드(Node)를 사용하여 다양한 기기 및 서비스 간의 데이터 흐름을 구축
  4. 데이터를 변환, 처리 및 저장할 수 있음.
  5. 센서 데이터를 수집하고, 데이터베이스에 저장하고, 알림을 보내는 등의 작업을 자동화할 수 있음.

실습 1 : aws & node-red

Responsive image

실습 순서
aws
  1. 사물 정책을 추가.
  2. Responsive image
  1. Node-RED 실행:
  2. 터미널에서 다음 명령어를 실행하여 Node-RED를 시작.
    
        $ node-red                                     
                                        

    "Started flows" 메시지가 표시되면 로컬에서 실행 중임.

  3. Node-RED 접속:
  4. 브라우저에서 http://localhost:1880 로 접속.

  5. 노드 추가:
  6. 노드 구성
    Responsive image

  7. Inject 노드 설정:
  8. Responsive image

  9. MQTT Out 노드 설정:
  10. MQTT Out 노드
    Responsive image

    MQTT Out broker 노드
    Responsive image

    MQTT Out tls-config 노드
    Responsive image

  11. MQTT In 노드도 이와 같이 배치.


  12. AWS에서 주제 구독(Topic Subscribe)를 선택하고 해당 토픽을 구독.
  13. Responsive image

  14. Node-RED에서 발행한 메시지를 확인할 수 있음.
  15. Responsive image

실습 2 : 온습도값 AWS mqtt & Node-RED 출력

Responsive image

실습 순서
  1. Node-RED 접속:
  2. 브라우저에서 http://localhost:1880 로 접속.

  3. 노드 추가:
  4. 노드 구성
    Responsive image

  5. MQTT Out 노드 설정:
  6. - topic을 esp32/pub으로 바꿈.

  7. function 노드 설정:
  8. - humidity

    
        msg.payload = msg.payload.humidity;
        return msg;
    

    - temperature

    
        msg.payload = msg.payload.temperature;
        return msg;
    


  9. 결과 확인

  10. - Serial Monitor
    Responsive image

    - node-red debug
    Responsive image

    - node-red dashboard
    Responsive image

코드

                            
    #include "secrets.h"
    #include ≶WiFiClientSecure.h>
    #include ≶MQTTClient.h>
    #include ≶ArduinoJson.h>
    #include ≶DHT.h>
    #include ≶WiFi.h>
    
    // AWS IoT 설정
    #define AWS_IOT_PUBLISH_TOPIC   "esp32/pub"
    #define AWS_IOT_SUBSCRIBE_TOPIC "esp32/sub"
    
    // DHT11 센서 설정
    #define DHT_PIN 13       // DHT11 데이터 핀
    #define DHT_TYPE DHT11  // DHT11 센서
    
    WiFiClientSecure net;
    MQTTClient client;
    
    DHT dht(DHT_PIN, DHT_TYPE);
    
    void connectAWS()
    {
        WiFi.mode(WIFI_STA);
        WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
    
        Serial.println("Connecting to Wi-Fi");
    
        while (WiFi.status() != WL_CONNECTED){
        delay(500);
        Serial.print(".");
        }
    
        // Configure WiFiClientSecure to use the AWS IoT device credentials
        net.setCACert(AWS_CERT_CA);
        net.setCertificate(AWS_CERT_CRT);
        net.setPrivateKey(AWS_CERT_PRIVATE);
    
        // Connect to the MQTT broker on the AWS endpoint we defined earlier
        client.begin(AWS_IOT_ENDPOINT, 8883, net);
    
        // Create a message handler
        client.onMessage(messageHandler);
    
        Serial.print("Connecting to AWS IoT");
    
        while (!client.connect(THINGNAME)) {
        Serial.print(".");
        delay(100);
        }
    
        if(!client.connected()){
        Serial.println("AWS IoT Timeout!");
        return;
        }
    
        // Subscribe to a topic
        client.subscribe(AWS_IOT_SUBSCRIBE_TOPIC);
    
        Serial.println("AWS IoT Connected!");
    }
    
    void publishMessage(float temperature, float humidity)
    {
        StaticJsonDocument≶200> doc;
        doc["temperature"] = temperature;
        doc["humidity"] = humidity;
        char jsonBuffer[512];
        serializeJson(doc, jsonBuffer);
    
        client.publish(AWS_IOT_PUBLISH_TOPIC, jsonBuffer);
    }
    
    void messageHandler(String &topic, String &payload) {
        Serial.println("incoming: " + topic + " - " + payload);
    }
    
    void setup() {
        Serial.begin(9600);
        connectAWS();
        dht.begin();
    }
    
    void loop() {
        // 온습도 데이터 읽기
        float temperature = dht.readTemperature();
        float humidity = dht.readHumidity();
        Serial.println(temperature);
        Serial.println(humidity);
    
        // 온습도 데이터를 Node-RED로 전송
        // JSON 형식으로 데이터를 생성하여 MQTT 메시지로 전송
        StaticJsonDocument≶200> doc;
        doc["temperature"] = temperature;
        doc["humidity"] = humidity;
        char jsonBuffer[512];
        serializeJson(doc, jsonBuffer);
        client.publish("node-red/esp32-data", jsonBuffer); // Node-RED에서 subscribe할 토픽을 "node-red/esp32-data"로 지정
    
        // AWS IoT에도 데이터를 전송
        publishMessage(temperature, humidity);
    
        // AWS IoT 클라이언트 루프
        client.loop();
    
        delay(1000);
    }                            

느낀점

  1. 성공적으로 실습을 끝내고 지난 시간에 배웠던 내용을 응용해서 node-red 실습을 할 수 있어서 좋았음.
  2. node-red와 같은 오픈소스 비주얼 프로그래밍 툴 사용법을 익히고 mqtt와 mqtt브로커에 대해서 배울 수 있었음.

Previous   /