フォルダー構造
$ tree mqtt_subscribe/
mqtt_subscribe/
├── mqtt_subscribe.ino
├── setupLTE.ino
└── setup_mqtt.ino
mqtt_subscribe.ino
// ---------------------------------------------------------------
/*
mqtt_subscribe.ino
Aug/20/2021
*/
// ---------------------------------------------------------------
#include <WioLTEforArduino.h>
#include <WioLTEClient.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include <stdio.h>
#define MQTT_SERVER_HOST "example.com"
#define MQTT_SERVER_PORT (1883)
#define ID "WioLTE"
#define OUT_TOPIC "sample/imageTopic"
#define IN_TOPIC "sample/imageTopic"
WioLTE Wio;
WioLTEClient WioClient(&Wio);
PubSubClient MqttClient;
int icount = 0;
// ---------------------------------------------------------------
void callback(char* topic, byte* payload, unsigned int length)
{
SerialUSB.println("*** callback ***");
payload[length] = '\0';
String msg = String((char*) payload);
SerialUSB.println(msg);
}
// ---------------------------------------------------------------
void setup()
{
setupLTE();
setup_mqtt_proc();
SerialUSB.println("*** Setup completed *** Aug/20/2021 PM 20:20 ***");
}
// ---------------------------------------------------------------
void loop()
{
DynamicJsonDocument doc(512);
char data_json[128];
if ((icount % 1000) == 0)
{
doc["icount"] = icount;
doc["uptime"] = millis() / 1000;
serializeJson(doc, data_json);
SerialUSB.println(data_json);
}
MqttClient.loop();
icount++;
}
// ---------------------------------------------------------------
setupLTE.ino はこちら
UDP で温度と湿度を Harvest に送る
setup_mqtt.ino はこちら
ブラウザーから MQTT Publish でブザーを鳴らす
シリアルモニタの表示
20:15:22.403 -> *** Connecting to "soracom.io" ***
20:15:23.529 -> *** SetupLTE completed ***
20:15:23.529 -> *** end *** seupLTE ***
20:15:23.529 -> ### Connecting to MQTT server "example.com"
20:15:23.761 -> *** subscribe ***
20:15:23.761 -> *** Setup completed *** Aug/20/2021 PM 20:20 ***
20:15:23.761 -> {"icount":0,"uptime":14}
20:15:24.192 -> *** callback ***
20:15:24.192 -> {"buzzer":"off"}
20:15:27.180 -> {"icount":1000,"uptime":17}
20:15:30.266 -> {"icount":2000,"uptime":20}
20:15:32.389 -> *** callback ***
20:15:32.389 -> {"buzzer":"on"}
20:15:33.649 -> {"icount":3000,"uptime":24}
20:15:36.767 -> {"icount":4000,"uptime":27}
20:15:37.496 -> *** callback ***
20:15:37.496 -> {"buzzer":"off"}
20:15:39.884 -> *** callback ***
20:15:39.884 -> {"buzzer":"on"}
20:15:40.482 -> {"icount":5000,"uptime":31}
20:15:43.599 -> {"icount":6000,"uptime":34}
20:15:46.684 -> {"icount":7000,"uptime":37}
20:15:49.769 -> {"icount":8000,"uptime":40}
20:15:52.887 -> {"icount":9000,"uptime":43}
20:15:56.072 -> {"icount":10000,"uptime":46}