Last active
October 17, 2015 13:18
-
-
Save laclefyoshi/efad97e3bea24d2e1c1a to your computer and use it in GitHub Desktop.
ESP8266でMQTTブローカを経由したmyThingsメッセージを受け取る
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <ESP8266WiFi.h> | |
#include <PubSubClient.h> | |
#include <aJSON.h> | |
const char* ssid = "WIFI_SSID"; | |
const char* password = "WIFI_PASS"; | |
const char* mqtt_server = "MESHBLU"; | |
const char* mqtt_clientid = "esp8266"; | |
const char* mqtt_topic = "MESHBLU_ACTION_UUID"; | |
const char* mqtt_user = "MESHBLU_ACTION_UUID"; | |
const char* mqtt_passwd = "MESHBLU_ACTION_PASS"; | |
WiFiClient client; | |
PubSubClient mqtt(client); | |
void setup() { | |
Serial.begin(115200); | |
delay(10); | |
WiFi.begin(ssid, password); | |
while (WiFi.status() != WL_CONNECTED) { | |
delay(500); | |
Serial.print("."); | |
} | |
Serial.println(""); | |
Serial.println("WiFi connected"); | |
Serial.print("IP address: "); | |
Serial.println(WiFi.localIP()); | |
mqtt.setServer(mqtt_server, 1883); | |
mqtt.setCallback(callback); | |
} | |
void loop() { | |
connect_mqtt(); | |
mqtt.loop(); | |
} | |
void callback(char* topic, byte* payload, unsigned int length) { | |
char buffer[1000]; | |
snprintf(buffer, sizeof(buffer), "%s", payload); | |
Serial.println(buffer); | |
aJsonObject* jsonObj = aJson.parse(buffer); | |
aJsonObject* d = aJson.getObjectItem(jsonObj, "data"); | |
aJsonObject* pl = aJson.getObjectItem(d, "payload"); | |
String msg = String(pl->valuestring); | |
Serial.println(String("\t") + msg); | |
} | |
void connect_mqtt() { | |
if (mqtt.connected()) { | |
return; | |
} | |
mqtt.connect(mqtt_clientid, mqtt_user, mqtt_passwd); | |
while (!mqtt.connected()) { | |
Serial.println("failed to connect to mqtt broker"); | |
mqtt.disconnect(); | |
delay(2000); | |
mqtt.connect(mqtt_clientid, mqtt_user, mqtt_passwd); | |
} | |
Serial.println("succeeded to connect to mqtt broker"); | |
mqtt.subscribe(mqtt_topic); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment