1 of 48

챗GPT로 코딩하기

[강의교안 이용 안내]

  • 본 강의교안의 저작권은 양재삼한빛아카데미㈜에 있습니다.
  • 이 자료를 무단으로 전제하거나 배포할 경우 저작권법 136조에 의거하여 벌금에 처할 수 있고 �이를 병과(倂科)할 수도 있습니다.

마이크로파이썬을 활용한 사물인터넷

2 of 48

Chapter

11

Node-RED�서버 만들고 활용하기

3 of 48

index

Installing Node-RED

11.2

Node-RED Flow Edit

11. 3

Controlling MQTT

11.4

Dashboard making

11.5

11.1

Node-RED Overview

addition Node and expansion function

11.6

3/48

4 of 48

11.1 Node-RED Overview

5 of 48

1. What is NODE-RED ?

11.1 Node-RED Overview

What is Node-RED?

programming developed by IBM equipment

Visual Programming

To make it easy to visually connect IoT devices, APIs, and various services. Designed

Node-based configuration

A flow is formed by connecting nodes with lines, and each node is a group of programs that perform a specific function .

Scalability

there are many open source nodes, with approximately 5,100 nodes registered as of October 2024.

※ Since IoT systems generate data from multiple devices, it is necessary to display, share, and analyze this data in an easily viewable manner. box

The controller, which is the core of the IoT system, controls devices, links to external systems, and provides dashboard functions. Perform​

Node- RED is optimized for implementing these controllers and has a highly scalable ecosystem .

5/48

6 of 48

2. Low-code and event- driven

11.1 Node-RED Overview

low-code development method

event Driven functioning method

  • that allows you to build application systems quickly with less code. Supported
  • Visually structure data models, logic flows, and user interfaces to streamline the development process. Simplify
  • Reduces complex coding tasks, enabling non-experts to easily participate in application system development .
  • Traditional MicroPython implements logic by considering sequential execution order . Adopted
  • There is a problem that code complexity increases significantly when handling concurrent situations.
  • Node-RED only defines the processing steps and relationships between events by listing multiple events . Used
  • for easy handling of concurrent events. Has features

6/48

7 of 48

2. Low-code and event- driven

11.1 Node-RED Overview

Operating environment

Internet browser

Using JavaScript to display dynamic information

Node.js

Chrome's JavaScript runtime engine

Node-RED

A platform that runs on Node.js

- If you install Node.js first and then install Node-RED, it will run on most operating systems. possible

- Node-RED editor and dashboard can be accessed and viewed through an internet browser.

- When using Node-RED for controlling IoT devices, Raspberry Pi is more power-efficient and cost-effective. From the side economic

- For your convenience, this book installs Mosquitto and Node-RED on Windows. Used​

7/48

8 of 48

11.2 Installing Node-RED

9 of 48

Download and install Node.js

11.2 Installing Node-RED

Download

Download the LTS version from https://nodejs.org/

installation

Run the downloaded installation file

check

Check version information with node -v and npm -v in the command prompt.

9/48

10 of 48

Installing Node-RED

11.2 Installing Node-RED

Run Command Prompt

Command with administrator privileges prompt execution

Enter the installation command

npm install -g --unsafe-perm node-red

Confirm installation completion

When the installation process is completed successfully message Displayed

10/48

11 of 48

3. Node-RED Server Run

11.2 Installing Node-RED

Execute command

Type node-red at the command prompt

How to connect

Enter http://127.0.0.1:1880 or http://localhost:1880 in your browser.

caution

The running command prompt window is

Should not be closed

11/48

12 of 48

11.3 Installing Node-RED

13 of 48

Edit Node-RED screen

11.3 Installing Node-RED

edit screen composition element

palette

The node list area on the left, grouped by function

canvas

A centrally located workspace where you can place nodes and connect them with wires to configure your flow.

Sidebar

The area on the right provides node information, debug messages, help, etc.

13/48

14 of 48

2. First flow Write

11.3 Installing Node-RED

inject node

manually or periodically

debug node

Check by outputting msg data during flow test

Flow file: [File name: flows-11-1-inject-debug.json]

14/48

15 of 48

2. First flow Write

11.3 Installing Node-RED

inject node

Data output function

The inject node performs the function of outputting data.

Manual output

Manual printing is possible with the click of a button

Automatic output

Automatic output at set times and cycles is possible.

Various data formats

By default, it outputs the current time, but it can output various data formats depending on the options.

Can be printed

15/48

16 of 48

2. First flow Write

11.3 Installing Node-RED

inject node

16/48

17 of 48

2. First flow Write

11.3 Installing Node-RED

debug node function

  • Check by outputting msg data during flow test
  • Change between enabled and disabled status with the right button
  • Output Target : Multiple selections possible from 'Debug Window', 'System Console', and 'Node Status'
  • Target : Select from 'msg', 'the entire msg object', and 'J: expression'

17/48

18 of 48

11.4 Controlling MQTT

19 of 48

1. Run usemqttclient.py

11.4 Controlling MQTT

About this program

The module usemqttclient.py contains the class UseMQTTClient and the code for the main() function that can be used to test this class.

Here we are running this module alone to use the functionality of the main() function.

Node-RED flow runs in response to this program

Execution order of main() function

Modify config.py to your own in advance

  1. Connect to Wi-Fi
  1. Connect to the mqtt server
  1. Setting up a will (LWT)
  1. Online status issued
  1. Subscribe to Command Topics
  1. TELEPERIOD issued
  1. Issued as sensor data with a serial number incremented at 10-second intervals
  1. If there is a topic received, follow up processing

19/48

20 of 48

1. Run usemqttclient.py

11.4 Controlling MQTT

config.py

  • Contains information about WiFi and MQTT
  • You must modify it to use it as your own.

DEVICE = 'ESP32-01' # The actual device name, used as part of the topic.

SSID = 'my-ssid' # Change to actual value

SSID_PASS = 'my-ssid-pass' # Change to actual value

MQTT_SERVER = '192.168.xxx.xxx' # Change to actual value

MQTT_PORT = 1883

MQTT_USER = 'SECOND_USER' # Value registered in pw.txt

MQTT_PASS = 'SECOND_PASSWORD' # Value registered in pw.txt

import binascii

import machine

""" Create a unique value using the device's MAC address """

MQTT_CLIENT_ID = binascii.hexlify(machine.unique_id()).decode()DEVICE = 'ESP32-01' # This is the actual device name and is used as part of the topic.

SSID = 'my-ssid' # Change to actual value

SSID_PASS = 'my-ssid-pass' # Change to actual value

MQTT_SERVER = '192.168.xxx.xxx' # Change to actual value

MQTT_PORT = 1883

MQTT_USER = 'SECOND_USER' # Value registered in pw.txt

MQTT_PASS = 'SECOND_PASSWORD' # Value registered in pw.txt

import binascii

import machine

""" Create a unique value using the device's MAC address """

MQTT_CLIENT_ID = binascii.hexlify(machine.unique_id()).decode()

20/48

21 of 48

1. Run usemqttclient.py

11.4 Controlling MQTT

Wi-Fi connection

Start Wi-Fi and complete connection

MQTT connection

Connecting to an MQTT server and setting up LWT

Data publication

Periodic release of sensor data

connect_Wi-Fi> Starting Wi-Fi (my-ssid)... connect_Wi-Fi> Starting Wi-Fi (your_ssid)... connect_Wi-Fi> Wi-Fi connection complete: ('192.168.24.207', '255.255.255.0', '192.168.24.177', '61.41.153.2') connect_mqtt> Starting MQTT connection LWT> tele/ESP32-01/LWT, |Offline|, retain=True connect_mqtt> MQTT connection complete pub> tele/ESP32-01/LWT, |Online|, retain=True, qos=0 sub> cmnd/ESP32-01/#, qos=0 on_connect() called pub> tele/ESP32-01/INFO, |{"TELEPERIOD": 10}|, retain=True, qos=0 pub> tele/ESP32-01/SENSOR, |{"ser": 1}|, retain=False, qos=0 pub> tele/ESP32-01/SENSOR, |{"ser": 2}|, retain=False, qos=0 pub> tele/ESP32-01/SENSOR, |{"ser": 3}|, retain=False, qos=0

21/48

22 of 48

2. Flow Write

11.4 Controlling MQTT

Receive topic

Receive 4 topics

Data verification

Output to debug node

Issue command

Issue commands with the inject node

Topic publication

Issue TELEPERIOD value

22/48

23 of 48

2. Flow Write

11.4 Controlling MQTT

mqtt -broker information Register​

once at first Just register

MQTT in/out node Must be preceded when used box

Server Settings

Server address, port, user authentication information, etc. Set up

Security Settings

Username and password if required �By setting Security Reinforcement​

23/48

24 of 48

2. Flow Write

11.4 Controlling MQTT

24/48

25 of 48

2. Flow Write

11.4 Controlling MQTT

mqtt in node Set up

About the mqtt server and topic to subscribe to information registration

You can also use wildcards (+,#) when specifying topics .

Example of topic settings

  • tele/ESP32-01/LWT - Subscribe to specific topics only
  • tele/+/LWT - Subscribe to LWT topics on all devices
  • tele/ESP32-01/# - Subscribe to all topics on ESP32-01

25/48

26 of 48

2. Flow Write

11.4 Controlling MQTT

debug node Set up

out the output value of a specific node

Select output destination

If you select 'Node Status (32 characters)' as the output target, it will be displayed under the corresponding node in the editing window.

Specify output format

To output the entire message or only specific properties

Can be set

Console output options

You can also set it to output to the system console .

26/48

27 of 48

2. Flow Write

11.4 Controlling MQTT

Specifying a payload in the inject node

to output a specific value method

  • Select payload type (string, number, boolean, JSON, etc.)
  • Enter payload value
  • Specify a topic (optional)
  • Repeat settings (optional)

27/48

28 of 48

2. Flow Write

11.4 Controlling MQTT

mqtt out node Set up

The server and topic to be published Designated​

QoS and retained are also added designation possible

How to set a topic

  • Fixed topics - specified directly in node settings
  • Dynamic topics - using the msg.topic property

Payload transfer

The value of msg.payload is the message content. Sent​

28/48

29 of 48

2. Flow Write

11.4 Controlling MQTT

Click the inject node

The TELEPERIOD value has changed and is being passed to the device.

Device reception

Receive topic 'cmnd/ESP32-01/TELEPERIOD' and payload

Device handling

Change the sensor data release time

Results publication

Publish the command execution result to the topic 'stat/ESP32-01/TELEPERIOD'

Information Update

Issue TELEPERIOD value to topic 'tele/ESP32-01/INFO'

29/48

30 of 48

11.5 Creating a Dashboard

31 of 48

Basic Description

11.5 Creating a Dashboard

User interface

The dashboard is provided by Node-RED.

User interface

Visualization

The execution results and process of the flow

Display on a separate screen

Separate installation

for Node-RED dashboards are Separately

Need to install

Latest version

The latest dashboard version is

'@flowfuse/node-red-dashboard'

31/48

32 of 48

1. On the palette Dashboard Install

11.5 Creating a Dashboard

Open menu

Menu in the top right corner Button Click

Select Palette Management

Select [ Manage Palettes ] from the drop-down menu

Node search

In the search box

Enter '@flowfuse/node-red-dashboard '

Installation complete

installation button Click to complete installation

32/48

33 of 48

2. Dashboard Node Add​

11.5 Creating a Dashboard

Widget

Individual dashboard nodes

Group

A collection of related widgets

Page

Screen containing multiple groups

- In order to use the dashboard node, [ui-base], [ui-page], and [ui-group] nodes must be created first. box

- These nodes can be set when adding a dashboard node for the first time.

- When adding a dashboard node later , you can select and use the already set [Page] and [Group] nodes .

- Additional [Page] and [Group] nodes as needed Can be created

- Dashboard When accessing, use a URL in the format http://localhost:1880/dashboard/page1

33/48

34 of 48

2. Dashboard Node Add​

11.5 Creating a Dashboard

1

[Figure 11-29]

In 'Edit text node', 'Add node type of ui-group...'

2

[Figure 11-30]

In 'Add ui-group settings node', 'Add ui-page node type...'

3

[Figure 11-31]

In 'Add ui-page settings node', 'Add ui-base node type...'

4

[Figure 11-32]

In 'Add ui-base setting node', enter the name ('UI name') and

Specify Path('/dashboard')

5

[Figure 11-33]

In 'Add ui-page settings node', name ('Page 1')

Specify Path('/page1')

6

[Figure 11-34]

In 'Add ui-group settings node', specify the name ('group 1') and size.

7

[Figure 11-35]

In 'Edit Node of Text', select Group and give it a name ('LWT')

Specify Label('Device Connection')

34/48

35 of 48

3. Dashboard Flow Complete

11.5 Creating a Dashboard

Node-RED Flow

[ File name : flows-11-3-mqtt-dashboard.json]

receives MQTT messages

On the dashboard Displaying Function Implemented​

35/48

36 of 48

3. Dashboard Flow Complete

11.5 Creating a Dashboard

text node Set up

  1. displayed in the dashboard editing window or dashboard layout. �Specify the node name
  1. Among the specified ones select
  1. [Size]: Widgets are generally selected as 'auto'. Convenient
  1. Appears on the dashboard name
  1. Where to display the text designation
  1. [Complete]: Click the button to complete the setup.

36/48

37 of 48

3. Dashboard Flow Complete

11.5 Creating a Dashboard

switch node Set up

  1. name displayed in the dashboard editing window. designation
  1. item with msg.payload.ser setting
  1. , the flow goes to port 1. Connect​
  1. [is null]: If there is no value, the flow goes to port 2. Connect ( Follow- up Node doesn't exist )
  1. [+Add]: Test conditions addition
  1. executes the flow whenever one is true. Connect​ �If you select [End with first matching condition], only one or less flows will be Connected​
  1. Click the button Finish setting​

37/48

38 of 48

3. Dashboard Flow Complete

11.5 Creating a Dashboard

change node Set up

  1. Node displayed in the dashboard editing window Name it
  1. The value of [Property that gives value] is assigned to [Property whose value will be changed]. Come in
  1. [Property whose value will change]: The value is entered into this property and is passed as msg.payload. setting
  1. [Property that gives value]: Passes the value of this property, as msg.payload.ser. setting
  1. [Deep copy value]: If you select this item, a new value will be created that is separate from the original. �Copy it Therefore, the original Not affected even if the value changes No
  1. Items to change addition
  1. Click the button setting Finally

38/48

39 of 48

3. Dashboard Flow Complete

11.5 Creating a Dashboard

dropdown node Set up

  1. name displayed in the dashboard editing window. designation
  1. Displayed on the dashboard Text
  1. to the next node via msg.payload. Delivered​
  1. Displayed in the drop-down list Text
  1. [+option] : Drop-down list items addition
  1. Used when selecting multiple items from a drop-down list.
  1. [Show as Chip Shape]: The selected item will be shown as a round chip shape. show
  1. Click the button setting Machip

39/48

40 of 48

3. Dashboard Flow Complete

11.5 Creating a Dashboard

Dashboard layout Adjust

  • Dashboard nodes are managed by widgets belonging to pages and groups.
  • You can move widgets using the dashboard layout feature, �and change what is displayed using the edit feature.
  • Click button ❶ on the right sidebar and select ❷ Dashboard 2.0 to view �the entire dashboard by hierarchy.
  • ❸ You can select the widget you want and move it by dragging it , �or change the display method using the Edit function.

40/48

41 of 48

11.6 Additional Nodes and Extensions

42 of 48

1. Context data

11.6 Additional Nodes and Extensions

Node-RED can utilize a wide range of context data .

  • Flow context : static data available within the same flow
  • Global context : static data available within all flows

42/48

43 of 48

2. JSONata

11.6 Additional Nodes and Extensions

An expression language that allows you to query, transform, and filter JSON data.

Can be used for data processing in change nodes, switch nodes, etc.

// Example: Extract only temperature values

payload.readings.temperature

43/48

44 of 48

3. function node

11.6 Additional Nodes and Extensions

function node Through JavaScript code By writing Advanced logic avatar

// Example : Temperature conversion function

var temp = msg.payload.temp ;

msg.payload = (temp * 9/5) + 32;

return msg ;

44/48

45 of 48

4. Node- RED Python Connect

11.6 Additional Nodes and Extensions

Connecting Python to Node-RED

node-red- contrib -python-function -ps : This node's internal code can be written in Python.

Running a Python shell

node-red- contrib - pythonshel l : A node that executes a separately created Python program and returns the result.

45/48

46 of 48

5. Flow Import / Export

11.6 Additional Nodes and Extensions

Save your flow in JSON format and export it to the clipboard or file.

46/48

47 of 48

Practice Problems (1/2 )

Practice configuring Node-RED flows and dashboards with the following exercises.

Problem Overview

Based on the flow in [Figure 11-38] and the dashboard in [Figure 11-39], we build a system that processes virtual sensor data.

File name: flows-11-3-mqtt-dashboard.json → flowsexam-11-1-dashboard.json

Sensor data configuration

  • Generate virtual sensor data every 10 seconds (Topic: 'tele/ESP32-01/SENSOR')
  • Temperature: 20~30 with 1 decimal place
  • Humidity: integer value between 40 and 60

{

"DHT22": {

"Temperature": any number,

"Humidity": any number

}

}

Dashboard implementation

Receive topic 'tele/ESP-01/SENSOR', separate temperature and humidity values, and display them in the gauge node of the dashboard.

Configure the flow shown in Figure 11-47 and complete the dashboard as shown in Figure 11-48.

47/48

48 of 48

Q&A

Copyright© 2025 Hanbit Academy, Inc.

All rights reserved.