본문 바로가기

RaspberryPi/W55RP20

[W55RP20-4032] W55RP20 Arduino - W55RP20_Ethernet3 라이브러리 이용 MQTT 테스트

W55RP20 Arduino 환경에서 네트웍 전송률은 조금? 느리지만 기존 작성된 다양한 라이브러리를 쉽게 사용할수 있는 장점이 있다.

이번에는 MQTT로 데이터 전송 예제 코드를 작성해 보자.

 

PubSubClient 라이브러리를 이용하면 아주 쉽게 MQTT 데이터를 송수신 할 수 있다.

#include <W55RP20_Ethernet3.h> // W55RP20 전용 하드웨어 가속 라이브러리
#include <PubSubClient.h>  

// 2. MQTT 서버 정보 및 매크로 설정
const char* mqtt_host = "mqtt.host.com";
const int mqtt_port = 1883; 

#define MQTT_CLIENT_ID "Test_ID_778899_Nexp"
#define MQTT_USERNAME "mqttest"
#define MQTT_PASSWORD "1234"
#define MQTT_PUBLISH_TOPIC "msg/pub"
#define MQTT_PUBLISH_PAYLOAD "Test"
#define MQTT_PUBLISH_PERIOD (1000 * 10) 
#define MQTT_KEEP_ALIVE 60              

//구독할 토픽 정의
const char* subscribe_topic = "testtopic/1";

EthernetClient ethClient;
PubSubClient mqttClient(ethClient);

unsigned long lastMsgTime = 0;

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("\n[수신] 토픽: ");
  Serial.println(topic);

  Serial.print("내용 (Payload): ");
  for (unsigned int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
}

void reconnect() {
  while (!mqttClient.connected()) {
    Serial.print("Attempting MQTT connection...");

    if (mqttClient.connect(MQTT_CLIENT_ID, MQTT_USERNAME, MQTT_PASSWORD)) {
      Serial.println("connected!");
      
      if (mqttClient.subscribe(subscribe_topic)) {
        Serial.print("구독 성공 완료 토픽 -> ");
        Serial.println(subscribe_topic);
      } else {
        Serial.println("구독 신청 실패!");
      }

    } else {
      Serial.print("failed, rc=");
      Serial.print(mqttClient.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}

void setup() {
  Serial.begin(115200);
  while (!Serial) { ; }

  Serial.println("=== W55RP20 MQTT Sub/Pub Client Start ===");

  Ethernet.begin(mac, ip, subnet, gateway, dnsServer);
  delay(1500); 

  mqttClient.setServer(mqtt_host, mqtt_port);
  mqttClient.setCallback(callback);
  mqttClient.setKeepAlive(MQTT_KEEP_ALIVE);
}

void loop() {
  if (!mqttClient.connected()) {
    reconnect();
  }
  
  mqttClient.loop();

  // 10초 주기 주기적 Publish 
  unsigned long now = millis();
  if (now - lastMsgTime > MQTT_PUBLISH_PERIOD) {
    lastMsgTime = now;

    Serial.print("[송신] ");
    Serial.println(MQTT_PUBLISH_PAYLOAD);
    mqttClient.publish(MQTT_PUBLISH_TOPIC, MQTT_PUBLISH_PAYLOAD);
  }
}

 

 

임시 MQTT broker사이트에 접속하여 서버를 생성한다.

 

 

코드 실행하면 MQTT Brocker에 접속해서 데이터 송수신 하는 것을 확인 할 수 있다.

 

=== W55RP20 MQTT Sub/Pub Client Start ===

Attempting MQTT connection...connected!

구독 성공 완료 토픽 -> testtopic/1

[송신] Test

 

[수신] 토픽: testtopic/1

내용 (Payload): aaaaaa

[송신] Test

 

[수신] 토픽: testtopic/1

내용 (Payload): Test2

[송신] Test

[송신] Test

 

 

잘 작성된 라이브러리를 쉽게 활용하는 측면에서는 Arduino 개발환경이 쉽고 빠르게 테스트 할수 있는것 같다.