LoginSignup
1
0

More than 1 year has passed since last update.

Grove IoT スターターキット for SORACOM で MQTT クライアントを使う

Posted at

パブリック MQTT ブローカー broker.emqx.io に接続するサンプルです。

フォルダー構造

$ tree mqtt_client/
mqtt_client/
├── mqtt_client.ino
└── setupLTE.ino
mqtt_client.ino
// ---------------------------------------------------------------
/*
    mqtt_client.ino

                    Aug/10/2021
*/
// ---------------------------------------------------------------
#include <WioLTEforArduino.h>
#include <WioLTEClient.h>
#include <PubSubClient.h>
#include <stdio.h>

#define MQTT_SERVER_HOST  "broker.emqx.io"
#define MQTT_SERVER_PORT  (1883)

#define ID                "WioLTE"
#define OUT_TOPIC         "example/testTopic"
#define IN_TOPIC          "example/testTopic"

#define INTERVAL          (60000)

WioLTE Wio;
WioLTEClient WioClient(&Wio);
PubSubClient MqttClient;

// ---------------------------------------------------------------
void callback(char* topic, byte* payload, unsigned int length) {
    SerialUSB.print("Subscribe:");
    for (int i = 0; i < length; i++) SerialUSB.print((char)payload[i]);
    SerialUSB.println("");
}

// ---------------------------------------------------------------
void setup() {
    setupLTE();

    SerialUSB.println("### Connecting to MQTT server \""MQTT_SERVER_HOST"\"");
    MqttClient.setServer(MQTT_SERVER_HOST, MQTT_SERVER_PORT);
    MqttClient.setCallback(callback);
    MqttClient.setClient(WioClient);
    if (!MqttClient.connect(ID)) {
        SerialUSB.println("### ERROR! ###");
        return;
    }
    MqttClient.subscribe(IN_TOPIC);

    SerialUSB.println("*** Setup completed *** Aug/10/2021 PM 18:54 ***");
}

// ---------------------------------------------------------------
void loop() {
    char data[100];
    sprintf(data, "{\"uptime\":%lu}", millis() / 1000);
    SerialUSB.print("Publish:");
    SerialUSB.print(data);
    SerialUSB.println("");
    MqttClient.publish(OUT_TOPIC, data);

err:
    unsigned long next = millis();
    while (millis() < next + INTERVAL)
    {
    Wio.LedSetRGB(1, 1, 0); 
        MqttClient.loop();
        SerialUSB.println("*** check ***");

    Wio.LedSetRGB(0, 0, 1); 
    delay(1000);
    Wio.LedSetRGB(0, 1, 0); 
    delay(1000);
    Wio.LedSetRGB(1, 1, 1); 
    delay(1000);
    Wio.LedSetRGB(0, 0, 0); 
    delay(1000);
    }
}

// ---------------------------------------------------------------

setupLTE.ino はこちら
UDP で温度と湿度を Harvest に送る

次のコマンドで publish をします。

go_pub_mqtt.sh
BROKER="broker.emqx.io"
#
echo $BROKER
message="Hello Mqtt "`date`
mosquitto_pub -d -t orz -m "${message}" \
    -h  $BROKER \
    --topic example/testTopic

シリアルモニタの結果
mqtt_aug10.png

参考ページ
パブリック MQTT ブローカーの使い方

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0