Last active
October 17, 2015 13:18
-
-
Save laclefyoshi/38d047c37b96f92c46a5 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 <DHT.h> | |
#include <PubSubClient.h> | |
#include <aJSON.h> | |
#define DHTPIN 4 | |
#define DHTTYPE DHT11 | |
const char* ssid = "WIFI_SSID"; | |
const char* password = "WIFI_PASS"; | |
const char* mqtt_server = "MESHBLU"; | |
const char* mqtt_clientid = "esp8266"; | |
const char* mqtt_user = "MESHBLU_TRIGGER_UUID"; | |
const char* mqtt_passwd = "MESHBLU_TRIGGER_PASS"; | |
const char* mqtt_topic = "message"; | |
const char* mqtt_action = "MESHBLU_ACTION_UUID"; | |
DHT dht(DHTPIN, DHTTYPE); | |
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()); | |
dht.begin(); | |
mqtt.setServer(mqtt_server, 1883); | |
} | |
void loop() { | |
connect_mqtt(); | |
float h = dht.readHumidity(); | |
float t = dht.readTemperature(); | |
Serial.print("Humidity: "); | |
Serial.print(h); | |
Serial.print(" %\t"); | |
Serial.print("Temperature: "); | |
Serial.print(t); | |
Serial.println(" *C"); | |
aJsonObject* root = aJson.createObject(); | |
aJsonObject* devices = aJson.createArray(); | |
aJson.addItemToArray(devices, aJson.createItem(mqtt_action)); | |
aJson.addItemToObject(root, "devices", devices); | |
aJsonObject* payload = aJson.createObject(); | |
aJson.addNumberToObject(payload, "humidity", h); | |
aJson.addNumberToObject(payload, "temperature", t); | |
aJson.addItemToObject(root, "payload", payload); | |
char* msg = aJson.print(root); | |
Serial.println(msg); | |
mqtt.publish(mqtt_topic, msg); | |
delay(5000); | |
} | |
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"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment