AWS IoT Core - raspberry PI mqtt 설정, AWS와 연동

18871 단어 awsaws

Raspberry PI mqtt 설정

  • 개발환경: Raspberry PI 3, rasbian OS
# 1. 시스템 업데이트
$ sudo apt update && sudo apt upgrade

# 2. 모스키토 설치
$ sudo apt install mosquitto
$ sudo apt install mosquitto-clients

# 3. config file 설정
$ sudo vim /etc/mosquitto/mosquitto.conf

  • /etc/mosquitto/mosquitto.conf 파일 내부
# Place your local configuration in /etc/mosquitto/conf.d/
#
# A full description of the configuration file is at
# /usr/share/doc/mosquitto/examples/mosquitto.conf.example

pid_file /var/run/mosquitto.pid

persistence true
persistence_location /var/lib/mosquitto/

log_dest file /var/log/mosquitto/mosquitto.log	# 지우기

include_dir /etc/mosquitto/conf.d		# 지우기

  • 아래 처럼 수정
# Place your local configuration in /etc/mosquitto/conf.d/
#
# A full description of the configuration file is at
# /usr/share/doc/mosquitto/examples/mosquitto.conf.example

pid_file /var/run/mosquitto.pid

persistence true
persistence_location /var/lib/mosquitto/

# From Here
log_dest topic

log_type error
log_type warning
log_type notice
log_type information

connection_messages true
log_timestamp true

include_dir /etc/mosquitto/conf.d

  • raspberry PI reboot
$ sudo reboot now

MQTT Server start

  • 서버 동작 시작
$ sudo /etc/init.d/mosquitto start

  • 혹시 모스키토 대몬이 에러나면 force-reload 옵션으로 재개
$ sudo /etc/init.d/mosquitto force-reload


  • 두개의 터미널로 통신 테스트
  1. subscriber
$ mosquitto_sub -d -t hello/world

  1. publisher
$ mosquitto_pub -d -t hello/world -m "hello"

  1. 결과
  • 3-1. subscriber

    subscriberpolling 방식으로 계속 recv

  • 3-2. publisher

AWS IoT Core + Raspberry PI


디바이스 SDK 설치

0. Prerequisit

  • cmake, libssl-dev, git, python3(over v3.5), pip3
    • 없다면 설치하자!
  • 설치 명령어
$ sudo apt install cmake libssl-dev git python3-pip

  • 라즈베리파이에서 구동된다.

1. 현재 Python용 AWS IoT 디바이스 SDK 설치

$ cd ~
$ git clone https://github.com/aws/aws-iot-device-sdk-python-v2.git
$ python3 -m pip install ./aws-iot-device-sdk-python-v2

인증서 설치

1. 인증서를 설치할 디렉터리 만든다.

$ cd ~
$ mkdir certs

인증서 파일 이름

filepath
루트 CA 인증서~/certs/Amazon-root-CA-1.pem
디바이스 인증서~/certs/device.pem.crt
프라이빗 키~/certs/private.pem.key
  • 디바이스에 연결된 인증서파일들을 가져온다.
  • 참고

publish.py on raspberryPI


  • 퍼블리쉬파일은 라즈베리 파이에서 구동된다.

    • 라즈베리파이에서 publish.py 파일을 하나 만들자.
  • publish.py

# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0

from awscrt import io, mqtt, auth, http
from awsiot import mqtt_connection_builder
import time as t
import json

# Define ENDPOINT, CLIENT_ID, PATH_TO_CERT, PATH_TO_KEY, PATH_TO_ROOT, MESSAGE, TOPIC, and RANGE
ENDPOINT = "커스텀 엔드 포인트 URL"
CLIENT_ID = "디바이스 ID"
PATH_TO_CERT = "a1b23cd45e-certificate.pem.crt 절대 경로 명시"
PATH_TO_KEY = "a1b23cd45e-private.pem.key 절대 경로 명시"
PATH_TO_ROOT = "root.pem 절대 경로 명시"
MESSAGE = "Hello World"
TOPIC = "test/testing" # 토픽
RANGE = 20

# Spin up resources
event_loop_group = io.EventLoopGroup(1)
host_resolver = io.DefaultHostResolver(event_loop_group)
client_bootstrap = io.ClientBootstrap(event_loop_group, host_resolver)
mqtt_connection = mqtt_connection_builder.mtls_from_path(
            endpoint=ENDPOINT,
            cert_filepath=PATH_TO_CERT,
            pri_key_filepath=PATH_TO_KEY,
            client_bootstrap=client_bootstrap,
            ca_filepath=PATH_TO_ROOT,
            client_id=CLIENT_ID,
            clean_session=False,
            keep_alive_secs=6
            )
print("Connecting to {} with client ID '{}'...".format(
        ENDPOINT, CLIENT_ID))
# Make the connect() call
connect_future = mqtt_connection.connect()
# Future.result() waits until a result is available
connect_future.result()
print("Connected!")
# Publish message to server desired number of times.
print('Begin Publish')
for i in range (RANGE):
    data = "{} [{}]".format(MESSAGE, i+1)
    message = {"message" : data}
    mqtt_connection.publish(topic=TOPIC, payload=json.dumps(message), qos=mqtt.QoS.AT_LEAST_ONCE)
    print("Published: '" + json.dumps(message) + "' to the topic: " + "'test/testing'")
    t.sleep(0.1)
print('Publish End')
disconnect_future = mqtt_connection.disconnect()
disconnect_future.result()

  • 위 설정 부분을 신경 써야한다.

ENDPOINT

ENDPOINT = "a24768b6yw7k31-ats.iot.ap-northeast-2.amazonaws.com"	# HTTPS
CLIENT_ID = "Test_dhyang"	# 장치이름

PATH CERTS

  • 디바이스와 연결된 인증서 및 정책과 연결된 인증서 절대경로로 명시
PATH_TO_CERT = "/home/pi/certs/e0e2bfcbab-certificate.pem.crt"
PATH_TO_KEY = "/home/pi/certs/e0e2bfcbab-private.pem.key"
PATH_TO_ROOT = "/home/pi/certs/CA.pem"

TOPIC

  • Client subscriber가 받을 토픽
TOPIC = "test/testing"

subscribe AWS


주고 받기


  • Publish Raspberry PI
$ python3 ./publish.py
Connecting to a24768b6yw7k31-ats.iot.ap-northeast-2.amazonaws.com with client ID 'Test_dhyang'...
Connected!
Begin Publish
Published: '{"message": "Hello World [1]"}' to the topic: 'test/testing'
Published: '{"message": "Hello World [2]"}' to the topic: 'test/testing'
Published: '{"message": "Hello World [3]"}' to the topic: 'test/testing'
Published: '{"message": "Hello World [4]"}' to the topic: 'test/testing'
Published: '{"message": "Hello World [5]"}' to the topic: 'test/testing'
Published: '{"message": "Hello World [6]"}' to the topic: 'test/testing'
Published: '{"message": "Hello World [7]"}' to the topic: 'test/testing'
Published: '{"message": "Hello World [8]"}' to the topic: 'test/testing'
Published: '{"message": "Hello World [9]"}' to the topic: 'test/testing'
Published: '{"message": "Hello World [10]"}' to the topic: 'test/testing'
Published: '{"message": "Hello World [11]"}' to the topic: 'test/testing'
Published: '{"message": "Hello World [12]"}' to the topic: 'test/testing'
Published: '{"message": "Hello World [13]"}' to the topic: 'test/testing'
Published: '{"message": "Hello World [14]"}' to the topic: 'test/testing'
Published: '{"message": "Hello World [15]"}' to the topic: 'test/testing'
Published: '{"message": "Hello World [16]"}' to the topic: 'test/testing'
Published: '{"message": "Hello World [17]"}' to the topic: 'test/testing'
Published: '{"message": "Hello World [18]"}' to the topic: 'test/testing'
Published: '{"message": "Hello World [19]"}' to the topic: 'test/testing'
Published: '{"message": "Hello World [20]"}' to the topic: 'test/testing'
Publish End
  • Subscribe AWS server

좋은 웹페이지 즐겨찾기