Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- 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 <SPI.h>
- #include <Ethernet.h>
- #include <PubSubClient.h>
- // Replace UNIQUE with the number you received in the workshop
- #define MQTTid "arduinoClient-PW-UNIQUE"
- // If you do this project on your own you will need to create an account
- // on Adafruit.IO. You will populate your own username and AIO key
- // It's generally not good to share your key. I will be revoking this key
- // after the workshop.
- #define MQTTuser "REDACTED"
- #define MQTTpsw "REDACTED"
- // MAC address for the Ethernet Shield. This needs to be unique on the network.
- // Replace 'UNIQUE' with the number you were given at the workshop
- byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xUNIQUE };
- 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();
- }
- EthernetClient ethClient;
- PubSubClient client(ethClient);
- void reconnect() {
- // Loop until we're reconnected
- while (!client.connected()) {
- Serial.print("Attempting MQTT connection...");
- // Attempt to connect
- if (client.connect(MQTTid, MQTTuser, MQTTpsw)) {
- Serial.println("connected");
- // Once connected, publish an announcement...
- // Replace UNIQUE with the number you received in the workshop
- client.publish("REDACTED/feeds/plant-waterer-sensors.pw-messagereceive","PW-UNIQUE connected");
- // ... and resubscribe
- client.subscribe("REDACTED/feeds/plant-waterer-sensors.pw-messagepublish");
- } 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("io.adafruit.com", 1883);
- client.setCallback(callback);
- Ethernet.begin(mac);
- // Allow the hardware to sort itself out
- delay(1500);
- }
- void loop()
- {
- if (!client.connected()) {
- reconnect();
- }
- client.loop();
- }
Add Comment
Please, Sign In to add comment