티스토리 뷰

ARM 서버 스터디 그룹의 일환으로 라즈베리 파이와 센서를 이용하여 온도를 측정하고, 측정된 온도를 ARM 서버로 수집하여 다시 퍼블릭 클라우드의 로깅 서버로 수집하여 시각화까지 하는 활동들을 해 봤다. 

요즘 근래에 Elastic Stack이라는 책을 사서 Elastic Search와 Kibana 등을 보고 있는데, 마침 이런 활동을 하길래 책으로만 보고 있던 Elastic Search 공부도 할겸 해서 이번 활동에서 Elastic Search를 활용해 보았다. 또한 Naver Cloud에서 후원받은 VM 인스턴스를 활용하여 Elastic Search와 Kibana도 설치해 보고, 해당 어플리케이션으로 시각화도 한번 해 봤다.

[라즈베리파이] 센서 연결하기

온도를 수집하기 위해서는 센서를 라즈베리파이에 연결해야 한다. 친절한 스터디원들 덕분에 쉽게 조립을 할 수 있었다. 

[Client] 라즈베리파이에서 온도 측정하기

지난 스터디 시간에 배워고, 공부했던것들을 토대로 라즈베리파이에서 온도 정보와 습도 정보를 수집하는 파이썬 스크립트와 ARM 서버로 데이터를 전송하는 파이썬 스크립트를 이용하여 다음과 같은 간단하 파이썬 스크립트를 짠다.

ubuntu@ubuntu:~$ cat publisher-dht.py
import paho.mqtt.client as mqtt

import json
import os
import time
from datetime import datetime
import Adafruit_DHT
sensor = Adafruit_DHT.DHT11
pin = 4

#
# Callback functions to check the publisher's action
#

# on_connect is a callback function to check connection status while setup mqtt client.
def on_connect(client, userdata, flags, rc):
    if rc == 0:
        print("connected OK")
    else:
        print("Bad connection Returned code=", rc)

# on_disconnect is a callback function at the client disconnected
def on_disconnect(client, userdata, flags, rc=0):
    print(str(rc))

# on_publish is a logging callback function while publish a message to MQTT server
def on_publish(client, userdata, mid):
    print("In on_pub callback mid= ", mid)


#
# main logics
#

# 1. create mqtt client
client = mqtt.Client()

# 2. register callback functions on the mqtt client.
client.on_connect = on_connect
client.on_disconnect = on_disconnect
client.on_publish = on_publish

# 3. assign account information and try connect to MQTT server
client.username_pw_set(username="유저아이디", password="패스워드")
client.connect('MQTT 서버 주소', 7883)

# 4. start mqtt loop
client.loop_start()

# 5. check sensor status and issue temperature sensing values to MQTT server.
index=1
while True:
    # colloct sensor data
    h, t = Adafruit_DHT.read_retry(sensor, pin)

    # publish the temperature and humidity data
    if h is not None and t is not None :
        client.publish('common', json.dumps({"index": index, "date": str(datetime.now()), "temperature": t, "humidity": h}), 1)
    time.sleep(1)
    index=index+1

# 6. stop the mqtt server publish client
client.loop_stop()

# 7. distonnect the client
client.disconnect()

 

[ARM 서버] 수집한 온도 데이터를 ElasticSerch로 보내기

유명환 대표님의 회사인 엑세스랩에서 후원해 준 ARM 서버에 라이베리파이로부터 수집 받은 온도 데이터를 ElasticSearch에 저장하는 파이썬 스크립트를 아래와 같이 작성한다.

root@vraptor:~# cat subscribe.py 
import paho.mqtt.client as mqtt
import json
import time

# on_connect is a callback function to check connection status while setup mqtt client.
def on_connect(client, userdata, flags, rc):
    if rc == 0:
        print("connected OK")
    else:
        print("Bad connection Returned code=", rc)

# on_disconnect is a callback function at the client disconnected        
def on_disconnect(client, userdata, flags, rc=0):
    print(str(rc))

# on_publish is a logging callback function while publish a message to MQTT server
def on_publish(client, userdata, mid):
    print("In on_pub callback mid= ", mid)

# on_subscribe is a logging callback function while subscribe a message
def on_subscribe(client, userdata, mid, granted_qos):
    print("subscribed: " + str(mid) + " " + str(granted_qos))

# on_message is for sending data to ELK
def on_message(client, userdata, msg):
    body = json.loads(str(msg.payload.decode("utf-8")))
    index = body['index']
    date = body['date']
    temperature = body['temperature']
    humidity = body['humidity']
    
    print("temperature: " + str(temperature) + " humidity: " + str(humidity))

    import requests
    response = requests.post(
            url="http://엘라스틱서치주소:9200/arm/_doc/"+str(index),
            headers={
                "Content-Type": "application/x-ndjson; charset=utf-8",
            },
            data=json.dumps({
                "date": date,
                "temperature": temperature,
                "humidity": humidity
            })
        )

# 1. create mqtt client
client = mqtt.Client()

# 2. register callback functions on the mqtt client.
client.on_connect = on_connect
client.on_disconnect = on_disconnect
client.on_publish = on_publish
client.on_message = on_message

# 3. assign account information and try connect to MQTT server
client.username_pw_set(username="유저아이디", password="패스워드")
client.connect('127.0.0.1', 1883)

# 4. start mqtt loop
client.loop_start()

# 5. send temperature data to ELK
while True:
  client.subscribe('common', 1)
  time.sleep(2)

# 6. stop the mqtt server publish client
client.loop_stop()

# 7. distonnect the client
client.disconnect()
root@vraptor:~#

 

[Collect] 센서 데이터 수집하기

이제 앞에서 작성한 파이썬 스크립트들을 실행해 보자. 먼저 라즈베리파이에서 아래와 같이 실행한다. 

ubuntu@ubuntu:~$ sudo python3 publisher-dht.py 
connected OK
In on_pub callback mid=  1
In on_pub callback mid=  2
In on_pub callback mid=  3
In on_pub callback mid=  4
In on_pub callback mid=  5
In on_pub callback mid=  6
In on_pub callback mid=  7
In on_pub callback mid=  8

 그 다음에 ARM 서버에서도 실행해 보자. 

root@vraptor:~# python3 subscribe.py 
connected OK
temperature: 28.0 humidity: 31.0
temperature: 28.0 humidity: 31.0
temperature: 28.0 humidity: 31.0
temperature: 28.0 humidity: 31.0
temperature: 28.0 humidity: 31.0
temperature: 28.0 humidity: 31.0
temperature: 28.0 humidity: 31.0
temperature: 28.0 humidity: 31.0

 

[Elastic Search] Kibana를 통해 Elastic Search 데이터 시각화하기

이렇게해서 실행한 스크립트를 통해 데이터가 수집이 잘 되고 있는지 Kibana를 통해 확인해 보자.

시각화를 하기위해서는 먼저 Index Patten을 만들어야 한다. 메뉴에서 [Stack Manangement > Index Pattens] 메뉴를 선택하여 아래와 같이 arm이라는 인덱스 패턴을 생성한다.

인덱스 패턴이 생성되면 [Analysis > Discover] 메뉴에서 아래와 같이 데이터가 수집되고 있는지를 확인할 수 있다.

그리고, 이렇게 수집된 데이터를 이용하여 아래와 같이 그래프를 이용해 시각화를 할 수 있다. 현재 날짜를 같이 수집했는데 날짜 포맷을 좀 수정하면 더 보기가 좋을 것 같다. 

이렇게 해서 나도 데이터 수집을 해서 시각화까지 해 봤다~~~~ 다음에는 프로메테우스로 해봐야겠다.

최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/03   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함