Skip to content

Instantly share code, notes, and snippets.

@j3tm0t0
Created January 24, 2018 19:35
Show Gist options
  • Save j3tm0t0/5b3385d2cd558d8de8f0090dde80c5cd to your computer and use it in GitHub Desktop.
Save j3tm0t0/5b3385d2cd558d8de8f0090dde80c5cd to your computer and use it in GitHub Desktop.
Bi-directional MQTT demo for SORACOM Beam and Azure IoT Hub
#include <WioLTEforArduino.h>
#include <WioLTEClient.h>
#include <PubSubClient.h> // https://github.com/knolleary/pubsubclient
#include <stdio.h>
#define APN "soracom.io"
#define USERNAME "sora"
#define PASSWORD "sora"
#define MQTT_SERVER_HOST "beam.soracom.io"
#define MQTT_SERVER_PORT (1883)
#define ID "WioLTE"
#define OUT_TOPIC "devices/WioLTE/messages/events/"
#define IN_TOPIC "devices/WioLTE/messages/devicebound/#"
#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("");
if((payload[0] == '#') && (length==7))
{
String hexstring=String((char *)payload);
int number = (int) strtol( &hexstring[1], NULL, 16);
int r = number >> 16;
int g = number >> 8 & 0xFF;
int b = number & 0xFF;
SerialUSB.print("Setting LED as "); SerialUSB.println(hexstring);
Wio.LedSetRGB(r,g,b);
}
}
void setup() {
delay(200);
SerialUSB.println("");
SerialUSB.println("--- START ---------------------------------------------------");
SerialUSB.println("### I/O Initialize.");
Wio.Init();
SerialUSB.println("### Power supply ON.");
Wio.PowerSupplyLTE(true);
delay(5000);
SerialUSB.println("### Turn on or reset.");
if (!Wio.TurnOnOrReset()) {
SerialUSB.println("### ERROR! ###");
return;
}
SerialUSB.println("### Connecting to \""APN"\".");
delay(5000);
if (!Wio.Activate(APN, USERNAME, PASSWORD)) {
SerialUSB.println("### ERROR! ###");
return;
}
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);
}
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)
{
MqttClient.loop();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment