Last active
October 29, 2016 15:18
-
-
Save jbott/f343e8871a5579458805ab79de113fba to your computer and use it in GitHub Desktop.
This file contains 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
/* | |
Basic MQTT example | |
This sketch demonstrates the basic capabilities of the library. | |
It connects to an MQTT server then: | |
- publishes "hello world" to the topic "outTopic" | |
- subscribes to the topic "inTopic", printing out any messages | |
it receives. NB - it assumes the received payloads are strings not binary | |
It will reconnect to the server if the connection is lost using a blocking | |
reconnect function. See the 'mqtt_reconnect_nonblocking' example for how to | |
achieve the same result without blocking the main loop. | |
*/ | |
#include <ArduinoJson.h> | |
#include <Bridge.h> | |
#include <YunClient.h> | |
#include <PubSubClient.h> | |
IPAddress server(192, 168, 0, 100); | |
String hostname; | |
void callback(char* topic, byte* payload, unsigned int length) { | |
Serial.print("Message arrived ["); | |
Serial.print(topic); | |
Serial.print("] "); | |
for (int i=0;i<length;i++) { | |
Serial.print((char)payload[i]); | |
} | |
Serial.println(); | |
} | |
YunClient yun; | |
PubSubClient client(yun); | |
void reconnect() { | |
// Loop until we're reconnected | |
while (!client.connected()) { | |
Serial.print("Attempting MQTT connection..."); | |
// Attempt to connect | |
if (client.connect(hostname.c_str())) { | |
Serial.println("connected"); | |
// Once connected, publish an announcement... | |
client.publish("outTopic","hello world"); | |
// ... and resubscribe | |
client.subscribe("inTopic"); | |
} else { | |
Serial.print("failed, rc="); | |
Serial.print(client.state()); | |
Serial.println(" try again in 5 seconds"); | |
// Wait 5 seconds before retrying | |
delay(5000); | |
} | |
} | |
} | |
void setup() | |
{ | |
Serial.begin(9600); | |
client.setServer(server, 1883); | |
client.setCallback(callback); | |
Bridge.begin(); | |
Process p; | |
p.runShellCommand("hostname"); | |
hostname += "arduino-"; | |
hostname += p.readString(); | |
} | |
void loop() | |
{ | |
if (!client.connected()) { | |
reconnect(); | |
} | |
client.loop(); | |
StaticJsonBuffer<200> jsonBuffer; | |
JsonObject& root = jsonBuffer.createObject(); | |
root["unit"] = "F"; | |
root["data"] = 73; | |
String string_status; | |
root.printTo(string_status); | |
client.publish("sensor/front/temp", string_status.c_str()); | |
delay(2000); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment